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
Core/Awake/core/src/com/cs446/awake/ui/BackpackScreen.kt
ErastoRuuuuuush
497,435,431
false
null
package com.cs446.awake.ui import com.badlogic.gdx.Gdx import com.badlogic.gdx.audio.Music import com.badlogic.gdx.graphics.Color import com.badlogic.gdx.graphics.Pixmap import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.g2d.BitmapFont import com.badlogic.gdx.graphics.g2d.SpriteBatch import com.badlogic.gdx.graphics.g2d.TextureRegion import com.badlogic.gdx.scenes.scene2d.InputEvent import com.badlogic.gdx.scenes.scene2d.InputListener import com.badlogic.gdx.scenes.scene2d.ui.* import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane.ScrollPaneStyle import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable import com.cs446.awake.Awake import com.cs446.awake.model.* import com.cs446.awake.utils.BaseActor import com.cs446.awake.utils.BaseScreen import com.cs446.awake.utils.DragDropActor val TOTAL_ITEM = itemInfo.getStored().size val TOTAL_MATERIAL = materialInfo.getStored().size class BackpackScreen(val g: Int) : BaseScreen() { private val screenWidth = Gdx.graphics.width.toFloat() private val screenHeight = Gdx.graphics.height.toFloat() private val buttonHeight = screenHeight / 6 - 75f // Timer variables private var worldTimer = -1 private var activeTimer = false private val timerLimit = 10 // Not 0 in case of concurrency issue. private var endTimeFcn : () -> Unit = {} // lambda function about what to do when time ends private var duringTimeFcn : () -> Unit = {} // lambda function about what to do when each frame passed. private var list = mutableListOf<String>("s","a") private lateinit var scrollPane : ScrollPane private lateinit var material : BaseActor private lateinit var weapon : BaseActor private lateinit var back : BaseActor private lateinit var paper : BaseActor private lateinit var name : Label private lateinit var use : Label private lateinit var ip : Label private lateinit var mp : Label private lateinit var villageMusic : Music // Function that active the timer private fun startTimer(frames: Int, endTime : () -> Unit, duringTime : () -> Unit) { endTimeFcn = endTime duringTimeFcn = duringTime worldTimer = frames activeTimer = true } // Function that count down the timer. Stop timer when time ends. private fun runTimer() { if (activeTimer) { if (worldTimer <= timerLimit) { // Time up activeTimer = false endTimeFcn() } else { // During count down duringTimeFcn() worldTimer-- } } } fun showInfo(card: MergableCard) { name.setText(card.cardName) name.setFontScale(0.8f) name.setPosition(paper.x + 100, paper.y + 300) name.setSize(paper.width, paper.height) name.wrap = true if (g == 1){ name.moveBy(0f, -55f) use.setText("Amount: " + card.count.toString()) use.setFontScale(0.8f) use.setPosition(paper.x + 100, paper.y) use.setSize(paper.width, paper.height) use.wrap = true } else { use.setText(card.usage + "\n\n wood: ${card.wood}, \n fire: ${card.fire}, \n earth: ${card.earth}, \n " + "metal: ${card.metal}, \n water: ${card.water}, \n electr: ${card.electric}, \n wind: ${card.wind} \n.") use.setFontScale(0.6f) use.setPosition(paper.x + 30, paper.y - 50) use.setSize(paper.width -10f, paper.height) use.wrap = true } } fun backpackScroll(i: Int) { paper = BaseActor(0f, 0f, stage) paper.loadTexture("map/empty.png") paper.setPosition(screenWidth / 20, screenHeight / 4 - 125f) paper.setSize(390f, screenHeight / 5 * 4f) name = Label("", Label.LabelStyle(BitmapFont(Gdx.files.internal("font/font4_black.fnt")), Color.WHITE)) use = Label("", Label.LabelStyle(BitmapFont(Gdx.files.internal("font/font4_black.fnt")), Color.WHITE)) stage.addActor(name) stage.addActor(use) var table = Table() var container = Table() // Card's border val borderTexture = Texture(Gdx.files.internal("highlight_border.png")) // TODO: change the texture val borderImage = Image(borderTexture) borderImage.isVisible = false for (c in storage.getStored()) { if (i == 1 && c is MaterialCard) { continue } if (i == 2 && c is ItemCard) { continue } if (g == 1 && c.count == 0) { continue } val cardActor = BaseActor(0f, 0f, stage) cardActor.loadTexture(c.img) val cardHeight = screenHeight / 3 * 2f cardActor.setSize(cardHeight / cardActor.height*cardActor.width, cardHeight) cardActor.addListener(object : InputListener() { override fun touchDown( event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int ): Boolean { showInfo(c) val borderWidth = 30 borderImage.setSize( cardActor.width + 25, cardActor.height + 25 ) borderImage.setPosition(cardActor.x-10, cardActor.y-10) borderImage.isVisible = true cardActor.toFront() return true } }) table.add(cardActor) } table.add(borderImage) table.row() scrollPane = ScrollPane(table) scrollPane.scrollTo(0f,0f,0f,0f) container.add(scrollPane) container.setPosition(screenWidth / 4.5f, screenHeight / 4 - 125f) container.setSize(screenWidth / 5 * 3.9f, screenHeight / 5 * 4f) var skin = Skin() skin.add("logo", Texture("bpback.png")); container.background(skin.getDrawable("logo")) container.row() container.getCell(scrollPane).size(1720f,container.height /2*3) stage.addActor(container) back = BaseActor(0f, 0f, stage) back.loadTexture("backButton.png") back.setSize(buttonHeight / back.height * back.width, buttonHeight) back.setPosition(screenWidth / 20, 20f) // Set event action back.addListener(object : InputListener() { override fun touchDown( event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int ): Boolean { villageMusic.stop() Awake.setActiveScreen(BackpackScreen(g)) return true } }) } override fun initialize() { Gdx.input.inputProcessor = stage //stage.addActor(countdownLabel) //countdownLabel.setPosition(screenWidth/2 - countdownLabel.width/2, screenHeight/2 + countdownLabel.height/2) // Music villageMusic = Gdx.audio.newMusic(Gdx.files.internal("sound/village_bgm.wav")) villageMusic.setLooping(true) villageMusic.volume = 200f villageMusic.play() // Background Picture val background = BaseActor(0f, 0f, stage) background.loadTexture("darkbackground.png") background.setSize(screenWidth, (screenWidth / background.width * background.height)) background.centerAtPosition(screenWidth / 2, screenHeight / 2) weapon = BaseActor(0f, 0f, stage) weapon.loadTexture("equipment.png") weapon.setSize(800f, 850f) weapon.centerAtPosition(screenWidth / 3f, screenHeight / 2) // Set event action weapon.addListener(object : InputListener() { override fun touchDown( event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int ): Boolean { weapon.remove() material.remove() back.remove() ip.isVisible = false mp.isVisible = false backpackScroll(1) return true } }) material = BaseActor(0f, 0f, stage) material.loadTexture("material.png") material.setSize(800f, 850f) material.centerAtPosition(screenWidth / 2.8f * 2, screenHeight / 2) // Set event action material.addListener(object : InputListener() { override fun touchDown( event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int ): Boolean { weapon.remove() material.remove() back.remove() ip.isVisible = false mp.isVisible = false backpackScroll(2) return true } }) var ilen = 0 var mlen = 0 for (c in storage.getStored()) { if (c is ItemCard) { ilen += 1 } else { mlen += 1 } } ip = Label("$ilen / $TOTAL_ITEM", Label.LabelStyle(BitmapFont(Gdx.files.internal("font/font4_brown.fnt")), Color.WHITE)) mp = Label("$mlen / $TOTAL_MATERIAL", Label.LabelStyle(BitmapFont(Gdx.files.internal("font/font4_brown.fnt")), Color.WHITE)) ip.setPosition(weapon.x + 300, weapon.y + 825) mp.setPosition(material.x + 300, material.y + 825) stage.addActor(ip) stage.addActor(mp) if (g == 1) { ip.isVisible = false mp.isVisible = false } back = BaseActor(0f, 0f, stage) back.loadTexture("backButton.png") back.setSize(buttonHeight / back.height * back.width, buttonHeight) back.setPosition(screenWidth / 20, 20f) // Set event action back.addListener(object : InputListener() { override fun touchDown( event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int ): Boolean { villageMusic.stop() Awake.setActiveScreen(VillageScreen()) return true } }) } override fun update(delta: Float) { runTimer() return } }
1
Kotlin
2
0
3d11175e20e2be3238c561e6e6cd89a523731877
10,750
CS446-Awake
MIT License
SceytChatUiKit/src/main/java/com/sceyt/sceytchatuikit/presentation/uicomponents/mediaview/videoview/CustomVideoView.kt
sceyt
549,073,085
false
null
package com.sceyt.sceytchatuikit.presentation.uicomponents.mediaview.videoview import android.content.Context import android.net.Uri import android.util.AttributeSet import android.view.LayoutInflater import android.widget.FrameLayout import com.sceyt.sceytchatuikit.databinding.SceytVideoViewBinding import com.sceyt.sceytchatuikit.presentation.uicomponents.mediaview.SceytMediaActivity import com.sceyt.sceytchatuikit.presentation.uicomponents.mediaview.videoview.VideoControllerView.MediaPlayerControl class CustomVideoView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0, ) : FrameLayout(context, attrs, defStyleAttr), MediaPlayerControl { private val binding = SceytVideoViewBinding.inflate(LayoutInflater.from(context), this, true) private var currentMediaPath: String? = null init { binding.controllerView.setAnchorView(binding.root) binding.controllerView.player = this binding.videoView.onSurfaceUpdated = { binding.controllerView.reloadUI() } } private fun initPlayer(mediaPath: String?) { if (mediaPath == null) return if (binding.videoView.isPlaying) { binding.videoView.reset() } binding.videoView.setDataSource(mediaPath) } private fun initPlayer(uri: Uri) { if (binding.videoView.isPlaying) { binding.videoView.reset() } binding.videoView.setDataSource(context, uri) } private fun initPlayer(rawId: Int) { if (binding.videoView.isPlaying) { binding.videoView.reset() } binding.videoView.setRawData(rawId) } private fun setInitialState() { } fun setVideoPath(mediaPath: String?, startPlay: Boolean = false, isLooping: Boolean = false) { if (currentMediaPath == mediaPath) return currentMediaPath = mediaPath initPlayer(mediaPath) binding.videoView.prepareAsync { if (startPlay) binding.videoView.start() binding.videoView.isLooping = isLooping post { binding.controllerView.setUserVisibleHint((context as SceytMediaActivity).isShowMediaDetail()) } } } fun setVideoRaw(resId: Int, startPlay: Boolean = false, isLooping: Boolean = false) { initPlayer(resId) if (startPlay) { binding.videoView.prepareAsync { binding.videoView.start() binding.videoView.isLooping = isLooping post { binding.controllerView.setUserVisibleHint((context as SceytMediaActivity).isShowMediaDetail()) } } } } fun setVideoUri(uri: Uri, startPlay: Boolean = false, isLooping: Boolean = false) { initPlayer(uri) if (startPlay) { binding.videoView.prepareAsync { binding.videoView.start() binding.videoView.isLooping = isLooping post { binding.controllerView.setUserVisibleHint((context as SceytMediaActivity).isShowMediaDetail()) } } } } fun setLooping(isLooping: Boolean) { binding.videoView.isLooping = isLooping } fun release() { binding.videoView.release() setInitialState() } fun hideController() { binding.controllerView.hide() } fun showController() { binding.controllerView.show(3000) } fun showController(isShow: Boolean) { if (isShow) { binding.controllerView.show() } else { binding.controllerView.hide() } } fun setUserVisibleHint(isVisibleToUser: Boolean) { binding.controllerView.setUserVisibleHint(isVisibleToUser) } fun setPlayingListener(listener: VideoControllerView.PlayingListener) { binding.controllerView.setPlayingListener(listener) } override fun start() { binding.videoView.start() } override fun pause() { binding.videoView.pause() } val mediaPlayer get() = binding.videoView.mediaPlayer override val duration: Int get() = binding.videoView.duration override val currentPosition: Int get() = binding.videoView.currentPosition override fun seekTo(pos: Int) { binding.videoView.seekTo(pos) } override val isPlaying: Boolean get() = binding.videoView.isPlaying override fun canPause(): Boolean = true }
0
Kotlin
0
0
0b135841180b7c4fdd66b1b0f7655d8d79fe8a03
4,576
sceyt-chat-android-uikit
MIT License
app/src/main/java/com/skydev/gymexercise/data/repo/ExerciseRepo.kt
skydev-x
804,560,212
false
{"Kotlin": 39191}
package com.skydev.gymexercise.data.repo import com.skydev.gymexercise.data.model.Exercise interface ExerciseRepo { fun getAll() : List<Exercise> fun getExerciseById(id: String) : Exercise fun insertAll(exercises: List<Exercise>) fun findExerciseByName(name: String) fun deleteAll() fun delete(exercise: Exercise) fun deleteById(id: String) }
0
Kotlin
0
0
6e675f62dcfdc533c5ee93af9edcc2e2166708fb
372
gym-ex-app
Apache License 2.0
android/core/data/src/main/java/com/jaino/data/repository/auth/AuthRepository.kt
pknu-wap
615,959,763
false
null
package com.jaino.data.repository.auth interface AuthRepository { suspend fun signInService(token: String) : Result<Unit> fun setAccessToken(token: String) fun setRefreshToken(token: String) fun setNickName(nickName: String) fun setUserId(userId: Int) }
4
Kotlin
2
4
d14a2e8855f93689c921fef534c6181d6bcab257
279
2023_1_WAT_BeJuRyu
MIT License
app/src/main/java/com/kovcom/mowid/ui/feature/home/HomeViewModel.kt
mkovalyk
694,371,684
false
{"Kotlin": 251818}
package com.kovcom.mowid.ui.feature.home import androidx.lifecycle.viewModelScope import com.kovcom.domain.interactor.MotivationPhraseInteractor import com.kovcom.mowid.base.ui.BaseViewModel import com.kovcom.mowid.model.toUIModel import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.* import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class HomeViewModel @Inject constructor( private val motivationPhraseInteractor: MotivationPhraseInteractor ) : BaseViewModel<HomeState, HomeEvent, HomeEffect>() { init { motivationPhraseInteractor.getGroupPhraseListFlow() .onStart { setState { copy(isLoading = true) } } .flowOn(Dispatchers.IO) .onEach { data -> setState { copy( isLoading = false, groupPhraseList = data.toUIModel() ) } } .onCompletion { setState { copy(isLoading = false) } } .catch { HomeEffect.ShowError( message = it.message.toString() ).sendEffect() } .launchIn(viewModelScope) } override fun createInitialState(): HomeState = HomeState( isLoading = true, groupPhraseList = emptyList() ) override fun handleEvent(event: HomeEvent) { when (event) { is HomeEvent.GroupItemClicked -> { // handle directly on UI } HomeEvent.ShowGroupModal -> { // handle directly on UI } HomeEvent.HideGroupModal -> { // handle directly on UI } is HomeEvent.AddGroupClicked -> { viewModelScope.launch { motivationPhraseInteractor.addGroup( name = event.name, description = event.description ) } } is HomeEvent.OnItemDeleted -> deleteGroup((event.id)) is HomeEvent.OnEditClicked -> { viewModelScope.launch { motivationPhraseInteractor.editGroup( groupId = event.id, editedName = event.editedName, editedDescription = event.editedDescription ) } } } } private fun deleteGroup(id: String) { viewModelScope.launch { motivationPhraseInteractor.deleteGroup(id) } } }
0
Kotlin
0
0
70770267bd1003664c71b6be8054414a3fc0a434
2,725
mowid
Apache License 2.0
old-app-kotlin/src/main/java/tech/thdev/kotlin_udemy_sample/view/image/adapter/model/ImageViewAdapterContract.kt
becooni
133,846,675
true
{"Kotlin": 125549, "Java": 48845}
package tech.thdev.kotlin_udemy_sample.view.image.adapter.model import android.view.MotionEvent import tech.thdev.kotlin_udemy_sample.data.RecentPhotoItem import tech.thdev.kotlin_udemy_sample.listener.OnItemTouchListener import java.util.* /** * Created by tae-hwan on 11/13/16. */ interface ImageViewAdapterContract { interface View { /** * ItemTouch event */ val onItemTouchListener: OnItemTouchListener? fun setOnItemTouchListener(onTouch: (MotionEvent?, Int) -> Boolean) fun reload() } /** * Adapter에서 사용할 Model에 대한 interface 정의 */ interface Model { fun addItem(item: RecentPhotoItem?) fun getItems(): ArrayList<RecentPhotoItem> fun getItem(position: Int): RecentPhotoItem /** * Item clear 추가 */ fun clear() } }
0
Kotlin
0
1
6d4964e1f6e70162b33a8d76023f1bd7557c2dfd
868
Kotlin-Udemy-Sample
Apache License 2.0
core/src/main/kotlin/com/github/prologdb/dbms/KnowledgeBaseMetadata.kt
prologdb
113,687,585
false
null
package com.github.prologdb.dbms import com.github.prologdb.util.metadata.MetadataRepository /** * Metadata about a knowledge base in general (does not include * nested metadata objects, such as for a fact store). * * Wrapper for typesafe access to a [MetadataRepository] */ class KnowledgeBaseMetadata(private val nested: MetadataRepository) { }
10
Kotlin
0
2
788ab81bf872fa82c86f89bcbae8a13247e77e05
354
prologdb
MIT License
kotest-framework/kotest-framework-engine/src/jsMain/kotlin/io/kotest/engine/test/interceptors/interceptors.kt
busches
421,923,261
true
{"Kotlin": 3300619, "CSS": 352, "Java": 145}
package io.kotest.engine.test.interceptors import io.kotest.common.platform import io.kotest.core.concurrency.CoroutineDispatcherFactory import io.kotest.core.config.Configuration internal actual fun coroutineDispatcherFactoryInterceptor( defaultCoroutineDispatcherFactory: CoroutineDispatcherFactory ): TestExecutionInterceptor = error("Unsupported on $platform") internal actual fun blockedThreadTimeoutInterceptor(configuration: Configuration): TestExecutionInterceptor = error("Unsupported on $platform") internal actual fun coroutineErrorCollectorInterceptor(): TestExecutionInterceptor = error("Unsupported on $platform")
0
Kotlin
0
0
5b81fb0d8d5b15bf1956e678f80b9818237e73ba
641
kotest
Apache License 2.0
app/src/main/java/com/perol/asdpl/pixivez/data/model/User.kt
ultranity
258,955,010
false
null
/* * MIT License * * Copyright (c) 2022 ultranity * * 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.perol.asdpl.pixivez.data.model import androidx.lifecycle.MutableLiveData import com.perol.asdpl.pixivez.base.EmptyAsNullJsonTransformingSerializer import com.perol.asdpl.pixivez.objects.CopyFrom import com.perol.asdpl.pixivez.objects.UserCacheRepo import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.serialization.Serializable import kotlinx.serialization.Transient import kotlinx.serialization.encoding.Decoder import java.util.WeakHashMap /** * id : 19887389 * name : kkrin1013 * account : kkrin1013 * profile_image_urls : {"medium":"https://i.pximg.net/user-profile/img/2017/12/04/10/46/10/13525660_fc11c3a777f794271125c1f7ab043168_170.png"} * comment:"Aliterと申します。\r\nいつもお気に入り、ブクマ、フォロー等々ありがとうございます!\r\n皆さんと一绪に交流していきたいと思います。\r\n\r\nThis is Aliter.\r\nThank you all for your comments, favorites and bookmarks.\r\nI also hope to comunicate with everyone.\r\n\r\n这里是Aliter;\r\n感谢各位的点赞、收藏与关注;\r\n同时也希望能和大家多多交流。\r\n\r\n這裡是Aliter;\r\n感謝各位的點贊、收藏與關注;\r\n同時也希望能和大家多多交流。\r\n\r\nTwitter: @aliter_c\r\n微博链接(weibo link):http://weibo.com/aliter08\r\n半次元链接(bcy link):https://bcy.net/u/1561764\r\n\r\n欢迎勾搭\r\n\r\n暂不接受约稿", * is_followed : false */ @Serializable class UserX( var id: Int, var name: String, var account: String, var profile_image_urls: ProfileImageUrls, var comment: String = "", var is_access_blocking_user: Boolean = false, ) : CopyFrom<User> { @Transient private val binders = WeakHashMap<MutableLiveData<Boolean>, String>() fun addBinder(key: String, binder: MutableLiveData<Boolean>) { binders[binder] = key } var is_followed: Boolean = false set(value) { val updated = field != value if (updated) { field = value CoroutineScope(Dispatchers.Main).launch { binders.forEach { it.key.value = value } } } } override fun copyFrom(src: User) { //TODO: id = src.id name = src.name account = src.account profile_image_urls = src.profile_image_urls comment = src.comment is_followed = src.is_followed } } // workaround until https://github.com/Kotlin/kotlinx.serialization/issues/1169 fixed typealias User = @Serializable(with = UserSerializer::class) UserX object UserSerializer : EmptyAsNullJsonTransformingSerializer<User>(User.serializer()) { override fun deserialize(decoder: Decoder): User { var user = super.deserialize(decoder) user = UserCacheRepo.update(user.id, user) return user } } /** * {"medium":"https://i.pximg.net/user-profile/img/2017/12/04/10/46/10/13525660_fc11c3a777f794271125c1f7ab043168_170.png"} */ @Serializable data class ProfileImageUrls( val medium: String )
6
null
33
692
d5caf81746e4f16a1af64d45490a358fd19aec1a
3,982
Pix-EzViewer
MIT License
app/src/main/java/com/zero/neon/game/booster/BoosterType.kt
mariodujic
434,687,700
false
{"Kotlin": 126192}
package com.zero.neon.game.booster import androidx.annotation.DrawableRes import com.zero.neon.R enum class BoosterType(@DrawableRes val drawableId: Int) { ULTIMATE_WEAPON_BOOSTER(R.drawable.booster_ultimate_weapon), SHIELD_BOOSTER(R.drawable.booster_shield), HEALTH_BOOSTER(R.drawable.booster_health), LASER_BOOSTER(R.drawable.booster_red_lasers), TRIPLE_LASER_BOOSTER(R.drawable.booster_triple_laser) }
0
Kotlin
8
70
9aafafbaf41d6d57e95df8639c10dc36539ecda7
426
Neon
MIT License
js/js.libraries/src/core/domViews.kt
staltz
38,581,975
true
{"Markdown": 34, "XML": 687, "Ant Build System": 40, "Ignore List": 8, "Git Attributes": 1, "Kotlin": 18510, "Java": 4307, "Protocol Buffer": 4, "Text": 4085, "JavaScript": 63, "JAR Manifest": 3, "Roff": 30, "Roff Manpage": 10, "INI": 7, "HTML": 135, "Groovy": 20, "Maven POM": 50, "Gradle": 71, "Java Properties": 10, "CSS": 3, "Proguard": 1, "JFlex": 2, "Shell": 9, "Batchfile": 8, "ANTLR": 1}
package org.w3c.dom.views deprecated("Use declarations from org.w3c.dom instead") native public trait AbstractView { }
0
Java
0
1
80074c71fa925a1c7173e3fffeea4cdc5872460f
121
kotlin
Apache License 2.0
hoon/HoonAlgorithm/src/main/kotlin/programmers/lv01/Lv1_FindKim.kt
boris920308
618,428,844
false
{"Kotlin": 57019, "Swift": 40496, "Java": 2698, "Rich Text Format": 407}
/** * https://school.programmers.co.kr/learn/courses/30/lessons/12919 */ fun main(args: Array<String>) { val stringArray = arrayOf<String>("kim", "jane", "jeong", "park", "lee", "choi", "Son", "Ryu") solution(stringArray) println("${solution(stringArray)}") } private fun solution(seoul: Array<String>): String { return "김서방은 ${seoul.indexOf("kim")}에 있다" }
1
Kotlin
1
2
0e495912539ae3ba49e03880cb406bcb99f6457b
376
HoOne
Apache License 2.0
app/src/main/java/com/apps/madnotdead/notiapp/ui/adapter/ArticlesAdapter.kt
madnotdead
98,843,792
false
null
package com.apps.madnotdead.notiapp.ui.adapter import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import com.apps.madnotdead.notiapp.R import com.apps.madnotdead.notiapp.data.model.Article import com.apps.madnotdead.notiapp.utils.loadFromUrl import com.apps.madnotdead.notiapp.utils.toDateWithFormat /** * Created by madnotdead on 7/29/17. */ class ArticlesAdapter(val listener: (Article) -> Unit) : RecyclerView.Adapter<ArticlesAdapter.ArticleHolder> () { private var articles: List<Article> = ArrayList() override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ArticlesAdapter.ArticleHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false) return ArticleHolder(view) } override fun onBindViewHolder(holder: ArticlesAdapter.ArticleHolder?, position: Int) { with(articles[position]) { holder?.bindArticle(this) holder?.itemView!!.setOnClickListener { listener (this)} } } override fun getItemCount(): Int = articles.size fun loadArticles(articles: List<Article>) { this.articles = articles notifyDataSetChanged() } fun clearArticles() { this.articles = ArrayList() notifyDataSetChanged() } class ArticleHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) { var ivImage: ImageView? = itemView?.findViewById(R.id.image) var tvTitle: TextView? = itemView?.findViewById(R.id.title) var tvDescription: TextView? = itemView?.findViewById(R.id.description) var tvDate: TextView? = itemView?.findViewById(R.id.date) fun bindArticle(article: Article) { with(article) { tvTitle?.text = title tvDescription?.text = description tvDate?.text = publishedAt?.toDateWithFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", "MMM dd") ivImage?.loadFromUrl(image) } } } }
0
Kotlin
0
0
5ab77de673e8a3cd30b3522741097fb334265e17
2,141
notiapp
Apache License 2.0
src/main/kotlin/com/lykke/matching/engine/services/validators/business/impl/StopOrderBusinessValidatorImpl.kt
yestechgroup
156,660,216
true
{"Kotlin": 1789975, "Java": 37493}
package com.lykke.matching.engine.services.validators.business.impl import com.lykke.matching.engine.services.validators.business.StopOrderBusinessValidator import com.lykke.matching.engine.services.validators.common.OrderValidationUtils import org.springframework.stereotype.Component import java.math.BigDecimal @Component class StopOrderBusinessValidatorImpl: StopOrderBusinessValidator { override fun performValidation(availableBalance: BigDecimal, limitVolume: BigDecimal) { OrderValidationUtils.validateBalance(availableBalance, limitVolume) } }
0
Kotlin
0
0
7aa4d1ca989f16f5ebc99616d996ef4e358acafe
569
MatchingEngine
MIT License
library/src/main/java/wannabe/grid/operations/Operation.kt
pforhan
14,547,654
false
null
package wannabe.grid.operations import wannabe.Voxel /** A unit of work to perform on a Voxel. May optionally perform filtering as well. */ interface Operation { /** Whether this operation has changed since the last time it was used. */ open val isDirty: Boolean get() = false /** Whether the given Voxel should be included. */ open fun includes(voxel: Voxel): Boolean = true /** Performs the operation on a Voxel, returning a new Voxel instance. */ abstract fun apply(voxel: Voxel): Voxel }
12
Kotlin
0
1
d20f9fe7227f0333a2cbc04d24a8dafdfa5e076b
516
wannabe
MIT License
app/src/main/java/com/example/jetphotos/MainPresentation/Search/SearchScreen.kt
arfinhosainn
529,504,086
false
null
package com.example.jetphotos.MainPresentation.Search import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.example.jetphotos.MainPresentation.Home.component.ImageListScreen import com.example.jetphotos.MainPresentation.Home.component.SearchBar import com.example.jetphotos.presentation.navigation.Screen import com.example.jetphotos.ui.theme.DarkGray @Composable fun SearchScreen( searchViewModel: SearchViewModel = hiltViewModel(), navController: NavController ) { val searchQuery by searchViewModel.search Box( modifier = Modifier .fillMaxSize() .background(DarkGray) ) { Column { SearchBar( hint = "Search...", modifier = Modifier.fillMaxWidth(), state = searchQuery, onTextChange = { searchViewModel.updateSearchQuery(query = it) }, onSearchClicked = { searchViewModel.searchHeroes(query = it) } ) ImageListScreen(images = searchViewModel.searchImages, onImageClick = { navController.navigate(Screen.Detail.route + "/${it.id}") }) } } }
0
Kotlin
0
0
f156ca366a255322fabf5e0ec8c600691236d333
1,658
JetPhotos
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsintegrationevents/services/S3Service.kt
ministryofjustice
772,145,800
false
{"Kotlin": 160570, "Shell": 3805, "Dockerfile": 1150, "Makefile": 154}
package uk.gov.justice.digital.hmpps.hmppsintegrationevents.services import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.stereotype.Service import software.amazon.awssdk.services.s3.S3Client import software.amazon.awssdk.services.s3.model.GetObjectRequest import uk.gov.justice.digital.hmpps.hmppsintegrationevents.config.HmppsS3Properties import java.io.InputStream @Service @EnableConfigurationProperties( HmppsS3Properties::class, ) class S3Service(private val s3Client: S3Client) { fun getDocumentFile(bucketName: String, fileName: String): InputStream { val request = GetObjectRequest.builder() .bucket(bucketName) .key(fileName) .build() return s3Client.getObject(request) } }
0
Kotlin
0
0
6ee5acea4cfdda529d415d05d6073fdeac3602c5
773
hmpps-integration-events
MIT License
light/src/main/kotlin/net/kotlinx/domain/batchTask/BatchTaskExecutor.kt
mypojo
565,799,715
false
{"Kotlin": 1495826, "Jupyter Notebook": 13540, "Java": 9531}
package net.kotlinx.domain.batchTask import mu.KotlinLogging import net.kotlinx.aws.lambda.dispatch.synch.s3Logic.S3LogicInput import net.kotlinx.aws.lambda.dispatch.synch.s3Logic.S3LogicOutput import net.kotlinx.aws.lambda.dispatch.synch.s3Logic.S3LogicRuntime import net.kotlinx.collection.flatten import net.kotlinx.concurrent.coroutineExecute import net.kotlinx.json.gson.GsonData import net.kotlinx.json.gson.toGsonArray import net.kotlinx.koin.Koins.koinOrCheck import net.kotlinx.time.TimeStart /** * 배치 작업 실행기 * S3LogicRuntime 를 구현한다. * */ class BatchTaskExecutor : S3LogicRuntime { /** S3LogicRuntime 구현체 */ override suspend fun executeLogic(inputs: S3LogicInput): S3LogicOutput { val logicOption = GsonData.parse(inputs.logicOption) val datas = inputs.datas val resultMap = executeLogic(logicOption, datas) return S3LogicOutput( GsonData.fromObj(datas), GsonData.fromObj(resultMap), ) } /** 일반적인 실행 */ fun executeLogic(logicOption: GsonData, datas: List<String>): Map<String, GsonData> { val batchTaskIds = logicOption[BatchTaskOptionUtil.BATCH_TASK_IDS].map { it.str!! } log.info { "로직 ${batchTaskIds.size}건 실행 -> 데이터 ${datas.size}건 -> ${datas.take(2).joinToString(",")}.. " } val start = TimeStart() val taskResults = batchTaskIds.map { batchTaskId -> suspend { val each = TimeStart() val batchTask = koinOrCheck<BatchTask>(batchTaskId) log.debug { " -> 로직 [${batchTask.name}] 실행 시작.." } batchTask.runtime.executeLogic(logicOption, datas).apply { log.info { " -> 로직 [${batchTask.name}] 종료 -> $each" } } } }.coroutineExecute() val jobResults = taskResults.flatten().map { it.key to it.value.toGsonArray() }.toMap() log.info { "전체로직 ${batchTaskIds.size}건 완료 -> 전체 걸린시간 : $start" } return jobResults } companion object { private val log = KotlinLogging.logger {} } }
0
Kotlin
0
1
1b361a5ae8aae718f0e81768452e6803c0990e71
2,081
kx_kotlin_support
MIT License
app/src/main/java/ca/on/hojat/gamenews/core/data/api/common/calladapter/ApiResultCallAdapter.kt
hojat72elect
574,228,468
false
null
package ca.on.hojat.gamenews.core.data.api.common.calladapter import ca.on.hojat.gamenews.core.data.api.common.ErrorMessageExtractor import ca.on.hojat.gamenews.core.data.api.common.ApiResult import retrofit2.Call import retrofit2.CallAdapter import java.lang.reflect.Type class ApiResultCallAdapter<R>( private val successType: Type, private val errorMessageExtractor: ErrorMessageExtractor ) : CallAdapter<R, Call<ApiResult<R>>> { override fun adapt(call: Call<R>): Call<ApiResult<R>> { return ApiResultCall( delegate = call, successType = successType, errorMessageExtractor = errorMessageExtractor ) } override fun responseType(): Type = successType }
0
null
8
4
b1c07551e90790ee3d273bc4c0ad3a5f97f71202
731
GameHub
MIT License
transport-database/testSrc/com/android/tools/datastore/database/DatabaseTestConnection.kt
JetBrains
60,701,247
false
{"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19}
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.datastore.database import java.sql.Connection import java.sql.PreparedStatement import java.sql.Statement /** * A connection class that returns {@link TestStatement} and {@TestPreparedStatement}'s in place * of a statement that writes to the database. */ class DatabaseTestConnection(val conn: Connection) : Connection by conn { override fun createStatement(): Statement { return DatabaseTestStatement(conn.createStatement()) } override fun prepareStatement(sql: String?): PreparedStatement { return DatabaseTestPreparedStatement(conn.prepareStatement(sql)) } override fun prepareStatement(sql: String?, columnNames: Array<out String>?): PreparedStatement { return DatabaseTestPreparedStatement(conn.prepareStatement(sql, columnNames)) } }
5
Kotlin
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,416
android
Apache License 2.0
api/src/main/java/com/example/api/model/requests/UpdateProfileRequest.kt
Marvel999
347,535,139
false
null
package com.example.api.model.requests import com.example.api.model.entity.UpdateUserProfileEntity import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class UpdateProfileRequest( @Json(name = "user") val updateUserProfileEntity: UpdateUserProfileEntity )
1
Kotlin
4
8
3709e521a897317d8cd90d1e89745aeeee2d9722
320
Conduit-Android-kotlin
MIT License
archives/jetbrains-plugins/vite-jetbrains-plugin/src/main/kotlin/com/rxliuli/vite/settings/ViteAppSettingsState.kt
rxliuli
368,450,196
false
{"TypeScript": 504981, "Kotlin": 8473, "JavaScript": 4865, "CSS": 1582}
package com.rxliuli.vite.settings import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.util.xmlb.XmlSerializerUtil @State(name = "com.rxliuli.vite.settings.ViteAppSettingsState", storages = [Storage("SdkSettingsPlugin.xml")]) class ViteAppSettingsState : PersistentStateComponent<ViteAppSettingsState?> { var template = "react-ts" val templates = arrayOf( "vanilla", "vanilla-ts", "vue", "vue-ts", "react", "react-ts", "preact", "preact-ts", "lit", "lit-ts", "svelte", "svelte-ts", ) override fun getState(): ViteAppSettingsState { return this } override fun loadState(state: ViteAppSettingsState) { XmlSerializerUtil.copyBean(state, this) } companion object { val instance: ViteAppSettingsState get() = ApplicationManager.getApplication().getService(ViteAppSettingsState::class.java) } }
0
TypeScript
5
68
31cbb94af2cd182ae20c25b6992654fa54c12d1d
1,143
liuli-tools
MIT License
core/src/main/kotlin/dev/minutest/experimental/events.kt
dmcg
148,457,652
false
null
package dev.minutest.experimental import dev.minutest.Context import dev.minutest.Node import dev.minutest.Test import org.opentest4j.TestAbortedException import org.opentest4j.TestSkippedException fun <F> Node<F>.telling(listener: TestEventListener): Node<F> = when (this) { is Test<F> -> this.telling(listener) is Context<F, *> -> this.telling(listener) } fun <PF, F> Context<PF, F>.telling(listener: TestEventListener): Context<PF, F> = ContextWrapper(this, onOpen = { listener.contextOpened(this, it) }, children = children.map { it.telling(listener) }, onClose = { listener.contextClosed(this, it) } ) private fun <F> Test<F>.telling(listener: TestEventListener) = copy( f = { fixture, testDescriptor -> listener.testStarting(this, fixture, testDescriptor) try { this(fixture, testDescriptor).also { listener.testComplete(this, fixture, testDescriptor) } } catch (skipped: TestSkippedException) { listener.testSkipped(this, fixture, testDescriptor, skipped) throw skipped } catch (skipped: MinutestSkippedException) { listener.testSkipped(this, fixture, testDescriptor, skipped) throw skipped } catch (aborted: TestAbortedException) { listener.testAborted(this, fixture, testDescriptor, aborted) throw aborted } catch (t: Throwable) { listener.testFailed(this, fixture, testDescriptor, t) throw t } } )
4
Kotlin
10
99
75a969ff708d1b17bdb8778e7c68c07d3386629f
1,569
minutest
Apache License 2.0
app/src/test/java/org/sil/storyproducer/model/ParseBloomTBTest.kt
sillsdev
93,890,166
false
{"Kotlin": 819773, "HTML": 168357, "Java": 164820, "Dockerfile": 1612, "Shell": 770}
package org.sil.storyproducer.model import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith // import org.mockito.Mockito import org.robolectric.RobolectricTestRunner import androidx.test.core.app.ApplicationProvider import org.sil.storyproducer.tools.file.getChildDocuments import java.io.File // See below for some background to Roboelectric // https://www.vogella.com/tutorials/Robolectric/article.html @RunWith(RobolectricTestRunner::class) class ParseBloomTBTest { var result: Story? = null // saved 'one-time' parsed story for validation with each test init { // WARNING: parsing Bloom HTML Templates is not just read-only - in for some stories extra concatenated audio files could be produced result = parse_BTB_Story() // parse the SP authored template once, on class initialization } @Test fun parsed_BTB_Should_get_getChildDocuments() { Assert.assertTrue(getChildDocuments(ApplicationProvider.getApplicationContext(), "Chicken+and+Millipede").size > 0) } @Test fun parsed_BTB_Should_ReturnAStory() { Assert.assertNotNull(result) Assert.assertEquals(Story::class.java, result!!.javaClass) } // @Test fun parsed_BTB_Should_get_isSPAuthored_False() { // This currently cannot be tested as isSPAuthored has not been added as a member of the Story class // Assert.assertTrue(result!!.???) } @Test fun parsed_BTB_Should_get_StoryTitleFromBookFrontCover() { Assert.assertEquals("Chicken+and+Millipede", result!!.title) } @Test fun parsed_BTB_Should_get_ProvidedPagesPlusSong() { Assert.assertEquals(18, result!!.slides.size.toLong()) } // this test initialization code should only need to be called once private fun parse_BTB_Story(): Story? { setupWorkspace() // NB: This story is currently not under git to save space. Please download from: https://bloomlibrary.org/book/XV844n7KiK // and unzip to the test_data folder (also do not check into git in for now). val storyPath = Workspace.workdocfile.findFile("Chicken+and+Millipede") return parseBloomHTML(ApplicationProvider.getApplicationContext(), storyPath!!) } private fun setupWorkspace() { // println(System.getProperty("user.dir")) var df = androidx.documentfile.provider.DocumentFile.fromFile(File("app/src/test/test_data")) if(!df.isDirectory){ df = androidx.documentfile.provider.DocumentFile.fromFile(File("src/test/test_data")) } Workspace.workdocfile = df } }
92
Kotlin
11
5
9f318851c0c954f69f39ca5753f5635bb92410c2
2,621
StoryProducer
MIT License
app/src/main/java/com/teobaranga/monica/database/OrderBy.kt
teobaranga
686,113,276
false
{"Kotlin": 269714}
package com.teobaranga.monica.database data class OrderBy( val columnName: String, val isAscending: Boolean, )
1
Kotlin
1
8
b14afe98fc1d5eb67782ad106aeee607ab267c80
120
monica
Apache License 2.0
nanokt-jvm/src/main/java/com/conena/nanokt/jvm/io/FileExtensions.kt
conena
592,106,905
false
{"Kotlin": 415799}
/* * Copyright (C) 2023 Fabian Andera * * 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. * */ @file:Suppress("NOTHING_TO_INLINE", "unused") package com.conena.nanokt.jvm.io import java.io.File /** * @return For directories, the sum of the size of all files in the folder in bytes. * For normal files the call is delegated to [File.length]. */ inline fun File.totalLength(): Long { return if (isDirectory) walkTopDown().filter(File::isFile).map(File::length).sum() else length() }
1
Kotlin
1
77
0f3315d5a2d9ba602f6a4ea9757d859bdb040a29
1,002
nanokt
Apache License 2.0
lib/src/main/java/com/sd/lib/compose/libcore/ViewModelScope.kt
zj565061763
795,846,454
false
{"Kotlin": 58199}
package com.sd.lib.compose.core import android.os.Looper import androidx.annotation.MainThread import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.lifecycle.HasDefaultViewModelProviderFactory import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelStore import androidx.lifecycle.ViewModelStoreOwner import androidx.lifecycle.viewmodel.CreationExtras import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import androidx.lifecycle.viewmodel.compose.viewModel /** * 创建[ComposeViewModelScope], * 如果调用此方法的地方在组合中被移除,[ComposeViewModelScope]会清空所有保存的[ViewModel] */ @Composable inline fun <reified VM : ViewModel> rememberVMScope(): ComposeViewModelScope<VM> { val vmClass = VM::class.java val scope = remember(vmClass) { ViewModelScopeImpl(vmClass) } DisposableEffect(scope) { onDispose { scope.destroy() } } return scope } interface ComposeViewModelScope<VM : ViewModel> { /** * 根据[key]获取[ViewModel] */ @Composable fun get(key: String): VM /** * 根据[key]获取[ViewModel],如果[ViewModel]不存在,从[factory]创建 */ @Composable fun get(key: String, factory: (CreationExtras) -> VM): VM /** * 根据[key]获取[ViewModel],每次调用此方法都会从[factory]中获取 */ @Composable fun create(key: String, factory: @Composable (CreateVMParams<VM>) -> VM): VM /** * 移除[key]对应的[ViewModel] */ @MainThread fun remove(key: String) } /** * 创建[ViewModel]参数 */ data class CreateVMParams<VM : ViewModel>( val vmClass: Class<VM>, val viewModelStoreOwner: ViewModelStoreOwner, val key: String, ) @PublishedApi internal class ViewModelScopeImpl<VM : ViewModel>( private val clazz: Class<VM>, ) : ComposeViewModelScope<VM>, ViewModelStoreOwner { private var _isDestroyed = false private val _viewModelStore = ViewModelStore() private val _vmMap: MutableMap<String, ViewModel> = _viewModelStore.vmMap() override val viewModelStore: ViewModelStore get() = _viewModelStore @Composable override fun get(key: String): VM { return create(key) { params -> viewModel( modelClass = params.vmClass, viewModelStoreOwner = params.viewModelStoreOwner, key = params.key, ) } } @Composable override fun get(key: String, factory: (CreationExtras) -> VM): VM { val factoryUpdated by rememberUpdatedState(factory) val defaultFactory = remember { object : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { @Suppress("UNCHECKED_CAST") return factoryUpdated(CreationExtras.Empty) as T } override fun <T : ViewModel> create(modelClass: Class<T>, extras: CreationExtras): T { @Suppress("UNCHECKED_CAST") return factoryUpdated(extras) as T } } } return create(key) { params -> viewModel( modelClass = params.vmClass, viewModelStoreOwner = params.viewModelStoreOwner, key = params.key, factory = defaultFactory, ) } } @Composable override fun create(key: String, factory: @Composable (CreateVMParams<VM>) -> VM): VM { if (_isDestroyed) error("Scope is destroyed.") val realOwner = this@ViewModelScopeImpl val localOwner = checkNotNull(LocalViewModelStoreOwner.current) val viewModelStoreOwner = remember(localOwner) { if (localOwner is HasDefaultViewModelProviderFactory) { ViewModelStoreOwnerHasDefault( owner = realOwner, factory = localOwner, ) } else { realOwner } } val params = CreateVMParams( vmClass = clazz, viewModelStoreOwner = viewModelStoreOwner, key = key, ) return factory(params).also { vm -> check(vm === _vmMap[key]) { "ViewModel was not found with key:$key, you should create ViewModel with CreateVMParams." } } } override fun remove(key: String) { _vmMap.vmRemove(key) } /** * 销毁所有[ViewModel] */ @MainThread fun destroy() { checkMainThread() _isDestroyed = true viewModelStore.clear() } private class ViewModelStoreOwnerHasDefault( private val owner: ViewModelStoreOwner, private val factory: HasDefaultViewModelProviderFactory, ) : ViewModelStoreOwner, HasDefaultViewModelProviderFactory { override val defaultViewModelProviderFactory: ViewModelProvider.Factory get() = factory.defaultViewModelProviderFactory override val defaultViewModelCreationExtras: CreationExtras get() = factory.defaultViewModelCreationExtras override val viewModelStore: ViewModelStore get() = owner.viewModelStore } } /** * 根据[key]移除[ViewModel] */ @MainThread private fun MutableMap<String, ViewModel>.vmRemove(key: String): Boolean { checkMainThread() val viewModel = remove(key) ?: return false ViewModel::class.java.run { try { getDeclaredMethod("clear") } catch (e: Throwable) { null } ?: error("clear method was not found in ${ViewModel::class.java.name}") }.let { method -> method.isAccessible = true method.invoke(viewModel) return true } } /** * 获取[ViewModelStore]内保存[ViewModel]的[Map] */ private fun ViewModelStore.vmMap(): MutableMap<String, ViewModel> { return ViewModelStore::class.java.run { try { getDeclaredField("map") } catch (e: Throwable) { null } ?: try { getDeclaredField("mMap") } catch (e: Throwable) { null } ?: error("map field was not found in ${ViewModelStore::class.java.name}") }.let { field -> field.isAccessible = true @Suppress("UNCHECKED_CAST") field.get(this@vmMap) as MutableMap<String, ViewModel> } } private fun checkMainThread() { check(Looper.myLooper() === Looper.getMainLooper()) { "Expected main thread but was " + Thread.currentThread().name } }
0
Kotlin
0
0
7f2f00cd52d539a3bca3195bad967aaa015571c2
6,692
compose-libcore
MIT License
amani-sdk-v1/src/main/kotlin/ai/amani/sdk/data/repository/nfc/NFCRepositoryImp.kt
AMANI-AI-ORG
644,307,729
false
null
package ai.amani.sdk.data.repository.nfc import ai.amani.sdk.Amani import ai.amani.sdk.data.mapper.UploadResultModelMapper import ai.amani.sdk.interfaces.INfcCallBack import ai.amani.sdk.interfaces.IUploadCallBack import ai.amani.sdk.model.UploadResultModel import ai.amani.sdk.model.mrz.MRZResult import android.app.Activity import android.content.Context import android.graphics.Bitmap import android.nfc.Tag import androidx.fragment.app.FragmentActivity import datamanager.model.autocrop.Mrz import datamanager.model.customer.Errors /** * @Author: zekiamani * @Date: 26.09.2022 */ class NFCRepositoryImp: NFCRepository { override fun upload( activity: FragmentActivity, type: String?, onComplete: (uploadResult: UploadResultModel) -> Unit ) { var uploadResultModel: UploadResultModel Amani.sharedInstance().ScanNFC().upload( activity, type!!, object: IUploadCallBack { override fun cb(isSucess: Boolean, result: String?, errors: MutableList<Errors>?) { uploadResultModel = UploadResultModelMapper.map( isSucess, result, errors) onComplete.invoke(uploadResultModel) } } ) } override fun getMRZ( type: String, onComplete: (mrz: MRZResult) -> Unit, onError: (error : Errors) -> Unit ) { Amani.sharedInstance().IDCapture().getMRZ( type, onComplete, onError ) } fun scan( tag: Tag, context: Context, birthDate: String, expireDate: String, documentNumber: String, onComplete: () -> Unit, onFailure: () -> Unit ) { Amani.sharedInstance().ScanNFC().start( tag, context, birthDate, expireDate, documentNumber ) { _, isSuccess, _ -> if (isSuccess) onComplete.invoke() else onFailure.invoke() } } }
0
Kotlin
0
0
b875e3852a6eadc2a3ac1a7ad3d41097cf96716a
2,120
Android.SDK.UI
MIT License
app/src/main/java/com/jason/rickandmorty/data/database/PageManager.kt
h11128
324,210,115
false
null
package com.jason.rickandmorty.data.database import android.content.SharedPreferences import javax.inject.Inject const val file_name: String = "PageData" const val default_page: Int = 1 class PageManager @Inject constructor(val instance: SharedPreferences) { fun putPage(key: String, value: Int) { with(instance.edit()) { putInt(key, value) apply() } } fun getPage(key: String, default: Int = default_page): Int { return instance.getInt(key, default) } fun incrementPage(key: String){ val page = getPage(key) + 1 putPage(key, page) } /* companion object{ private var sharedPreferences: SharedPreferences? = null val instance: SharedPreferences get() { return sharedPreferences ?: synchronized(this){ sharedPreferences = MyApplication.getInstance().getSharedPreferences(file_name, Context.MODE_PRIVATE) sharedPreferences!! } } }*/ }
0
Kotlin
0
0
e501e02e2914399ad8ea399853bd9f8df472645b
1,046
RickAndMorty
MIT License
http4k-serverless/lambda/src/testFixtures/kotlin/org/http4k/connect/amazon/lambda/Lambda.kt
http4k
86,003,479
false
{"Kotlin": 2855594, "Java": 41165, "HTML": 14220, "Shell": 3200, "Handlebars": 1455, "Pug": 944, "JavaScript": 777, "Dockerfile": 256, "CSS": 248}
package org.http4k.connect.amazon.lambda import dev.forkhandles.result4k.Result import org.http4k.connect.amazon.RemoteFailure interface Lambda { operator fun <R : Any> invoke(action: LambdaAction<R>): Result<R, RemoteFailure> companion object }
34
Kotlin
249
2,615
7ad276aa9c48552a115a59178839477f34d486b1
257
http4k
Apache License 2.0
app - Copy/src/main/java/com/SShayar/greenglobe/utils/Constant.kt
krishanmurariji
758,800,116
false
{"Kotlin": 89166, "Shell": 5766, "Batchfile": 2674}
package com.SShayar.greenglobe.utils const val USER_NODE="User" const val USER_PROFILE_FOLDER="Profile" const val POST_FOLDER="PostImages" const val REEl_FOLDER="Reel" const val POST="Post" const val REEL="Reel" const val FOLLOW="FOLLOW"
0
Kotlin
0
0
4f53717b823d016747f009c3f057aee0248efab3
240
GreenGlobe-app
MIT License
Application-Challenge/【毛巾队】在线云家教/在线云家教/edusdk-api/src/main/kotlin/io/agora/education/api/record/listener/EduRecordEventListener.kt
AgoraIO-Community
355,093,340
false
null
package io.agora.education.api.record.listener import io.agora.education.api.record.data.EduRecordInfo interface EduRecordEventListener { fun onRecordStarted(record: EduRecordInfo) fun onRecordEnded(record: EduRecordInfo) }
1
null
1
1
558c96cf0f029fb02188ca83f60920c89afd210f
235
RTE-2021-Innovation-Challenge
MIT License
SmartCredentials_aOS/oneclickbusinessclient/src/main/java/de/telekom/smartcredentials/oneclickbusinessclient/factory/SmartCredentialsOneClickBusinessClientFactory.kt
telekom
184,036,324
false
null
/* * Copyright (c) 2019 Telekom Deutschland AG * * 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 de.telekom.smartcredentials.oneclickbusinessclient.factory import android.content.Context import de.telekom.smartcredentials.core.api.CoreApi import de.telekom.smartcredentials.core.api.IdentityProviderApi import de.telekom.smartcredentials.core.api.OneClickApi import de.telekom.smartcredentials.core.api.StorageApi import de.telekom.smartcredentials.core.blacklisting.SmartCredentialsModuleSet import de.telekom.smartcredentials.core.controllers.CoreController import de.telekom.smartcredentials.core.exceptions.InvalidCoreApiException import de.telekom.smartcredentials.oneclickbusinessclient.OneClickClientConfiguration import de.telekom.smartcredentials.oneclickbusinessclient.controllers.OneClickBusinessClientController import de.telekom.smartcredentials.oneclickbusinessclient.di.ObjectGraphCreatorOneClickBusinessClient /** * Created by <EMAIL> at 22/03/2023 */ @Suppress("unused") object SmartCredentialsOneClickBusinessClientFactory { private val MODULE_NOT_INITIALIZED_EXCEPTION = "SmartCredentials OneClickBusinessClient Module have not been initialized" private var sOneClickBusinessClientController: OneClickBusinessClientController? = null @JvmStatic @Synchronized fun initSmartCredentialsOneClickBusinessClientModule( context: Context, coreApi: CoreApi, identityProviderApi: IdentityProviderApi, storageApi: StorageApi, oneClickClientConfig: OneClickClientConfiguration ): OneClickApi { val coreController: CoreController = if (coreApi is CoreController) { coreApi } else { throw InvalidCoreApiException(SmartCredentialsModuleSet.ONE_CLICK_BUSINESS_CLIENT_MODULE.moduleName) } sOneClickBusinessClientController = ObjectGraphCreatorOneClickBusinessClient.getInstance() .provideApiControllerOneClickBusinessClient( context, coreController, identityProviderApi, storageApi, oneClickClientConfig ) return sOneClickBusinessClientController as OneClickBusinessClientController } @JvmStatic @get:Synchronized val oneClickBusinessClientApi: OneClickApi get() { if (sOneClickBusinessClientController == null) { throw RuntimeException(MODULE_NOT_INITIALIZED_EXCEPTION) } return sOneClickBusinessClientController!! } fun clear() { ObjectGraphCreatorOneClickBusinessClient.destroy() sOneClickBusinessClientController = null } }
4
Java
3
10
c6686cb5725e575b793acf7f9f4277deb26885fb
3,248
SmartCredentials-SDK-android
Apache License 2.0
src/main/kotlin/icu/windea/pls/script/psi/impl/ParadoxScriptVariableStubImpl.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.script.psi.impl import com.intellij.psi.stubs.* import icu.windea.pls.script.psi.* class ParadoxScriptVariableStubImpl( parent: StubElement<*>, override val name: String ) : StubBase<ParadoxScriptVariable>(parent, ParadoxScriptStubElementTypes.VARIABLE), ParadoxScriptVariableStub{ override fun toString(): String { return "ParadoxScriptVariableStub: (key= $name)" } }
1
Kotlin
1
6
31eb30d9de8366ee932d9b158d855137cd66d0da
401
Paradox-Language-Support
MIT License
app/src/main/java/com/mcatta/mockksample/ui/MainPresenter.kt
mcatta
250,817,588
false
{"Kotlin": 8985}
package com.mcatta.mockksample.ui import com.mcatta.mockksample.data.DataRepository import com.mcatta.mockksample.utils.MyUselessUtils import io.reactivex.Single import io.reactivex.SingleObserver import io.reactivex.disposables.Disposable class MainPresenter( private val view: MainContract.View, private val dataRepository: DataRepository ) : MainContract.Presenter { override fun fetchData() { log("fetchData") try { val result = dataRepository.fetchData() view.onResult(result.map { UiDataModel( MyUselessUtils.generateUUID(), it.id, it.value ) }) } catch (err: Throwable) { view.onError(err) } } override fun fetchDataViaRX() { log("fetchDataViaRX") dataRepository.fetchDataWithRX() .flatMap { result -> val output = result.map { UiDataModel(MyUselessUtils.generateUUID(), it.id, it.value) } Single.just(output) } .subscribe(object : SingleObserver<List<UiDataModel>> { override fun onSuccess(t: List<UiDataModel>) { view.onResult(t) } override fun onSubscribe(d: Disposable) {} override fun onError(e: Throwable) { view.onError(e) } }) } override fun fetchDataViaCallback() { log("fetchDataViaCallback") try { dataRepository.fetchData { data -> view.onResult(data.map { UiDataModel( MyUselessUtils.generateUUID(), it.id, it.value ) }) } } catch (err: Exception) { view.onError(err) } } override fun log(message: String, tag: String) { print("TAG: $tag Message: $message") } }
0
Kotlin
2
1
ef272d938ea820290adc37bef1110734cd3db229
2,058
MockkSample
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/nomisprisonerapi/helper/builders/CSIPReport.kt
ministryofjustice
444,895,409
false
{"Kotlin": 2620592, "PLSQL": 311165, "Dockerfile": 1112}
package uk.gov.justice.digital.hmpps.nomisprisonerapi.helper.builders import org.springframework.data.repository.findByIdOrNull import org.springframework.stereotype.Component import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.CSIPAreaOfWork import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.CSIPIncidentLocation import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.CSIPIncidentType import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.CSIPPlan import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.CSIPReport import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.OffenderBooking import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.Staff import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.CSIPReportRepository import uk.gov.justice.digital.hmpps.nomisprisonerapi.jpa.repository.ReferenceCodeRepository @DslMarker annotation class CSIPReportDslMarker @NomisDataDslMarker interface CSIPReportDsl { @CSIPPlanDslMarker fun plan( identifiedNeed: String = "They need help", intervention: String = "Support their work", reportingStaff: Staff, dsl: CSIPPlanDsl.() -> Unit = {}, ): CSIPPlan } @Component class CSIPReportBuilderFactory( private val repository: CSIPReportBuilderRepository, private val csipPlanBuilderFactory: CSIPPlanBuilderFactory, ) { fun builder(): CSIPReportBuilder { return CSIPReportBuilder( repository, csipPlanBuilderFactory, ) } } @Component class CSIPReportBuilderRepository( private val repository: CSIPReportRepository, val typeRepository: ReferenceCodeRepository<CSIPIncidentType>, val locationRepository: ReferenceCodeRepository<CSIPIncidentLocation>, val areaOfWorkRepository: ReferenceCodeRepository<CSIPAreaOfWork>, ) { fun save(csipReport: CSIPReport): CSIPReport = repository.save(csipReport) fun lookupType(code: String) = typeRepository.findByIdOrNull(CSIPIncidentType.pk(code))!! fun lookupLocation(code: String) = locationRepository.findByIdOrNull(CSIPIncidentLocation.pk(code))!! fun lookupAreaOfWork(code: String) = areaOfWorkRepository.findByIdOrNull(CSIPAreaOfWork.pk(code))!! } class CSIPReportBuilder( private val repository: CSIPReportBuilderRepository, private val csipPlanBuilderFactory: CSIPPlanBuilderFactory, ) : CSIPReportDsl { private lateinit var csipReport: CSIPReport fun build( offenderBooking: OffenderBooking, type: String, location: String, areaOfWork: String, reportedBy: Staff, ): CSIPReport = CSIPReport( offenderBooking = offenderBooking, rootOffenderId = offenderBooking.offender.rootOffenderId ?: offenderBooking.offender.id, type = repository.lookupType(type), location = repository.lookupLocation(location), areaOfWork = repository.lookupAreaOfWork(areaOfWork), reportedBy = reportedBy, ) .let { repository.save(it) } .also { csipReport = it } override fun plan( identifiedNeed: String, intervention: String, referredBy: Staff, dsl: CSIPPlanDsl.() -> Unit, ): CSIPPlan = csipPlanBuilderFactory.builder() .let { builder -> builder.build( csipReport = csipReport, identifiedNeed = identifiedNeed, intervention = intervention, referredBy = referredBy, ) .also { csipReport.plans += it } .also { builder.apply(dsl) } } }
1
Kotlin
1
0
151da6e994bb59b578f533b24aec46516702827d
3,375
hmpps-nomis-prisoner-api
MIT License
feature/user/src/main/java/com/wkk/user/screen/login/LoginViewModel.kt
knight-kk
323,264,507
false
null
/* * Copyright 2022 knight-kk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.wkk.user import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.wkk.model.DataResult import com.wkk.user.repository.UserRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.stateIn import javax.inject.Inject @HiltViewModel class LoginViewModel @Inject constructor( private val userRepository: UserRepository, ) : ViewModel() { private val _uiState = MutableStateFlow<LoginUiState>(LoginUiState.None) val uiState: StateFlow<LoginUiState> = _uiState.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(5000L), initialValue = LoginUiState.None, ) suspend fun login(userName: String, password: String) { _uiState.value = LoginUiState.Loading if (userName.isEmpty()) { _uiState.value = LoginUiState.Error("请输入用户名") return } if (password.isEmpty()) { _uiState.value = LoginUiState.Error("请输入密码") return } val result = userRepository.login(userName, password) _uiState.value = when (result) { is DataResult.Error -> LoginUiState.Error(result.message) is DataResult.Success -> LoginUiState.Success } } } sealed interface LoginUiState { object None : LoginUiState object Loading : LoginUiState object Success : LoginUiState data class Error(val message: String) : LoginUiState }
0
null
1
5
e50e1655b403023b7683c480cba7be936e55f381
2,236
wanandroid_compose
Apache License 2.0
designs/design-headless/src/commonTest/kotlin/components/layouts/LinearLayoutsTest.kt
CLOVIS-AI
582,955,979
false
{"Kotlin": 313151, "JavaScript": 1822, "Dockerfile": 1487, "Shell": 556, "HTML": 372, "CSS": 280}
package opensavvy.decouple.headless.components.layouts import io.kotest.matchers.shouldBe import opensavvy.decouple.components.actions.Button import opensavvy.decouple.components.display.Text import opensavvy.decouple.components.layout.Row import opensavvy.decouple.headless.prepared.headlessUI import opensavvy.prepared.suite.SuiteDsl fun SuiteDsl.linearLayouts() = suite("Column & Row") { test("Column") { val ui = headlessUI { Row { Text("This is a test") Button({}) { Text("Test") } } }.immediate("ui") ui.paused { find(Row).reverse shouldBe false } } }
0
Kotlin
0
2
5ab114a29cb15c2d334d56b1d5915cd1124388d3
588
Decouple
Apache License 2.0
src/main/kotlin/io/swagger/client/models/AuthResponse.kt
em-ad
443,796,768
false
null
/** * Datyar REST APIs * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: 1.0.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. */ package io.swagger.client.models /** * * @param contributors * @param key * @param roomId * @param username */ data class AuthResponse ( val contributors: kotlin.Array<kotlin.String>? = null, val key: kotlin.String? = null, val roomId: kotlin.String? = null, val username: kotlin.String? = null ) { }
0
Kotlin
0
0
be4c2e4a6222d467a51d9148555eed25264c7eb0
670
kotlinsdk
Condor Public License v1.1
app/src/main/java/com/appp/nira/utils/Constant.kt
keyur9779
433,909,449
false
{"Kotlin": 27272}
package com.appp.nira.utils object Constant { fun updateFormat(value: Int): String = String.format("%,d", value) //------limit number of visibleItems to be overlapped const val numberOfItemToBeOverlapped = 6 //------set value of item overlapping in percentage between 0 to 100 const val overlapWidthInPercentage = 10 const val PREF = "Nira_Pref" }
0
Kotlin
0
0
fc703a418a6a49fda63a1049a47f92677b2d4cdc
380
NiraFinance
Apache License 2.0
src/main/kotlin/br/com/zup/pix/bcb/DeletePixKeyRequest.kt
celofelix
355,176,451
true
{"INI": 2, "Gradle": 2, "Shell": 5, "YAML": 8, "Markdown": 1, "Dockerfile": 1, "Batchfile": 1, "Text": 2, "JSON": 1, "Ignore List": 1, "Kotlin": 51, "Protocol Buffer": 121, "XML": 2, "Java": 80, "SQL": 4, "Motorola 68K Assembly": 2, "HTML": 1, "CSS": 2, "JavaScript": 1}
package br.com.zup.pix.bcb data class DeletePixKeyRequest( val key: String, val participant: String )
0
Java
0
0
23f80d0d8ee78bb49bc12ad1e65d349315ad25fb
110
orange-talents-01-template-pix-keymanager-grpc
Apache License 2.0
app/src/main/java/mil/nga/msi/ui/radiobeacon/RadioBeaconNavigation.kt
ngageoint
588,211,646
false
{"Kotlin": 1755228}
package mil.nga.msi.ui.radiobeacon import android.net.Uri import androidx.compose.ui.graphics.Color import androidx.core.os.BundleCompat import androidx.navigation.* import androidx.navigation.compose.composable import com.google.accompanist.navigation.material.ExperimentalMaterialNavigationApi import com.google.accompanist.navigation.material.bottomSheet import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import mil.nga.msi.datasource.DataSource import mil.nga.msi.datasource.radiobeacon.RadioBeacon import mil.nga.msi.repository.radiobeacon.RadioBeaconKey import mil.nga.msi.ui.action.RadioBeaconAction import mil.nga.msi.ui.filter.FilterScreen import mil.nga.msi.ui.navigation.RadioBeacon import mil.nga.msi.ui.navigation.Route import mil.nga.msi.ui.radiobeacon.detail.RadioBeaconDetailScreen import mil.nga.msi.ui.radiobeacon.list.RadioBeaconsScreen import mil.nga.msi.ui.radiobeacon.sheet.RadioBeaconSheetScreen import mil.nga.msi.ui.sort.SortScreen sealed class RadioBeaconRoute( override val name: String, override val title: String, override val shortTitle: String, override val color: Color = DataSource.RADIO_BEACON.color ): Route { object Main: RadioBeaconRoute("radioBeacons", "Radio Beacons", "Beacons") object Detail: RadioBeaconRoute("radioBeacons/detail", "Radio Beacon Details", "Beacon Details") object List: RadioBeaconRoute("radioBeacons/list", "Radio Beacons", "Beacons") object Sheet: RadioBeaconRoute("radioBeacons/sheet", "Radio Beacon Sheet", "Beacon Sheet") object Filter: RadioBeaconRoute("radioBeacons/filter", "Radio Beacon Filter", "Radio Beacon Filter") object Sort: RadioBeaconRoute("radioBeacons/sort", "Radio Beacon Sort", "Radio Beacon Sort") } @OptIn(ExperimentalMaterialNavigationApi::class) fun NavGraphBuilder.radioBeaconGraph( navController: NavController, bottomBarVisibility: (Boolean) -> Unit, openNavigationDrawer: () -> Unit, share: (Pair<String, String>) -> Unit, showSnackbar: (String) -> Unit ) { val shareBeacon: (RadioBeacon) -> Unit = { beacon -> share(Pair("Share Radio Beacon Information", beacon.toString())) } navigation( route = RadioBeaconRoute.Main.name, startDestination = RadioBeaconRoute.List.name ) { composable( route = RadioBeaconRoute.List.name, deepLinks = listOf(navDeepLink { uriPattern = "marlin://${RadioBeaconRoute.List.name}" }) ) { bottomBarVisibility(true) RadioBeaconsScreen( openDrawer = { openNavigationDrawer() }, openFilter = { navController.navigate(RadioBeaconRoute.Filter.name) }, openSort = { navController.navigate(RadioBeaconRoute.Sort.name) }, onAction = { action -> when (action) { is RadioBeaconAction.Share -> shareBeacon(action.radioBeacon) is RadioBeaconAction.Location -> showSnackbar("${action.text} copied to clipboard") else -> action.navigate(navController) } } ) } composable( route = "${RadioBeaconRoute.Detail.name}?key={key}", arguments = listOf(navArgument("key") { type = NavType.RadioBeacon }) ) { backstackEntry -> bottomBarVisibility(false) backstackEntry.arguments?.let { bundle -> BundleCompat.getParcelable(bundle, "key", RadioBeaconKey::class.java) }?.let { key -> RadioBeaconDetailScreen( key, close = { navController.popBackStack() }, onAction = { action -> when (action) { is RadioBeaconAction.Share -> shareBeacon(action.radioBeacon) is RadioBeaconAction.Location -> showSnackbar("${action.text} copied to clipboard") else -> action.navigate(navController) } } ) } } bottomSheet( route = "${RadioBeaconRoute.Sheet.name}?key={key}", arguments = listOf(navArgument("key") { type = NavType.RadioBeacon }) ) { backstackEntry -> backstackEntry.arguments?.let { bundle -> BundleCompat.getParcelable(bundle, "key", RadioBeaconKey::class.java) }?.let { key -> RadioBeaconSheetScreen(key = key, onDetails = { val encoded = Uri.encode(Json.encodeToString(key)) navController.navigate( "${RadioBeaconRoute.Detail.name}?key=$encoded") }) } } bottomSheet(RadioBeaconRoute.Filter.name) { FilterScreen( dataSource = DataSource.RADIO_BEACON, close = { navController.popBackStack() } ) } bottomSheet(RadioBeaconRoute.Sort.name) { SortScreen( dataSource = DataSource.RADIO_BEACON, close = { navController.popBackStack() } ) } } }
0
Kotlin
0
0
a7288e3f64f5d070e332eb787af9818ede0122fc
5,066
marlin-android
MIT License
src/main/kotlin/io/github/emikaelsilveira/domain/services/implementations/UserServiceImpl.kt
Emikael
205,024,998
false
null
package io.github.emikaelsilveira.domain.services.implementations import io.github.emikaelsilveira.domain.entities.User import io.github.emikaelsilveira.domain.repositories.UserRepository import io.github.emikaelsilveira.domain.services.AddressService import io.github.emikaelsilveira.domain.services.UserService class UserServiceImpl( private val repository: UserRepository, private val addressService: AddressService ) : UserService { override fun getAll() = repository.getAll() override fun getOne(id: Long) = repository.getOne(id) override fun create(userParameter: User): User { val user = getUserWithAddress(userParameter) return repository.create(user) } override fun update(id: Long, userParameter: User): User { val user = getUserWithAddress(userParameter) return repository.update(id, user) } override fun delete(id: Long) = repository.delete(id) private fun getUserWithAddress(user: User): User { val address = user.address?.cep ?.let { addressService.getByCep(it) } ?.let { addressService.createOrUpdate(it) } return user.copy(address = address) } }
0
Kotlin
0
0
02aa43adb7fa1617541ff946fd4f0687c91bf978
1,186
kotlin-full-sample
The Unlicense
test-app/build-tools/android-metadata-generator/src/src/com/telerik/metadata/parsing/classes/NativeClassDescriptor.kt
VladimirAmiorkov
224,983,339
true
{"C++": 8369197, "C": 5644964, "Java": 2287743, "JavaScript": 424761, "Kotlin": 33805, "CMake": 17102, "Shell": 5892, "Objective-C": 2518, "TypeScript": 1833, "CSS": 265}
package com.telerik.metadata.parsing.classes import com.telerik.metadata.parsing.classes.kotlin.metadata.MetadataAnnotation import com.telerik.metadata.parsing.classes.kotlin.properties.KotlinPropertyDescriptor import java.util.Optional /** * Describes the properties of a native class */ interface NativeClassDescriptor { val isClass: Boolean val isInterface: Boolean val isEnum: Boolean val isStatic: Boolean val isPublic: Boolean val isProtected: Boolean val methods: Array<NativeMethodDescriptor> val properties: Array<KotlinPropertyDescriptor> val fields: Array<NativeFieldDescriptor> val metadataInfoAnnotation: MetadataInfoAnnotationDescriptor? val kotlinClassMetadataAnnotation: Optional<MetadataAnnotation> val interfaceNames: Array<String> val packageName: String val className: String val superclassName: String }
0
null
0
0
a007089c2e5d4357c151f001f5199eef2f73573b
904
android-runtime
Apache License 2.0
gravifon/src/main/kotlin/org/gravidence/gravifon/playback/AudioFlow.kt
gravidence
448,136,601
false
null
package org.gravidence.gravifon.playback import org.gravidence.gravifon.GravifonContext import org.gravidence.gravifon.domain.track.VirtualTrack import org.gravidence.gravifon.playlist.manage.PlaylistManager import org.springframework.stereotype.Component @Component class AudioFlow(private val playlistManager: PlaylistManager) { fun next(): VirtualTrack? { return GravifonContext.activePlaylist.value?.let { playlistManager.resolveNext(it)?.track } } }
0
Kotlin
0
0
916f884e3c67172fb5e11caaf7b0c7ac0cf6f33b
474
gravifon
MIT License
app/src/main/java/com/josecuentas/android_exercise_mvp_recyclerinrecycler_kotlin/domain/model/SubItem.kt
PibeDx
104,276,202
false
null
/** * Copyright 2017, <NAME>. * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.josecuentas.android_exercise_mvp_recyclerinrecycler_kotlin.domain.model import java.io.Serializable /** * Created by jcuentas on 20/09/17. */ data class SubItem(val subItemId: Int, val path: String) : Serializable { }
0
Kotlin
0
0
37db0b9e0fdf09531151a39220300f6ef535630d
835
Android-Exercise-MVP-RecyclerInRecycler-Kotlin
Apache License 2.0
gaia-sdk-java/gaia-sdk-graphql/src/main/kotlin/gaia/sdk/response/type/BehaviourNodeExecution.kt
leftshiftone
218,051,248
false
{"Python": 597076, "TypeScript": 553203, "Kotlin": 517386, "JavaScript": 6976, "ANTLR": 2281}
package gaia.sdk.response.type import gaia.sdk.Uuid import gaia.sdk.ISO8601 import gaia.sdk.Struct import gaia.sdk.response.intf.* import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.annotation.JsonCreator import gaia.sdk.request.enumeration.* /** * Represents behaviour node execution information */ data class BehaviourNodeExecution @JsonCreator constructor( @JsonProperty("activityId") val activityId:String? = null, @JsonProperty("behaviourQualifier") val behaviourQualifier:String? = null, @JsonProperty("behaviourId") val behaviourId:String? = null, @JsonProperty("reference") val reference:Uuid? = null, @JsonProperty("qualifier") val qualifier:String? = null, @JsonProperty("state") val state:String? = null, @JsonProperty("type") val type:String? = null, @JsonProperty("created") val created:ISO8601? = null )
8
Python
2
1
10190c1de4b2b5f1d4a5f014602c4ccc5c11bee4
889
gaia-sdk
MIT License
src/main/kotlin/io/github/slimeyar/create/experienced/AmplifiedExperienceNuggetItem.kt
SLimeyMC
648,171,260
false
null
package io.github.slimeyar.create.experienced import net.minecraft.item.Item import net.minecraft.item.ItemStack class AmplifiedExperienceNuggetItem(settings: Settings?) : Item(settings) { override fun hasGlint(stack: ItemStack?): Boolean { return true } }
0
Kotlin
0
0
819b164ca312f0273a794d2258d620e2d0ca6f61
263
create-experienced
Creative Commons Zero v1.0 Universal
src/main/kotlin/io/github/slimeyar/create/experienced/AmplifiedExperienceNuggetItem.kt
SLimeyMC
648,171,260
false
null
package io.github.slimeyar.create.experienced import net.minecraft.item.Item import net.minecraft.item.ItemStack class AmplifiedExperienceNuggetItem(settings: Settings?) : Item(settings) { override fun hasGlint(stack: ItemStack?): Boolean { return true } }
0
Kotlin
0
0
819b164ca312f0273a794d2258d620e2d0ca6f61
263
create-experienced
Creative Commons Zero v1.0 Universal
clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/model/CatalogsProductGroupStatus.kt
oapicf
489,369,143
false
{"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31}
/** * Pinterest REST API * Pinterest's REST API * * The version of the OpenAPI document: 5.12.0 * Contact: <EMAIL> * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.server.models /** * * Values: ACTIVE,INACTIVE */ enum class CatalogsProductGroupStatus(val value: kotlin.String) { ACTIVE("ACTIVE"), INACTIVE("INACTIVE"); }
0
Java
0
2
dcd328f1e62119774fd8ddbb6e4bad6d7878e898
476
pinterest-sdk
MIT License
app/src/main/java/com/sunnyweather/android/ui/weather/WeatherActivity.kt
CodeZyl
630,761,863
false
null
package com.sunnyweather.android.ui.weather import android.content.Context import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.* import androidx.annotation.RequiresApi import androidx.core.view.GravityCompat import androidx.databinding.DataBindingUtil import androidx.drawerlayout.widget.DrawerLayout import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.get import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import com.sunnyweather.android.R import com.sunnyweather.android.logic.model.Weather import com.sunnyweather.android.logic.model.getSky import org.w3c.dom.Text import java.text.SimpleDateFormat import java.util.* class WeatherActivity : AppCompatActivity() { val viewModel by lazy { ViewModelProvider(this).get(WeatherViewModel::class.java)} //lateinit var binding : ActivityWeatherBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_weather) val navBtn : Button = findViewById(R.id.navBtn) val drawerLayout : DrawerLayout = findViewById(R.id.drawerLayout) navBtn.setOnClickListener { drawerLayout.openDrawer(GravityCompat.START) } drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener { override fun onDrawerStateChanged(newState: Int) {} override fun onDrawerSlide(drawerView: View, slideOffset: Float) {} override fun onDrawerOpened(drawerView: View) {} override fun onDrawerClosed(drawerView: View) { val manager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager manager.hideSoftInputFromWindow(drawerView.windowToken, InputMethodManager.HIDE_NOT_ALWAYS) } }) val decorView = window.decorView decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE window.statusBarColor = Color.TRANSPARENT if (viewModel.locationLng.isEmpty()) { viewModel.locationLng = intent.getStringExtra("location_lng") ?: "" } if (viewModel.locationLat.isEmpty()) { viewModel.locationLat = intent.getStringExtra("location_lat") ?: "" } if (viewModel.placeName.isEmpty()) { viewModel.placeName = intent.getStringExtra("place_name") ?: "" } val swipeRefresh : SwipeRefreshLayout = findViewById(R.id.swipeRefresh) viewModel.weatherLiveData.observe(this, androidx.lifecycle.Observer { result -> val weather = result.getOrNull() if (weather != null) { Log.d("WeatherActivity" , "${weather}") showWeatherInfo(weather) } else { Toast.makeText(this, "无法成功获取天气信息", Toast.LENGTH_SHORT).show() result.exceptionOrNull()?.printStackTrace() } swipeRefresh.isRefreshing = false }) swipeRefresh.setColorSchemeResources(R.color.colorPrimary) refreshWeather() swipeRefresh.setOnRefreshListener { refreshWeather() } } fun refreshWeather() { val swipeRefresh : SwipeRefreshLayout = findViewById(R.id.swipeRefresh) viewModel.refreshWeather(viewModel.locationLng, viewModel.locationLat) swipeRefresh.isRefreshing = true } private fun showWeatherInfo(weather: Weather) { val placeName : TextView = findViewById(R.id.placeName) placeName.text = viewModel.placeName val realtime = weather.realtime val daily = weather.daily val currentTempText = "${realtime.temperature.toInt()} ℃" val currentTemp : TextView = findViewById(R.id.currentTemp) currentTemp.text = currentTempText val currentSky : TextView = findViewById(R.id.currentSky) currentSky.text = getSky(realtime.skycon).info val currentPM25Text = "空气指数 ${realtime.airQuality.aqi.chn.toInt()}" val currentAQI : TextView = findViewById(R.id.currentAQI) currentAQI.text = currentPM25Text val nowLayout : RelativeLayout = findViewById(R.id.nowLayout) nowLayout.setBackgroundResource(getSky(realtime.skycon).bg) val forecastLayout : LinearLayout = findViewById(R.id.forecastLayout) forecastLayout.removeAllViews() val days = daily.skycon.size for(i in 0 until days) { val skycon = daily.skycon[i] val temperature = daily.temperature[i] val view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false) val dateInfo = view.findViewById(R.id.dateInfo) as TextView val skyIcon = view.findViewById(R.id.skyIcon) as ImageView val skyInfo = view.findViewById(R.id.skyInfo) as TextView val temperatureInfo = view.findViewById(R.id.temperatureInfo) as TextView val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) dateInfo.text = simpleDateFormat.format(skycon.date) val sky = getSky(skycon.value) skyIcon.setImageResource(sky.icon) skyInfo.text = sky.info val tempText = "${temperature.min.toInt()} ~ ${temperature.max.toInt()} ℃" temperatureInfo.text = tempText forecastLayout.addView(view) } val lifeIndex = daily.lifeIndex val coldRiskText : TextView= findViewById(R.id.coldRiskText) val dressingText : TextView= findViewById(R.id.dressingText) val ultravioletText : TextView= findViewById(R.id.ultravioletText) val carWashingText : TextView= findViewById(R.id.carWashingText) val weatherLayout : ScrollView = findViewById(R.id.weatherLayout) coldRiskText.text = lifeIndex.coldRisk[0]?.desc dressingText.text = lifeIndex.dressing[0].desc ultravioletText.text = lifeIndex.ultraviolet[0].desc carWashingText.text = lifeIndex.carWashing[0].desc // coldRiskText.text = "zyl" // dressingText.text = "zyl" // ultravioletText.text = "zyl" // carWashingText.text = "zyl" weatherLayout.visibility = View.VISIBLE } } /* placeName.text = viewModel.placeName val realtime = weather.realtime val daily = weather.daily // 填充now.xml布局中的数据 val currentTempText = "${realtime.temperature.toInt()} ℃" currentTemp.text = currentTempText currentSky.text = getSky(realtime.skycon).info val currentPM25Text = "空气指数 ${realtime.airQuality.aqi.chn.toInt()}" currentAQI.text = currentPM25Text nowLayout.setBackgroundResource(getSky(realtime.skycon).bg) // 填充forecast.xml布局中的数据 forecastLayout.removeAllViews() val days = daily.skycon.size for (i in 0 until days) { val skycon = daily.skycon[i] val temperature = daily.temperature[i] val view = LayoutInflater.from(this).inflate(R.layout.forecast_item, forecastLayout, false) val dateInfo = view.findViewById(R.id.dateInfo) as TextView val skyIcon = view.findViewById(R.id.skyIcon) as ImageView val skyInfo = view.findViewById(R.id.skyInfo) as TextView val temperatureInfo = view.findViewById(R.id.temperatureInfo) as TextView val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) dateInfo.text = simpleDateFormat.format(skycon.date) val sky = getSky(skycon.value) skyIcon.setImageResource(sky.icon) skyInfo.text = sky.info val tempText = "${temperature.min.toInt()} ~ ${temperature.max.toInt()} ℃" temperatureInfo.text = tempText forecastLayout.addView(view) } // 填充life_index.xml布局中的数据 val lifeIndex = daily.lifeIndex coldRiskText.text = lifeIndex.coldRisk[0].desc dressingText.text = lifeIndex.dressing[0].desc ultravioletText.text = lifeIndex.ultraviolet[0].desc carWashingText.text = lifeIndex.carWashing[0].desc weatherLayout.visibility = View.VISIBLE } */
0
Kotlin
0
0
7565372809a0db356e72811b1e885630188b424d
8,126
SunnyWeather
Apache License 2.0
dist/k8s/application/code/project/src/main/kotlin/tech/glar/hellok8s/health/HealthController.kt
Gaeel
239,577,754
false
null
package tech.glar.hellok8s.health import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController class HealthController { @GetMapping("/health") fun health(): HealthData { return HealthData("up") } }
0
null
0
2
d0665c0184c614ce62d337bf26b2714ac6d42414
298
KubernetesAppAutoscaling
Apache License 2.0
app/common/src/commonJvmMain/kotlin/com/denchic45/studiversity/ui/navigation/ChildrenContainer.kt
denchic45
435,895,363
false
{"Kotlin": 2033820, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
package com.denchic45.studiversity.ui.navigation import com.arkivanov.decompose.router.slot.ChildSlot import com.arkivanov.decompose.router.slot.SlotNavigation import com.arkivanov.decompose.router.stack.ChildStack import com.arkivanov.decompose.router.stack.StackNavigation import com.arkivanov.decompose.value.Value import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf interface ChildrenContainer { fun hasChildrenFlow(): Flow<Boolean> } interface StackChildrenContainer<C : Any, T : Any> : ChildrenContainer { val navigation: StackNavigation<C> val childStack: Value<ChildStack<C, T>> override fun hasChildrenFlow(): Flow<Boolean> { return childStack.hasBackStackFlow() } } interface SlotChildrenContainer<C : Any, T : Any> : ChildrenContainer { val slotNavigation: SlotNavigation<C> val childSlot: Value<ChildSlot<C, T>> override fun hasChildrenFlow(): Flow<Boolean> { return childSlot.isActiveFlow() } } interface EmptyChildrenContainer : ChildrenContainer { override fun hasChildrenFlow(): Flow<Boolean> { return flowOf(false) } }
0
Kotlin
0
7
9d1744ffd9e1652e93af711951e924b739e96dcc
1,135
Studiversity
Apache License 2.0
actionviews/src/main/java/com/tanchuev/actionviews/viewmodel/fragment/ActionsFragment.kt
tanchuev
136,659,251
false
{"Kotlin": 44579}
package com.tanchuev.actionviews.viewmodel.fragment import android.arch.lifecycle.Observer import android.os.Bundle import android.support.v4.app.Fragment import android.view.View import com.tanchuev.actionviews.viewmodel.R import com.tanchuev.actionviews.viewmodel.utils.findViewById import com.tanchuev.actionviews.viewmodel.utils.findViewByIdNullable import com.tanchuev.actionviews.viewmodel.utils.mutableLazy import com.tanchuev.actionviews.viewmodel.view.EmptyContentView import com.tanchuev.actionviews.viewmodel.view.ErrorView import com.tanchuev.actionviews.viewmodel.view.LoadingView import com.tanchuev.actionviews.viewmodel.view.NoInternetView import com.tanchuev.actionviews.viewmodel.viewmodel.ActionsViewModel import com.tanchuev.actionviews.viewmodel.widget.ToastView /** * @author tanchuev */ abstract class ActionsFragment : Fragment() { abstract val viewModel: ActionsViewModel var contentActionView: View by mutableLazy { findViewById<View>(R.id.contentView) } var loadingActionView: LoadingView? by mutableLazy { findViewByIdNullable<View>(R.id.loadingView) as LoadingView? } var noInternetActionView: NoInternetView? by mutableLazy { findViewByIdNullable<View>(R.id.noInternetView) as NoInternetView? } var emptyContentActionView: EmptyContentView? by mutableLazy { findViewByIdNullable<View>(R.id.emptyContentView) as EmptyContentView? } open var errorActionView: ErrorView by mutableLazy { ToastView(requireActivity()) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initViewModel() } fun initViewModel() { viewModel.contentVisibility.observe(this, Observer { }) viewModel.loadingVisibility.observe(this, Observer { loadingActionView?.setVisibility(it!!, contentActionView) }) viewModel.noInternetVisibility.observe(this, Observer { if (it!!) { if (noInternetActionView != null) { noInternetActionView!!.setVisibility(it, contentActionView) } else { errorActionView.showError(R.string.errorNoInternet) } } else { noInternetActionView?.setVisibility(it, contentActionView) } }) viewModel.emptyContentVisibility.observe(this, Observer { if (it!!) { if (emptyContentActionView != null) { emptyContentActionView!!.setVisibility(it, contentActionView) } else { errorActionView.showError(R.string.errorEmptyContent) } } else { emptyContentActionView?.setVisibility(it, contentActionView) } }) viewModel.isContentEmpty.observe(this, Observer { emptyContentActionView?.isContentEmpty = it!! }) viewModel.error.observe(this, Observer { errorActionView.showError(it!!) }) } }
0
Kotlin
0
8
7ab13e9f91e493d9408953d569d393607ee26ab7
2,999
ActionViews-ViewModel
MIT License
animated-drawable/src/main/java/com/facebook/fresco/animation/bitmap/preparation/ondemandanimation/AnimationBitmapFrame.kt
facebook
31,533,997
false
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package com.facebook.fresco.animation.bitmap.preparation.ondemandanimation import android.graphics.Bitmap import com.facebook.common.references.CloseableReference import java.io.Closeable class AnimationBitmapFrame(var frameNumber: Int, val bitmap: CloseableReference<Bitmap>) : Closeable { fun isValidFor(frameNumber: Int): Boolean = this.frameNumber == frameNumber && bitmap.isValid fun isValid(): Boolean = bitmap.isValid override fun close() { bitmap.close() } }
233
null
3751
17,073
dbb46cebfffeeabf289db5f4a8d64950ba1e020d
678
fresco
MIT License
tony-boot-demo/tony-dto/src/main/kotlin/com/tony/dto/req/ModuleAssignReq.kt
beingEggache
312,472,927
false
{"Java": 1825396, "HTML": 354682, "Kotlin": 287327, "Dockerfile": 2745, "Shell": 2105, "CSS": 1466}
package com.tony.dto.req import io.swagger.annotations.ApiModel import io.swagger.annotations.ApiModelProperty import javax.validation.constraints.NotEmpty /** * * @author tangli * @since 2020-11-14 13:50 */ @ApiModel("分配权限请求") data class ModuleAssignReq( @get:NotEmpty(message = "请选择模块分组") @ApiModelProperty("模块分组", required = true) val moduleGroupList: List<String> = listOf(), @get:NotEmpty(message = "请选择角色") @ApiModelProperty("用户ID", required = true) val roleIdList: List<String> = listOf() )
1
null
1
1
1c2991364067f3c28e7f99cd46df3e8f4000b18c
530
tony-boot
MIT License
src/main/kotlin/org/move/ide/inspections/MvUnresolvedReferenceInspection.kt
pontem-network
279,299,159
false
{"Kotlin": 2117384, "Move": 38257, "Lex": 5509, "HTML": 2114, "Java": 1275}
package org.move.ide.inspections import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import org.move.cli.settings.isDebugModeEnabled import org.move.ide.inspections.imports.AutoImportFix import org.move.lang.core.psi.* import org.move.lang.core.psi.ext.* import org.move.lang.core.resolve2.PathKind.* import org.move.lang.core.resolve2.pathKind import org.move.lang.core.types.infer.inference import org.move.lang.core.types.ty.TyUnknown class MvUnresolvedReferenceInspection: MvLocalInspectionTool() { var ignoreWithoutQuickFix: Boolean = false override val isSyntaxOnly get() = false private fun ProblemsHolder.registerUnresolvedReferenceError(path: MvPath) { // no errors in pragmas if (path.hasAncestor<MvPragmaSpecStmt>()) return val candidates = AutoImportFix.findApplicableContext(path)?.candidates.orEmpty() if (candidates.isEmpty() && ignoreWithoutQuickFix) return val referenceName = path.referenceName ?: return val parent = path.parent val description = when (parent) { is MvPathType -> "Unresolved type: `$referenceName`" is MvCallExpr -> "Unresolved function: `$referenceName`" else -> "Unresolved reference: `$referenceName`" } val highlightedElement = path.referenceNameElement ?: path val fix = if (candidates.isNotEmpty()) AutoImportFix(path) else null registerProblem( highlightedElement, description, ProblemHighlightType.LIKE_UNKNOWN_SYMBOL, *listOfNotNull(fix).toTypedArray() ) } override fun buildMvVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object: MvVisitor() { override fun visitPath(path: MvPath) { // skip specs in non-dev mode, too many false-positives if (path.isMslScope && !isDebugModeEnabled()) return if (path.isMslScope && path.isSpecPrimitiveType()) return if (path.isUpdateFieldArg2) return if (path.isPrimitiveType()) return // destructuring assignment like `Coin { val1: _ } = get_coin()` if (path.textMatches("_") && path.isInsideAssignmentLhs()) return // assert macro if (path.text == "assert") return // attribute values are special case if (path.hasAncestor<MvAttrItem>()) return val pathReference = path.reference ?: return val pathKind = path.pathKind() when (pathKind) { is NamedAddress, is ValueAddress -> return is UnqualifiedPath -> { if (pathReference.resolve() == null) { holder.registerUnresolvedReferenceError(path) } } is QualifiedPath -> { if (pathKind !is QualifiedPath.Module) { val qualifier = pathKind.qualifier // qualifier is unresolved, no need to resolve current path if (qualifier.reference?.resolve() == null) return } if (pathReference.resolve() == null) { holder.registerUnresolvedReferenceError(path) } } } } override fun visitFieldPat(patField: MvFieldPat) { if (patField.isMsl() && !isDebugModeEnabled()) { return } val resolvedStructDef = patField.structPat.path.maybeStruct ?: return if (!resolvedStructDef.fieldNames.any { it == patField.referenceName }) { holder.registerProblem( patField.referenceNameElement, "Unresolved field: `${patField.referenceName}`", ProblemHighlightType.LIKE_UNKNOWN_SYMBOL ) } } override fun visitStructLitField(litField: MvStructLitField) { if (litField.isMsl() && !isDebugModeEnabled()) { return } if (litField.isShorthand) { val resolvedItems = litField.reference.multiResolve() val resolvedStructField = resolvedItems.find { it is MvNamedFieldDecl } if (resolvedStructField == null) { holder.registerProblem( litField.referenceNameElement, "Unresolved field: `${litField.referenceName}`", ProblemHighlightType.LIKE_UNKNOWN_SYMBOL ) } val resolvedBinding = resolvedItems.find { it is MvBindingPat } if (resolvedBinding == null) { holder.registerProblem( litField.referenceNameElement, "Unresolved reference: `${litField.referenceName}`", ProblemHighlightType.LIKE_UNKNOWN_SYMBOL ) } } else { if (litField.reference.resolve() == null) { holder.registerProblem( litField.referenceNameElement, "Unresolved field: `${litField.referenceName}`", ProblemHighlightType.LIKE_UNKNOWN_SYMBOL ) } } } override fun visitSchemaLitField(field: MvSchemaLitField) { if (field.isShorthand) { val resolvedItems = field.reference.multiResolve() val fieldBinding = resolvedItems.find { it is MvBindingPat && it.owner is MvSchemaFieldStmt } if (fieldBinding == null) { holder.registerProblem( field.referenceNameElement, "Unresolved field: `${field.referenceName}`", ProblemHighlightType.LIKE_UNKNOWN_SYMBOL ) } val letBinding = resolvedItems.find { it is MvBindingPat } if (letBinding == null) { holder.registerProblem( field.referenceNameElement, "Unresolved reference: `${field.referenceName}`", ProblemHighlightType.LIKE_UNKNOWN_SYMBOL ) } } else { if (field.reference.resolve() == null) { holder.registerProblem( field.referenceNameElement, "Unresolved field: `${field.referenceName}`", ProblemHighlightType.LIKE_UNKNOWN_SYMBOL ) } } } override fun visitDotExpr(dotExpr: MvDotExpr) { if (dotExpr.isMsl() && !isDebugModeEnabled()) { return } val receiverTy = dotExpr.inference(false)?.getExprType(dotExpr.expr) // disable inspection is object is unresolved if (receiverTy is TyUnknown) return val dotField = dotExpr.structDotField ?: return if (dotField.unresolved) { holder.registerProblem( dotField.referenceNameElement, "Unresolved field: `${dotField.referenceName}`", ProblemHighlightType.LIKE_UNKNOWN_SYMBOL ) } } // override fun visitModuleUseSpeck(o: MvModuleUseSpeck) { // val moduleRef = o.fqModuleRef ?: return // if (!moduleRef.resolvable) { // val refNameElement = moduleRef.referenceNameElement ?: return // holder.registerProblem( // refNameElement, // "Unresolved reference: `${refNameElement.text}`", // ProblemHighlightType.LIKE_UNKNOWN_SYMBOL // ) // } // } // override fun visitItemUseSpeck(o: MvItemUseSpeck) { // val moduleRef = o.fqModuleRef // if (!moduleRef.resolvable) { // val refNameElement = moduleRef.referenceNameElement ?: return // holder.registerProblem( // refNameElement, // "Unresolved reference: `${refNameElement.text}`", // ProblemHighlightType.LIKE_UNKNOWN_SYMBOL // ) // return // } // val useItems = o.descendantsOfType<MvUseItem>() // for (useItem in useItems) { // if (!useItem.resolvable) { // val refNameElement = useItem.referenceNameElement // holder.registerProblem( // refNameElement, // "Unresolved reference: `${refNameElement.text}`", // ProblemHighlightType.LIKE_UNKNOWN_SYMBOL // ) // } // } // } } }
3
Kotlin
29
69
c0192da133a0d0b0cb22456f55d3ee8c7a973109
9,058
intellij-move
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/RankingPodium.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline 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.rounded.Icons public val Icons.Outline.RankingPodium: ImageVector get() { if (_rankingPodium != null) { return _rankingPodium!! } _rankingPodium = Builder(name = "RankingPodium", defaultWidth = 24.0.dp, defaultHeight = 24.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) { moveToRelative(20.5f, 16.0f) horizontalLineToRelative(-3.5f) verticalLineToRelative(-3.5f) curveToRelative(0.0f, -1.93f, -1.57f, -3.5f, -3.5f, -3.5f) horizontalLineToRelative(-3.0f) curveToRelative(-1.93f, 0.0f, -3.5f, 1.57f, -3.5f, 3.5f) verticalLineToRelative(0.5f) horizontalLineToRelative(-3.5f) curveToRelative(-1.93f, 0.0f, -3.5f, 1.57f, -3.5f, 3.5f) verticalLineToRelative(4.0f) curveToRelative(0.0f, 1.93f, 1.57f, 3.5f, 3.5f, 3.5f) horizontalLineToRelative(17.0f) curveToRelative(1.93f, 0.0f, 3.5f, -1.57f, 3.5f, -3.5f) verticalLineToRelative(-1.0f) curveToRelative(0.0f, -1.93f, -1.57f, -3.5f, -3.5f, -3.5f) close() moveTo(9.0f, 12.5f) curveToRelative(0.0f, -0.827f, 0.673f, -1.5f, 1.5f, -1.5f) horizontalLineToRelative(3.0f) curveToRelative(0.827f, 0.0f, 1.5f, 0.673f, 1.5f, 1.5f) verticalLineToRelative(9.5f) horizontalLineToRelative(-6.0f) verticalLineToRelative(-9.5f) close() moveTo(2.0f, 20.5f) verticalLineToRelative(-4.0f) curveToRelative(0.0f, -0.827f, 0.673f, -1.5f, 1.5f, -1.5f) horizontalLineToRelative(3.5f) verticalLineToRelative(7.0f) horizontalLineToRelative(-3.5f) curveToRelative(-0.827f, 0.0f, -1.5f, -0.673f, -1.5f, -1.5f) close() moveTo(22.0f, 20.5f) curveToRelative(0.0f, 0.827f, -0.673f, 1.5f, -1.5f, 1.5f) horizontalLineToRelative(-3.5f) verticalLineToRelative(-4.0f) horizontalLineToRelative(3.5f) curveToRelative(0.827f, 0.0f, 1.5f, 0.673f, 1.5f, 1.5f) verticalLineToRelative(1.0f) close() moveTo(22.0f, 11.5f) curveToRelative(0.0f, -0.275f, -0.224f, -0.5f, -0.5f, -0.5f) horizontalLineToRelative(-0.5f) curveToRelative(-0.552f, 0.0f, -1.0f, -0.447f, -1.0f, -1.0f) reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f) curveToRelative(0.276f, 0.0f, 0.5f, -0.225f, 0.5f, -0.5f) reflectiveCurveToRelative(-0.224f, -0.5f, -0.5f, -0.5f) horizontalLineToRelative(-2.0f) curveToRelative(-0.552f, 0.0f, -1.0f, -0.447f, -1.0f, -1.0f) reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f) horizontalLineToRelative(2.0f) curveToRelative(1.378f, 0.0f, 2.5f, 1.121f, 2.5f, 2.5f) curveToRelative(0.0f, 0.424f, -0.107f, 0.824f, -0.294f, 1.175f) curveToRelative(0.488f, 0.456f, 0.794f, 1.105f, 0.794f, 1.825f) curveToRelative(0.0f, 1.379f, -1.122f, 2.5f, -2.5f, 2.5f) horizontalLineToRelative(-2.5f) curveToRelative(-0.552f, 0.0f, -1.0f, -0.447f, -1.0f, -1.0f) reflectiveCurveToRelative(0.448f, -1.0f, 1.0f, -1.0f) horizontalLineToRelative(2.5f) curveToRelative(0.276f, 0.0f, 0.5f, -0.225f, 0.5f, -0.5f) close() moveTo(4.0f, 6.0f) curveToRelative(0.0f, -0.552f, -0.449f, -1.0f, -1.0f, -1.0f) reflectiveCurveToRelative(-1.0f, 0.448f, -1.0f, 1.0f) reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f) reflectiveCurveToRelative(-1.0f, -0.447f, -1.0f, -1.0f) curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f) reflectiveCurveToRelative(3.0f, 1.346f, 3.0f, 3.0f) curveToRelative(0.0f, 1.364f, -1.267f, 2.275f, -2.538f, 3.0f) horizontalLineToRelative(1.538f) curveToRelative(0.552f, 0.0f, 1.0f, 0.447f, 1.0f, 1.0f) reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f) lineTo(1.608f, 11.0f) curveToRelative(-0.765f, 0.0f, -1.376f, -0.416f, -1.557f, -1.06f) curveToRelative(-0.188f, -0.669f, 0.138f, -1.374f, 0.83f, -1.795f) curveToRelative(0.25f, -0.152f, 0.552f, -0.315f, 0.876f, -0.49f) curveToRelative(0.555f, -0.3f, 2.243f, -1.211f, 2.243f, -1.655f) close() moveTo(9.293f, 3.08f) curveToRelative(-0.391f, -0.391f, -0.391f, -1.023f, 0.0f, -1.414f) lineToRelative(1.242f, -1.242f) curveToRelative(0.415f, -0.414f, 1.033f, -0.536f, 1.574f, -0.312f) curveToRelative(0.542f, 0.225f, 0.891f, 0.748f, 0.891f, 1.334f) verticalLineToRelative(5.555f) curveToRelative(0.0f, 0.553f, -0.448f, 1.0f, -1.0f, 1.0f) reflectiveCurveToRelative(-1.0f, -0.447f, -1.0f, -1.0f) lineTo(11.0f, 2.787f) lineToRelative(-0.293f, 0.293f) curveToRelative(-0.39f, 0.391f, -1.023f, 0.391f, -1.414f, 0.0f) close() } } .build() return _rankingPodium!! } private var _rankingPodium: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
6,491
icons
MIT License
serverless-simulator/opendc/opendc-serverless/src/main/kotlin/com/atlarge/opendc/serverless/core/ArimaForecastModel.kt
atlarge-research
297,702,102
false
{"Jupyter Notebook": 11330813, "Kotlin": 547073, "Python": 15018, "R": 1048}
package com.atlarge.opendc.serverless.core import com.atlarge.opendc.serverless.monitor.UsageMonitor import org.rosuda.REngine.REXP import java.lang.StringBuilder import java.util.* /** * ARIMA Time series forecast model. */ class ArimaForecastModel(private val rThread: RServeThread, funcUids:MutableSet<UUID>, val usageMonitor: UsageMonitor){ init { rThread.engine().eval("library(forecast)") rThread.engine().eval("library(xts)") for (uid in funcUids) { usageMonitor.functionProfiles[uid]!!.dataframe = IdleTimeDataFrame(uid,rThread) } } fun addIdleTime(funcUid:UUID, timestamp:Long, idleTime:Long) = usageMonitor.functionProfiles[funcUid]!!.dataframe.addIdleTime(timestamp, idleTime) fun buildModel(funcUid: UUID){ val dataFrame = usageMonitor.functionProfiles[funcUid]!!.dataframe dataFrame.build() rThread.engine().eval("model${dataFrame.dfName} = auto.arima(${dataFrame.toTimeSeries()}, D=1)") } fun forecast(funcUid: UUID):Long{ val dataFrame = usageMonitor.functionProfiles[funcUid]!!.dataframe val forecastValue = rThread.engine().eval("as.numeric(forecast(model${dataFrame.dfName}, 1)\$mean)") return forecastValue.asDouble().toLong() } } class IdleTimeDataFrame(private val uid:UUID, private val rThread: RServeThread){ val dfName = "dataframe${uid.leastSignificantBits}" private val timestampCol: StringBuilder = StringBuilder() private val idleTimeCol: StringBuilder = StringBuilder() private var firstInsert: Boolean = true init { rThread.engine().eval("$dfName <- data.frame(timestamp=c(), idleTime=c())") timestampCol.append("c()") idleTimeCol.append("c()") } fun addIdleTime(timestamp: Long, idleTime: Long){ if (firstInsert) { timestampCol.insert(timestampCol.indexOf(')'), "$timestamp") idleTimeCol.insert(idleTimeCol.indexOf(')'), "$idleTime") firstInsert = false } else{ timestampCol.insert(timestampCol.indexOf(')'), ",$timestamp") idleTimeCol.insert(idleTimeCol.indexOf(')'), ",$idleTime") } } fun build(): REXP = rThread.engine().eval("$dfName <- data.frame(timestamp=c(as.POSIXct($timestampCol/1000, origin=\"1970-01-01\", tz=\"UTC\")), idleTime=c($idleTimeCol))") fun toTimeSeries():String{ rThread.engine().eval("ts_$dfName <- as.xts(x = $dfName[, -1], order.by = $dfName\$timestamp)") return "ts_$dfName" } }
0
Jupyter Notebook
1
2
11c772bcb3fc7a7c2590d6ed6ab979b78cb9fec9
2,554
opendc-serverless
MIT License
Aula_2/VarVal.kt
Leonardo-Gaspar
841,706,227
false
{"Kotlin": 2779}
//Variáveis /* var = mutável val = imutável */ fun main(){ val imutavel: Int = 5 var mutavel: Int = 10 var sobrenome = "Silva" mutavel = 15 //OK imutavel = 15 // Erro! Não é permitido println("$mutavel, $imutavel") if(true){ val sobrenome = "Silva" println("$sobrenome") } }
0
Kotlin
0
0
75e7eb5612cf203e1a839e357dd6fa3ca52a1881
341
mad-android2
Apache License 2.0
base/build-system/gradle-api/src/main/java/com/android/build/api/sourcesets/AndroidSourceFile.kt
qiangxu1996
301,210,525
false
{"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121}
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.api.sourcesets import org.gradle.api.Incubating import java.io.File import org.gradle.api.Named /** An AndroidSourceFile represents a single file input for an Android project. * * This interface is not currently usable. It is a work in progress. */ @Incubating interface AndroidSourceFile : Named { /** * Returns the file. * @return the file input. */ var srcFile: File /** * Sets the location of the file. Returns this object. * * @param srcPath The source directory. This is evaluated as for * [org.gradle.api.Project.file] * @return the AndroidSourceFile object */ fun srcFile(srcPath: Any): AndroidSourceFile }
1
Java
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
1,330
vmtrace
Apache License 2.0
base/build-system/gradle-api/src/main/java/com/android/build/api/sourcesets/AndroidSourceFile.kt
qiangxu1996
301,210,525
false
{"Java": 38854631, "Kotlin": 10438678, "C++": 1701601, "HTML": 795500, "FreeMarker": 695102, "Starlark": 542991, "C": 148853, "RenderScript": 58853, "Shell": 51803, "CSS": 36591, "Python": 32879, "XSLT": 23593, "Batchfile": 8747, "Dockerfile": 7341, "Emacs Lisp": 4737, "Makefile": 4067, "JavaScript": 3488, "CMake": 3295, "PureBasic": 2359, "GLSL": 1628, "Objective-C": 308, "Prolog": 214, "D": 121}
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.build.api.sourcesets import org.gradle.api.Incubating import java.io.File import org.gradle.api.Named /** An AndroidSourceFile represents a single file input for an Android project. * * This interface is not currently usable. It is a work in progress. */ @Incubating interface AndroidSourceFile : Named { /** * Returns the file. * @return the file input. */ var srcFile: File /** * Sets the location of the file. Returns this object. * * @param srcPath The source directory. This is evaluated as for * [org.gradle.api.Project.file] * @return the AndroidSourceFile object */ fun srcFile(srcPath: Any): AndroidSourceFile }
1
Java
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
1,330
vmtrace
Apache License 2.0
src/main/kotlin/com/merrylab/example/ndjson/config/WebConfig.kt
bulbulpaul
276,386,449
false
null
package com.merrylab.example.ndjson.config import com.merrylab.example.ndjson.config.converter.TodoListHttpMessageConverter import org.springframework.context.annotation.Configuration import org.springframework.http.converter.HttpMessageConverter import org.springframework.web.servlet.config.annotation.WebMvcConfigurer @Configuration class WebConfig : WebMvcConfigurer { override fun extendMessageConverters(converters: MutableList<HttpMessageConverter<*>>) { converters.add(TodoListHttpMessageConverter()) } }
0
Kotlin
0
1
d5ad6d85dd3a6e672ea6eb81ec95fa3c2506b15e
532
springboot-ndjson-example
MIT License
core-api/core/src/main/java/love/forte/simbot/core/configuration/CoreListenerRegistrar.kt
simple-robot
554,852,615
false
null
/* * * * Copyright (c) 2020. ForteScarlet All rights reserved. * * Project simple-robot * * File MiraiAvatar.kt * * * * You can contact the author through the following channels: * * github https://github.com/ForteScarlet * * gitee https://gitee.com/ForteScarlet * * email <EMAIL> * * QQ 1149159218 * */ package love.forte.simbot.core.configuration import love.forte.common.ioc.DependBeanFactory import love.forte.common.ioc.annotation.ConfigBeans import love.forte.common.ioc.annotation.Depend import love.forte.common.ioc.annotation.PostPass import love.forte.simbot.bot.BotManager import love.forte.simbot.core.TypedCompLogger import love.forte.simbot.core.infof import love.forte.simbot.listener.ListenerManager import love.forte.simbot.listener.ListenerRegistered import love.forte.simbot.listener.PostListenerRegistrar @ConfigBeans("coreListenerRegistrar") public class CoreListenerRegistrar { private companion object : TypedCompLogger(CoreListenerRegistrar::class.java) @Depend private lateinit var dependBeanFactory: DependBeanFactory @Depend private lateinit var listenerManager: ListenerManager @Depend private lateinit var botManager: BotManager @PostPass public fun registerListeners(){ logger.debug("Start register listeners.") // do register. dependBeanFactory.allBeans.mapNotNull { if (PostListenerRegistrar::class.java.isAssignableFrom(dependBeanFactory.getType(it))) { dependBeanFactory[it] as PostListenerRegistrar } else null }.forEach { logger.debug("Starter register listeners by $it.") it.registerListenerFunctions(listenerManager) } logger.debug("Listeners registered.") dependBeanFactory.allBeans.mapNotNull { if (ListenerRegistered::class.java.isAssignableFrom(dependBeanFactory.getType(it))) { dependBeanFactory[it] as ListenerRegistered } else null }.forEach { logger.debug("Do registered by $it.") it.onRegistered(listenerManager) } val bots = botManager.bots // show bots. if (bots.isEmpty()) { logger.warn("Registration Bots is empty.") } else { bots.map { bot -> val i = bot.botInfo NameCodeLevel(i.botName, i.botCode, i.botLevel) }.forEach { info -> logger.debug("Try get botInfo for ${info.name}(${info.code})") if (info.level >= 0) { logger.infof("Registration Bot: code={}, name={}, level={}", info.code, info.name, info.level) } else { logger.infof("Registration Bot: code={}, name={}", info.code, info.name) } } } } } private data class NameCodeLevel(val name: String, val code: String, val level: Long = -1)
21
Kotlin
24
3
c5d7c9ca8c81b2bddc250090739d7c7d0c110328
2,963
simple-robot-v2
Apache License 2.0
usecases/src/main/kotlin/usecase/usecases/source/DeleteSourceUsecase.kt
semicolondsm
418,085,977
false
null
package usecase.usecases.source import domain.SourceNotFoundException import domain.entity.ResourceType import domain.repository.ResourceRepository import usecase.Environment import usecase.model.DefaultResponse import usecase.model.DeleteSourceRequest import usecase.usecases.AuthUsecase import usecase.usecases.common.deleteFile import usecase.usecases.common.suspendedTx class DeleteSourceUsecase ( private val repository: ResourceRepository, private val environment: Environment ) : AuthUsecase<DeleteSourceRequest, DefaultResponse>() { override suspend fun executor(request: DeleteSourceRequest): DefaultResponse { repository.findByNameAndType(request.name, ResourceType.SOUR) ?: throw SourceNotFoundException() deleteFile("environment.uploadDir/source/${request.name}") suspendedTx { repository.deleteByNameAndType(request.name, ResourceType.SOUR) } return DefaultResponse("소스가 성공적으로 삭제되었습니다.") } }
1
Kotlin
0
0
f75470363d95ff8ef5044a795b7aa0f7e70bd3a1
990
Leesauce-Server
MIT License
app/src/main/java/com/precopia/rxtracker/view/addtimestamp/bulidlogic/AddTimeStampLogicFactory.kt
DavidPrecopia
243,413,607
false
null
package com.precopia.rxtracker.view.addtimestamp.bulidlogic import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.precopia.domain.repository.IPrescriptionRepoContract import com.precopia.domain.repository.ITimeStampRepoContract import com.precopia.rxtracker.util.IUtilSchedulerProviderContract import com.precopia.rxtracker.view.addtimestamp.AddTimeStampLogic import io.reactivex.rxjava3.disposables.CompositeDisposable class AddTimeStampLogicFactory( private val prescriptionRepo: IPrescriptionRepoContract, private val timeStampRepo: ITimeStampRepoContract, private val utilSchedulerProvider: IUtilSchedulerProviderContract, private val disposable: CompositeDisposable ): ViewModelProvider.NewInstanceFactory() { @Suppress("UNCHECKED_CAST") override fun <T: ViewModel?> create(modelClass: Class<T>): T { return AddTimeStampLogic( prescriptionRepo, timeStampRepo, utilSchedulerProvider, disposable ) as T } }
0
Kotlin
0
0
4209c7c951820f91b84e184415e4cba2ac986018
1,024
RxTracker
Apache License 2.0
core/common/src/main/kotlin/com/espressodev/gptmap/core/common/GmViewModel.kt
f-arslan
714,072,263
false
{"Kotlin": 279197, "Dockerfile": 852}
package com.espressodev.gptmap.core.common import android.util.Log import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.espressodev.gptmap.core.common.snackbar.SnackbarManager import com.espressodev.gptmap.core.common.snackbar.SnackbarMessage.Companion.toSnackbarMessage import com.espressodev.gptmap.core.data.LogService import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch open class GmViewModel(private val logService: LogService) : ViewModel() { fun launchCatching(snackbar: Boolean = true, block: suspend CoroutineScope.() -> Unit) = viewModelScope.launch( CoroutineExceptionHandler { _, throwable -> if (snackbar) { SnackbarManager.showMessage(throwable.toSnackbarMessage()) } logService.logNonFatalCrash(throwable) Log.e("GmViewModel", "launchCatching: ", throwable) }, block = block, ) }
0
Kotlin
0
2
df5a50a63d1689ce3024f74985d37e10fce37d74
1,045
GptMap
MIT License
paletteon-kobweb/src/jsMain/kotlin/dev/teogor/paletteon/kobweb/ui/icons/ContrastInverseSvg.kt
teogor
849,961,511
false
{"Kotlin": 482882}
/* * Copyright 2024 Teogor (Teodor Grigor) * * 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 dev.teogor.paletteon.kobweb.ui.icons import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.graphics.Color import com.varabyte.kobweb.compose.dom.svg.Path import com.varabyte.kobweb.compose.dom.svg.SVGSvgAttrsScope import com.varabyte.kobweb.compose.dom.svg.Svg import com.varabyte.kobweb.compose.ui.Modifier import com.varabyte.kobweb.compose.ui.toAttrs import dev.teogor.paletteon.kobweb.ui.color.asRgba @Composable public fun ContrastInverseSvg( tint: Color, modifier: Modifier = Modifier ) { // Caching the SVG path and attributes val svgAttrs = remember(tint) { modifier.toAttrs<SVGSvgAttrsScope> { width(24) height(24) viewBox(0, 0, 24, 24) fill(tint.asRgba()) } } // Using the cached attributes for the Svg component Svg(attrs = svgAttrs) { Path { d { moveTo(12.0f, 0.0f) curveTo(18.6289f, 0.0f, 24.0f, 5.3711f, 24.0f, 12.0f) curveTo(24.0f, 18.6289f, 18.6289f, 24.0f, 12.0f, 24.0f) curveTo(5.3711f, 24.0f, 0.0f, 18.6289f, 0.0f, 12.0f) curveTo(0.0f, 5.3711f, 5.3711f, 0.0f, 12.0f, 0.0f) closePath() moveTo(12.0f, 22.0f) lineTo(12.0f, 2.0f) curveTo(6.4766f, 2.0f, 2.0f, 6.4766f, 2.0f, 12.0f) curveTo(2.0f, 17.5234f, 6.4766f, 22.0f, 12.0f, 22.0f) closePath() moveTo(12.0f, 22.0f) } } } }
0
Kotlin
0
2
de712f6bb9d48be94e204086cbddabd32110d61d
2,031
paletteon
Apache License 2.0
android/app/src/androidTest/java/com/trustwallet/core/app/blockchains/filecoin/TestFilecoin.kt
trustwallet
170,738,310
false
null
package com.trustwallet.core.app.blockchains.filecoin import com.google.protobuf.ByteString import com.trustwallet.core.app.utils.toHexByteArray import com.trustwallet.core.app.utils.toHexBytesInByteString import org.junit.Assert.assertEquals import org.junit.Test import wallet.core.java.AnySigner import wallet.core.jni.* import wallet.core.jni.proto.Filecoin import wallet.core.jni.proto.Filecoin.SigningOutput class TestFilecoin { init { System.loadLibrary("TrustWalletCore") } @Test fun testCreateAddress() { val privateKey = PrivateKey("1d969865e189957b9824bd34f26d5cbf357fda1a6d844cbf0c9ab1ed93fa7dbe".toHexByteArray()) val publicKey = privateKey.getPublicKeySecp256k1(false) val address = AnyAddress(publicKey, CoinType.FILECOIN) assertEquals("f1z4a36sc7mfbv4z3qwutblp2flycdui3baffytbq", address.description()) } @Test fun testCreateDelegatedAddress() { val privateKey = PrivateKey("825d2bb32965764a98338139412c7591ed54c951dd65504cd8ddaeaa0fea7b2a".toHexByteArray()) val publicKey = privateKey.getPublicKeySecp256k1(false) val address = AnyAddress(publicKey, FilecoinAddressType.DELEGATED) assertEquals("f410fvak24cyg3saddajborn6idt7rrtfj2ptauk5pbq", address.description()) } @Test fun testAddressConverter() { val ethereumAddress = FilecoinAddressConverter.convertToEthereum("f410frw6wy7w6sbsguyn3yzeygg34fgf72n5ao5sxyky") assertEquals(ethereumAddress, "0x8dbD6c7Ede90646a61Bbc649831b7c298BFd37A0") assert(AnyAddress.isValid(ethereumAddress, CoinType.ETHEREUM)) val filecoinAddress = FilecoinAddressConverter.convertFromEthereum("0x8dbD6c7Ede90646a61Bbc649831b7c298BFd37A0") assertEquals(filecoinAddress, "f410frw6wy7w6sbsguyn3yzeygg34fgf72n5ao5sxyky") assert(AnyAddress.isValid(filecoinAddress, CoinType.FILECOIN)) } @Test fun testSigner() { val input = Filecoin.SigningInput.newBuilder() .setPrivateKey("<KEY>".toHexBytesInByteString()) .setTo("<KEY>") .setNonce(2) // 600 FIL .setValue(ByteString.copyFrom("2086ac351052600000".toHexByteArray())) .setGasLimit(1000) .setGasFeeCap(ByteString.copyFrom("25f273933db5700000".toHexByteArray())) .setGasPremium(ByteString.copyFrom("2b5e3af16b18800000".toHexByteArray())) .build() val output = AnySigner.sign(input, CoinType.FILECOIN, SigningOutput.parser()) val expected = """{"Message":{"From":"f1z4a36sc7mfbv4z3qwutblp2flycdui3baffytbq","GasFeeCap":"700000000000000000000","GasLimit":1000,"GasPremium":"800000000000000000000","Method":0,"Nonce":2,"To":"f3um6uo3qt5of54xjbx3hsxbw5mbsc6auxzrvfxekn5bv3duewqyn2tg5rhrlx73qahzzpkhuj7a34iq7oifsq","Value":"600000000000000000000"},"Signature":{"Data":"jMRu+OZ/lfppgmqSfGsntFrRLWZnUg3ZYmJTTRLsVt4V1310vR3VKGJpaE6S4sNvDOE6sEgmN9YmfTkPVK2qMgE=","Type":1}}""" assertEquals(expected, output.json) } }
44
null
1585
2,829
164074847176cbf462df7ca77e13b4337541ea0f
3,021
wallet-core
Apache License 2.0
app/src/main/java/com/yatatsu/expiresmemo/data/DateProvider.kt
yatatsu
75,637,344
false
null
package com.yatatsu.expiresmemo.data import java.util.Date interface DateProvider { fun now(): Date }
0
Kotlin
0
0
194d42381bafa85088b1bb3c9f201f193f8d5e43
107
Android-ExpiresMemo
Apache License 2.0
testData/module/exportAssignment/exportDefaultInline.d.kt
Kotlin
16,728,854
false
null
@file:JsModule("foo") package exportDefaultInline.foo external fun baz(): Unit = definedExternally @JsName("default") external fun bar(): String = definedExternally
6
Kotlin
28
325
d473b7597ea0262e91efa1697adeeb97c7d300de
166
ts2kt
Apache License 2.0
domain/src/commonMain/kotlin/ly/david/musicsearch/domain/search/history/usecase/GetSearchHistory.kt
lydavid
458,021,427
false
{"Kotlin": 1354732, "HTML": 674577, "Python": 3489, "Shell": 1543, "Ruby": 955}
package ly.david.musicsearch.domain.search.history.usecase import ly.david.musicsearch.core.models.network.MusicBrainzEntity import ly.david.musicsearch.domain.search.history.SearchHistoryRepository import org.koin.core.annotation.Single @Single class GetSearchHistory( private val searchHistoryRepository: SearchHistoryRepository, ) { operator fun invoke( entity: MusicBrainzEntity, ) = searchHistoryRepository.observeSearchHistory(entity) }
104
Kotlin
0
6
4f49e75742e4c2135161e98df9db15b418c6c3fe
465
MusicSearch
Apache License 2.0
src/test/kotlin/no/nav/cv/eures/eures/EuresServiceIntegrationTest.kt
navikt
245,109,239
false
null
package no.nav.cv.eures.eures import com.nhaarman.mockitokotlin2.eq import no.nav.cv.eures.cv.CvXml import no.nav.cv.eures.cv.CvXmlRepository import no.nav.cv.eures.eures.dto.GetDetails.CandidateDetail.Status.ACTIVE import no.nav.cv.eures.eures.dto.GetDetails.CandidateDetail.Status.CLOSED import no.nav.security.token.support.test.spring.TokenGeneratorConfiguration import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertAll import org.mockito.Mockito import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.jdbc.EmbeddedDatabaseConnection import org.springframework.boot.test.autoconfigure.jdbc.AutoConfigureTestDatabase import org.springframework.boot.test.context.SpringBootTest import org.springframework.context.annotation.Import import org.springframework.test.annotation.DirtiesContext import org.springframework.test.context.ActiveProfiles import java.time.ZonedDateTime @SpringBootTest @ActiveProfiles("test") @AutoConfigureTestDatabase(connection = EmbeddedDatabaseConnection.H2) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD) @Import(TokenGeneratorConfiguration::class) class EuresServiceIntegrationTest { @Autowired lateinit var euresService: EuresService @Autowired lateinit var cvXmlRepository: CvXmlRepository private var oneDayAgo = ZonedDateTime.now().minusDays(1) private fun testData() = listOf( CvXml().update("PAM-1", "1234567890", oneDayAgo, oneDayAgo, null, xml = "SOME XML", checksum = "SOME CHECKSUM"), CvXml().update("PAM-2", "1234567891", oneDayAgo, oneDayAgo.plusHours(12), null, xml = "SOME XML", checksum = "SOME CHECKSUM"), CvXml().update("PAM-3", "1234567892", oneDayAgo, oneDayAgo.plusHours(12), oneDayAgo.plusDays(1), xml = "SOME XML", checksum = "SOME CHECKSUM") ) private val active = listOf(testData()[0], testData()[1]) @BeforeEach fun setUp() { euresService = EuresService(cvXmlRepository) //testData().forEach { cvXmlRepository.save(it) } } @Test @DirtiesContext fun `records skal endre type basert paa timestamps`() { var now = ZonedDateTime.now().minusHours(2) val candidate = cvXmlRepository.save(CvXml().update("PAM-4", "1234567893", now, now, null, xml = "SOME XML", checksum = "SOME CHECKSUM")) assertEquals(1, euresService.getChangedReferences(now.minusSeconds(1)).createdReferences.size) now = ZonedDateTime.now().plusHours(1) cvXmlRepository.save(candidate.update(candidate.reference, candidate.foedselsnummer, candidate.opprettet, now, null, "SOME UPDATED XML", checksum = "SOME CHECKSUM")) val modified = euresService.getChangedReferences(now.minusMinutes(1)) assertEquals(0, modified.createdReferences.size) assertEquals(1, modified.modifiedReferences.size) assertEquals(0, modified.closedReferences.size) now = ZonedDateTime.now().plusHours(1) cvXmlRepository.save(candidate.update(candidate.reference, candidate.foedselsnummer, candidate.opprettet, now, now, "SOME UPDATED XML", checksum = "SOME CHECKSUM")) val closed = euresService.getChangedReferences(now.minusMinutes(1)) assertEquals(0, closed.createdReferences.size) assertEquals(0, closed.modifiedReferences.size) assertEquals(1, closed.closedReferences.size) } }
0
Kotlin
0
0
38197b90267975730a450d8751c30f03b28e45d3
3,546
pam-eures-cv-eksport
MIT License
kotlin-antd/src/main/kotlin/antd/autocomplete/AutoCompleteDsl.kt
PCasafont
284,043,514
true
{"Kotlin": 1197947, "CSS": 29526, "HTML": 6470, "JavaScript": 980}
package antd.autocomplete import react.RBuilder import react.RHandler fun RBuilder.autoComplete(handler: RHandler<AutoCompleteProps>) = child(AutoCompleteComponent::class, handler)
0
null
0
0
29d81bd5e8d27b239550aaa9725d912a9a5768f4
183
kotlin-js-wrappers
Apache License 2.0
fullast/src/main/kotlin/org/mangolang/fullast/BinaryOperatorAST.kt
mangolang
124,457,591
false
null
/* Mango compiler (mangolang.org) | Apache 2.0 license, © 2018. */ package org.mangolang.fullast import org.mangolang.token.OperatorToken import org.mangolang.util.HASH_CODE_MULT /** * Type for binary operators (not operations; just the operator itself). */ interface BinaryOperatorAST : ExpressionAST /** * A binary operator. */ data class ConcreteBinaryOperator(val token: OperatorToken) : BinaryOperatorAST { val symbol = token.symbol override fun asText(): CharSequence = token.asText() val isAddSub: Boolean get() = token.isAddSub val isMultDiv: Boolean get() = token.isMultDiv override fun equals(other: Any?): Boolean = other is ConcreteBinaryOperator && this::class == other::class && this.symbol == other.symbol override fun hashCode(): Int = this::class.hashCode() + HASH_CODE_MULT * token.hashCode() }
0
Kotlin
0
0
4c5261a9c4841569e487a3e7e5d00a7498c1b940
862
compiler-kt
Apache License 2.0
stream-video-android-ui-compose/src/main/kotlin/io/getstream/video/android/compose/ui/components/plugins/RememberBlurPainter.kt
GetStream
505,572,267
false
{"Kotlin": 2549850, "MDX": 279508, "Python": 18285, "Shell": 4455, "JavaScript": 1112, "PureBasic": 107}
/* * Copyright (c) 2014-2023 Stream.io Inc. All rights reserved. * * Licensed under the Stream License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/GetStream/stream-video-android/blob/main/LICENSE * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getstream.video.android.compose.ui.components.plugins import android.graphics.Bitmap import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asAndroidBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.graphics.painter.Painter import com.google.android.renderscript.Toolkit /** * Originated from [Landscapist](https://github.com/skydoves/landscapist). * * This is an extension of the [Painter] for giving blur transformation effect to the given [imageBitmap]. * * @param imageBitmap an image bitmap for loading the content. * @property radius The radius of the pixels used to blur, a value from 1 to 25. Default is 10. */ @Composable internal fun Painter.rememberBlurPainter( imageBitmap: ImageBitmap, radius: Int, ): Painter { var androidBitmap = imageBitmap.asAndroidBitmap() if (!( androidBitmap.config == Bitmap.Config.ARGB_8888 || androidBitmap.config == Bitmap.Config.ALPHA_8 ) ) { androidBitmap = androidBitmap.copy(Bitmap.Config.ARGB_8888, false) } val blurredBitmap = remember(imageBitmap, radius) { iterativeBlur(androidBitmap, radius) } return remember(this) { TransformationPainter( imageBitmap = blurredBitmap.asImageBitmap(), painter = this, ) } } private fun iterativeBlur( androidBitmap: Bitmap, radius: Int, ): Bitmap { val iterate = (radius + 1) / 25 var bitmap: Bitmap = Toolkit.blur( inputBitmap = androidBitmap, radius = (radius + 1) % 25, ) for (i in 0 until iterate) { bitmap = Toolkit.blur( inputBitmap = bitmap, radius = 25, ) } return bitmap }
3
Kotlin
30
308
1c67906e4c01e480ab180f30b39f341675bc147e
2,487
stream-video-android
FSF All Permissive License
MVVM Sqlite/app/src/main/java/com/example/mvvmsqllite/LoginViewModelFactory.kt
ggwplarin
376,823,596
false
null
package com.example.mvvmsqllite import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider class LoginViewModelFactory(private val listener: LoginResultCallBacks): ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return LoginViewModel(listener) as T } }
0
Kotlin
0
0
1b66ee8d41934ebc1d5fe5c06d09d7b99fb7e153
348
S6_Android
MIT License
app/src/test/java/com/speakerboxlite/rxentity/EntityObservableUnitTest.kt
AlexExiv
240,526,542
false
null
package com.speakerboxlite.rxentity import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.schedulers.Schedulers import io.reactivex.rxjava3.subjects.BehaviorSubject import org.junit.Test import org.junit.Assert.* data class TestEntity(val id: Int, val value: String, val indirectId: Int = 0, val indirectValue: String = ""): Entity<Int> { override val _key: Int get() = id } /* data class TestEntityBack(val id: Int, val value: String): EntityBack<Int> { override val _key: Int get() = id } */ data class ExtraParams(val test: String) data class ExtraCollectionParams(val test: String) class EntityObservableUnitTest { /*@Test fun testUpdates() { val collection = EntityObservableCollectionInt<TestEntity>(Schedulers.trampoline()) val single0 = collection.createSingle(1) { Observable.just(TestEntity(1, "1")) } var disp = single0.subscribe { assertEquals(it.id, 1) assertEquals(it.value, "1") } disp.dispose() val pages0 = collection.createPaginator { Observable.just(listOf(TestEntity(1, "2"), TestEntity(2, "3"))) } disp = pages0.subscribe { assertEquals(pages0.page, PAGINATOR_END) assertEquals(it[0].id, 1) assertEquals(it[0].value, "2") assertEquals(it[1].id, 2) assertEquals(it[1].value, "3") } disp.dispose() disp = single0.subscribe { assertEquals(it.id, 1) assertEquals(it.value, "2") } ///////// disp.dispose() disp = collection .RxRequestForUpdate(key = 1) { it.copy(value = "5") } .subscribe() disp.dispose() disp = single0.subscribe { assertEquals(it.id, 1) assertEquals(it.value, "5") } disp.dispose() disp = pages0.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "5") } ///////// disp.dispose() disp = collection .RxRequestForUpdate(keys = listOf(1, 2)) { it.copy(value = "${it.id}") } .subscribe() disp.dispose() disp = single0.subscribe { assertEquals(it.id, 1) assertEquals(it.value, "1") } disp.dispose() disp = pages0.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "1") assertEquals(it[1].id, 2) assertEquals(it[1].value, "2") } ///////// disp.dispose() disp = collection .RxUpdate(entity = TestEntity(1, "25")) .subscribe() disp.dispose() disp = single0.subscribe { assertEquals(it.id, 1) assertEquals(it.value, "25") } disp.dispose() disp = pages0.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "25") } ///////// disp.dispose() single0.refresh() disp = single0.subscribe { assertEquals(it.id, 1) assertEquals(it.value, "1") } ///////// disp.dispose() pages0.refresh() disp = pages0.subscribe { assertEquals(pages0.page, PAGINATOR_END) assertEquals(it[0].id, 1) assertEquals(it[0].value, "2") assertEquals(it[1].id, 2) assertEquals(it[1].value, "3") } disp.dispose() disp = single0.subscribe { assertEquals(it.id, 1) assertEquals(it.value, "2") } }*/ @Test fun testExtra() { val collection = EntityObservableCollectionInt<TestEntity>(Schedulers.trampoline()) val single0 = collection.createSingleExtra(key = 1, extra = ExtraParams(test = "1")) { if (it.first) assertEquals(it.extra!!.test, "1") else { assertEquals(it.extra!!.test, "2") assertEquals(it.refreshing, true) } Single.just(Optional(TestEntity(1, it.extra!!.test))) } var disp = single0.subscribe { assertEquals(it.value!!.id, 1) assertEquals(it.value!!.value, "1") } disp.dispose() val s = single0 as SingleObservableInt<TestEntity> single0.refresh(extra = ExtraParams(test = "2")) //single0.refresh(extra = ExtraParams("2")) disp = single0.subscribe { assertEquals(it.value!!.id, 1) assertEquals(it.value!!.value, "2") } disp.dispose() val page0 = collection.createPaginatorExtra(extra = ExtraParams(test = "1")) { if (it.first) assertEquals(it.extra!!.test, "1") else { assertEquals(it.extra!!.test, "2") assertEquals(it.refreshing, true) assertEquals(it.page, 0) } Single.just(listOf(TestEntity(1, it.extra!!.test), TestEntity(2, it.extra!!.test + "1"))) } disp = page0.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "1") assertEquals(it[1].id, 2) assertEquals(it[1].value, "11") } disp.dispose() page0.refresh(extra = ExtraParams("2")) disp = page0.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "2") assertEquals(it[1].id, 2) assertEquals(it[1].value, "21") } disp.dispose() } @Test fun testCollectionExtra() { val collection = EntityObservableCollectionExtraInt<TestEntity, ExtraCollectionParams>(Schedulers.trampoline(), collectionExtra = ExtraCollectionParams(test="2")) val single0 = collection.createSingleExtra(key = 1, extra = ExtraParams(test = "1")) { if (it.first) assertEquals(it.collectionExtra!!.test, "2") else { assertEquals(it.extra!!.test, "1") assertEquals(it.collectionExtra!!.test, "4") assertEquals(it.refreshing, true) } Single.just(Optional(TestEntity(1, it.extra!!.test))) } val page0 = collection.createPaginatorExtra(extra = ExtraParams(test = "1")) { if (it.first) assertEquals(it.collectionExtra!!.test, "2") else { assertEquals(it.extra!!.test, "1") assertEquals(it.collectionExtra!!.test, "4") assertEquals(it.refreshing, true) assertEquals(it.page, 0) } Single.just(listOf(TestEntity(1, it.extra!!.test), TestEntity(2, it.extra!!.test + "1"))) } collection.refresh(collectionExtra = ExtraCollectionParams(test = "4")) var disp = single0.subscribe { assertEquals(it.value!!.id, 1) assertEquals(it.value!!.value, "1") } disp.dispose() disp = page0.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "1") assertEquals(it[1].id, 2) assertEquals(it[1].value, "11") } disp.dispose() } @Test fun testArrayGetSingle() { val collection = EntityObservableCollectionExtraInt<TestEntity, ExtraCollectionParams>(Schedulers.trampoline(), collectionExtra = ExtraCollectionParams(test="2")) collection.singleFetchCallback = { if (it.first) assertEquals(it.collectionExtra!!.test, "2") else { //assertEquals(it.collectionExtra!!.test, "4") assertEquals(it.refreshing, true) } Single.just(Optional(TestEntity(it.last!!.id, it.collectionExtra!!.test + it.last!!.id))) } val page0 = collection.createPaginatorExtra(extra = ExtraParams(test = "1")) { if (it.first) assertEquals(it.collectionExtra!!.test, "2") else { assertEquals(it.extra!!.test, "1") assertEquals(it.collectionExtra!!.test, "4") assertEquals(it.refreshing, true) assertEquals(it.page, 0) } Single.just(listOf(TestEntity(1, it.collectionExtra!!.test + "1"), TestEntity(2, it.collectionExtra!!.test + "2"))) } val single0 = page0[0] var disp = single0.subscribe { assertEquals(it.value!!.id, 1) assertEquals(it.value!!.value, "21") } disp.dispose() val single1 = page0[1] disp = single1.subscribe { assertEquals(it.value!!.id, 2) assertEquals(it.value!!.value, "22") } disp.dispose() single0.refresh() single1.refresh() disp = single0.subscribe { assertEquals(it.value!!.id, 1) assertEquals(it.value!!.value, "21") } disp.dispose() disp = single1.subscribe { assertEquals(it.value!!.id, 2) assertEquals(it.value!!.value, "22") } disp.dispose() collection.refresh(collectionExtra = ExtraCollectionParams(test = "4")) disp = single0.subscribe { assertEquals(it.value!!.id, 1) assertEquals(it.value!!.value, "41") } disp.dispose() disp = single1.subscribe { assertEquals(it.value!!.id, 2) assertEquals(it.value!!.value, "42") } disp.dispose() } @Test fun testArrayInitial() { var i = 0 val collection = EntityObservableCollectionExtraInt<TestEntity, ExtraCollectionParams>(Schedulers.trampoline(), collectionExtra = ExtraCollectionParams(test="2")) collection.arrayFetchCallback = { pp -> if (pp.first) assertEquals(pp.collectionExtra!!.test, "2") else { //assertEquals(it.collectionExtra!!.test, "4") assertEquals(pp.refreshing, true) } Single.just(pp.keys.map { TestEntity(it, pp.collectionExtra!!.test + it) }) } val array = collection.createKeyArray(initial = listOf(TestEntity(1, "2"), TestEntity(2, "3"))) var disp = array.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "2") assertEquals(it[1].id, 2) assertEquals(it[1].value, "3") } disp.dispose() collection.refresh() disp = array.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "21") assertEquals(it[1].id, 2) assertEquals(it[1].value, "22") } disp.dispose() collection.refresh(collectionExtra = ExtraCollectionParams(test = "4")) disp = array.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "41") assertEquals(it[1].id, 2) assertEquals(it[1].value, "42") } disp.dispose() } /* @Test fun testArrayResend() { var i = 0 val rxSender = BehaviorSubject.create<List<TestEntity>>() val collection = EntityObservableCollectionExtraInt<TestEntity, ExtraCollectionParams>(Schedulers.trampoline(), collectionExtra = ExtraCollectionParams(test="2")) val arr = collection.createKeyArray { rxSender } rxSender.onNext(listOf(TestEntity(1, "2"), TestEntity(2, "3"))) var disp = arr.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "2") assertEquals(it[1].id, 2) assertEquals(it[1].value, "3") } disp.dispose() rxSender.onNext(listOf(TestEntity(1, "21"), TestEntity(2, "22"), TestEntity(3, "4"))) disp = arr.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "21") assertEquals(it[1].id, 2) assertEquals(it[1].value, "22") assertEquals(it[2].id, 3) assertEquals(it[2].value, "4") } disp.dispose() } */ @Test fun testCollectionPagination() { val collection = EntityObservableCollectionExtraInt<TestEntity, ExtraCollectionParams>(Schedulers.trampoline(), collectionExtra = ExtraCollectionParams(test = "2")) val page0 = collection.createPaginatorExtra(extra = ExtraParams(test = "1"), perPage = 2) { if (it.first) Single.just(listOf(TestEntity(1, it.extra!!.test), TestEntity(2, it.extra!!.test + "1"))) else Single.just(listOf(TestEntity(4, it.extra!!.test))) } assertEquals(page0.page, 0) page0.next() assertEquals(page0.page, PAGINATOR_END) } @Test fun testMergeWithSingle() { val collection = EntityObservableCollectionInt<TestEntity>(Schedulers.trampoline()) val rxObs = BehaviorSubject.createDefault("2") val rxObs1 = BehaviorSubject.createDefault("3") collection.combineLatest(rxObs) { e, t -> Pair(e.copy(value = t), true) } collection.combineLatest(rxObs1) { e, t -> Pair(e.copy(value = t), true) } val single0 = collection.createSingle(1) { Single.just(Optional(TestEntity(1, "1"))) } var disp = single0.subscribe { assertEquals(it.value!!.id, 1) assertEquals(it.value!!.value, "3") } disp.dispose() rxObs.onNext("4") rxObs1.onNext("4") disp = single0.subscribe { assertEquals(it.value!!.id, 1) assertEquals(it.value!!.value, "4") } disp.dispose() rxObs1.onNext("5") disp = single0.subscribe { assertEquals(it.value!!.id, 1) assertEquals(it.value!!.value, "5") } disp.dispose() } @Test fun testMergeWithPaginator() { val collection = EntityObservableCollectionInt<TestEntity>(Schedulers.trampoline()) val rxObs = BehaviorSubject.createDefault("2") val rxObs1 = BehaviorSubject.createDefault("3") collection.combineLatest(rxObs) { e, t -> Pair(e.copy(value = "${e.id}$t"), true) } collection.combineLatest(rxObs1) { e, t -> Pair(e.copy(value = "${e.id}$t"), true) } val pager = collection.createPaginator(perPage = 2) { if (it.page == 0) Single.just(listOf(TestEntity(1, "1"), TestEntity(2, "1"))) else Single.just(listOf(TestEntity(3, "1"), TestEntity(4, "1"))) } var disp = pager.subscribe { assertEquals(it.size, 2) assertEquals(it[0].id, 1) assertEquals(it[0].value, "13") } disp.dispose() rxObs.onNext("4") rxObs1.onNext("4") disp = pager.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "14") } disp.dispose() rxObs1.onNext("5") disp = pager.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "15") } disp.dispose() pager.next() disp = pager.subscribe { assertEquals(it.size, 4) assertEquals(it[2].id, 3) assertEquals(it[2].value, "35") } disp.dispose() } @Test fun testArrayInitialMerge() { var i = 0 val collection = EntityObservableCollectionExtraInt<TestEntity, ExtraCollectionParams>(Schedulers.trampoline(), collectionExtra = ExtraCollectionParams(test="2")) val rxObs = BehaviorSubject.createDefault("2") val rxObs1 = BehaviorSubject.createDefault("3") collection.combineLatest(rxObs) { e, t -> Pair(e.copy(value = "${e.id}$t"), true) } collection.combineLatest(rxObs1) { e, t -> Pair(e.copy(value = "${e.id}$t"), true) } collection.arrayFetchCallback = { pp -> Single.just(listOf()) } val array = collection.createKeyArray(initial = listOf(TestEntity(1, "2"), TestEntity(2, "3"))) var disp = array.subscribe { assertEquals(it.size, 2) assertEquals(it[0].id, 1) assertEquals(it[0].value, "13") } disp.dispose() rxObs.onNext("4") rxObs1.onNext("4") disp = array.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "14") } disp.dispose() rxObs1.onNext("5") disp = array.subscribe { assertEquals(it[0].id, 1) assertEquals(it[0].value, "15") } disp.dispose() } @Test fun testCommits() { val collection = EntityObservableCollectionExtraInt<TestEntity, ExtraCollectionParams>(Schedulers.trampoline(), collectionExtra = ExtraCollectionParams(test="2")) collection.singleFetchCallback = { Single.just(Optional(null)) } collection.arrayFetchCallback = { Single.just(listOf()) } val array = collection.createKeyArray(initial = listOf(TestEntity(id = 1, value = "2"), TestEntity(id = 2, value = "3"))) val single = collection.createSingle(key = 1) collection.commit(TestEntity(id = 1, value = "12"), UpdateOperation.Update) var d = single.subscribe { assertEquals("12", it.value!!.value) } d.dispose() d = array.subscribe { assertEquals("12", it[0].value) } d.dispose() collection.commitByKey(1) { TestEntity(id = 1, value = "13") } d = single.subscribe { assertEquals("13", it.value!!.value) } d.dispose() d = array.subscribe { assertEquals("13", it[0].value) } d.dispose() collection.commitByKeys(listOf(1, 2)) { TestEntity(id = it.id, value = "${it.id}4") } d = single.subscribe { assertEquals("14", it.value!!.value) } d.dispose() d = array.subscribe { assertEquals("14", it[0].value) assertEquals("24", it[1].value) } d.dispose() } }
0
Kotlin
0
0
d100c2a1bd34c0e791df6e812f30a611b6779725
18,380
RxEntity-Kotlin
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/manageoffencesapi/config/WebClientConfiguration.kt
ministryofjustice
460,455,417
false
{"Kotlin": 359440, "Dockerfile": 1564, "Shell": 1564}
package uk.gov.justice.digital.hmpps.manageoffencesapi.config import org.springframework.beans.factory.annotation.Value import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.http.HttpHeaders import org.springframework.scheduling.annotation.EnableScheduling import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository import org.springframework.security.oauth2.client.web.reactive.function.client.ServletOAuth2AuthorizedClientExchangeFilterFunction import org.springframework.util.MultiValueMap import org.springframework.web.reactive.function.client.ClientRequest import org.springframework.web.reactive.function.client.ExchangeFilterFunction import org.springframework.web.reactive.function.client.ExchangeFunction import org.springframework.web.reactive.function.client.WebClient @Configuration @EnableScheduling class WebClientConfiguration( @Value("\${api.base.url.sdrs}") private val standingDataReferenceServiceApiUrl: String, @Value("\${api.base.url.prison.api}") private val prisonApiUrl: String, ) { @Bean fun standingDataReferenceServiceApiWebClient(builder: WebClient.Builder): WebClient { return builder.baseUrl(standingDataReferenceServiceApiUrl) .defaultHeaders { headers -> headers.addAll(createHeaders()) } .build() } @Bean fun prisonApiWebClient( builder: WebClient.Builder, authorizedClientManager: OAuth2AuthorizedClientManager, ): WebClient { val oauth2Client = ServletOAuth2AuthorizedClientExchangeFilterFunction(authorizedClientManager) oauth2Client.setDefaultClientRegistrationId("prison-api") return builder .baseUrl(prisonApiUrl) .apply(oauth2Client.oauth2Configuration()) .build() } // To be used when passing through the users token - rather than using system credentials @Bean fun prisonApiUserWebClient(builder: WebClient.Builder): WebClient { return builder .baseUrl(prisonApiUrl) .filter(addAuthHeaderFilterFunction()) .build() } private fun addAuthHeaderFilterFunction(): ExchangeFilterFunction { return ExchangeFilterFunction { request: ClientRequest, next: ExchangeFunction -> val filtered = ClientRequest.from(request) .header(HttpHeaders.AUTHORIZATION, UserContext.getAuthToken()) .build() next.exchange(filtered) } } @Bean fun authorizedClientManager( clientRegistrationRepository: ClientRegistrationRepository?, oAuth2AuthorizedClientService: OAuth2AuthorizedClientService?, ): OAuth2AuthorizedClientManager? { val authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder().clientCredentials().build() val authorizedClientManager = AuthorizedClientServiceOAuth2AuthorizedClientManager( clientRegistrationRepository, oAuth2AuthorizedClientService, ) authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider) return authorizedClientManager } private fun createHeaders(): MultiValueMap<String, String> { val headers = HttpHeaders() headers.add(HttpHeaders.CONTENT_TYPE, "application/json") headers.add(HttpHeaders.ACCEPT, "application/json") return headers } }
0
Kotlin
0
0
b34587dbb50c9bb8f5620ded403c4b2fc57eda14
3,616
hmpps-manage-offences-api
MIT License
src/source.kt
CiganOliviu
257,980,861
false
null
/* MIT License Copyright (c) 2020 <NAME> 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 org.Source class FactorialSource { fun Factorial (Number: Int) : Int { var Result = 1 if (Number == 0 || Number == 1) return Result Result = Factorial (Number - 1) * Number; return Result } } class FibonacciSource { fun Fibonacci (Number: Int) : Int { var Result = 1 if (Number == 1 || Number == 2) return Result Result = Fibonacci(Number - 1) + Fibonacci(Number - 2) return Result } } class LargestCommonDivisorSource { fun GetTheLargestCommonDivisor (LowPoint: Int, HighPoint: Int) : Int { var Result = 1 var CopyLowPoint = LowPoint var CopyHighPoint = HighPoint var rest = CopyLowPoint % CopyHighPoint while (rest != 0) { CopyLowPoint = CopyHighPoint CopyHighPoint = rest; rest = CopyLowPoint % CopyHighPoint } Result = CopyHighPoint return Result } }
0
Kotlin
0
0
8cf1cf8b2cec78dbf22c815f3709f9eecac7ff30
2,063
kotlin-tdd
MIT License
kotlin/src/1858.kt
danielcandidos
136,951,942
false
{"Kotlin": 92529}
package lista05 import java.util.Scanner fun main(args: Array<String>) { val input = Scanner(System.`in`) val qtd = input.nextInt() var min = 21 var response = 0 for (i in 1..qtd) { val x = input.nextInt() if (min > x) { min = x response = i } } println(response) }
0
Kotlin
1
6
2b5a93ba25abfa4e55f0b5841b6cdc32a2c1cda6
347
URI
MIT License
cqrs-simple-core/src/main/kotlin/com/tgirard12/cqrssimple/Middleware.kt
tgirard12
123,339,745
false
null
package com.tgirard12.cqrssimple import org.slf4j.LoggerFactory.getLogger import kotlin.reflect.KClass import kotlin.reflect.full.isSubclassOf import kotlin.reflect.jvm.jvmErasure /** * */ interface MiddlewareAction : Clazz /** * */ interface PreActionMiddleware : MiddlewareAction /** * */ interface PostActionMiddleware : MiddlewareAction /** * */ interface MiddlewareBus { fun dispatchPreAction(preAction: PreActionMiddleware): Unit fun dispatchPostAction(postAction: PostActionMiddleware): Unit } /** * */ @Suppress("AddVarianceModifier") fun interface MiddlewareHandler<M : MiddlewareAction> : Clazz { fun handle(middleware: M): Unit } /** * */ class MiddlewareBusImpl : MiddlewareBus { val logger = getLogger("MiddlewareBus") internal val preHandlers = mutableMapOf<KClass<*>, (PreActionMiddleware) -> Unit>() internal val postHandlers = mutableMapOf<KClass<*>, (PostActionMiddleware) -> Unit>() @Suppress("UNCHECKED_CAST") fun <M : MiddlewareAction> register(handler: MiddlewareHandler<M>, kClass: KClass<*>) { if (kClass.isSubclassOf(PreActionMiddleware::class)) { if (preHandlers.containsKey(kClass)) throw java.lang.IllegalArgumentException("Middleware '$kClass' have already register") else preHandlers[kClass] = { handler.handle(it as M) } } if (kClass.isSubclassOf(PostActionMiddleware::class)) { if (postHandlers.containsKey(kClass)) throw java.lang.IllegalArgumentException("Middleware '$kClass' have already register") else postHandlers[kClass] = { handler.handle(it as M) } } } inline fun <reified M : MiddlewareAction> register(handler: MiddlewareHandler<M>) = register(handler, M::class) override fun dispatchPreAction(preAction: PreActionMiddleware) { preAction::class.supertypes .forEach { type -> preHandlers[type.jvmErasure] ?.let { logger.debug("invoke middleware for ${preAction.clazzFullName}") it.invoke(preAction) } } } override fun dispatchPostAction(postAction: PostActionMiddleware) { postAction::class.supertypes .forEach { type -> postHandlers[type.jvmErasure] ?.let { logger.debug("invoke middleware for ${postAction.clazzFullName}") it.invoke(postAction) } } } }
0
Kotlin
1
1
8102d1ca6224cdcfc811bf9ffbb536db9061b533
2,619
cqrs-simple
Apache License 2.0
ImageGalleryProject/app/src/main/java/com/nicolas/imagegallery/ui/fragment/AbstractFragment.kt
nicolasjafelle
180,864,326
false
null
package com.nicolas.imagegallery.ui.fragment import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment /** * Created by nicolas on 11/8/17. */ abstract class AbstractFragment<T> : Fragment() { protected var callback: T? = null protected abstract fun getMainLayoutResId(): Int protected abstract fun createViewModel() protected abstract fun initUI(view: View) protected abstract fun setLiveDataObservers() protected abstract fun setListeners() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onAttach(context: Context?) { super.onAttach(context) try { callback = context as? T } catch (e: ClassCastException) { throw ClassCastException(context.toString() + " must implement Callback interface") } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) createViewModel() setLiveDataObservers() } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(getMainLayoutResId(), container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initUI(view) setListeners() } override fun onDetach() { super.onDetach() callback = null } }
0
Kotlin
0
0
be383c2c83fd12075f384551d2870ecf7efe64ed
1,672
ImageGalleryApp
Apache License 2.0
src/main/kotlin/hs/kr/equus/user/domain/admin/domain/repository/AdminRepository.kt
EntryDSM
687,797,765
false
{"Kotlin": 63988, "Dockerfile": 567}
package hs.kr.equus.user.domain.admin.domain.repository import hs.kr.equus.user.domain.admin.domain.Admin import org.springframework.data.jpa.repository.JpaRepository import java.util.UUID interface AdminRepository : JpaRepository<Admin, UUID> { fun findByAdminId(adminId: String): Admin? }
1
Kotlin
0
4
7fafb4ab1db9c56c1673795d5854742173704842
297
Equus-User
MIT License
charts/src/main/java/com/smassive/bitcointicker/charts/data/datasource/local/ChartLocalDatasource.kt
SmasSive
152,783,544
false
null
package com.smassive.bitcointicker.charts.data.datasource.local import com.smassive.bitcointicker.charts.data.datasource.local.model.ChartEntity import com.smassive.bitcointicker.charts.data.datasource.local.model.ChartWithValuesEntity import com.smassive.bitcointicker.charts.data.datasource.local.model.mapper.ChartWithValuesEntityMapper import com.smassive.bitcointicker.charts.data.datasource.remote.model.ChartNameDto import com.smassive.bitcointicker.core.data.exception.LocalDataExpiredException import com.smassive.bitcointicker.core.data.exception.NoDataException import com.smassive.bitcointicker.core.infrastructure.annotation.OpenClassOnDebug import io.reactivex.Flowable import javax.inject.Inject @OpenClassOnDebug class ChartLocalDatasource @Inject constructor(private val chartDao: ChartDao, private val chartValueDao: ChartValueDao, private val chartLocalDataValidator: ChartLocalDataValidator, private val chartWithValuesEntityMapper: ChartWithValuesEntityMapper) { fun getChart(chartName: String, forceLocal: Boolean): Flowable<ChartWithValuesEntity> { return chartDao.getChart(chartName) .flatMap { chartEntities -> if (chartEntities.isEmpty()) Flowable.error(NoDataException()) else { if (forceLocal || chartLocalDataValidator.isValid(chartEntities)) completeDataFromLocal(chartEntities) else Flowable.error(LocalDataExpiredException()) } } } private fun completeDataFromLocal(chartEntities: List<ChartEntity>): Flowable<ChartWithValuesEntity> { return Flowable.just(chartEntities.first()).flatMap( { chartValueDao.getChartValues(ChartNameDto.MARKET_PRICE) }, { chartEntity, chartValueEntities -> chartWithValuesEntityMapper.map(chartEntity, chartValueEntities) } ) } fun saveMarketPriceChart(chartWithValuesEntity: ChartWithValuesEntity) { chartDao.insert(chartWithValuesEntity.chart) chartValueDao.insertAll(chartWithValuesEntity.values) } }
0
Kotlin
0
2
b3a25e45ef0e4de228d868d574fa9e9ddc52b332
2,128
BitcoinTicker
Apache License 2.0
app/src/main/java/com/rohitjakhar/dsa450/ui/viewmodel/HomeViewModel.kt
rohitjakhar
363,835,738
false
null
package com.rohitjakhar.dsa450.ui.viewmodel import android.app.Application import android.util.Log import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.rohitjakhar.dsa450.model.Category import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.Types import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch class HomeViewModel(application: Application) : AndroidViewModel(application) { private var _categoryList: MutableStateFlow<List<Category>> = MutableStateFlow(emptyList()) val categoryList: StateFlow<List<Category>> get() = _categoryList private fun getAllCategory(application: Application) = viewModelScope.launch(Dispatchers.IO) { try { val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() val listType = Types.newParameterizedType(List::class.java, Category::class.java) val adapter: JsonAdapter<List<Category>> = moshi.adapter(listType) val myJson = application.assets.open("dsa450.json").bufferedReader().use { it.readText() } _categoryList.value = adapter.fromJson(myJson)!! } catch (e: Exception) { Log.d("Error", e.message.toString()) } } init { getAllCategory(application = application) } }
0
Kotlin
0
2
846855a24db0f6bdb0f58ff29e699bbe2a69f94a
1,567
DSA450
MIT License
libtailscale/src/main/kotlin/gay/pizza/tailscale/lib/LibTailscale.kt
GayPizzaSpecifications
609,766,487
false
null
package gay.pizza.tailscale.lib import com.sun.jna.Library import com.sun.jna.ptr.IntByReference interface LibTailscale : Library { fun tailscale_new(): TailscaleHandle fun tailscale_start(handle: TailscaleHandle): TailscaleError fun tailscale_up(handle: TailscaleHandle): TailscaleError fun tailscale_close(handle: TailscaleHandle): TailscaleError fun tailscale_set_dir(handle: TailscaleHandle, dir: String): TailscaleError fun tailscale_set_hostname(handle: TailscaleHandle, host: String): TailscaleError fun tailscale_set_authkey(handle: TailscaleHandle, authkey: String): TailscaleError fun tailscale_set_control_url(handle: TailscaleHandle, controlUrl: String): TailscaleError fun tailscale_set_ephemeral(handle: TailscaleHandle, ephemeral: Int): TailscaleError fun tailscale_set_logfd(handle: TailscaleHandle, fd: Int): TailscaleError fun tailscale_dial(handle: TailscaleHandle, network: String, addr: String, conn: TailscaleConnHandleOut): TailscaleError fun tailscale_listen(handle: TailscaleHandle, network: String, addr: String, listener: TailscaleListenerHandleOut): TailscaleError fun tailscale_listener_close(handle: TailscaleListenerHandle): TailscaleError fun tailscale_accept(handle: TailscaleListenerHandle, conn: TailscaleConnHandleOut): TailscaleError fun tailscale_errmsg(handle: TailscaleHandle, chars: CharArray, len: Int): Int } typealias TailscaleHandle = Int typealias TailscaleConnHandle = Int typealias TailscaleListenerHandle = Int typealias TailscaleConnHandleOut = IntByReference typealias TailscaleListenerHandleOut = IntByReference typealias TailscaleError = Int
0
Kotlin
0
2
e4eca796345d74511f839b99fff5ca21a4b93d9e
1,632
libtailscale
MIT License
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/interceptor/GlobalRateLimitQueueInterceptor.kt
christopherthielen
95,167,316
false
{"Gradle": 28, "Slim": 1, "YAML": 11, "TOML": 1, "Dockerfile": 1, "Java Properties": 4, "Shell": 6, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "Text": 2, "Markdown": 19, "Groovy": 657, "Kotlin": 93, "Java": 185, "JSON": 28, "XML": 1, "Scala": 5}
/* * Copyright 2017 Netflix, 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 com.netflix.spinnaker.orca.q.interceptor import com.netflix.spectator.api.Registry import com.netflix.spinnaker.config.TrafficShapingProperties import com.netflix.spinnaker.orca.q.InterceptorType import com.netflix.spinnaker.orca.q.Message import com.netflix.spinnaker.orca.q.TrafficShapingInterceptor import com.netflix.spinnaker.orca.q.TrafficShapingInterceptorCallback import com.netflix.spinnaker.orca.q.ratelimit.RateLimit import com.netflix.spinnaker.orca.q.ratelimit.RateLimitBackend import com.netflix.spinnaker.orca.q.ratelimit.RateLimitContext import org.slf4j.Logger import org.slf4j.LoggerFactory /** * Throttles requests globally. */ class GlobalRateLimitQueueInterceptor( private val backend: RateLimitBackend, private val registry: Registry, private val properties: TrafficShapingProperties.GlobalRateLimitingProperties ) : TrafficShapingInterceptor { private val log: Logger = LoggerFactory.getLogger(javaClass) private val throttledMessagesId = registry.createId("queue.trafficShaping.globalRateLimit.throttledMessages") override fun getName() = "globalRateLimit" override fun supports(type: InterceptorType): Boolean = type == InterceptorType.MESSAGE override fun interceptPoll(): Boolean = false override fun interceptMessage(message: Message): TrafficShapingInterceptorCallback? { val rateLimit: RateLimit try { rateLimit = backend.incrementAndGet( "globalQueue", RateLimitContext( getName(), properties.capacity, !properties.learning ) ) } catch (e: Exception) { log.error("Rate limiting backend threw exception, disabling interceptor for message", e) return null } if (rateLimit.limiting) { if (rateLimit.enforcing) { log.info("Throttling message: $message") return { queue, message, ack -> queue.push(message, rateLimit.duration) ack.invoke() registry.counter(throttledMessagesId.withTag("learning", "false")).increment() } } registry.counter(throttledMessagesId.withTag("learning", "true")).increment() log.info("Would have throttled message, but learning-mode enabled: $message") } return null } }
1
null
1
1
d3887dffe81b7a54b5e4f12f23e13166ee2226b0
2,842
orca
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/medialive/CfnInputMediaConnectFlowRequestPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.medialive import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.medialive.CfnInput /** * Settings that apply only if the input is a MediaConnect input. * * The parent of this entity is Input. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.medialive.*; * MediaConnectFlowRequestProperty mediaConnectFlowRequestProperty = * MediaConnectFlowRequestProperty.builder() * .flowArn("flowArn") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-medialive-input-mediaconnectflowrequest.html) */ @CdkDslMarker public class CfnInputMediaConnectFlowRequestPropertyDsl { private val cdkBuilder: CfnInput.MediaConnectFlowRequestProperty.Builder = CfnInput.MediaConnectFlowRequestProperty.builder() /** * @param flowArn The ARN of one or two MediaConnect flows that are the sources for this * MediaConnect input. */ public fun flowArn(flowArn: String) { cdkBuilder.flowArn(flowArn) } public fun build(): CfnInput.MediaConnectFlowRequestProperty = cdkBuilder.build() }
4
null
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
1,472
awscdk-dsl-kotlin
Apache License 2.0
core-logic/src/main/kotlin/com/laomuji666/compose/core/logic/analytics/FirebaseAnalytics.kt
laomuji666
844,336,531
false
{"Kotlin": 231998}
package com.laomuji666.compose.core.logic.analytics import android.os.Bundle import com.google.firebase.Firebase import com.google.firebase.analytics.analytics import javax.inject.Singleton @Singleton internal class FirebaseAnalytics : Analytics { override fun logEvent(name: String, bundle: Bundle?) { Firebase.analytics.logEvent(name, bundle) } }
1
Kotlin
0
95
2bed2f7dae79b7a9e42eb20a595a5e2d1a7f149b
367
Quickly-Use-Jetpack-Compose
Apache License 2.0
src/test/kotlin/g0201_0300/s0300_longest_increasing_subsequence/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4901773, "TypeScript": 50437, "Python": 3646, "Shell": 994}
package g0201_0300.s0300_longest_increasing_subsequence import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun lengthOfLIS() { assertThat(Solution().lengthOfLIS(intArrayOf(10, 9, 2, 5, 3, 7, 101, 18)), equalTo(4)) } @Test fun lengthOfLIS2() { assertThat(Solution().lengthOfLIS(intArrayOf(0, 1, 0, 3, 2, 3)), equalTo(4)) } @Test fun lengthOfLIS3() { assertThat(Solution().lengthOfLIS(intArrayOf(7, 7, 7, 7, 7, 7, 7)), equalTo(1)) } }
0
Kotlin
20
43
471d45c60f669ea1a2e103e6b4d8d54da55711df
602
LeetCode-in-Kotlin
MIT License
reaktive/src/commonMain/kotlin/com/badoo/reaktive/observable/BufferCountSkip.kt
badoo
174,194,386
false
null
package com.badoo.reaktive.observable /** * Returns an [Observable] that emits buffered [List]s of elements it collects from the source [Observable]. * The first buffer is started with the first element emitted by the source [Observable]. * Every subsequent buffer is started every [skip] elements, making overlapping buffers possible. * Buffers are emitted once the size reaches [count] elements. * * Please refer to the corresponding RxJava [document](http://reactivex.io/RxJava/javadoc/io/reactivex/Observable.html#buffer-int-int-). */ fun <T> Observable<T>.buffer(count: Int, skip: Int = count): Observable<List<T>> = window(count = count.toLong(), skip = skip.toLong()) .flatMapSingle { it.toList() }
8
Kotlin
49
956
c712c70be2493956e7057f0f30199994571b3670
726
Reaktive
Apache License 2.0
rest/src/main/kotlin/builder/automoderation/AutoModerationActionBuilder.kt
kordlib
202,856,399
false
null
package dev.kord.rest.builder.automoderation import dev.kord.common.annotation.KordDsl import dev.kord.common.entity.AutoModerationActionType import dev.kord.common.entity.AutoModerationActionType.* import dev.kord.common.entity.DiscordAutoModerationAction import dev.kord.common.entity.DiscordAutoModerationActionMetadata import dev.kord.common.entity.Snowflake import dev.kord.common.entity.optional.Optional import dev.kord.common.entity.optional.optional import dev.kord.common.entity.optional.optionalSnowflake import dev.kord.rest.builder.RequestBuilder import kotlin.time.Duration /** * A [RequestBuilder] for building [actions][DiscordAutoModerationAction] which will execute whenever a * [rule][AutoModerationRuleBuilder] is triggered. */ @KordDsl public sealed class AutoModerationActionBuilder : RequestBuilder<DiscordAutoModerationAction> { /** The type of action. */ public abstract val type: AutoModerationActionType protected open fun buildMetadata(): Optional<DiscordAutoModerationActionMetadata> = Optional.Missing() final override fun toRequest(): DiscordAutoModerationAction = DiscordAutoModerationAction( type = type, metadata = buildMetadata(), ) } /** An [AutoModerationActionBuilder] for building actions with type [BlockMessage]. */ @Suppress("CanSealedSubClassBeObject") // keep it as a class in case we want to add more in the future @KordDsl public class BlockMessageAutoModerationActionBuilder : AutoModerationActionBuilder() { override val type: BlockMessage get() = BlockMessage } /** An [AutoModerationActionBuilder] for building actions with type [SendAlertMessage]. */ @KordDsl public class SendAlertMessageAutoModerationActionBuilder( /** The ID of the channel to which user content should be logged. */ public var channelId: Snowflake, ) : AutoModerationActionBuilder() { override val type: SendAlertMessage get() = SendAlertMessage override fun buildMetadata(): Optional.Value<DiscordAutoModerationActionMetadata> = DiscordAutoModerationActionMetadata(channelId = channelId.optionalSnowflake()).optional() } /** An [AutoModerationActionBuilder] for building actions with type [Timeout]. */ @KordDsl public class TimeoutAutoModerationActionBuilder( /** The timeout duration (maximum of 2419200 seconds (4 weeks)). */ public var duration: Duration, ) : AutoModerationActionBuilder() { override val type: Timeout get() = Timeout override fun buildMetadata(): Optional.Value<DiscordAutoModerationActionMetadata> = DiscordAutoModerationActionMetadata(durationSeconds = duration.optional()).optional() }
54
Kotlin
63
649
ca0462dec1628ed60a7455b97a07a4939965fa83
2,637
kord
MIT License
domain/src/main/kotlin/com/duj/example/cleankt/domain/usecase/ICreateParkingLotUseCase.kt
CorreiaEduardo
415,375,934
false
{"Kotlin": 24682}
package com.duj.example.cleankt.domain.usecase import com.duj.example.cleankt.domain.entity.ParkingLot import com.duj.example.cleankt.domain.stereotype.validation.SelfValidating import java.time.LocalTime import javax.validation.constraints.NotNull interface ICreateParkingLotUseCase { fun execute(parkingLot: ParkingLotDTO): ParkingLot class ParkingLotDTO( @NotNull val capacity: Int, @NotNull val openingTime: LocalTime, @NotNull val closingTime: LocalTime, ) : SelfValidating<ParkingLotDTO>() { fun toDomain() = ParkingLot(null, capacity, openingTime, closingTime, emptyList()) } }
0
Kotlin
0
0
d3b8b989919517501fd1fa19c8a9807d95bbd8b1
636
ex-clean-spring-kt
MIT License
spring-app/src/main/kotlin/pl/starchasers/up/security/IsAdmin.kt
Starchasers
255,645,145
false
null
package pl.starchasers.up.security import org.springframework.security.access.annotation.Secured @Target(AnnotationTarget.FUNCTION) @Retention(AnnotationRetention.RUNTIME) @Secured("ROLE_ADMIN") annotation class IsAdmin
26
Kotlin
0
9
90759d835f3be8fbcb9403dd20ca0e13f18bcfbc
222
up
MIT License
features/sample/src/commonMain/kotlin/io/github/gmvalentino8/features/sample/contract/SampleResult.kt
wasabi-muffin
457,416,965
false
{"Kotlin": 55509}
package io.github.gmvalentino8.features.sample.contract import io.github.gmvalentino8.cyklone.contract.ProcessEventResult import io.github.gmvalentino8.cyklone.contract.Result import io.github.gmvalentino8.cyklone.contract.SendEventResult import io.github.gmvalentino8.domain.core.DomainError import io.github.gmvalentino8.domain.entities.User sealed class SampleResult : Result{ object Loading : SampleResult() data class GetUsersSuccess(val users: List<User>) : SampleResult() data class GetUsersError(val error: DomainError) : SampleResult() data class SendEvent(override val event: SampleEvent) : SampleResult(), SendEventResult<SampleEvent> data class ProcessEvent(override val event: SampleEvent) : SampleResult(), ProcessEventResult<SampleEvent> }
1
Kotlin
0
0
56f14f334670e691775f4028c97b3e76d947fb3a
777
Cyclone-Modular-Template-KMM
MIT License
app/src/main/java/com/binkos/starlypancacke/app/ui/auth/signin/SignInFragmentScreen.kt
binkos
314,630,978
false
null
package com.binkos.starlypancacke.app.ui.auth.signin import com.github.terrakok.cicerone.androidx.FragmentScreen class SignInFragmentScreen : FragmentScreen(fragmentCreator = { SignInFragment.getNewInstance() })
0
Kotlin
0
0
c4ac85cd86c1e8e8132b62769962f509ec506b50
213
starly-pancake
Apache License 2.0
sirius-hub/src/main/kotlin/org/starcoin/sirius/hub/Hub.kt
westarlabs
174,323,114
false
null
package org.starcoin.sirius.hub import kotlinx.coroutines.channels.ReceiveChannel import org.starcoin.sirius.core.* import java.util.* interface Hub { var hubMaliciousFlag: EnumSet<HubService.HubMaliciousFlag> val stateRoot: AMTreeNode val hubInfo: HubInfo //return previous Flags suspend fun resetHubMaliciousFlag(): EnumSet<HubService.HubMaliciousFlag> fun start() fun stop() suspend fun registerParticipant(participant: Participant, initUpdate: Update): Update suspend fun deposit(participant: Address, amount: Long) suspend fun getHubAccount(address: Address): HubAccount? suspend fun getHubAccount(eon: Int, address: Address): HubAccount? suspend fun sendNewTransfer(iou: IOU) suspend fun receiveNewTransfer(receiverIOU: IOU) suspend fun queryNewTransfer(address: Address): List<OffchainTransaction> suspend fun getProof(address: Address): AMTreeProof? suspend fun getProof(eon: Int, address: Address): AMTreeProof? fun currentEon(): Eon? suspend fun watch(address: Address): ReceiveChannel<HubEvent> { return this.watch { event -> event.isPublicEvent || event.address == address } } suspend fun watch(predicate: (HubEvent) -> Boolean): ReceiveChannel<HubEvent> }
4
Kotlin
6
15
27ccb840a5d8d3787fcef3c9914d0afd8a59ed1f
1,278
sirius
MIT License
src/main/kotlin/com/fgakk/samples/springkotlinexample/ApplicationConfiguration.kt
fgakk
244,494,621
false
null
package com.fgakk.samples.springkotlinexample import com.fgakk.samples.springkotlinexample.entity.Article import com.fgakk.samples.springkotlinexample.entity.User import com.fgakk.samples.springkotlinexample.repository.ArticleRepository import com.fgakk.samples.springkotlinexample.repository.UserRepository import com.thedeanda.lorem.Lorem import com.thedeanda.lorem.LoremIpsum import org.springframework.boot.ApplicationRunner import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class ApplicationConfiguration { @Bean fun lorem() = LoremIpsum.getInstance(); @Bean fun databaseInitializer(userRepository: UserRepository, articleRepository: ArticleRepository, lorem: Lorem) = ApplicationRunner { val fgakk = userRepository.save(User(login = "fgakk", firstName = "Fatih", lastName = "Akkaya", email = "[email protected]")) val xgamer = userRepository.save(User(login = "xgamer", firstName = "XPerson", lastName = "Gamer", email = "[email protected]")) // For each author save 50 articles for (i in 1..50) { articleRepository.save( Article( headline = lorem.getTitle(2, 4), author = fgakk, body = lorem.getParagraphs(1, 2) )) articleRepository.save( Article( headline = lorem.getTitle(2, 4), author = xgamer, body = lorem.getParagraphs(1, 2) )) } } }
0
Kotlin
0
0
4268b53644f16e40e69e959187f624ca4ffd5e10
1,711
spring-kotlin-example
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/Puppy.kt
apm-christian-dziuba
342,242,620
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge import androidx.annotation.DrawableRes data class Puppy(val name: String, val type: PuppyType, @DrawableRes val imageResourceId: Int) enum class PuppyType { CAT, DOG, UNKNOWN }
0
Kotlin
0
0
fd3a046baf1c4390a2be4b724bb1200148da1fc7
840
android-dev-challenge-compose
Apache License 2.0