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
vector/src/main/java/im/vector/riotx/features/home/room/detail/composer/ComposerEditText.kt
michaelwechner
224,202,170
true
{"Kotlin": 3784708, "Java": 24146, "HTML": 22673, "Shell": 20887}
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package im.vector.riotx.features.home.room.detail.composer import android.content.Context import android.net.Uri import android.os.Build import android.util.AttributeSet import android.view.inputmethod.EditorInfo import android.view.inputmethod.InputConnection import androidx.appcompat.widget.AppCompatEditText import androidx.core.view.inputmethod.EditorInfoCompat import androidx.core.view.inputmethod.InputConnectionCompat class ComposerEditText @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = android.R.attr.editTextStyle) : AppCompatEditText(context, attrs, defStyleAttr) { interface Callback { fun onRichContentSelected(contentUri: Uri): Boolean } var callback: Callback? = null override fun onCreateInputConnection(editorInfo: EditorInfo): InputConnection { val ic: InputConnection = super.onCreateInputConnection(editorInfo) EditorInfoCompat.setContentMimeTypes(editorInfo, arrayOf("*/*")) val callback = InputConnectionCompat.OnCommitContentListener { inputContentInfo, flags, _ -> val lacksPermission = (flags and InputConnectionCompat.INPUT_CONTENT_GRANT_READ_URI_PERMISSION) != 0 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N_MR1 && lacksPermission) { try { inputContentInfo.requestPermission() } catch (e: Exception) { return@OnCommitContentListener false } } callback?.onRichContentSelected(inputContentInfo.contentUri) ?: false } return InputConnectionCompat.createWrapper(ic, editorInfo, callback) } }
0
null
0
0
4690754f5fafda66915a1a5dd3389b0497ac1e6c
2,405
riotX-android
Apache License 2.0
modules/wasm-binary/src/commonMain/kotlin/tree/sections/NameNodeKind.kt
wasmium
761,480,110
false
{"Kotlin": 584714, "JavaScript": 203}
package org.wasmium.wasm.binary.tree.sections public enum class NameNodeKind(public val nameNodeKindId: Int) { MODULE(0), FUNCTION(1), LOCAL(2), EXCEPTION(3), /** No NameNodeKind. */ NONE(-1), ; public companion object { public fun fromNameNodeKind(nameNodeKindId: Int): NameNodeKind = NameNodeKind.values().find { it.nameNodeKindId == nameNodeKindId } ?: NONE } }
0
Kotlin
0
3
4c474db29b638e2ad09f19ad9d90dd648fc7c776
412
wasmium-wasm-binary
Apache License 2.0
app/src/main/java/com/bookcrossing/mobile/util/adapters/BooksAdapter.kt
fobo66
96,350,722
false
null
/* * Copyright 2019 <NAME> * * 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.bookcrossing.mobile.util.adapters import android.view.LayoutInflater import android.view.ViewGroup import com.bookcrossing.mobile.R.layout import com.bookcrossing.mobile.models.Book import com.bookcrossing.mobile.util.BookCoverResolver import com.firebase.ui.database.FirebaseRecyclerAdapter import com.firebase.ui.database.FirebaseRecyclerOptions /** Adapter for books on main screen */ class BooksAdapter( private val bookCoverResolver: BookCoverResolver, options: FirebaseRecyclerOptions<Book> ) : FirebaseRecyclerAdapter<Book, BooksViewHolder>(options) { override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): BooksViewHolder { val view = LayoutInflater.from(parent.context) .inflate(layout.book_list_item_main, parent, false) return BooksViewHolder(view) } override fun onBindViewHolder( holder: BooksViewHolder, position: Int, model: Book ) { val key = getRef(position).key.orEmpty() holder.key = key holder.loadCover(bookCoverResolver.resolveCover(key)) holder.bind(model) } }
10
Kotlin
1
3
3428041869733e10d48250a935cf84ec7ab2c36d
1,701
BookcrossingMobile
Apache License 2.0
kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/specs/feature/FeatureSpecOneInstanceTest.kt
besil
234,156,653
true
{"Kotlin": 1813982, "JavaScript": 457, "HTML": 423, "Java": 153, "Shell": 125}
//package com.sksamuel.kotest.specs.feature // //import io.kotest.core.spec.IsolationMode //import io.kotest.core.spec.style.FeatureSpec //import io.kotest.shouldBe //import io.kotest.specs.FeatureSpec //import java.util.concurrent.atomic.AtomicInteger // //class FeatureSpecOneInstanceTest : FeatureSpec() { // // override fun isolationMode(): IsolationMode = IsolationMode.InstancePerTest // // val count = AtomicInteger(0) // // init { // feature("1") { // count.incrementAndGet().shouldBe(1) // scenario("1.1") { // count.incrementAndGet().shouldBe(2) // } // and("1.2") { // count.incrementAndGet().shouldBe(2) // scenario("1.2.1") { // count.incrementAndGet().shouldBe(3) // } // and("1.2.2") { // count.incrementAndGet().shouldBe(3) // scenario("1.2.2.1") { // count.incrementAndGet().shouldBe(4) // } // scenario("1.2.2.2") { // count.incrementAndGet().shouldBe(4) // } // } // } // } // feature("2") { // count.incrementAndGet().shouldBe(1) // and("2.1") { // count.incrementAndGet().shouldBe(2) // scenario("2.1.1") { // count.incrementAndGet().shouldBe(3) // } // scenario("2.1.2") { // count.incrementAndGet().shouldBe(3) // } // } // } // } //}
0
null
0
0
722ebe230b17ff12615be6dc2979d51f84f2e0bf
1,385
kotlintest
Apache License 2.0
vector/src/main/java/im/vector/app/features/home/room/list/RoomListViewState.kt
iiitomo
313,868,666
true
{"Kotlin": 7936105, "Java": 157700, "Shell": 30205, "HTML": 24199, "Python": 11382, "FreeMarker": 7721, "JavaScript": 1782}
/* * Copyright 2019 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.app.features.home.room.list import android.content.Context import android.content.SharedPreferences import androidx.annotation.StringRes import androidx.preference.PreferenceManager import com.airbnb.mvrx.Async import com.airbnb.mvrx.MvRxState import com.airbnb.mvrx.Uninitialized import im.vector.app.R import im.vector.app.features.home.RoomListDisplayMode import im.vector.app.features.home.room.ScSdkPreferences import org.matrix.android.sdk.api.session.room.members.ChangeMembershipState import org.matrix.android.sdk.api.session.room.model.Membership import org.matrix.android.sdk.api.session.room.model.RoomSummary data class RoomListViewState( val displayMode: RoomListDisplayMode, val asyncRooms: Async<List<RoomSummary>> = Uninitialized, val roomFilter: String = "", val asyncFilteredRooms: Async<RoomSummaries> = Uninitialized, val roomMembershipChanges: Map<String, ChangeMembershipState> = emptyMap(), val isInviteExpanded: Boolean = true, val isFavouriteRoomsExpanded: Boolean = true, val isDirectRoomsExpanded: Boolean = true, val isGroupRoomsExpanded: Boolean = true, val isCombinedRoomsExpanded: Boolean = true, val isLowPriorityRoomsExpanded: Boolean = true, val isServerNoticeRoomsExpanded: Boolean = true, val scSdkPreferences: ScSdkPreferences? = null ) : MvRxState { companion object { const val ROOM_LIST_ROOM_EXPANDED_LOW_PRIORITY_PREFIX = "ROOM_LIST_ROOM_EXPANDED_LOW_PRIORITY_" const val ROOM_LIST_ROOM_EXPANDED_NORMAL_PRIORITY_PREFIX = "ROOM_LIST_ROOM_EXPANDED_NORMAL_PRIORITY_" const val ROOM_LIST_ROOM_EXPANDED_FAVORITE_PREFIX = "ROOM_LIST_ROOM_EXPANDED_FAVORITE_" const val ROOM_LIST_ROOM_EXPANDED_DIRECT_PREFIX = "ROOM_LIST_ROOM_EXPANDED_DIRECT_" const val ROOM_LIST_ROOM_EXPANDED_GROUP_PREFIX = "ROOM_LIST_ROOM_EXPANDED_GROUP_" const val ROOM_LIST_ROOM_EXPANDED_SERVER_NOTICE_PREFIX = "ROOM_LIST_ROOM_EXPANDED_SERVER_NOTICE_" } constructor(args: RoomListParams) : this(displayMode = args.displayMode) private fun getSharedPreferences(context: Context): SharedPreferences { return PreferenceManager.getDefaultSharedPreferences(context) } private fun getRoomListExpandedPref(prefix: String, displayMode: RoomListDisplayMode): String { return prefix + displayMode.toString() } // SC addition fun initWithContext(context: Context, displayMode: RoomListDisplayMode): RoomListViewState { val sp = getSharedPreferences(context) val prefLowPrio = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_LOW_PRIORITY_PREFIX, displayMode) val prefNormalPrio = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_NORMAL_PRIORITY_PREFIX, displayMode) val prefFavourite = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_FAVORITE_PREFIX, displayMode) val prefDirect = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_DIRECT_PREFIX, displayMode) val prefGroup = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_GROUP_PREFIX, displayMode) val prefServerNotice = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_SERVER_NOTICE_PREFIX, displayMode) val scSdkPreferences = ScSdkPreferences(context) return copy(isLowPriorityRoomsExpanded = sp.getBoolean(prefLowPrio, isLowPriorityRoomsExpanded), isCombinedRoomsExpanded = sp.getBoolean(prefNormalPrio, isCombinedRoomsExpanded), isFavouriteRoomsExpanded = sp.getBoolean(prefFavourite, isFavouriteRoomsExpanded), isDirectRoomsExpanded = sp.getBoolean(prefDirect, isDirectRoomsExpanded), isGroupRoomsExpanded = sp.getBoolean(prefGroup, isGroupRoomsExpanded), isServerNoticeRoomsExpanded = sp.getBoolean(prefServerNotice, isServerNoticeRoomsExpanded), scSdkPreferences = scSdkPreferences) } // SC addition fun persistWithContext(context: Context, displayMode: RoomListDisplayMode) { val sp = getSharedPreferences(context) val prefLowPrio = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_LOW_PRIORITY_PREFIX, displayMode) val prefNormalPrio = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_NORMAL_PRIORITY_PREFIX, displayMode) val prefFavourite = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_FAVORITE_PREFIX, displayMode) val prefDirect = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_DIRECT_PREFIX, displayMode) val prefGroup = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_GROUP_PREFIX, displayMode) val prefServerNotice = getRoomListExpandedPref(ROOM_LIST_ROOM_EXPANDED_SERVER_NOTICE_PREFIX, displayMode) sp.edit() .putBoolean(prefLowPrio, isLowPriorityRoomsExpanded) .putBoolean(prefNormalPrio, isCombinedRoomsExpanded) .putBoolean(prefFavourite, isFavouriteRoomsExpanded) .putBoolean(prefDirect, isDirectRoomsExpanded) .putBoolean(prefGroup, isGroupRoomsExpanded) .putBoolean(prefServerNotice, isServerNoticeRoomsExpanded) .apply() } fun isCategoryExpanded(roomCategory: RoomCategory): Boolean { return when (roomCategory) { RoomCategory.INVITE -> isInviteExpanded RoomCategory.FAVOURITE -> isFavouriteRoomsExpanded RoomCategory.DIRECT -> isDirectRoomsExpanded RoomCategory.GROUP -> isGroupRoomsExpanded RoomCategory.COMBINED -> isCombinedRoomsExpanded RoomCategory.LOW_PRIORITY -> isLowPriorityRoomsExpanded RoomCategory.SERVER_NOTICE -> isServerNoticeRoomsExpanded } } fun toggle(roomCategory: RoomCategory): RoomListViewState { return when (roomCategory) { RoomCategory.INVITE -> copy(isInviteExpanded = !isInviteExpanded) RoomCategory.FAVOURITE -> copy(isFavouriteRoomsExpanded = !isFavouriteRoomsExpanded) RoomCategory.DIRECT -> copy(isDirectRoomsExpanded = !isDirectRoomsExpanded) RoomCategory.GROUP -> copy(isGroupRoomsExpanded = !isGroupRoomsExpanded) RoomCategory.COMBINED -> copy(isCombinedRoomsExpanded = !isCombinedRoomsExpanded) RoomCategory.LOW_PRIORITY -> copy(isLowPriorityRoomsExpanded = !isLowPriorityRoomsExpanded) RoomCategory.SERVER_NOTICE -> copy(isServerNoticeRoomsExpanded = !isServerNoticeRoomsExpanded) } } val hasUnread: Boolean get() = asyncFilteredRooms.invoke() ?.flatMap { it.value } ?.filter { it.membership == Membership.JOIN } ?.any { it.scHasUnreadMessages(scSdkPreferences) } ?: false } typealias RoomSummaries = LinkedHashMap<RoomCategory, List<RoomSummary>> enum class RoomCategory(@StringRes val titleRes: Int) { INVITE(R.string.invitations_header), FAVOURITE(R.string.bottom_action_favourites), DIRECT(R.string.bottom_action_people_x), GROUP(R.string.bottom_action_rooms), COMBINED(R.string.normal_priority_header), LOW_PRIORITY(R.string.low_priority_header), SERVER_NOTICE(R.string.system_alerts_header) } fun RoomSummaries?.isNullOrEmpty(): Boolean { return this == null || this.values.flatten().isEmpty() }
0
Kotlin
0
0
d6bc7d02ec56e8b5f86b45f238cea50411da35da
7,984
ChatonMessenger-android
Apache License 2.0
app/src/main/java/io/alexeychurchill/dplayer/media/presentation/CoverArtPath.kt
alexeychurchill
795,201,879
false
{"Kotlin": 213307}
package io.alexeychurchill.dplayer.media.presentation sealed interface CoverArtPath { data class LocalUri(val mediaUri: String) : CoverArtPath }
0
Kotlin
1
0
b022fd85542ef05d8d06a4cac35061cc34159227
152
DPlayer
MIT License
dusseldorf-ktor-auth/src/test/kotlin/no/nav/helse/dusseldorf/ktor/auth/ClaimEnforcerTest.kt
navikt
177,815,271
false
{"Kotlin": 263645, "Shell": 4117}
package no.nav.helse.dusseldorf.ktor.auth import com.auth0.jwt.JWT import com.auth0.jwt.interfaces.Claim import java.util.* import kotlin.test.Test import kotlin.test.assertEquals class ClaimEnforcerTest { private val requiredAudience = "my-own-client" private val authorizedClients = setOf("clientA", "clientB", "clientC") private val requiredGroups = setOf("groupA","groupB","groupC") private val requiredRoles = setOf("roleA","roleB","roleC") private val enforcer = ClaimEnforcer(oneOf = setOf( setOf( StandardClaimRules.Companion.EnforceAudienceEquals(requiredAudience), AzureClaimRules.Companion.EnforceAuthorizedClient(authorizedClients), AzureClaimRules.Companion.EnforceCertificateClientAuthentication(), AzureClaimRules.Companion.EnforceInAllGroups(requiredGroups), AzureClaimRules.Companion.EnforceHasAllRoles(requiredRoles) ) )) @Test(expected = IllegalStateException::class) fun `Azure Token uten Versjon claim feiler`() { val claims = getClaims("{}") getOutcomes(enforcer, claims) } @Test(expected = IllegalStateException::class) fun `Azure token med ugyldig versjon feiler`() { val claims = getClaims("""{ "ver" : "3.0" }""".trimIndent()) getOutcomes(enforcer, claims) } @Test fun `Azure token 1_0 uten påkrevde claims feiler`() { val claims = getClaims("""{ "ver" : "1.0" }""".trimIndent()) val outcomes = getOutcomes(enforcer, claims).first() val failure = outcomes.filterIsInstance<Failure>() val successful = outcomes.filterIsInstance<Successful>() assertEquals(5, failure.size) assertEquals(0, successful.size) } @Test fun `Azure token 1_0 med riktige claims, men ikke medlem av riktige grupper`() { val claims = getClaims("""{ "ver" : "1.0", "aud": "$requiredAudience", "appid": "clientA", "appidacr": "2", "roles": ["roleA","roleB","roleC"], "groups": ["feilgruppeA", "feilgruppeB"] }""".trimIndent()) val outcomes = getOutcomes(enforcer, claims).first() val failure = outcomes.filterIsInstance<Failure>() val successful = outcomes.filterIsInstance<Successful>() assertEquals(1, failure.size) assertEquals(4, successful.size) assertEquals("groups", failure.first().claimName) assertEquals("[feilgruppeA, feilgruppeB]", failure.first().actual) assertEquals("[groupA, groupB, groupC]", failure.first().expected) } @Test fun `Azure token 1_0 med riktige claims`() { val claims = getClaims("""{ "ver" : "1.0", "aud": "$requiredAudience", "appid": "clientA", "appidacr": "2", "roles": ["roleA","roleB","roleC"], "groups": ["groupA", "groupB", "groupC"] }""".trimIndent()) val outcomes = getOutcomes(enforcer, claims).first() val failure = outcomes.filterIsInstance<Failure>() val successful = outcomes.filterIsInstance<Successful>() assertEquals(0, failure.size) assertEquals(5, successful.size) } @Test fun `Azure token 2_0 med riktige claims 1_0 claims`() { val claims = getClaims("""{ "ver" : "2.0", "aud": "$requiredAudience", "appid": "clientA", "appidacr": "2", "roles": ["roleA","roleB","roleC"], "groups": ["groupA", "groupB", "groupC"] }""".trimIndent()) val outcomes = getOutcomes(enforcer, claims).first() val failure = outcomes.filterIsInstance<Failure>() val successful = outcomes.filterIsInstance<Successful>() assertEquals(2, failure.size) assertEquals(3, successful.size) } @Test fun `Azure token 2_0 med riktige claims`() { val claims = getClaims("""{ "ver" : "2.0", "aud": "$requiredAudience", "azp": "clientA", "azpacr": "2", "roles": ["roleA","roleB","roleC"], "groups": ["groupA", "groupB", "groupC"] }""".trimIndent()) val outcomes = getOutcomes(enforcer, claims).first() val failure = outcomes.filterIsInstance<Failure>() val successful = outcomes.filterIsInstance<Successful>() assertEquals(0, failure.size) assertEquals(5, successful.size) } @Test fun `Azure token med scope håndteres riktig`() { val medAlle = getClaims("""{"scp":"en to tre"}""".trimIndent()) val manglerEn = getClaims("""{"scp":"en to"}""".trimIndent()) val uten = getClaims("{}") val tom = getClaims("""{"scp":""}""".trimIndent()) val scopeEnforcer = ClaimEnforcer(oneOf = setOf(setOf(AzureClaimRules.Companion.EnforceHasAllScopes(setOf("en", "to", "tre"))))) assertOutcome(getOutcomes(scopeEnforcer, medAlle).first(), 1, 0) assertOutcome(getOutcomes(scopeEnforcer, manglerEn).first(), 0, 1) assertOutcome(getOutcomes(scopeEnforcer, uten).first(), 0, 1) assertOutcome(getOutcomes(scopeEnforcer, tom).first(), 0, 1) } private fun assertOutcome(outcomes: Set<EnforcementOutcome>, expectedSuccess: Int, expectedFailure: Int) { val successful = outcomes.filterIsInstance<Successful>() val failure = outcomes.filterIsInstance<Failure>() assertEquals(expectedSuccess, successful.size) assertEquals(expectedFailure, failure.size) } private fun getOutcomes( enforcer: ClaimEnforcer, claims: Map<String, Claim> ) : Set<Set<EnforcementOutcome>> { return try { setOf(enforcer.enforce(claims)) } catch (cause: ClaimEnforcementFailed) { cause.outcomes } } private fun getClaims(claims : String) : Map<String, Claim> { val encodedHeaders = Base64.getEncoder().encodeToString("{}".toByteArray()) val encodedClaims = Base64.getEncoder().encodeToString(claims.toByteArray()) val encodedSignature = Base64.getEncoder().encodeToString("im-a-signature".toByteArray()) val token = "$encodedHeaders.$encodedClaims.$encodedSignature" return JWT.decode(token).claims } }
2
Kotlin
2
3
b3c6cac00002940aa3f670a13facb7cc339dbdf6
6,425
dusseldorf-ktor
MIT License
app/src/main/java/com/goodweather/android/util/String.kt
freelunch2016
380,457,383
false
{"Kotlin": 26618}
package com.goodweather.android.util import android.widget.Toast import com.goodweather.android.GoodWeatherApplication fun String.toastShow(duration:Int = Toast.LENGTH_SHORT){ Toast.makeText(GoodWeatherApplication.context,this,duration).show() }
0
Kotlin
0
0
9e5336c16c90edebe5b547ba32b4e491e00db708
254
GoodWeather2
Apache License 2.0
libnavui-maps/src/main/java/com/mapbox/navigation/ui/maps/util/RoutesRenderedCallbackExtensions.kt
mapbox
87,455,763
false
{"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624}
package com.mapbox.navigation.ui.maps.util import com.mapbox.navigation.base.ExperimentalPreviewMapboxNavigationAPI import com.mapbox.navigation.ui.maps.route.line.api.DelayedRoutesRenderedCallback import com.mapbox.navigation.ui.maps.route.line.api.RoutesRenderedCallback @OptIn(ExperimentalPreviewMapboxNavigationAPI::class) internal fun RoutesRenderedCallback.toDelayedRoutesRenderedCallback(): DelayedRoutesRenderedCallback = DelayedRoutesRenderedCallback(this)
508
Kotlin
318
621
88163ae3d7e34948369d6945d5b78a72bdd68d7c
472
mapbox-navigation-android
Apache License 2.0
core-ui/src/main/kotlin/com/laomuji666/compose/core/ui/we/icons/Search.kt
laomuji666
844,336,531
false
{"Kotlin": 235984}
package com.laomuji666.compose.core.ui.we.icons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import kotlin.Suppress val WeIcons.Search: ImageVector get() { if (_Search != null) { return _Search!! } _Search = ImageVector.Builder( name = "WeIcons.Search", defaultWidth = 24.dp, defaultHeight = 24.dp, viewportWidth = 24f, viewportHeight = 24f ).apply { path( fill = SolidColor(Color(0xFF000000)), fillAlpha = 0.9f, pathFillType = PathFillType.EvenOdd ) { moveTo(15.453f, 16.401f) curveTo(14.243f, 17.4f, 12.691f, 18f, 11f, 18f) curveTo(7.134f, 18f, 4f, 14.866f, 4f, 11f) curveTo(4f, 7.134f, 7.134f, 4f, 11f, 4f) curveTo(14.866f, 4f, 18f, 7.134f, 18f, 11f) curveTo(18f, 12.743f, 17.363f, 14.336f, 16.31f, 15.561f) lineTo(20.071f, 19.322f) curveTo(20.266f, 19.517f, 20.266f, 19.834f, 20.071f, 20.029f) lineTo(19.929f, 20.171f) curveTo(19.734f, 20.366f, 19.417f, 20.366f, 19.222f, 20.171f) lineTo(15.453f, 16.401f) close() moveTo(16.8f, 11f) curveTo(16.8f, 14.203f, 14.203f, 16.8f, 11f, 16.8f) curveTo(7.797f, 16.8f, 5.2f, 14.203f, 5.2f, 11f) curveTo(5.2f, 7.797f, 7.797f, 5.2f, 11f, 5.2f) curveTo(14.203f, 5.2f, 16.8f, 7.797f, 16.8f, 11f) close() } }.build() return _Search!! } @Suppress("ObjectPropertyName") private var _Search: ImageVector? = null
1
Kotlin
0
99
55ebed2733bdbc2330f3297b74b5514fea786ba3
1,982
Quickly-Use-Jetpack-Compose
Apache License 2.0
app/src/main/java/com/brins/locksmith/ui/main/MineFragment.kt
BrinsLee
224,311,693
false
null
package com.brins.locksmith.ui.main import android.content.Context import android.view.View import androidx.lifecycle.ViewModelProvider import butterknife.OnClick import com.brins.locksmith.R import com.brins.locksmith.ui.activity.BaseActivity import com.brins.locksmith.ui.activity.MainActivity import com.brins.locksmith.ui.base.BaseFragment import com.brins.locksmith.utils.InjectorUtil import com.brins.locksmith.utils.jumpToWebActivity import com.brins.locksmith.viewmodel.card.SaveCardViewModel import com.brins.locksmith.viewmodel.save.SavePasswordViewModel class MineFragment : BaseFragment() { private lateinit var mSavePasswordViewModel: SavePasswordViewModel private lateinit var mSaveCardViewModel: SaveCardViewModel companion object { val HOW_TO_PROTECT = "file:////android_asset/how-protect.html" val PROLICY = "file:////android_asset/privacy-policy.html" } override fun onAttach(context: Context) { super.onAttach(context) mSavePasswordViewModel = (activity as MainActivity).getSavePasswordViewModel() mSaveCardViewModel = (activity as MainActivity).getSaveCardViewModel() } override fun getLayoutId(): Int { return R.layout.fragment_mine } override fun initEventAndData() { } @OnClick(R.id.how_protect_rl,R.id.prolicy_rl) fun onClick(v: View) { when (v.id) { R.id.how_protect_rl -> { jumpToWebActivity(activity as BaseActivity, HOW_TO_PROTECT) } R.id.prolicy_rl -> { jumpToWebActivity(activity as BaseActivity, PROLICY) } } } }
0
Kotlin
0
1
e1fd0e515a410c49c33c6b9e94411ae07936f1e3
1,652
Locksmith
MIT License
data/database/impl/src/main/java/com/onseok/marvelpedia/database/impl/dao/MarvelHeroDao.kt
onseok
733,347,236
false
{"Kotlin": 111071}
/* * Copyright 2023 onseok * * 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.onseok.marvelpedia.database.impl.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import com.onseok.marvelpedia.database.impl.entity.MarvelHeroEntity import kotlinx.coroutines.flow.Flow @Dao interface MarvelHeroDao { @Query("SELECT * FROM marvel_hero") fun getFavoriteMarvelHeroes(): Flow<List<MarvelHeroEntity>> @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertFavoriteMarvelHero(marvelHero: MarvelHeroEntity) @Query("DELETE FROM marvel_hero WHERE id = :marvelHeroId") suspend fun deleteFavoriteMarvelHero(marvelHeroId: Int) @Query("SELECT COUNT(id) FROM marvel_hero WHERE id = :marvelHeroId") suspend fun getCountForFavoriteMarvelHero(marvelHeroId: Int): Int suspend fun isFavoriteMarvelHero(marvelHeroId: Int): Boolean { return getCountForFavoriteMarvelHero(marvelHeroId) > 0 } @Query("SELECT COUNT(id) FROM marvel_hero") suspend fun getFavoriteMarvelHeroesCount(): Int @Query("DELETE FROM marvel_hero WHERE id IN (SELECT id FROM marvel_hero ORDER BY added_at ASC LIMIT 1)") suspend fun deleteOldestFavoriteMarvelHero() }
1
Kotlin
0
2
e2148252f5892a543f8661c1725b0f88539f0a79
1,793
Marvelpedia
Apache License 2.0
app/shared/state-machine/ui/public/src/commonTest/kotlin/build/wallet/statemachine/BodyModelMock.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.statemachine import build.wallet.analytics.events.screen.EventTrackerScreenInfo import build.wallet.statemachine.core.BodyModel /** A fake [BodyModel] for testing, identifiable by its id. */ data class BodyModelMock<PropsT : Any>( val id: String, val latestProps: PropsT, override val eventTrackerScreenInfo: EventTrackerScreenInfo? = null, ) : BodyModel()
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
386
bitkey
MIT License
src/main/kotlin/com/vicheGallery/post/ui/PostController.kt
ssamzag
561,648,517
false
null
package com.vicheGallery.post.ui import com.vicheGallery.auth.domain.AuthenticationPrincipal import com.vicheGallery.auth.domain.LoginUser import com.vicheGallery.post.dto.PostRequest import com.vicheGallery.post.application.PostService import com.vicheGallery.post.dto.PostRead import com.vicheGallery.post.dto.PostsResponse import com.vicheGallery.post.dto.UpdateRequest import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController import javax.validation.Valid @RestController @RequestMapping("/posts") class PostController( private val postService: PostService) { @PostMapping fun createPost( @RequestBody @Valid request: PostRequest, @AuthenticationPrincipal user: LoginUser ): ResponseEntity<String> { val id = postService.write(request) return ResponseEntity.ok().body("/post/${id}") } @GetMapping fun getPosts(): ResponseEntity<PostsResponse> { return ResponseEntity.ok() .body(postService.findAllDesc()) } @GetMapping("/{postId}") fun getPost(@PathVariable postId: Long): ResponseEntity<PostRead> { return ResponseEntity.ok() .body(postService.findByPostIdOrThrow(postId)) } @PutMapping("/{postId}") fun update(@AuthenticationPrincipal user: LoginUser, @PathVariable postId: Long, @RequestBody req: UpdateRequest): ResponseEntity<Any> { postService.updatePost(postId, req) return ResponseEntity.noContent().build() } @DeleteMapping("/{postId}") fun delete(@AuthenticationPrincipal user: LoginUser, @PathVariable postId: Long): ResponseEntity<Any> { postService.deletePost(postId) return ResponseEntity.noContent().build() } }
0
Kotlin
0
0
3f1b70a73ddda2b9aef9bfd9aa58010467de16d9
2,223
viche-gallery
Apache License 2.0
binary-transcoders/src/main/kotlin/com/kamelia/sprinkler/transcoder/binary/decoder/DecoderUtils.kt
Black-Kamelia
579,095,832
false
{"Kotlin": 647359, "Java": 18620}
@file:JvmName("DecoderUtils") package com.kamelia.sprinkler.transcoder.binary.decoder import com.kamelia.sprinkler.transcoder.binary.decoder.core.* import com.kamelia.sprinkler.util.ExtendedCollectors import com.kamelia.sprinkler.util.unsafeCast import com.zwendo.restrikt.annotation.HideFromJava import java.util.stream.Collector import java.util.stream.Collectors /** * Creates a decoder that maps the result of `this` decoder to another decoder. The created decoder will delegate to * `this` decoder and then apply the given [mapper] to the result to produce the next decoder. * * &nbsp; * * Here is an example of a decoder that decodes different types of numbers depending on the first byte: * * ``` * val numberDecoder = ByteDecoder().mapTo { * when (it.toInt()) { * 0 -> ByteDecoder() * 1 -> ShortDecoder() * 2 -> IntDecoder() * else -> LongDecoder() * } * } * * val result = numberDecoder.decode(byteArrayOf(1, 0, 7)).get() * // will return 7, 1st byte = 1 => next decoder will read a short which is 7 * ``` * * @receiver the decoder producing the result to be mapped * @param mapper the mapping function * @return a decoder producing a result of type [R] * @param T the type of the result of the decoder * @param R the type of the result of the returned decoder */ fun <T, R> Decoder<T>.mapTo(mapper: (T) -> Decoder<R>): Decoder<R> = object : Decoder<R> { private var nextReader: Decoder<R>? = null override fun decode(input: DecoderInput): Decoder.State<R> = if (nextReader == null) { this@mapTo.decode(input).mapState { nextReader = mapper(it) decodeNext(input) } } else { decodeNext(input) } private fun decodeNext(input: DecoderInput) = nextReader!!.decode(input).ifDone { nextReader = null } override fun reset() { this@mapTo.reset() nextReader = null } } /** * Creates a new decoder by applying the given [mapper] to the result of this decoder, to map it to a new value. The * created decoder will delegate to this decoder and then apply the given [mapper] to the result. * * &nbsp; * * Here is an example of a decoder that decodes an integer and then squares it: * * ``` * val numberDecoder = IntDecoder().mapResult { it * it } * * val result = numberDecoder.decode(byteArrayOf(0, 0, 0, 7)).get() // will return 49 * ``` * * **NOTE**: This method uses [Decoder.State.mapResult] to map the result, which means that the [mapper] will be called * only if the decoder returns a [Decoder.State.Done] state. * * &nbsp; * * @receiver the decoder producing the result to be mapped * @param mapper the mapping function * @return a decoder producing a result of type [R] * @param T the type of the result of the decoder * @param R the type of the result of the returned decoder */ fun <T, R> Decoder<T>.mapResult(mapper: (T) -> R): Decoder<R> = object : Decoder<R> { override fun decode(input: DecoderInput): Decoder.State<R> = this@mapResult.decode(input).mapResult(mapper) override fun reset() = this@mapResult.reset() } /** * Creates a new decoder by applying the given [mapper] to the result of this decoder, to map it to a new state. The * created decoder will delegate to this decoder and then apply the given [mapper] to the result. * * &nbsp; * * This method is usually preferred over [mapResult] when validation is required, as it allows the decoder to return * a [Decoder.State.Error] instead of throwing an exception. * * &nbsp; * * Here is an example of a decoder that decodes a byte and inverses it if it is non-zero: * * ``` * val numberDecoder = IntDecoder().mapState { * if (it == 0) { * Decoder.State.Error("Cannot inverse zero") * } else { * Decoder.State.Done(1 / it.toDouble()) * } * } * * val result = numberDecoder.decode(byteArrayOf(2)).get() // will return 0.5 * * val error = numberDecoder.decode(byteArrayOf(0)) // will return an error * ``` * * **NOTE**: This method uses [Decoder.State.mapState] to map the result, which means that the [mapper] will not be * called if the decoder returns an error. * * &nbsp; * * @receiver the decoder producing the result to be mapped * @param mapper the mapping function * @return a decoder producing a result of type [R] * @param T the type of the result of the decoder * @param R the type of the result of the returned decoder */ fun <T, R> Decoder<T>.mapState(mapper: (T) -> Decoder.State<R>): Decoder<R> = object : Decoder<R> { override fun decode(input: DecoderInput): Decoder.State<R> = this@mapState.decode(input).mapState(mapper) override fun reset() = this@mapState.reset() } /** * Creates a new decoder that decodes a nullable [T]. The created decoder will read first a boolean value from the input * to determine whether the value is null or not. If the value is null, the decoder will return `null`, otherwise it * will delegate to this decoder and return the result. * * @receiver the decoder decoding the non-null value * @param nullabilityDecoder the decoder decoding the nullability flag (defaults to [BooleanDecoder]) * @return a decoder decoding a nullable [T] * @param T the type of the result of the decoder */ @JvmOverloads fun <T : Any> Decoder<T>.toOptional( nullabilityDecoder: Decoder<Boolean> = BooleanDecoder(), ): Decoder<T?> { val nullDecoder = NullDecoder<T>() return nullabilityDecoder.mapTo { if (it) { this@toOptional } else { nullDecoder } } } /** * Creates a new decoder that decodes a collection of [T]s. * * &nbsp; * * The created decoder will read first the size of the * collection from the input, then it will read the specified number of elements from the input and return them as a * collection. * * @receiver the decoder decoding the elements of the collection * @param collector the collector used to create the collection * @param sizeDecoder the decoder decoding the size of the collection (defaults to the default [IntDecoder]) * @return a decoder decoding a [R] collection of [T]s * @param T the type of the elements of the collection * @param C the type of the accumulator of the collector * @param R the type of the result of the collector */ @JvmOverloads fun <T, C, R> Decoder<T>.toCollection( collector: Collector<T, C, R>, sizeDecoder: Decoder<Number> = IntDecoder(), ): Decoder<R> = PrefixedArityReductionDecoder(collector, this, sizeDecoder) /** * Creates a new decoder that decodes a collection of [T]s. * * &nbsp; * * The created decoder will read the specified number of elements from the input and return them as a collection. * * @receiver the decoder decoding the elements of the collection * @param collector the collector used to create the collection * @param size the size of the collection * @return a decoder decoding a [R] collection of [T]s * @param T the type of the elements of the collection * @param C the type of the accumulator of the collector * @param R the type of the result of the collector */ fun <T, C, R> Decoder<T>.toCollection( collector: Collector<T, C, R>, size: Int, ): Decoder<R> { require(size >= 0) { "Size must be non-negative, but was $size" } return ConstantArityReductionDecoder(collector, this, size) } /** * Creates a new decoder that decodes a collection of [T]s. * * &nbsp; * * The created decoder will read elements from the input until the specified [shouldStop] returns `true`, then it will * return the read elements as a collection. If [keepLast] is `true`, the last element will be kept in the collection. * * @receiver the decoder decoding the elements of the collection * @param collector the collector used to create the collection * @param keepLast whether the last element should be kept in the collection (defaults to `false`) * @param shouldStop the predicate used to determine whether the decoder should stop reading elements * @return a decoder decoding a [R] collection of [T]s * @param T the type of the elements of the collection * @param C the type of the accumulator of the collector * @param R the type of the result of the collector * @param shouldStop the predicate used to determine whether the decoder should stop reading elements */ @JvmOverloads fun <T, C, R> Decoder<T>.toCollection( collector: Collector<T, C, R>, keepLast: Boolean = false, shouldStop: (T) -> Boolean, ): Decoder<R> = MarkerEndedReductionDecoder(collector, this, keepLast, shouldStop) /** * Creates a new decoder that decodes a list of [T]s. * * &nbsp; * * The created decoder will read first the size of the list from the input, then it will read the specified number of * elements from the input and return them as a list. * * @receiver the decoder decoding the elements of the list * @param sizeDecoder the decoder decoding the size of the list (defaults to the default [IntDecoder]) * @return a decoder decoding a list of [T]s * @param T the type of the elements of the list * @see toCollection */ @JvmOverloads fun <T> Decoder<T>.toList(sizeDecoder: Decoder<Number> = IntDecoder()): Decoder<List<T>> = toCollection(toListCollector(), sizeDecoder) /** * Creates a new decoder that decodes a list of [T]s. * * &nbsp; * * The created decoder will read the specified number of elements from the input and return them as a list. * * @receiver the decoder decoding the elements of the list * @param size the size of the list * @return a decoder decoding a list of [T]s * @param T the type of the elements of the list * @see toCollection */ fun <T> Decoder<T>.toList(size: Int): Decoder<List<T>> { require(size >= 0) { "Size must be non-negative, but was $size" } return toCollection(toListCollector(), size) } /** * Creates a new decoder that decodes a list of [T]s. * * &nbsp; * * The created decoder will read elements from the input until the specified [shouldStop] returns `true`, then it will * return the read elements as a list. If [keepLast] is `true`, the last element will be kept in the list. * * @receiver the decoder decoding the elements of the list * @param keepLast whether the last element should be kept in the list (defaults to `false`) * @param shouldStop the predicate used to determine whether the decoder should stop reading elements * @return a decoder decoding a list of [T]s * @param T the type of the elements of the list * @see toCollection */ @JvmOverloads fun <T> Decoder<T>.toList(keepLast: Boolean = false, shouldStop: (T) -> Boolean): Decoder<List<T>> = toCollection(toListCollector(), keepLast, shouldStop) /** * Creates a new decoder that decodes a set of [T]s. * * &nbsp; * * The created decoder will read first the size of the set from the input, then it will read the specified number of * elements from the input and return them as a set. * * @receiver the decoder decoding the elements of the set * @param sizeDecoder the decoder decoding the size of the set (defaults to the default [IntDecoder]) * @return a decoder decoding a set of [T]s * @param T the type of the elements of the set * @see toCollection */ @JvmOverloads fun <T> Decoder<T>.toSet(sizeDecoder: Decoder<Number> = IntDecoder()): Decoder<Set<T>> = toCollection(toSetCollector(), sizeDecoder) /** * Creates a new decoder that decodes a set of [T]s. * * &nbsp; * * The created decoder will read the specified number of elements from the input and return them as a set. * * @receiver the decoder decoding the elements of the set * @param size the size of the set * @return a decoder decoding a set of [T]s * @param T the type of the elements of the set * @see toCollection */ fun <T> Decoder<T>.toSet(size: Int): Decoder<Set<T>> { require(size >= 0) { "Size must be non-negative, but was $size" } return toCollection(toSetCollector(), size) } /** * Creates a new decoder that decodes a set of [T]s. * * &nbsp; * * The created decoder will read elements from the input until the specified [shouldStop] returns `true`, then it will * return the read elements as a set. If [keepLast] is `true`, the last element will be kept in the set. * * @receiver the decoder decoding the elements of the set * @param keepLast whether the last element should be kept in the set (defaults to `false`) * @param shouldStop the predicate used to determine whether the decoder should stop reading elements * @return a decoder decoding a set of [T]s * @param T the type of the elements of the set * @see toCollection */ @JvmOverloads fun <T> Decoder<T>.toSet(keepLast: Boolean = false, shouldStop: (T) -> Boolean): Decoder<Set<T>> = toCollection(toSetCollector(), keepLast, shouldStop) /** * Creates a new decoder that decodes a map of [K]s to [V]s from a [Pair] decoder. * * &nbsp; * * The created decoder will read first the size of the map from the input, then it will read the specified number of * elements from the input and return them as a map. * * @receiver a [Pair] decoder decoding the keys and values of the map * @param sizeDecoder the decoder decoding the size of the map (defaults to the default [IntDecoder]) * @return a decoder decoding a map of [K]s to [V]s * @param K the type of the keys of the map * @param V the type of the values of the map * @see toCollection */ @JvmOverloads fun <K, V> Decoder<Pair<K, V>>.toMap(sizeDecoder: Decoder<Number> = IntDecoder()): Decoder<Map<K, V>> = toCollection(toMapCollector(), sizeDecoder) /** * Creates a new decoder that decodes a map of [K]s to [V]s from a [Pair] decoder. * * &nbsp; * * The created decoder will read the specified number of elements from the input and return them as a map. * * @receiver a [Pair] decoder decoding the keys and values of the map * @param size the size of the map * @return a decoder decoding a map of [K]s to [V]s * @param K the type of the keys of the map * @param V the type of the values of the map * @see toCollection */ fun <K, V> Decoder<Pair<K, V>>.toMap(size: Int): Decoder<Map<K, V>> { require(size >= 0) { "Size must be non-negative, but was $size" } return toCollection(toMapCollector(), size) } /** * Creates a new decoder that decodes a map of [K]s to [V]s from a [Pair] decoder. * * &nbsp; * * The created decoder will read elements from the input until the specified [shouldStop] returns `true`, then it will * return the read elements as a map. If [keepLast] is `true`, the last element will be kept in the map. * * @receiver a [Pair] decoder decoding the keys and values of the map * @param keepLast whether the last element should be kept in the map (defaults to `false`) * @param shouldStop the predicate used to determine whether the decoder should stop reading elements * @return a decoder decoding a map of [K]s to [V]s * @param K the type of the keys of the map * @param V the type of the values of the map * @see toCollection */ @JvmOverloads fun <K, V> Decoder<Pair<K, V>>.toMap( keepLast: Boolean = false, shouldStop: (Pair<K, V>) -> Boolean, ): Decoder<Map<K, V>> = toCollection(toMapCollector(), keepLast, shouldStop) /** * Creates a new decoder that decodes an array of [T]s. * * &nbsp; * * The created decoder will read the specified number of elements from the input and return them as an array. * * &nbsp; * * **NOTE**: most of the time the [factory] parameter can be [::arrayOfNulls][arrayOfNulls]. * * &nbsp; * * @receiver the decoder decoding the elements of the array * @param factory the factory used to create the array from the size * @param sizeDecoder the decoder decoding the size of the array (defaults to the default [IntDecoder]) * @return a decoder decoding an array of [T]s * @param T the type of the elements of the array * @see toCollection */ @JvmOverloads fun <T> Decoder<T>.toArray( factory: (Int) -> Array<T?>, sizeDecoder: Decoder<Number> = IntDecoder(), ): Decoder<Array<T>> = toCollection(ExtendedCollectors.toArray(factory), sizeDecoder) /** * Creates a new decoder that decodes an array of [T]s. * * &nbsp; * * The created decoder will read the specified number of elements from the input and return them as an array. * * &nbsp; * * **NOTE**: most of the time the [factory] parameter can be [::arrayOfNulls][arrayOfNulls]. * * &nbsp; * * @receiver the decoder decoding the elements of the array * @param factory the factory used to create the array from the size * @param size the size of the array * @return a decoder decoding an array of [T]s * @param T the type of the elements of the array * @see toCollection */ fun <T> Decoder<T>.toArray(factory: (Int) -> Array<T?>, size: Int): Decoder<Array<T>> { require(size >= 0) { "Size must be non-negative, but was $size" } return toCollection(ExtendedCollectors.toArray(factory), size) } /** * Creates a new decoder that decodes an array of [T]s. * * &nbsp; * * The created decoder will read elements from the input until the specified [shouldStop] returns `true`, then it will * return the read elements as an array. If [keepLast] is `true`, the last element will be kept in the array. * * &nbsp; * * **NOTE**: most of the time the [factory] parameter can be [::arrayOfNulls][arrayOfNulls]. * * &nbsp; * * @receiver the decoder decoding the elements of the array * @param keepLast whether the last element should be kept in the array (defaults to `false`) * @param shouldStop the predicate used to determine whether the decoder should stop reading elements * @param factory the factory used to create the array from the size * @return a decoder decoding an array of [T]s * @param T the type of the elements of the array * @see toCollection */ @JvmOverloads fun <T> Decoder<T>.toArray( factory: (Int) -> Array<T?>, keepLast: Boolean = false, shouldStop: (T) -> Boolean, ): Decoder<Array<T>> = toCollection(ExtendedCollectors.toArray(factory), keepLast, shouldStop) /** * Creates a new decoder that decodes a pair of [T]s and [U]s from two decoders. * * @receiver the decoder decoding the first element of the pair * @param other the decoder decoding the second element of the pair * @return a decoder decoding a pair of [T]s and [U]s * @param T the type of the first element of the pair * @param U the type of the second element of the pair * @see PairDecoder */ @HideFromJava infix fun <T, U> Decoder<T>.and(other: Decoder<U>): Decoder<Pair<T, U>> = PairDecoder(this, other) internal fun <T> toListCollector(): Collector<T, *, List<T>> = toList.unsafeCast() internal fun <T> toSetCollector(): Collector<T, *, Set<T>> = toSet.unsafeCast() internal fun <K, V> toMapCollector(): Collector<Pair<K, V>, *, Map<K, V>> = toMap.unsafeCast() private val toList = Collectors.toList<Any>() private val toSet = Collectors.toSet<Any>() private val toMap = ExtendedCollectors.toMap<Any, Any>()
3
Kotlin
0
6
c86847064925469383cdde0cce68572bcde1e57b
18,945
Sprinkler
MIT License
src/test/kotlin/com/intellij/aws/cloudformation/tests/InspectionsTests.kt
shalupov
15,524,636
false
null
package com.intellij.aws.cloudformation.tests import com.intellij.aws.cloudformation.inspections.JsonFormatViolationInspection import com.intellij.testFramework.InspectionFixtureTestCase class InspectionsTests : InspectionFixtureTestCase() { fun testFormatViolationInspection() { myFixture.testDataPath = TestUtil.testDataRoot.path doTest("inspections", JsonFormatViolationInspection()) } }
41
Kotlin
28
143
22a7a3aaee8784afc49b752c55da518b702fc067
405
idea-cloudformation
Apache License 2.0
android/app/src/main/kotlin/com/example/navigationcheck/MainActivity.kt
samrat19
273,435,256
false
{"Dart": 5710, "Swift": 404, "Kotlin": 132, "Objective-C": 38}
package com.example.navigationcheck import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
26556a1ef7e4b99ad5c78285c0d869a542396a93
132
navigation_with_provider
Apache License 2.0
common/sdk/profile/api/external/src/commonMain/kotlin/io/chefbook/sdk/profile/api/external/domain/usecases/SetDescriptionUseCase.kt
mephistolie
379,951,682
false
{"Kotlin": 1334117, "Ruby": 16819, "Swift": 352}
package io.chefbook.sdk.profile.api.external.domain.usecases import io.chefbook.libs.utils.result.EmptyResult interface SetDescriptionUseCase { suspend operator fun invoke(description: String?): EmptyResult }
0
Kotlin
0
12
ddaf82ee3142f30aee8920d226a8f07873cdcffe
214
chefbook-mobile
Apache License 2.0
app/src/main/kotlin/io/crypto/bitstamp/model/OpenOrderStatus.kt
jamiepg20
120,178,812
true
{"Kotlin": 133574}
package io.crypto.bitstamp.model data class OpenOrderStatus( val status: String? ) { companion object { val EMPTY = OpenOrderStatus(null) } }
0
Kotlin
0
0
0d072593f4feed5e4730c046432907d4d968423e
148
Bitcoin
Apache License 2.0
src/main/kotlin/com/example/plugins/Routing.kt
betulnecanli
591,738,048
false
null
package com.example.plugins import com.example.routes.characters import com.example.routes.root import com.example.routes.searchCharacters import io.ktor.server.routing.* import io.ktor.server.application.* import io.ktor.server.http.content.* fun Application.configureRouting() { routing { root() characters() searchCharacters() static("/image") { resources("/image") } } }
0
Kotlin
0
4
8166c8563f88f57fda784a0bce2f2083e7f368af
437
PowerpuffGirlsServer
Apache License 2.0
ERMSCompany/src/main/java/com/kust/erms_company/ui/complaints/ComplaintViewModel.kt
sabghat90
591,653,827
false
{"Kotlin": 583902, "HTML": 87217}
package com.kust.erms_company.ui.complaints import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.kust.erms_company.data.repositroy.ComplaintRepository import com.kust.ermslibrary.models.Complaint import com.kust.ermslibrary.models.ComplaintHistory import com.kust.ermslibrary.utils.UiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ComplaintViewModel @Inject constructor( private val complaintRepository: ComplaintRepository ) : ViewModel() { private val _getComplaints = MutableLiveData<UiState<List<Complaint>>>() val getComplaints: LiveData<UiState<List<Complaint>>> get() = _getComplaints private val _updateComplaint = MutableLiveData<UiState<String>>() val updateComplaint: LiveData<UiState<String>> get() = _updateComplaint private val _deleteComplaint = MutableLiveData<UiState<String>>() val deleteComplaint: LiveData<UiState<String>> get() = _deleteComplaint private val _getComplaintHistory = MutableLiveData<UiState<List<ComplaintHistory>>>() val getComplaintHistory: LiveData<UiState<List<ComplaintHistory>>> get() = _getComplaintHistory suspend fun getComplaints() { _getComplaints.value = UiState.Loading viewModelScope.launch { complaintRepository.getComplaints { _getComplaints.value = it } } } suspend fun updateComplaint(complaint: Complaint, updateComplaintHistory: ComplaintHistory) { _updateComplaint.value = UiState.Loading viewModelScope.launch { complaintRepository.updateComplaint(complaint, updateComplaintHistory) { _updateComplaint.value = it } } } suspend fun deleteComplaint(complaint: Complaint) { _deleteComplaint.value = UiState.Loading viewModelScope.launch { complaintRepository.deleteComplaint(complaint) { _deleteComplaint.value = it } } } suspend fun getComplaintHistory(id: String) { _getComplaintHistory.value = UiState.Loading viewModelScope.launch { complaintRepository.getComplaintHistory(id) { _getComplaintHistory.value = it } } } }
1
Kotlin
0
2
56497f553ddcbbe2bdbafb987caa40cb44d552e8
2,446
ERMS
MIT License
ui/src/main/java/com/pyamsoft/tetherfi/ui/Alpha.kt
pyamsoft
475,225,784
false
{"Kotlin": 933742, "Shell": 2212}
/* * Copyright 2024 pyamsoft * * 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.pyamsoft.tetherfi.ui import androidx.annotation.CheckResult import com.pyamsoft.pydroid.ui.defaults.TypographyDefaults @CheckResult fun surfaceAlpha(isEnabled: Boolean): Float { return if (isEnabled) 1F else 0.75F } @CheckResult fun textAlpha(isEnabled: Boolean): Float { return if (isEnabled) 1F else TypographyDefaults.ALPHA_DISABLED }
10
Kotlin
31
401
aebdfc88e59a967d2c343d68d5dccb49dfa4ac06
951
tetherfi
Apache License 2.0
src/test/kotlin/nl/joerihofman/avroexample/GenericMapperTest.kt
joerihofman
176,556,036
false
null
package nl.joerihofman.avroexample import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import java.time.LocalDate import java.util.* @TestInstance(TestInstance.Lifecycle.PER_CLASS) object GenericMapperTest { private lateinit var mapper: GenericMapper @BeforeAll fun setUp() { mapper = GenericMapper } @Test fun byteArrayExample() { val person = getCompletePerson() val byteArray = mapper.recordToByteArray(person) println(String(byteArray)) val personReturned = mapper.byteArrayToRecord(byteArray) println(personReturned) } @Test fun jsonExample() { val person = getCompletePerson() val json = mapper.recordToJson(person) println(json) val personReturned = mapper.jsonToRecord(json) println(personReturned) } @Test fun fileExample() { val person = getCompletePerson() // mapper.recordToFileTest(person) } fun getCompletePerson(): Person { val person = Person.newBuilder() person.id = UUID.randomUUID().toString() person.firstName = "Jon" person.lastName = "Doe" person.address = "Streetname 2, 1000 AA, Amsterdam" person.dateOfBirth = LocalDate.now() person.gender = Gender.UNSPECIFIED person.favoriteBand = "ABC" val job = Job.newBuilder() job.company = "Acme" job.title = "Software Engineer" job.salary = 3500 person.job = job.build() return person.build() } fun getPersonWithoutJob(): Person { val person = Person.newBuilder() person.id = UUID.randomUUID().toString() person.firstName = "Jon" person.lastName = "Doe" person.address = "Streetname 2, 1000 AA, Amsterdam" person.dateOfBirth = LocalDate.now() person.gender = Gender.UNSPECIFIED person.favoriteBand = "ABC" return person.build() } fun getPersonWithoutJobAndBand(): Person { val person = Person.newBuilder() person.id = UUID.randomUUID().toString() person.firstName = "Jon" person.lastName = "Doe" person.address = "Streetname 2, 1000 AA, Amsterdam" person.dateOfBirth = LocalDate.now() person.gender = Gender.UNSPECIFIED return person.build() } fun getInvalidPersonFirstNameMissing(): Person { val person = Person.newBuilder() person.id = UUID.randomUUID().toString() person.lastName = "Doe" person.address = "Streetname 2, 1000 AA, Amsterdam" person.dateOfBirth = LocalDate.now() person.gender = Gender.UNSPECIFIED person.favoriteBand = "ABC" return person.build() } }
0
Kotlin
0
0
1166e1a36d02f2e81eba5bfcbb5f8950c97cc6d7
2,821
avroExample
The Unlicense
src/commonMain/kotlin/net/notjustanna/lin/parser/parselets/value/ParenthesisParser.kt
annathelibri
280,314,655
false
{"Kotlin": 323273}
package net.notjustanna.lin.parser.parselets.value import net.notjustanna.lin.ast.node.Expr import net.notjustanna.lin.ast.node.InvalidNode import net.notjustanna.lin.ast.node.Node import net.notjustanna.lin.lexer.TokenType import net.notjustanna.tartar.api.grammar.PrefixParselet import net.notjustanna.tartar.api.parser.ParserContext import net.notjustanna.tartar.api.parser.SyntaxException import net.notjustanna.tartar.api.parser.Token public object ParenthesisParser : PrefixParselet<TokenType, Token<TokenType>, Node> { override fun parse(ctx: ParserContext<TokenType, Token<TokenType>, Node>, token: Token<TokenType>): Node { val node = ctx.parseExpression() if (node !is Expr) { return InvalidNode { section(token.section) child(node) error(SyntaxException("Expected an expression", node.section)) } } ctx.eat(TokenType.R_PAREN) return node } }
17
Kotlin
0
7
9178bacb49385bdbbbebceb54d757ecf96b37705
975
Lin
MIT License
model/src/main/kotlin/org/digma/intellij/plugin/model/rest/event/CodeObjectEventType.kt
digma-ai
472,408,329
false
null
package org.digma.intellij.plugin.model.rest.event enum class CodeObjectEventType { Unmapped, DurationChangeEvent, FirstImportantInsight, }
264
Kotlin
4
7
ec199eb6f3eca60536282b9fe2c9fbca3e581b45
153
digma-intellij-plugin
MIT License
src/main/kotlin/com/steven/model/dto/PageRequest.kt
Steven0038
521,627,330
false
null
package com.steven.model.dto import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.ws.rs.DefaultValue import javax.ws.rs.QueryParam open class PageRequest { @field:[ QueryParam("page") DefaultValue("1") Min(1) Max(100)] var page: Int = 1 @field:[ QueryParam("show") DefaultValue("10") Min(1) Max(100)] var show: Int = 10 }
0
Kotlin
1
0
65d7d83eea1b341e941de6c58ba197ac4b211834
413
todo-list
Apache License 2.0
src/main/kotlin/watch/craft/scrapers/GipsyHillScraper.kt
alexsparrow
279,883,860
true
{"Kotlin": 216874, "TypeScript": 36907, "CSS": 10390, "HCL": 1516, "JavaScript": 1092, "Shell": 440}
package watch.craft.scrapers import watch.craft.Offer import watch.craft.Scraper import watch.craft.Scraper.Job.Leaf import watch.craft.Scraper.ScrapedItem import watch.craft.utils.* import java.net.URI class GipsyHillScraper : Scraper { override val jobs = forRootUrls(ROOT_URL) { root -> root .selectMultipleFrom(".product") .map { el -> val a = el.selectFrom(".woocommerce-LoopProduct-link") val rawName = a.textFrom(".woocommerce-loop-product__title") Leaf(rawName, a.hrefFrom()) { doc -> val rawSummary = doc.textFrom(".summary") val numCans = doc.maybe { selectMultipleFrom(".woosb-title-inner") } ?.map { it.extractFrom(regex = "(\\d+) ×")[1].toInt() }?.sum() ?: 1 val style = rawSummary.maybe { extract("Style: (.*) ABV")[1] } val mixed = style in listOf("Various", "Mixed") val name = rawName.replace(" \\(.*\\)$".toRegex(), "") ScrapedItem( name = name, summary = if (mixed) null else style, desc = doc.maybe { formattedTextFrom(".description") }, mixed = mixed, available = true, // TODO abv = if (mixed) null else rawSummary.maybe { abvFrom(prefix = "ABV: ", noPercent = true) }, offers = setOf( Offer( quantity = numCans, totalPrice = el.priceFrom(".woocommerce-Price-amount"), sizeMl = rawSummary.maybe { sizeMlFrom() } ) ), thumbnailUrl = a.srcFrom(".attachment-woocommerce_thumbnail") ) } } } companion object { private val ROOT_URL = URI("https://gipsyhillbrew.com") } }
0
null
0
0
7eda21a18754d0bd29e5e4ff3bbce5aacd3ff37e
1,739
craft-watch
MIT License
model/src/commonMain/kotlin/dev/stashy/symcollector/CollectSymbols.kt
stashymane
847,958,563
false
{"Kotlin": 9350}
package dev.stashy.symcollector /** * Marks an annotation as a collector for symbols. * * @property collectionName The name of the property your symbols will be placed in. * @property collectionType The fully-qualified type of your collection. * @property packageName The package your collected symbols will be placed into. * @property type The type of collection to be done. * @property property The property to collect with - only applies to `Type.MapByProperty`. * */ @Target(AnnotationTarget.ANNOTATION_CLASS) @Retention(AnnotationRetention.SOURCE) annotation class CollectSymbols( val collectionName: String = "symbols", val collectionType: String = "kotlin.reflect.KClass<*>", val packageName: String = "symbols", val type: Type = Type.List, val property: String = "" ) { enum class Type { /** * Collects all symbols to one list. */ List, /** * Collects all symbols to a map, indexed by a property. */ MapByProperty } }
0
Kotlin
0
0
d6c57ed1ceb871f863e6583481e3024ab3392752
1,033
ksp-symbol-collector
Apache License 2.0
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/TrashRestoreSolid.kt
DevSrSouza
311,134,756
false
{"Kotlin": 36719092}
package compose.icons.lineawesomeicons 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 compose.icons.LineAwesomeIcons public val LineAwesomeIcons.TrashRestoreSolid: ImageVector get() { if (_trashRestoreSolid != null) { return _trashRestoreSolid!! } _trashRestoreSolid = Builder(name = "TrashRestoreSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(14.0f, 4.0f) curveTo(13.477f, 4.0f, 12.941f, 4.183f, 12.563f, 4.563f) curveTo(12.184f, 4.94f, 12.0f, 5.477f, 12.0f, 6.0f) lineTo(12.0f, 7.0f) lineTo(5.0f, 7.0f) lineTo(5.0f, 9.0f) lineTo(6.094f, 9.0f) lineTo(8.0f, 27.094f) lineTo(8.094f, 28.0f) lineTo(23.906f, 28.0f) lineTo(24.0f, 27.094f) lineTo(25.906f, 9.0f) lineTo(27.0f, 9.0f) lineTo(27.0f, 7.0f) lineTo(20.0f, 7.0f) lineTo(20.0f, 6.0f) curveTo(20.0f, 5.477f, 19.816f, 4.942f, 19.438f, 4.563f) curveTo(19.059f, 4.185f, 18.523f, 4.0f, 18.0f, 4.0f) lineTo(14.0f, 4.0f) close() moveTo(14.0f, 6.0f) lineTo(18.0f, 6.0f) lineTo(18.0f, 7.0f) lineTo(14.0f, 7.0f) lineTo(14.0f, 6.0f) close() moveTo(8.125f, 9.0f) lineTo(23.875f, 9.0f) lineTo(22.094f, 26.0f) lineTo(9.906f, 26.0f) lineTo(8.125f, 9.0f) close() moveTo(16.0f, 12.0f) lineTo(12.0f, 16.0f) lineTo(15.0f, 16.0f) lineTo(15.0f, 23.0f) lineTo(17.0f, 23.0f) lineTo(17.0f, 16.0f) lineTo(20.0f, 16.0f) lineTo(16.0f, 12.0f) close() } } .build() return _trashRestoreSolid!! } private var _trashRestoreSolid: ImageVector? = null
17
Kotlin
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
2,869
compose-icons
MIT License
src/main/kotlin/uk/gov/justice/digital/hmpps/locationsinsideprison/jpa/repository/LocationRepository.kt
ministryofjustice
738,978,080
false
{"Kotlin": 459889, "Dockerfile": 1369}
package uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.repository import org.springframework.data.jpa.repository.JpaRepository import org.springframework.stereotype.Repository import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.Location import uk.gov.justice.digital.hmpps.locationsinsideprison.jpa.LocationType import java.util.UUID @Repository interface LocationRepository : JpaRepository<Location, UUID> { fun findAllByPrisonIdOrderByPathHierarchy(prisonId: String): List<Location> fun findOneByPrisonIdAndPathHierarchy(prisonId: String, pathHierarchy: String): Location? fun findAllByPrisonIdAndLocationTypeOrderByPathHierarchy(prisonId: String, locationType: LocationType): List<Location> }
2
Kotlin
0
1
2798f5b78a539effc3d62b2ffef03d96af714d46
724
hmpps-locations-inside-prison-api
MIT License
src/jvmMain/kotlin/topDecorationBar.kt
RM-camp-for-high-school-students
514,791,705
false
{"Kotlin": 111502}
import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp @Composable fun topDecorationBar() { MaterialTheme { Column { Spacer(modifier = Modifier.height(32.dp)) Row( modifier = Modifier.fillMaxWidth().height(120.dp).background(Color(38, 83, 179)).padding(start = 40.dp), verticalAlignment = Alignment.CenterVertically ) { Text(text = "camp-wms", color = Color.White, fontSize = 36.sp, fontFamily = HarmonyOS_Sans_SC, fontWeight = FontWeight.Medium) Spacer(modifier = Modifier.width(700.dp)) Icon( painterResource("innox_logo.svg"), contentDescription = "Innox Logo", tint = Color.White, modifier = Modifier.size(72.dp, 72.dp) ) Spacer(modifier = Modifier.width(32.dp)) } } } }
0
Kotlin
0
0
2d1acec4f6bab8d2e14e97f816a506e289112c7e
1,461
camp-wms-kotlin
MIT License
Movie App/app/src/main/java/com/example/cineaste/Adapters/MovieListAdapter.kt
bbandic1
830,579,083
false
{"Kotlin": 174133}
package com.example.cineaste.Adapters import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.cineaste.Data.Movie import com.example.cineaste.R class MovieListAdapter( private var movies: List<Movie>, private val onItemClicked: (movie: Movie) -> Unit ) : RecyclerView.Adapter<MovieListAdapter.MovieViewHolder>() { private val posterPath = "https://image.tmdb.org/t/p/w342" override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MovieViewHolder { val view = LayoutInflater .from(parent.context) .inflate(R.layout.item_movie, parent, false) return MovieViewHolder(view) } override fun getItemCount(): Int = movies.size override fun onBindViewHolder(holder: MovieViewHolder, position: Int) { holder.movieTitle.text = movies[position].title //Pronalazimo id drawable elementa na osnovu naziva zanra val context: Context = holder.movieImage.context var id: Int =context.getResources() .getIdentifier("picture1", "drawable", context.getPackageName()) holder.movieImage.setImageResource(id) holder.itemView.setOnClickListener{ onItemClicked(movies[position]) } Glide.with(context) .load(posterPath + movies[position].posterPath) .centerCrop() .placeholder(R.drawable.picture1) .error(id) .fallback(id) .into(holder.movieImage); holder.itemView.setOnClickListener{ onItemClicked(movies[position]) } } fun updateMovies(movies: List<Movie>) { this.movies = movies notifyDataSetChanged() } inner class MovieViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { val movieImage: ImageView = itemView.findViewById(R.id.movieImage) val movieTitle: TextView = itemView.findViewById(R.id.movieTitle) } }
0
Kotlin
0
0
49d050b368975f57c0d5fedd05f1eae121c88ed5
2,108
Android-Studio-Applications
MIT License
test45/src/main/java/Main.kt
ariannysOronoz
603,181,296
false
null
fun main(){ var miNumero : Int = 8 if (miNumero%2==0) { println("su numero: $miNumero es par ") }else{ println(" su numero: $miNumero no es par ") } }
0
Kotlin
0
0
a779f54a7ca7db9e377e2b911a101daaababf84c
186
tutorialKotlin
MIT License
src/main/kotlin/no/nav/tiltakspenger/mottak/serder/LocalDateTimeSerializer.kt
navikt
417,420,999
false
null
package no.nav.tiltakspenger.mottak.serder import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import java.time.LocalDateTime import java.time.ZoneId import java.time.ZonedDateTime object LocalDateTimeSerializer : KSerializer<LocalDateTime> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("LocalDateTime", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): LocalDateTime = ZonedDateTime.parse(decoder.decodeString()).withZoneSameInstant(ZoneId.of("Europe/Oslo")).toLocalDateTime() override fun serialize(encoder: Encoder, value: LocalDateTime) = encoder.encodeString(value.toString()) }
0
Kotlin
0
3
919e2ccaaec37d1da279faf68d419368946f1516
911
tiltakspenger-mottak
MIT License
libnavui-maps/src/test/java/com/mapbox/navigation/ui/maps/internal/route/line/RouteLineViewRenderRouteLineClearDataValueTest.kt
mapbox
87,455,763
false
{"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624}
package com.mapbox.navigation.ui.maps.internal.route.line import com.mapbox.navigation.testing.FieldsAreDoubledTest import com.mapbox.navigation.ui.maps.route.line.model.RouteLineClearValue import com.mapbox.navigation.ui.maps.route.line.model.RouteLineDynamicData internal class RouteLineViewRenderRouteLineClearDataValueTest : FieldsAreDoubledTest<RouteLineViewRenderRouteLineClearDataValue, RouteLineClearValue>() { override val fieldsTypesMap: Map<Class<*>, Class<*>> = mapOf( RouteLineDynamicData::class.java to RouteLineDynamicEventData::class.java, ) override fun getDoublerClass(): Class<*> { return RouteLineViewRenderRouteLineClearDataValue::class.java } override fun getOriginalClass(): Class<*> { return RouteLineClearValue::class.java } }
508
Kotlin
318
621
88163ae3d7e34948369d6945d5b78a72bdd68d7c
809
mapbox-navigation-android
Apache License 2.0
app/src/androidTest/java/testUtils/Mappers.kt
Wakamoly
331,492,101
false
null
package testUtils object Mappers{ /*fun ReminderDTO.toDomainModel(): ReminderDataItem { return ReminderDataItem( this.title, this.description, this.location, this.latitude, this.longitude, this.id ) }*/ }
0
Kotlin
0
2
bb03b30490d11d31363e38ed8b84e328c37e06fb
327
Taxidi
Apache License 2.0
solana/src/commonTest/kotlin/com/solana/serialization/AnchorDiscriminatorSerializerTests.kt
solana-mobile
719,706,022
false
{"Kotlin": 78285}
package com.solana.serialization import com.funkatronics.hash.Sha256 import com.funkatronics.kborsh.Borsh import kotlinx.serialization.Serializable import kotlinx.serialization.encodeToByteArray import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals class AnchorDiscriminatorSerializerTests { @Test fun `discriminator is first 8 bytes of identifier hash`() { // given val namespace = "test" val ixName = "testInstruction" val data = "data" val expectedDiscriminator = Sha256.hash( "$namespace:$ixName".encodeToByteArray() ).sliceArray(0..7) // when val serialized = Borsh.encodeToByteArray(AnchorInstructionSerializer(namespace, ixName), data) // then assertContentEquals(expectedDiscriminator, serialized.sliceArray(0..7)) } @Test fun `data is serialized after 8 byte identifier hash`() { // given val ixName = "testInstruction" val data = "data" val expectedEncodedData = Borsh.encodeToByteArray(data) // when val serialized = Borsh.encodeToByteArray(AnchorInstructionSerializer(ixName), data) // then assertContentEquals(expectedEncodedData, serialized.sliceArray(8 until serialized.size)) } @Test fun `serialize and deserialize data struct`() { // given @Serializable data class TestData(val name: String, val number: Int, val boolean: Boolean) val ixName = "testInstruction" val data = TestData("testName", 12345678, true) val expectedEncodedData = Borsh.encodeToByteArray(data) // when val serialized = Borsh.encodeToByteArray(AnchorInstructionSerializer(ixName), data) val deserialized: TestData = Borsh.decodeFromByteArray(AnchorInstructionSerializer(ixName), serialized) // then assertContentEquals(expectedEncodedData, serialized.sliceArray(8 until serialized.size)) assertEquals(data, deserialized) } }
2
Kotlin
1
0
e5a920560cd0584cbabf7de6199e6b29dd9ec658
2,044
web3-core
Apache License 2.0
app/src/main/java/me/ssttkkl/mrmemorizer/AppPreferences.kt
ssttkkl
437,893,611
false
{"Kotlin": 77581}
package me.ssttkkl.mrmemorizer import android.content.SharedPreferences import android.util.Log import androidx.preference.PreferenceManager import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import me.ssttkkl.mrmemorizer.ui.utils.LiveToday import java.time.LocalDate import java.time.LocalTime object AppPreferences { const val NOTIFICATION_CHANNEL_ID = "review_notification" private val pref = PreferenceManager.getDefaultSharedPreferences(MyApp.context) private const val KEY_STATISTICS_UPDATED_DATE = "statistics_updated_date" private const val KEY_TODAY_REVIEW_TIMES = "today_review_times" private const val KEY_TOTAL_REVIEW_TIMES = "total_review_times" private const val KEY_TODAY_PUNCTUALLY_REVIEW_TIMES = "today_punctually_review_times" private const val KEY_TOTAL_PUNCTUALLY_REVIEW_TIMES = "total_punctually_review_times" private var statisticsUpdatedDate: LocalDate get() = LocalDate.ofEpochDay(pref.getLong(KEY_STATISTICS_UPDATED_DATE, 0)) set(value) { pref.edit() .putLong(KEY_STATISTICS_UPDATED_DATE, value.toEpochDay()) .apply() } init { GlobalScope.launch(Dispatchers.Main) { LiveToday.observeForever { if (!statisticsUpdatedDate.isEqual(it)) { statisticsUpdatedDate = LocalDate.now() todayReviewTimes = 0 todayPunctuallyReviewTimes = 0 } } } } // 今日复习次数 var todayReviewTimes: Long get() = pref.getLong(KEY_TODAY_REVIEW_TIMES, 0) private set(value) { pref.edit() .putLong(KEY_TODAY_REVIEW_TIMES, value) .apply() } // 总共复习次数 var totalReviewTimes: Long get() = pref.getLong(KEY_TOTAL_REVIEW_TIMES, 0) private set(value) { pref.edit() .putLong(KEY_TOTAL_REVIEW_TIMES, value) .apply() } // 今日准时复习次数 var todayPunctuallyReviewTimes: Long get() = pref.getLong(KEY_TODAY_PUNCTUALLY_REVIEW_TIMES, 0) private set(value) { pref.edit() .putLong(KEY_TODAY_PUNCTUALLY_REVIEW_TIMES, value) .apply() } // 总共准时复习次数 var totalPunctuallyReviewTimes: Long get() = pref.getLong(KEY_TOTAL_PUNCTUALLY_REVIEW_TIMES, 0) private set(value) { pref.edit() .putLong(KEY_TOTAL_PUNCTUALLY_REVIEW_TIMES, value) .apply() } fun incReviewTime(punctual: Boolean) { todayReviewTimes++ totalReviewTimes++ if (punctual) { todayPunctuallyReviewTimes++ totalPunctuallyReviewTimes++ } Log.d("AppPreferences", "todayReviewTimes: $todayReviewTimes") Log.d("AppPreferences", "totalReviewTimes: $totalReviewTimes") Log.d("AppPreferences", "todayPunctuallyReviewTimes: $todayPunctuallyReviewTimes") Log.d("AppPreferences", "totalPunctuallyReviewTimes: $totalPunctuallyReviewTimes") } const val KEY_DAILY_NOTICE_ENABLED = "daily_notice_enabled" const val KEY_DAILY_NOTICE_TIME = "daily_notice_time" var dailyNoticeEnabled: Boolean get() = pref.getBoolean(KEY_DAILY_NOTICE_ENABLED, true) set(value) { pref.edit() .putBoolean(KEY_DAILY_NOTICE_ENABLED, value) .apply() } var dailyNoticeTime: LocalTime get() = LocalTime.ofSecondOfDay(pref.getInt(KEY_DAILY_NOTICE_TIME, 3600 * 20).toLong()) set(value) { pref.edit() .putInt(KEY_DAILY_NOTICE_TIME, value.toSecondOfDay()) .apply() } class OnDailyNoticeConfigChangeListener(val callback: () -> Unit) { internal val prefListener = SharedPreferences.OnSharedPreferenceChangeListener { _, key -> if (key == KEY_DAILY_NOTICE_ENABLED || key == KEY_DAILY_NOTICE_TIME) callback.invoke() } } fun registerOnDailyNoticeConfigChangeListener(listener: OnDailyNoticeConfigChangeListener) { pref.registerOnSharedPreferenceChangeListener(listener.prefListener) } }
0
Kotlin
0
2
3b2ef323465c71c5bfd214a6a71bf2c85c635882
4,294
Mr.MEMORIZER
MIT License
composeApp/src/commonMain/kotlin/eu/heha/cyclone/model/ComicPosition.kt
sihamark
614,073,078
false
{"Kotlin": 97200, "Swift": 692}
package eu.heha.cyclone.model data class ComicPosition( val chapterId: Long, val pageNumber: Long )
0
Kotlin
0
0
ae9a9ab8a11d212db7be0c0051752ba90d359661
108
ComicReader
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsintegrationapi/extensions/StringExtensionTest.kt
ministryofjustice
572,524,532
false
null
package uk.gov.justice.digital.hmpps.hmppsintegrationapi.extensions import io.kotest.core.spec.style.DescribeSpec import io.kotest.matchers.shouldBe class StringExtensionTest : DescribeSpec({ describe("#removeWhitespaceAndNewlines") { it("removes all whitespace and new lines") { """ { "never": "gonna", "give": "you", "up": null } """.removeWhitespaceAndNewlines().shouldBe("{\"never\":\"gonna\",\"give\":\"you\",\"up\":null}") } } })
2
Kotlin
1
1
e6136014e345ed405b4c969f8619056d95e1cfde
498
hmpps-integration-api
MIT License
app/src/main/java/smk/adzikro/moviezone/ui/main/home/HomeFragment.kt
al-qorut
683,978,951
false
{"Kotlin": 97687}
package smk.adzikro.moviezone.ui.main.home import android.content.Intent import android.os.Bundle import android.view.* import android.widget.ImageView import android.widget.TextView import androidx.appcompat.widget.AppCompatImageView import androidx.appcompat.widget.AppCompatRatingBar import androidx.core.app.ActivityOptionsCompat import androidx.core.util.Pair import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.paging.PagingData import androidx.recyclerview.widget.LinearLayoutManager import dagger.hilt.android.AndroidEntryPoint import smk.adzikro.moviezone.R import smk.adzikro.moviezone.core.data.source.remote.api.ApiParams.INCLUDE_ADULT import smk.adzikro.moviezone.core.data.source.remote.api.ApiParams.LANG import smk.adzikro.moviezone.core.data.source.remote.api.ApiParams.SORT_BY import smk.adzikro.moviezone.core.domain.model.Movie import smk.adzikro.moviezone.core.utils.debug import smk.adzikro.moviezone.databinding.FragmentHomeBinding import smk.adzikro.moviezone.ui.adapter.LoadingStateAdapter import smk.adzikro.moviezone.ui.adapter.MovieAdapter import smk.adzikro.moviezone.ui.detail.DetailActivity @AndroidEntryPoint class HomeFragment : Fragment(), MovieAdapter.OnItemClickCallback { private var _binding: FragmentHomeBinding? = null private val binding get() = _binding!! private val homeViewModel by viewModels<HomeViewModel>() private lateinit var movieAdapter: MovieAdapter private var path = "" override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { _binding = FragmentHomeBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) path = getString(R.string.img_path, "w500") setUpView() } private fun setUpView() { isOnLoading(true) movieAdapter = MovieAdapter(requireContext(), this) homeViewModel.getParams().observe(viewLifecycleOwner) { params -> params.let { val hashMap = HashMap<String, String>() hashMap[SORT_BY] = it.sortBy!! hashMap[INCLUDE_ADULT] = it.isAdult.toString() hashMap[LANG] = it.language!! path = getString(R.string.img_path, it.imageQuality) homeViewModel.getMovieAll(hashMap).observe(viewLifecycleOwner, movieObserver) } } binding.apply { rvHome.apply { setHasFixedSize(true) layoutManager = LinearLayoutManager(context) adapter = movieAdapter.withLoadStateFooter( footer = LoadingStateAdapter { movieAdapter.retry() }) } } } private val movieObserver = Observer<PagingData<Movie>> { isOnLoading(false) movieAdapter.submitData(lifecycle, it) } private fun isOnLoading(isLoading: Boolean) { binding.apply { shimmer.isVisible = isLoading } } override fun onDestroyView() { binding.rvHome.adapter = null super.onDestroyView() _binding = null movieAdapter.submitData(lifecycle, PagingData.empty()) } private fun isFavorite(data: Movie?) { if(data==null)return data.favorite = !data.favorite homeViewModel.favoriteMovie(data) } override fun onItemClicked( movie: Movie?, image: ImageView, desc: TextView, name: TextView, date: TextView, favo : AppCompatImageView, valueRating : AppCompatRatingBar ) { val options = ActivityOptionsCompat.makeSceneTransitionAnimation( requireActivity(), Pair(desc, "description"), Pair(image, "image"), Pair(name, "name"), Pair(date, "date"), Pair(valueRating, "rating"), Pair(favo, "favo") ) favo.setOnClickListener { debug("click favorite") isFavorite(movie) } val intent = Intent(requireActivity(), DetailActivity::class.java) intent.putExtra(DetailActivity.DETAIL, movie) startActivity(intent, options.toBundle()) } }
0
Kotlin
0
0
1057c8c290ff078d2d69a1e33317c07eea368348
4,485
MovieZone
Apache License 2.0
libs/packaging/packaging-core/src/main/kotlin/net/corda/libs/packaging/core/CpkManifest.kt
corda
346,070,752
false
{"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
package net.corda.libs.packaging.core import net.corda.data.packaging.CpkManifest as CpkManifestAvro data class CpkManifest(val cpkFormatVersion: CpkFormatVersion) { companion object { fun fromAvro(other: CpkManifestAvro) : CpkManifest = CpkManifest(CpkFormatVersion.fromAvro(other.version)) } fun toAvro(): CpkManifestAvro = CpkManifestAvro(cpkFormatVersion.toAvro()) }
11
Kotlin
27
69
d478e119ab288af663910f9a2df42a7a7b9f5bce
404
corda-runtime-os
Apache License 2.0
src/main/kotlin/dreifa/app/opentelemetry/ZipkinOpenTelemetryProvider.kt
dreifadotapp
478,598,303
false
null
package dreifa.app.opentelemetry import io.opentelemetry.api.common.Attributes import io.opentelemetry.exporter.zipkin.ZipkinSpanExporter import io.opentelemetry.sdk.OpenTelemetrySdk import io.opentelemetry.sdk.resources.Resource import io.opentelemetry.sdk.trace.SdkTracerProvider import io.opentelemetry.sdk.trace.data.SpanData import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor import io.opentelemetry.sdk.trace.export.SpanExporter import io.opentelemetry.sdk.trace.samplers.Sampler import io.opentelemetry.semconv.resource.attributes.ResourceAttributes class ZipkinOpenTelemetryProvider( memoryCacheEnabled: Boolean = false, serviceName: String = "app.dreifa", endpoint: String = "http://localhost:9411/api/v2/spans" ) : OpenTelemetryProvider { private val zipkinExporter = ZipkinSpanExporter.builder().setEndpoint(endpoint).build() private val inMemory: InMemorySpanExporter = if (memoryCacheEnabled) { InMemorySpanExporter(zipkinExporter) } else { InMemorySpanExporter(null) } private val exporter: SpanExporter = if (memoryCacheEnabled) inMemory else zipkinExporter private val propagators = MyPropagators() private val sdk: OpenTelemetrySdk = OpenTelemetrySdk.builder() .setTracerProvider( SdkTracerProvider.builder() .setResource(Resource.create(Attributes.of(ResourceAttributes.SERVICE_NAME, serviceName))) .addSpanProcessor(SimpleSpanProcessor.create(exporter)) .setSampler(Sampler.alwaysOn()) .build() ) .setPropagators(propagators) .build() override fun sdk() = sdk override fun spans(): ArrayList<SpanData> = inMemory.allSpans }
0
Kotlin
0
0
a31809cc91858259d1e48d109c3743762dca28a5
1,732
open-telemetry
MIT License
amazon/instancemetadata/client/src/main/kotlin/org/http4k/connect/amazon/instancemetadata/model/Ec2Credentials.kt
http4k
295,641,058
false
{"Kotlin": 1624429, "Handlebars": 10370, "CSS": 5434, "Shell": 3178, "JavaScript": 2076, "Python": 1834, "HTML": 675}
package org.http4k.connect.amazon.instancemetadata.model import org.http4k.aws.AwsCredentials import org.http4k.connect.amazon.core.model.AccessKeyId import org.http4k.connect.amazon.core.model.Expiration import org.http4k.connect.amazon.core.model.SecretAccessKey import org.http4k.connect.amazon.core.model.SessionToken import se.ansman.kotshi.JsonSerializable import java.time.Clock import java.time.Duration import java.time.ZonedDateTime @JsonSerializable data class Ec2Credentials( val Code: String, val LastUpdated: ZonedDateTime, val Type: String, val AccessKeyId: AccessKeyId, val SecretAccessKey: SecretAccessKey, val Token: SessionToken, val Expiration: Expiration ) { fun expiresWithin(clock: Clock, duration: Duration): Boolean = Expiration.value.toInstant() .minus(duration) .isBefore(clock.instant()) fun asHttp4k() = AwsCredentials(AccessKeyId.value, SecretAccessKey.value, Token.value) }
7
Kotlin
17
37
94e71e6bba87d9c79ac29f7ba23bdacd0fdf354c
976
http4k-connect
Apache License 2.0
myblog-jpa/src/main/kotlin/com/site/blog/service/ImgService.kt
yzqdev
394,679,800
false
{"Kotlin": 453510, "Java": 239310, "Vue": 114812, "HTML": 47519, "TypeScript": 29771, "Go": 22465, "Less": 8160, "JavaScript": 7120, "CSS": 4588, "SCSS": 979}
package com.site.blog.service import com.site.blog.model.entity.Img import org.springframework.web.multipart.MultipartFile /** * @author yanni * @date time 2021/10/29 12:46 * @modified By: */ interface ImgService { fun uploadImage(file: MultipartFile): Img fun deleteImage(fileName: String) fun createDirectory(path: String) fun getById(id: Long): Img fun removeById(id: Long) }
0
Kotlin
2
4
7f367dbe7883722bf1d650504265254d5224f69b
405
mild-blog
MIT License
src/main/kotlin/output/kanji/templates/kanji/KanjiPage.kt
Jackson-S
443,654,833
false
null
package output.kanji.templates.kanji import common.Language import kanjidic.datatypes.CharacterElement import kotlinx.html.body import kotlinx.html.dom.create import kotlinx.html.html import org.w3c.dom.Document import org.w3c.dom.Element import output.common.Page import output.kanji.templates.kanji.Definitions.definitions import output.kanji.templates.kanji.SubHeader.subheader import output.kanji.templates.kanji.Title.title class KanjiPage( document: Document, languages: List<Language>, entry: CharacterElement ) : Page { override val page: Element = document.create.html { body { title(entry) entry.readingMeaning?.forEach { readingMeaning -> subheader(readingMeaning) definitions(readingMeaning, languages) } } } }
0
Kotlin
0
0
3ce7765887d55a2701c2dbdcdd3fe82f97093fdc
829
JapaneseDictionaryRewrite
MIT License
src/main/kotlin/com/study/biddingwar/UserDto.kt
iandmyhand
385,786,113
false
null
package com.study.biddingwar data class UserDto( val name: String, val password: String )
2
Kotlin
3
2
9e3f0924aa66c885944038cbffbe88106d1f0a5e
99
bidding-war
MIT License
model-aws/src/generated/kotlin/uy/kohesive/iac/model/aws/clients/DeferredAWSElasticBeanstalk.kt
kohesive
81,814,921
false
null
package uy.kohesive.iac.model.aws.clients import com.amazonaws.services.elasticbeanstalk.AWSElasticBeanstalk import com.amazonaws.services.elasticbeanstalk.AbstractAWSElasticBeanstalk import com.amazonaws.services.elasticbeanstalk.model.* import uy.kohesive.iac.model.aws.IacContext import uy.kohesive.iac.model.aws.proxy.makeProxy open class BaseDeferredAWSElasticBeanstalk(val context: IacContext) : AbstractAWSElasticBeanstalk(), AWSElasticBeanstalk { override fun createApplication(request: CreateApplicationRequest): CreateApplicationResult { return with (context) { request.registerWithAutoName() CreateApplicationResult().withApplication( makeProxy<CreateApplicationRequest, ApplicationDescription>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateApplicationRequest::getApplicationName to ApplicationDescription::getApplicationName, CreateApplicationRequest::getDescription to ApplicationDescription::getDescription, CreateApplicationRequest::getResourceLifecycleConfig to ApplicationDescription::getResourceLifecycleConfig ) ) ).registerWithSameNameAs(request) } } override fun createApplicationVersion(request: CreateApplicationVersionRequest): CreateApplicationVersionResult { return with (context) { request.registerWithAutoName() CreateApplicationVersionResult().withApplicationVersion( makeProxy<CreateApplicationVersionRequest, ApplicationVersionDescription>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateApplicationVersionRequest::getApplicationName to ApplicationVersionDescription::getApplicationName, CreateApplicationVersionRequest::getDescription to ApplicationVersionDescription::getDescription, CreateApplicationVersionRequest::getVersionLabel to ApplicationVersionDescription::getVersionLabel, CreateApplicationVersionRequest::getSourceBuildInformation to ApplicationVersionDescription::getSourceBuildInformation, CreateApplicationVersionRequest::getSourceBundle to ApplicationVersionDescription::getSourceBundle ) ) ).registerWithSameNameAs(request) } } override fun createConfigurationTemplate(request: CreateConfigurationTemplateRequest): CreateConfigurationTemplateResult { return with (context) { request.registerWithAutoName() makeProxy<CreateConfigurationTemplateRequest, CreateConfigurationTemplateResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateConfigurationTemplateRequest::getSolutionStackName to CreateConfigurationTemplateResult::getSolutionStackName, CreateConfigurationTemplateRequest::getPlatformArn to CreateConfigurationTemplateResult::getPlatformArn, CreateConfigurationTemplateRequest::getApplicationName to CreateConfigurationTemplateResult::getApplicationName, CreateConfigurationTemplateRequest::getTemplateName to CreateConfigurationTemplateResult::getTemplateName, CreateConfigurationTemplateRequest::getDescription to CreateConfigurationTemplateResult::getDescription, CreateConfigurationTemplateRequest::getOptionSettings to CreateConfigurationTemplateResult::getOptionSettings ) ) } } override fun createEnvironment(request: CreateEnvironmentRequest): CreateEnvironmentResult { return with (context) { request.registerWithAutoName() makeProxy<CreateEnvironmentRequest, CreateEnvironmentResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request, copyFromReq = mapOf( CreateEnvironmentRequest::getEnvironmentName to CreateEnvironmentResult::getEnvironmentName, CreateEnvironmentRequest::getApplicationName to CreateEnvironmentResult::getApplicationName, CreateEnvironmentRequest::getVersionLabel to CreateEnvironmentResult::getVersionLabel, CreateEnvironmentRequest::getSolutionStackName to CreateEnvironmentResult::getSolutionStackName, CreateEnvironmentRequest::getPlatformArn to CreateEnvironmentResult::getPlatformArn, CreateEnvironmentRequest::getTemplateName to CreateEnvironmentResult::getTemplateName, CreateEnvironmentRequest::getDescription to CreateEnvironmentResult::getDescription, CreateEnvironmentRequest::getTier to CreateEnvironmentResult::getTier ) ) } } override fun createPlatformVersion(request: CreatePlatformVersionRequest): CreatePlatformVersionResult { return with (context) { request.registerWithAutoName() makeProxy<CreatePlatformVersionRequest, CreatePlatformVersionResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } override fun createStorageLocation(request: CreateStorageLocationRequest): CreateStorageLocationResult { return with (context) { request.registerWithAutoName() makeProxy<CreateStorageLocationRequest, CreateStorageLocationResult>( context = this@with, sourceName = getNameStrict(request), requestObject = request ) } } } class DeferredAWSElasticBeanstalk(context: IacContext) : BaseDeferredAWSElasticBeanstalk(context)
0
Kotlin
1
3
c52427c99384396ea60f436750932ed12aad4e6d
6,315
kohesive-iac
MIT License
server/src/main/kotlin/org/ivdnt/galahad/util/ResourceUtil.kt
INL
808,669,682
false
{"Kotlin": 407350, "Vue": 251252, "TypeScript": 81103, "Shell": 24857, "JavaScript": 2290, "Dockerfile": 2176, "HTML": 777, "XSLT": 362}
package org.ivdnt.galahad.util import java.io.InputStream fun getResourceStream(path: String): InputStream? = object {}.javaClass.classLoader.getResourceAsStream(path)
0
Kotlin
0
0
84a7fb40da99bd1b9ebada112e6958086d034b50
174
galahad
Apache License 2.0
src/main/kotlin/icu/windea/pls/core/annotations/TrickyApi.kt
DragonKnightOfBreeze
328,104,626
false
null
package icu.windea.pls.core.annotations /** * 注明了此API的实现使用了某种取巧的逻辑(例如反射)。 */ @MustBeDocumented @Retention(AnnotationRetention.SOURCE) annotation class TrickyApi
4
Kotlin
3
21
d9c2337ff189f114914d3c76431c95647721c7a5
163
Paradox-Language-Support
MIT License
shuttle/database/src/main/kotlin/shuttle/database/adapter/DateAdapter.kt
fardavide
462,194,990
false
{"Kotlin": 465845, "Shell": 11573}
package shuttle.database.adapter import com.squareup.sqldelight.ColumnAdapter import shuttle.database.model.DatabaseDate internal class DateAdapter : ColumnAdapter<DatabaseDate, Long> { override fun decode(databaseValue: Long) = DatabaseDate(databaseValue.toInt()) override fun encode(value: DatabaseDate): Long = value.dayNumber.toLong() }
12
Kotlin
1
14
375798a9ea6433839d5d34965afd0b216f82391a
353
Shuttle
Apache License 2.0
sdk/src/main/java/io/customer/sdk/queue/QueueStorage.kt
customerio
355,691,391
false
{"Kotlin": 459133, "Shell": 4485, "Makefile": 1568, "Ruby": 257}
package io.customer.sdk.queue import io.customer.base.extenstions.isOlderThan import io.customer.base.extenstions.subtract import io.customer.sdk.CustomerIOConfig import io.customer.sdk.data.store.FileStorage import io.customer.sdk.data.store.FileType import io.customer.sdk.queue.type.* import io.customer.sdk.util.DateUtil import io.customer.sdk.util.JsonAdapter import io.customer.sdk.util.Logger import io.customer.sdk.util.toSeconds import java.util.* import java.util.concurrent.TimeUnit interface QueueStorage { fun getInventory(): QueueInventory fun saveInventory(inventory: QueueInventory): Boolean fun create( type: String, data: String, groupStart: QueueTaskGroup?, blockingGroups: List<QueueTaskGroup>? ): QueueModifyResult fun update(taskStorageId: String, runResults: QueueTaskRunResults): Boolean fun get(taskStorageId: String): QueueTask? fun delete(taskStorageId: String): QueueModifyResult fun deleteExpired(): List<QueueTaskMetadata> } internal class QueueStorageImpl internal constructor( private val sdkConfig: CustomerIOConfig, private val fileStorage: FileStorage, private val jsonAdapter: JsonAdapter, private val dateUtil: DateUtil, private val logger: Logger ) : QueueStorage { @Synchronized override fun getInventory(): QueueInventory { val dataFromFile = fileStorage.get(FileType.QueueInventory()) ?: return emptyList() return jsonAdapter.fromJsonListOrNull(dataFromFile) ?: emptyList() } @Synchronized override fun saveInventory(inventory: QueueInventory): Boolean { val fileContents = jsonAdapter.toJson(inventory) return fileStorage.save(FileType.QueueInventory(), fileContents) } @Synchronized override fun create( type: String, data: String, groupStart: QueueTaskGroup?, blockingGroups: List<QueueTaskGroup>? ): QueueModifyResult { val existingInventory = getInventory().toMutableList() val beforeCreateQueueStatus = QueueStatus(sdkConfig.siteId, existingInventory.count()) val newTaskStorageId = UUID.randomUUID().toString() val newQueueTask = QueueTask(newTaskStorageId, type, data, QueueTaskRunResults(0)) if (!update(newQueueTask)) { logger.error("error trying to add new queue task to queue. $newQueueTask") return QueueModifyResult(false, beforeCreateQueueStatus) } // Update the inventory *after* a successful insert of the new task into storage. When a task is added to the inventory, it's assumed the task is available in device storage for use. val newInventoryItem = QueueTaskMetadata( newTaskStorageId, type, // Usually, we do not convert data types to a string before converting to a JSON string. We left the JSON parser to take care of the conversion for us. For groups, a String data type works good for use in the background queue. groupStart?.toString(), blockingGroups?.map { it.toString() }, dateUtil.now ) existingInventory.add(newInventoryItem) val updatedInventoryCount = existingInventory.count() val afterCreateQueueStatus = QueueStatus(sdkConfig.siteId, updatedInventoryCount) if (!saveInventory(existingInventory)) { logger.error("error trying to add new queue task to inventory. task: $newQueueTask, inventory item: $newInventoryItem") return QueueModifyResult(false, beforeCreateQueueStatus) } return QueueModifyResult(true, afterCreateQueueStatus) } @Synchronized override fun update(taskStorageId: String, runResults: QueueTaskRunResults): Boolean { var existingQueueTask = get(taskStorageId) ?: return false existingQueueTask = existingQueueTask.copy(runResults = runResults) return update(existingQueueTask) } @Synchronized override fun get(taskStorageId: String): QueueTask? { val fileContents = fileStorage.get(FileType.QueueTask(taskStorageId)) ?: return null return jsonAdapter.fromJsonOrNull(fileContents) } @Synchronized override fun delete(taskStorageId: String): QueueModifyResult { // update inventory first so if any deletion operation is unsuccessful, at least the inventory will not contain the task so queue doesn't try running it. val existingInventory = getInventory().toMutableList() val queueStatusBeforeModifyInventory = QueueStatus(sdkConfig.siteId, existingInventory.count()) existingInventory.removeAll { it.taskPersistedId == taskStorageId } if (!saveInventory(existingInventory) || !fileStorage.delete( FileType.QueueTask( taskStorageId ) ) ) { logger.error("error trying to delete task with storage id: $taskStorageId from queue") return QueueModifyResult(false, queueStatusBeforeModifyInventory) } return QueueModifyResult(true, QueueStatus(sdkConfig.siteId, existingInventory.count())) } @Synchronized override fun deleteExpired(): List<QueueTaskMetadata> { logger.debug("deleting expired tasks from the queue") val tasksToDelete: MutableSet<QueueTaskMetadata> = mutableSetOf() val queueTaskExpiredThreshold = Date().subtract( sdkConfig.backgroundQueueTaskExpiredSeconds.toSeconds().value, TimeUnit.SECONDS ) logger.debug("deleting tasks older then $queueTaskExpiredThreshold, current time is: ${Date()}") getInventory().filter { // Do not delete tasks that are at the start of a group of tasks. // Why? Take for example Identifying a profile. If we identify profile X in an app today, we expire the Identify queue task and delete the // queue task, and then profile X stays logged into an app for 6 months, that means we run the risk of 6 months of data never // successfully being sent to the API. // Also, queue tasks such as Identifying a profile are more rare queue tasks compared to tracking of events (that are not the start of a group). So, it should rarely // be a scenario when there are thousands of "expired" Identifying a profile tasks sitting in a queue. It's the queue tasks such as // tracking that are taking up a large majority of the queue inventory. Those we should be deleting more of. it.groupStart == null }.forEach { taskInventoryItem -> val isItemTooOld = taskInventoryItem.createdAt.isOlderThan(queueTaskExpiredThreshold) if (isItemTooOld) { tasksToDelete.add(taskInventoryItem) } } logger.debug("deleting ${tasksToDelete.count()} tasks. \n Tasks: $tasksToDelete") tasksToDelete.forEach { // Because the queue tasks we are deleting are not the start of a group, if deleting a task is not successful, we can ignore that // because it doesn't negatively effect the state of the SDK or the queue. this.delete(it.taskPersistedId) } return tasksToDelete.toList() } private fun update(queueTask: QueueTask): Boolean { val fileContents = jsonAdapter.toJson(queueTask) return fileStorage.save(FileType.QueueTask(queueTask.storageId), fileContents) } }
2
Kotlin
9
9
bbc770d513026e679bb17a5cd0d9d25221138f06
7,498
customerio-android
MIT License
clvr-back/platform/src/main/kotlin/com/clvr/platform/api/db/DBType.kt
spbu-math-cs
698,591,633
false
{"Kotlin": 94320, "TypeScript": 49419, "JavaScript": 8395, "Python": 8353, "CSS": 738}
package com.clvr.platform.api.db enum class DBType { JVM, EMBEDDED, REMOTE }
16
Kotlin
0
0
d5b1b910047bf60d22f628c20ebda1d329d743f5
89
ig-platform
Apache License 2.0
app/src/main/java/com/sample/application/cell/ThemeExtensions.kt
Raghuramchowdary-tech
363,732,877
false
null
package com.sample.application.cell import android.content.res.Resources import android.content.res.TypedArray import android.graphics.drawable.Drawable import androidx.annotation.AttrRes import androidx.annotation.ColorInt @ColorInt fun Resources.Theme.getColorAttr(@AttrRes attrRes: Int, default: Int = 0): Int { val a: TypedArray = obtainStyledAttributes(intArrayOf(attrRes)) val color = a.getColor(0, default) a.recycle() return color } fun Resources.Theme.getDrawableAttr(@AttrRes attrRes: Int): Drawable? { val a: TypedArray = obtainStyledAttributes(intArrayOf(attrRes)) val drawable = a.getDrawable(0) a.recycle() return drawable } fun Resources.Theme.getDimensionPixelSizeAttr(@AttrRes attrRes: Int, default: Int = 0): Int { val a: TypedArray = obtainStyledAttributes(intArrayOf(attrRes)) val dimen = a.getDimensionPixelSize(0, default) a.recycle() return dimen }
0
Kotlin
0
0
76910ece9b3e3ec8627052d20f4c0b93514bbd1e
923
Task
Apache License 2.0
sirius-wallet/src/main/kotlin/org/starcoin/sirius/wallet/core/Wallet.kt
fanngyuan
174,496,801
true
{"Kotlin": 542014, "Shell": 3030, "Dockerfile": 781}
package org.starcoin.sirius.wallet.core import kotlinx.coroutines.channels.Channel import org.starcoin.sirius.core.* import org.starcoin.sirius.protocol.Chain import org.starcoin.sirius.protocol.ChainAccount import org.starcoin.sirius.wallet.core.blockchain.BlockChain import java.math.BigInteger import kotlin.properties.Delegates class Wallet<T : ChainTransaction, A : ChainAccount> { internal var hub: Hub<T,A> by Delegates.notNull() private set internal var blockChain: BlockChain<T,A> by Delegates.notNull() private var account: A by Delegates.notNull() //TODO private var chain: Chain<T, out Block<T>, A> by Delegates.notNull() constructor(contractAddress: Address, chain: Chain<T, out Block<T>, A>, account: A ) { this.chain = chain this.account = account val contract=chain.loadContract(contractAddress) val hub = Hub(contract,account,null,chain) this.hub = hub blockChain = BlockChain(chain,hub,contract,account) val currentChainHeight=chain.getBlockNumber() val localHeight = blockChain.getLocalHeight() var startBlockHeight = hub.hubInfo.startBlockNumber if(localHeight>hub.hubInfo.startBlockNumber) startBlockHeight=localHeight val eonNumber=(currentChainHeight-localHeight.toLong())/hub.hubInfo.blocksPerEon if(eonNumber>1){ sync() startBlockHeight=BigInteger.valueOf(currentChainHeight) //hub.hubInfo.startBlockNumber+BigInteger.valueOf(hub.hubInfo.latestEon*hub.hubInfo.blocksPerEon.toLong()+1) } blockChain.startWatch=true blockChain.watachBlock(startBlockHeight) } fun deposit(value:BigInteger) = hub.deposit(value) fun balance():BigInteger = hub.getAvailableCoin() fun withdrawal(value:BigInteger)= hub.withDrawal(value) fun register():Update?= hub.register() fun openTransferChallenge(hash:Hash)= this.hub.openTransferChallenge(hash) internal fun initMessageChannel(){ hub.eonChannel = Channel(200) } internal fun getMessageChannel():Channel<ClientEventType>?{ return hub.eonChannel } fun hubTransfer(to:Address,value:BigInteger)=hub.newTransfer(to,value) internal fun hubAccount():HubAccount?=hub.accountInfo() internal fun cheat(flag:Int)= hub.cheat(flag) fun sync() = hub.sync() fun restore() = hub.restore() fun chainTransfer(to:Address,value:BigInteger)=hub.chainTransaction(to,value) suspend fun close() { blockChain.close() hub.eonChannel?.close() } }
0
Kotlin
0
0
c0f694340e1973204de355c496d11a4716fcd82a
2,615
sirius
MIT License
src/app/api/src/main/kotlin/yapp/be/apiapplication/auth/controller/model/UserSignUpRequest.kt
YAPP-Github
634,126,325
false
null
package yapp.be.apiapplication.auth.controller.model import yapp.be.apiapplication.auth.service.model.SignUpUserRequestDto import yapp.be.model.Email data class UserSignUpRequest( val nickname: String, val email: String, val phone: String, ) { fun toDto(): SignUpUserRequestDto { return SignUpUserRequestDto( email = Email(email), nickname = nickname, phone = phone, ) } }
2
Kotlin
0
3
6c5310cd9aa71b5af29f63e5c0c2db4532e57827
447
22nd-Web-Team-2-BE
Apache License 2.0
utils/StartSnapHelper/StartSnapHelper.kt
myung6024
738,118,126
false
{"Kotlin": 19351, "Java": 3591}
package com.runeanim.mytoyproject.util import android.view.View import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.OrientationHelper import androidx.recyclerview.widget.PagerSnapHelper import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.SmoothScroller.ScrollVectorProvider class StartSnapHelper : PagerSnapHelper() { private lateinit var mVerticalHelper: OrientationHelper private lateinit var mHorizontalHelper: OrientationHelper @Throws(IllegalStateException::class) override fun attachToRecyclerView(recyclerView: RecyclerView?) { super.attachToRecyclerView(recyclerView) } override fun calculateDistanceToFinalSnap( layoutManager: RecyclerView.LayoutManager, targetView: View ): IntArray { return intArrayOf( if (layoutManager.canScrollHorizontally()) distanceToStart(targetView, getHorizontalHelper(layoutManager)) else 0, if (layoutManager.canScrollVertically()) distanceToStart(targetView, getVerticalHelper(layoutManager)) else 0 ) } override fun findSnapView(layoutManager: RecyclerView.LayoutManager): View? { return if (layoutManager is LinearLayoutManager) { getStartView(layoutManager, getOrientationHelper(layoutManager)) } else { super.findSnapView(layoutManager) } } private fun distanceToStart(targetView: View, helper: OrientationHelper): Int { return helper.getDecoratedStart(targetView) - helper.startAfterPadding } private fun getStartView(layoutManager: RecyclerView.LayoutManager, helper: OrientationHelper?): View? { if (layoutManager is LinearLayoutManager) { var firstChild = layoutManager.findFirstVisibleItemPosition() val isLastItem = (layoutManager.findLastCompletelyVisibleItemPosition() == layoutManager.getItemCount() - 1) if (firstChild == RecyclerView.NO_POSITION) { return null } if (helper == null) { return null } if (isLastItem) { firstChild = layoutManager.getItemCount() - 1 return layoutManager.findViewByPosition(firstChild) } val child = layoutManager.findViewByPosition(firstChild) return if (helper.getDecoratedEnd(child) >= helper.getDecoratedMeasurement(child) / 2 && helper.getDecoratedEnd(child) > 0) { child } else { layoutManager.findViewByPosition(firstChild + 1) } } return super.findSnapView(layoutManager) } private fun getVerticalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper { if (::mVerticalHelper.isInitialized.not()) { mVerticalHelper = OrientationHelper.createVerticalHelper(layoutManager) } return mVerticalHelper } private fun getHorizontalHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper { if (::mHorizontalHelper.isInitialized.not()) { mHorizontalHelper = OrientationHelper.createHorizontalHelper(layoutManager) } return mHorizontalHelper } override fun findTargetSnapPosition(layoutManager: RecyclerView.LayoutManager, velocityX: Int, velocityY: Int): Int { val itemCount = layoutManager.itemCount if (itemCount == 0) { return RecyclerView.NO_POSITION } val orientationHelper = getOrientationHelper(layoutManager) ?: return RecyclerView.NO_POSITION var closestChildBeforeCenter: View? = null var distanceBefore = Int.MIN_VALUE var closestChildAfterCenter: View? = null var distanceAfter = Int.MAX_VALUE val childCount = layoutManager.childCount for (i in 0 until childCount) { val child = layoutManager.getChildAt(i) ?: continue val distance = distanceToStart(child, orientationHelper) if (distance in (distanceBefore + 1)..0) { distanceBefore = distance closestChildBeforeCenter = child } if (distance in 0 until distanceAfter) { distanceAfter = distance closestChildAfterCenter = child } } val forwardDirection = isForwardFling(layoutManager, velocityX, velocityY) if (forwardDirection && closestChildAfterCenter != null) { return layoutManager.getPosition(closestChildAfterCenter) } else if (!forwardDirection && closestChildBeforeCenter != null) { return layoutManager.getPosition(closestChildBeforeCenter) } val visibleView = (if (forwardDirection) closestChildBeforeCenter else closestChildAfterCenter) ?: return RecyclerView.NO_POSITION val visiblePosition = layoutManager.getPosition(visibleView) val snapToPosition = (visiblePosition + if (isReverseLayout(layoutManager) == forwardDirection) -1 else +1) return if (snapToPosition < 0 || snapToPosition >= itemCount) { RecyclerView.NO_POSITION } else { snapToPosition } } private fun isForwardFling( layoutManager: RecyclerView.LayoutManager, velocityX: Int, velocityY: Int ): Boolean { return if (layoutManager.canScrollHorizontally()) { velocityX > 0 } else { velocityY > 0 } } private fun isReverseLayout(layoutManager: RecyclerView.LayoutManager): Boolean { val itemCount = layoutManager.itemCount if (layoutManager is ScrollVectorProvider) { val vectorProvider = layoutManager as ScrollVectorProvider val vectorForEnd = vectorProvider.computeScrollVectorForPosition(itemCount - 1) if (vectorForEnd != null) { return vectorForEnd.x < 0 || vectorForEnd.y < 0 } } return false } private fun getOrientationHelper(layoutManager: RecyclerView.LayoutManager): OrientationHelper? { return if (layoutManager.canScrollVertically()) { getVerticalHelper(layoutManager) } else if (layoutManager.canScrollHorizontally()) { getHorizontalHelper(layoutManager) } else { null } } }
0
Kotlin
0
3
67dc5030f9ee69b2ecafbf511af0451a6d784511
6,409
Utility
Apache License 2.0
junit4-android-integration-rules/src/test/java/com/vanniktech/junit4androidintegrationrules/assertions.kt
vanniktech
99,514,897
false
null
package com.vanniktech.junit4androidintegrationrules import org.assertj.core.api.AbstractThrowableAssert import org.assertj.core.api.Java6Assertions.assertThat @Suppress("Detekt.InstanceOfCheckForException") // https://github.com/arturbosch/detekt/pull/1424 inline fun <reified T> assertThrows(block: () -> Unit): AbstractThrowableAssert<*, out Throwable> { try { block() } catch (e: Throwable) { if (e is T) { return assertThat(e) } else { throw e } } throw AssertionError("Expected ${T::class.simpleName}") }
0
Kotlin
0
14
0a324bbf8d5c18c2006c70cd4492db2f6a05c71a
550
junit-rules
Apache License 2.0
app/src/main/java/com/example/pexelapp/Models/WallPaperResponse.kt
Winstonexe
719,033,233
false
{"Kotlin": 27700}
package com.example.pexelapp.Models data class WallPaperResponse( val next_page: String, val page: Int, val per_page: Int, val photos: List<Photo>, val total_results: Int )
0
Kotlin
0
2
00de09e485fbf665fc1cc8cad491ad9206624a2d
193
PexelsApp
Apache License 2.0
app/src/main/java/com/javalon/xpensewhiz/presentation/home_screen/components/InfoBanner.kt
ezechuka
472,029,227
false
{"Kotlin": 333980}
package com.javalon.xpensewhiz.presentation.home_screen.components import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.core.FastOutLinearInEasing import androidx.compose.animation.core.LinearOutSlowInEasing import androidx.compose.animation.core.tween import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.MaterialTheme import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import com.javalon.xpensewhiz.presentation.home_screen.TransactionType import com.javalon.xpensewhiz.presentation.ui.theme.Amber500 import com.javalon.xpensewhiz.util.spacing @Composable fun InfoBanner(shown: Boolean, transactionType: TransactionType) { AnimatedVisibility( visible = shown, enter = slideInVertically( // Enters by sliding in from offset -fullHeight to 0. initialOffsetY = { fullHeight -> -fullHeight }, animationSpec = tween(durationMillis = 150, easing = LinearOutSlowInEasing) ), exit = slideOutVertically( // Exits by sliding out from offset 0 to -fullHeight. targetOffsetY = { fullHeight -> -fullHeight }, animationSpec = tween(durationMillis = 250, easing = FastOutLinearInEasing) ) ) { Surface( modifier = Modifier.fillMaxWidth().padding(MaterialTheme.spacing.medium), color = Amber500, shape = RoundedCornerShape(16.dp), elevation = 1.dp ) { Text( text = "Invalid ${transactionType.title} amount", modifier = Modifier.padding(16.dp), style = MaterialTheme.typography.subtitle2 ) } } }
1
Kotlin
5
52
7876f00908cca4f8444ab8b4460f1e7edb4cfa1a
2,075
xpense-whiz
MIT License
common/src/main/kotlin/org/collaborator/paymentlab/common/error/InvalidArgumentException.kt
f-lab-edu
665,758,863
false
{"Kotlin": 171941, "HTML": 1979, "Shell": 1679, "Dockerfile": 298}
package org.collaborator.paymentlab.common.error class InvalidArgumentException: ServiceException(ErrorCode.INVALID_INPUT)
0
Kotlin
1
9
5646d799f9cfd9f3fcf41d1119d41e18b30674af
123
payment-lab
MIT License
androidApp/src/main/java/com/m3u/androidApp/ui/AppNavHost.kt
oxyroid
592,741,804
false
{"Kotlin": 1102944}
package com.m3u.androidApp.ui import android.app.ActivityOptions import android.content.Intent import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import com.m3u.core.architecture.preferences.hiltPreferences import com.m3u.core.wrapper.eventOf import com.m3u.feature.playlist.configuration.navigateToPlaylistConfiguration import com.m3u.feature.playlist.configuration.playlistConfigurationScreen import com.m3u.feature.playlist.navigation.navigateToPlaylist import com.m3u.feature.playlist.navigation.playlistScreen import com.m3u.feature.playlist.navigation.playlistTvScreen import com.m3u.feature.channel.PlayerActivity import com.m3u.material.ktx.tv import com.m3u.ui.Destination import com.m3u.ui.Events import com.m3u.ui.SettingDestination @Composable fun AppNavHost( navController: NavHostController, navigateToRootDestination: (Destination.Root) -> Unit, contentPadding: PaddingValues, modifier: Modifier = Modifier, startDestination: String = Destination.Root.Foryou.name ) { val context = LocalContext.current val preferences = hiltPreferences() val tv = tv() NavHost( navController = navController, startDestination = startDestination, exitTransition = { slideOutVertically { -it / 5 } + fadeOut() }, popEnterTransition = { slideInVertically { -it / 5 } + fadeIn() }, modifier = modifier ) { rootGraph( contentPadding = contentPadding, navigateToPlaylist = { playlist -> navController.navigateToPlaylist(playlist.url, tv) }, navigateToChannel = { if (preferences.zappingMode && PlayerActivity.isInPipMode) return@rootGraph val options = ActivityOptions.makeCustomAnimation( context, 0, 0 ) context.startActivity( Intent(context, PlayerActivity::class.java), options.toBundle() ) }, navigateToSettingPlaylistManagement = { navigateToRootDestination(Destination.Root.Setting) Events.settingDestination = eventOf(SettingDestination.Playlists) }, navigateToPlaylistConfiguration = { navController.navigateToPlaylistConfiguration(it.url) } ) playlistScreen( navigateToChannel = { if (preferences.zappingMode && PlayerActivity.isInPipMode) return@playlistScreen val options = ActivityOptions.makeCustomAnimation( context, 0, 0 ) context.startActivity( Intent(context, PlayerActivity::class.java).apply { // addFlags(Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT or Intent.FLAG_ACTIVITY_NEW_TASK) }, options.toBundle() ) }, contentPadding = contentPadding ) playlistTvScreen() playlistConfigurationScreen(contentPadding) } }
34
Kotlin
33
375
ca92e3487c8e22b73b50197baa2d652185cb4f2e
3,575
M3UAndroid
Apache License 2.0
app/common/src/main/kotlin/me/zhanghai/android/files/provider/common/WatchServicePathObservable.kt
overphoenix
621,371,055
false
null
package me.zhanghai.android.files.provider.common import java8.nio.file.ClosedWatchServiceException import java8.nio.file.Path import java8.nio.file.StandardWatchEventKinds import java8.nio.file.WatchService import java.io.IOException import java.util.concurrent.atomic.AtomicInteger class WatchServicePathObservable(path: Path, intervalMillis: Long) : AbstractPathObservable( intervalMillis ) { private val watchService: WatchService private val poller: Poller init { var watchService: WatchService? = null var poller: Poller? = null var successful = false try { watchService = path.fileSystem.newWatchService() this.watchService = watchService path.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY ) poller = Poller() this.poller = poller poller.start() successful = true } finally { if (!successful) { poller?.interrupt() watchService?.close() } } } @Throws(IOException::class) override fun onCloseLocked() { poller.interrupt() watchService.close() } companion object { private val pollerId = AtomicInteger() } private inner class Poller : Thread( "WatchServicePathObservable.Poller-${pollerId.getAndIncrement()}" ) { init { isDaemon = true } override fun run() { while (true) { val key = try { watchService.take() } catch (e: ClosedWatchServiceException) { break } catch (e: InterruptedException) { break } if (key.pollEvents().isNotEmpty()) { notifyObservers() } if (!key.reset()) { break } } } } }
0
Kotlin
0
0
64264f261c2138d5f1932789702661917bbfae28
2,127
phoenix-android
Apache License 2.0
app/common/src/main/kotlin/me/zhanghai/android/files/provider/common/WatchServicePathObservable.kt
overphoenix
621,371,055
false
null
package me.zhanghai.android.files.provider.common import java8.nio.file.ClosedWatchServiceException import java8.nio.file.Path import java8.nio.file.StandardWatchEventKinds import java8.nio.file.WatchService import java.io.IOException import java.util.concurrent.atomic.AtomicInteger class WatchServicePathObservable(path: Path, intervalMillis: Long) : AbstractPathObservable( intervalMillis ) { private val watchService: WatchService private val poller: Poller init { var watchService: WatchService? = null var poller: Poller? = null var successful = false try { watchService = path.fileSystem.newWatchService() this.watchService = watchService path.register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY ) poller = Poller() this.poller = poller poller.start() successful = true } finally { if (!successful) { poller?.interrupt() watchService?.close() } } } @Throws(IOException::class) override fun onCloseLocked() { poller.interrupt() watchService.close() } companion object { private val pollerId = AtomicInteger() } private inner class Poller : Thread( "WatchServicePathObservable.Poller-${pollerId.getAndIncrement()}" ) { init { isDaemon = true } override fun run() { while (true) { val key = try { watchService.take() } catch (e: ClosedWatchServiceException) { break } catch (e: InterruptedException) { break } if (key.pollEvents().isNotEmpty()) { notifyObservers() } if (!key.reset()) { break } } } } }
0
Kotlin
0
0
64264f261c2138d5f1932789702661917bbfae28
2,127
phoenix-android
Apache License 2.0
app/src/main/java/com/example/noteapp/utils/di/NoteContractViewModuleFr.kt
rezakardan
719,037,194
false
{"Kotlin": 25568}
package com.example.noteapp.utils.di import androidx.fragment.app.Fragment import com.example.noteapp.ui.add.NoteContract import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.components.FragmentComponent @Module @InstallIn(FragmentComponent::class) class NoteContractViewModuleFr { @Provides fun addNote(fragment:Fragment): NoteContract.View{ return fragment as NoteContract.View } }
0
Kotlin
0
0
a77a5193a9ed24c43e58f8afca9e133919df7831
464
noteWithMvp_Git
MIT License
app/src/main/java/com/internshala/activitylifecycle/RegisterYourself.kt
AbhiiVops
494,532,783
false
null
package com.internshala.activitylifecycle import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.Toast class RegisterYourself : AppCompatActivity() { lateinit var register_button : Button override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.register_yourself) register_button = findViewById(R.id.register_button) register_button.setOnClickListener { Toast.makeText(this@RegisterYourself,"You Clicked on Register yourself",Toast.LENGTH_SHORT).show() } } }
0
Kotlin
1
0
e5ee793373d1065375d5aebbadd80baae0ae3969
651
Android-Development
The Unlicense
feature-nft-impl/src/main/java/com/dfinn/wallet/feature_nft_impl/presentation/nft/list/NftListItem.kt
finn-exchange
500,972,990
false
null
package com.dfinn.wallet.feature_nft_impl.presentation.nft.list import com.dfinn.wallet.common.presentation.LoadingState import com.dfinn.wallet.feature_wallet_api.presentation.model.AmountModel data class NftListItem( val content: LoadingState<Content>, val identifier: String, ) { data class Content( val issuance: String, val title: String, val price: AmountModel?, val media: String?, ) }
0
Kotlin
0
0
6cc7a0a4abb773daf3da781b7bd1dda5dbf9b01d
444
dfinn-android-wallet
Apache License 2.0
Conceito_iniciais/src/main/kotlin/Main.kt
ManoKondz
752,826,237
false
{"Kotlin": 2868}
fun main(args: Array<String>) { println("Nome: <NAME>") println("Idade: 17 Anos") }
0
Kotlin
0
0
de636ab75586d3c24c3094e6149a6fd3db1cc79a
91
Learning-Kotlin
MIT License
entity-service/src/main/kotlin/com/egm/stellio/entity/repository/PropertyRepository.kt
stellio-hub
257,818,724
false
null
package com.egm.stellio.entity.repository import com.egm.stellio.entity.model.Property import org.springframework.data.neo4j.repository.Neo4jRepository import org.springframework.data.neo4j.repository.query.Query import org.springframework.stereotype.Repository import java.net.URI @Repository interface PropertyRepository : Neo4jRepository<Property, URI> { @Query( "MATCH ({ id: \$subjectId })-[:HAS_VALUE]->(p:Property { name: \$propertyName }) " + "WHERE p.datasetId IS NULL " + "RETURN p" ) fun getPropertyOfSubject(subjectId: URI, propertyName: String): Property @Query( "MATCH ({ id: \$subjectId })-[:HAS_VALUE]->(p:Property { name: \$propertyName, datasetId: \$datasetId })" + "RETURN p" ) fun getPropertyOfSubject(subjectId: URI, propertyName: String, datasetId: URI): Property }
50
Kotlin
8
16
38bc7189a5fec1b14a46e86fc35e1ee7d842d8c0
868
stellio-context-broker
Apache License 2.0
mps-legacy-sync-plugin/src/main/java/org/modelix/model/mpsplugin/plugin/AddTransientModuleBinding_Action.kt
modelix
716,210,628
false
{"Kotlin": 918053, "Shell": 617, "JavaScript": 391}
package org.modelix.model.mpsplugin.plugin import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.project.Project import jetbrains.mps.ide.actions.MPSCommonDataKeys import jetbrains.mps.workbench.action.BaseAction import org.modelix.model.api.PNodeAdapter import org.modelix.model.lazy.RepositoryId import org.modelix.model.mpsplugin.CloudRepository import org.modelix.model.mpsplugin.ModelServerConnection import org.modelix.model.mpsplugin.TransientModuleBinding import org.modelix.model.mpsplugin.history.CloudNodeTreeNode import org.modelix.model.mpsplugin.history.ModelServerTreeNode import org.modelix.model.mpsplugin.history.RepositoryTreeNode import org.modelix.model.mpsplugin.history.TreeNodeBinding import org.modelix.model.mpsplugin.history.TreeNodeClassification import javax.swing.Icon import javax.swing.tree.TreeNode /*Generated by MPS */ class AddTransientModuleBinding_Action : BaseAction("Bind to Transient Module", "", ICON) { init { setIsAlwaysVisible(false) setExecuteOutsideCommand(true) } override fun isDumbAware(): Boolean { return true } override fun isApplicable(event: AnActionEvent, _params: Map<String, Any>): Boolean { return TreeNodeClassification.isModuleNode(event.getData(MPSCommonDataKeys.TREE_NODE)) && !( TreeNodeBinding.isBoundAsModule( event.getData(MPSCommonDataKeys.TREE_NODE), ) ) } public override fun doUpdate(event: AnActionEvent, _params: Map<String, Any>) { setEnabledState(event.presentation, isApplicable(event, _params)) } override fun collectActionData(event: AnActionEvent, _params: Map<String, Any>): Boolean { if (!(super.collectActionData(event, _params))) { return false } run({ val p: Project? = event.getData(CommonDataKeys.PROJECT) if (p == null) { return false } }) run({ val p: TreeNode? = event.getData(MPSCommonDataKeys.TREE_NODE) if (p == null) { return false } }) return true } public override fun doExecute(event: AnActionEvent, _params: Map<String, Any>) { addTransientModuleBinding( event.getData(MPSCommonDataKeys.TREE_NODE), event.getData(CommonDataKeys.PROJECT), event, ) } fun addTransientModuleBinding( treeNode: TreeNode?, mpsProject: Project?, event: AnActionEvent?, ): TransientModuleBinding { val nodeTreeNode: CloudNodeTreeNode? = treeNode as CloudNodeTreeNode? val modelServerConnection: ModelServerConnection = nodeTreeNode!!.getAncestor( ModelServerTreeNode::class.java, ).modelServer val repositoryId: RepositoryId = nodeTreeNode.getAncestor(RepositoryTreeNode::class.java).repositoryId val transientModuleBinding: TransientModuleBinding = TransientModuleBinding((nodeTreeNode.node as PNodeAdapter?)!!.nodeId) modelServerConnection!!.addBinding(repositoryId, transientModuleBinding) val treeInRepository: CloudRepository = CloudRepository(modelServerConnection, repositoryId) PersistedBindingConfiguration.Companion.getInstance(mpsProject)!! .addTransientBoundModule(treeInRepository, nodeTreeNode) return transientModuleBinding } companion object { private val ICON: Icon? = null } }
2
Kotlin
0
0
ba50a9cbb100f3886ed1602d60cc84e5f4f866a8
3,586
modelix.mps-plugins
Apache License 2.0
src/main/java/com/common/widgets/adapter/interfaces/DefaultAdapterHolderClickListener.kt
teddylinzz
604,409,249
false
null
package com.common.widgets.adapter.interfaces fun interface DefaultAdapterHolderClickListener { fun onItemClicked(position: Int) }
0
Kotlin
0
0
2378dde3361a1aaea14973bfbd7a2e52b607961e
135
common-widgets-android
Apache License 2.0
src/main/kotlin/com/ort/lastwolf/domain/service/ability/PsychicDomainService.kt
h-orito
288,476,085
false
{"Kotlin": 447706, "Batchfile": 522, "Shell": 454}
package com.ort.lastwolf.domain.service.ability import com.ort.lastwolf.domain.model.charachip.Chara import com.ort.lastwolf.domain.model.daychange.DayChange import com.ort.lastwolf.domain.model.message.Message import com.ort.lastwolf.domain.model.village.Village import com.ort.lastwolf.domain.model.village.participant.VillageParticipant import org.springframework.stereotype.Service @Service class PsychicDomainService { fun processDayChangeAction(dayChange: DayChange): DayChange { // 霊能がいない、または処刑・突然死がいない場合は何もしない val existsAlivePsychic = dayChange.village.participants.filterAlive().list.any { it.skill!!.toCdef().isHasPsychicAbility } if (!existsAlivePsychic) return dayChange val todayDeadParticipants = dayChange.village.todayDeadParticipants().list.filter { it.dead!!.toCdef().isPsychicableDeath } if (todayDeadParticipants.isEmpty()) return dayChange var messages = dayChange.messages.copy() todayDeadParticipants.forEach { deadParticipant -> messages = messages.add(createPsychicPrivateMessage(dayChange.village, deadParticipant)) } return dayChange.copy(messages = messages).setIsChange(dayChange) } // =================================================================================== // Assist Logic // ============ private fun createPsychicPrivateMessage( village: Village, deadParticipant: VillageParticipant ): Message { val isWolf = village.participants.first(deadParticipant.id).skill!!.toCdef().isPsychicResultWolf val text = createPsychicPrivateMessageString(deadParticipant.chara, isWolf) return Message.createPsychicPrivateMessage(text, village.days.latestDay().id, true) } private fun createPsychicPrivateMessageString(chara: Chara, isWolf: Boolean): String = "${chara.name.name}は人狼${if (isWolf) "の" else "ではない"}ようだ。" }
5
Kotlin
0
0
a86e0b7a55dbe616bfd390b69ea368c990aee99f
2,060
lastwolf-api
MIT License
app/src/main/java/id/dtprsty/simpleunittesting/MainActivity.kt
dtprsty
245,940,331
false
null
package id.dtprsty.simpleunittesting import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity(), View.OnClickListener { private lateinit var mainViewModel: MainViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) mainViewModel = MainViewModel(CuboidModel()) btnSave.setOnClickListener(this) btnCalculateVolume.setOnClickListener(this) btnCalculateSurface.setOnClickListener(this) btnCalculateCircumference.setOnClickListener(this) } private fun visible(){ btnCalculateVolume.visibility = View.VISIBLE btnCalculateSurface.visibility = View.VISIBLE btnSave.visibility = View.VISIBLE btnCalculateCircumference.visibility = View.VISIBLE } private fun gone(){ btnCalculateVolume.visibility = View.GONE btnCalculateSurface.visibility = View.GONE btnSave.visibility = View.GONE btnCalculateCircumference.visibility = View.GONE } override fun onClick(v: View?) { val length = etLength.text.toString().trim() val widht = etWidth.text.toString().trim() val height = etHeight.text.toString().trim() when{ length.isEmpty() -> etLength.error = "Field can not empty" widht.isEmpty() -> etWidth.error = "Field can not empty" height.isEmpty() -> etHeight.error = "Field can not empty" else -> { val l = length.toDouble() val w = widht.toDouble() val h = height.toDouble() when{ v?.id == R.id.btnSave -> { mainViewModel.save(w, l, h) visible() } v?.id == R.id.btnCalculateCircumference -> { tvResult.text = mainViewModel.getCircumference().toString() gone() } v?.id == R.id.btnCalculateVolume -> { tvResult.text = mainViewModel.getVolume().toString() gone() } v?.id == R.id.btnCalculateSurface -> { tvResult.text = mainViewModel.getSurfaceArea().toString() gone() } } } } } }
0
Kotlin
0
0
1865072bf40ecd62a50c5615a6ade6ad1b1eb8fd
2,601
simple-unit-testing
MIT License
android/src/main/kotlin/com/seyedjafariy/shuttle/ui/main/MainScreenContent.kt
seyedjafariy
520,298,973
false
{"Kotlin": 101839}
package com.seyedjafariy.shuttle.ui.main import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.material.CircularProgressIndicator import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.seyedjafariy.shuttle.R import com.seyedjafariy.shuttle.ui.main.state.CompanyInfoState import com.seyedjafariy.shuttle.ui.main.state.LaunchState import com.seyedjafariy.shuttle.ui.main.state.MainState import com.seyedjafariy.shuttle.utils.toStringResource @Composable fun MainScreenContent(modifier: Modifier, state: MainState, openLaunchOptions: (LaunchState) -> Unit) { LazyColumn(modifier.padding(horizontal = 16.dp)) { item(KEY_COMPANY_TITLE) { Column { Text(stringResource(id = R.string.company_section_title), Modifier.fillMaxWidth()) Spacer(modifier = Modifier.height(8.dp)) } } item(KEY_COMPANY_INFO) { Column { CompanyInfo(state.info) Spacer(modifier = Modifier.height(8.dp)) } } item(KEY_LAUNCH_TITLE) { Column { Text(stringResource(id = R.string.launches_section_title), Modifier.fillMaxWidth()) Spacer(modifier = Modifier.height(8.dp)) } } launchItems(state.launches, openLaunchOptions) } } @Composable private fun CompanyInfo(info: CompanyInfoState?) = Row { if (info == null) { CircularProgressIndicator() } else { Text( info.info.toStringResource(), modifier = Modifier.fillMaxWidth() ) } } private fun LazyListScope.launchItems(launches: List<LaunchState>, openLaunchOptions: (LaunchState) -> Unit) { items( launches.size, key = { launches[it].id } ) { LaunchRow(launches[it], openLaunchOptions) } } private const val KEY_COMPANY_TITLE = "KEY_COMPANY_TITLE" private const val KEY_LAUNCH_TITLE = "KEY_LAUNCH_TITLE" private const val KEY_COMPANY_INFO = "KEY_COMPANY_INFO"
0
Kotlin
0
7
65a91dbc992368e0552fde97c7975cdd5bed3b92
2,296
Shuttle
Apache License 2.0
account-bff/src/test/kotlin/se/sbab/es/demo/bff/AccountBffApplicationIT.kt
tnt-sbab
751,858,774
false
{"Kotlin": 145967}
package se.sbab.es.demo.bff import org.assertj.core.api.Assertions import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest import org.springframework.boot.test.web.server.LocalServerPort import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.test.web.reactive.server.expectBody @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) class AccountBffApplicationIT(@LocalServerPort port: Int) { val client = WebTestClient.bindToServer().baseUrl("http://localhost:$port").build() @Test fun `verify cortex-bff healthcheck response`() { client.get().uri("/account-bff/admin/healthcheck").exchange() .expectStatus().isOk .expectBody<String>() .consumeWith { result -> Assertions.assertThat(result.responseBody).contains("""status":"UP""") } } }
0
Kotlin
1
4
09ca03d73fe03e429c3253073e4b899519b780f7
899
spring-boot-event-store
Apache License 2.0
app/src/main/java/aelsi2/natkschedule/domain/use_cases/CleanCacheUseCase.kt
aelsi2
588,422,030
false
null
package aelsi2.natkschedule.domain.use_cases import aelsi2.natkschedule.data.preferences.FavoritesReader import aelsi2.natkschedule.data.preferences.SettingsReader import aelsi2.natkschedule.data.repositories.WritableScheduleAttributeRepository import aelsi2.natkschedule.data.repositories.WritableScheduleDayRepository import aelsi2.natkschedule.data.time.TimeManager import aelsi2.natkschedule.model.ScheduleIdentifier import kotlinx.coroutines.flow.first class CleanCacheUseCase( private val localDays: WritableScheduleDayRepository, private val localAttributes: WritableScheduleAttributeRepository, private val settings: SettingsReader, private val favorites: FavoritesReader, private val timeManager: TimeManager ) { suspend operator fun invoke() { cleanUnusedDays() cleanOldDays() cleanUnusedAttributes() } private suspend fun cleanOldDays() { val cleanCacheTimeDays = settings.savedScheduleMaxAgeDays.first() localDays.deleteAllBefore( timeManager.currentCollegeLocalDateTime.minusDays( cleanCacheTimeDays.toLong() ).toLocalDate() ) } private suspend fun cleanUnusedAttributes() { val favoriteSchedules = favorites.favoriteScheduleIds.first() val attributesToKeep = ArrayList(favoriteSchedules) val mainSchedule = favorites.mainScheduleId.first() if (mainSchedule != null) { attributesToKeep.add(mainSchedule) } localAttributes.deleteUnusedExcept(attributesToKeep) } private suspend fun cleanUnusedDays() { val schedulesToKeep = ArrayList<ScheduleIdentifier>() val cacheMainEnabled = settings.saveMainScheduleEnabled.first() if (cacheMainEnabled) { val mainSchedule = favorites.mainScheduleId.first() if (mainSchedule != null) { schedulesToKeep.add(mainSchedule) } } val cacheFavoritesEnabled = settings.saveFavoritesEnabled.first() if (cacheFavoritesEnabled) { val favorites = favorites.favoriteScheduleIds.first() schedulesToKeep.addAll(favorites) } localDays.deleteAllExcept(schedulesToKeep) } }
0
Kotlin
0
1
6494abd7cd80fd0c68c1cd5dbba5a3a7a546c654
2,255
NatkSchedule
Apache License 2.0
core/usecases/src/main/kotlin/theme/listAvailableOppositionValuesForCharacterInTheme/OppositionValuesAvailableForCharacterInTheme.kt
Soyle-Productions
239,407,827
false
null
package com.soyle.stories.usecase.theme.listAvailableOppositionValuesForCharacterInTheme import com.soyle.stories.usecase.theme.listOppositionsInValueWeb.OppositionValueItem import com.soyle.stories.usecase.theme.listValueWebsInTheme.ValueWebItem import java.util.* class OppositionValuesAvailableForCharacterInTheme( val themeId: UUID, val characterId: UUID, private val oppositionValues: List<AvailableValueWebForCharacterInTheme> ) : List<AvailableValueWebForCharacterInTheme> by oppositionValues class AvailableValueWebForCharacterInTheme( valueWebId: UUID, valueWebName: String, val oppositionCharacterRepresents: OppositionValueItem?, private val oppositionValues: List<AvailableOppositionValueForCharacterInTheme> ) : ValueWebItem(valueWebId, valueWebName), List<AvailableOppositionValueForCharacterInTheme> by oppositionValues { val characterRepresentsAnOpposition: Boolean get() = oppositionCharacterRepresents != null } class AvailableOppositionValueForCharacterInTheme( oppositionValueId: UUID, oppositionValueName: String ) : OppositionValueItem(oppositionValueId, oppositionValueName)
45
Kotlin
0
9
1a110536865250dcd8d29270d003315062f2b032
1,152
soyle-stories
Apache License 2.0
user/jwtdemo/src/main/kotlin/com/gongsung/user/service/UserService.kt
403-gallery-gongsung
736,332,935
false
{"Kotlin": 96306}
package com.gongsung.user.service import com.gongsung.common.authority.JwtTokenProvider import com.gongsung.common.authority.TokenInfo import com.gongsung.common.exception.InvalidInputException import com.gongsung.user.domain.dto.LoginDto import com.gongsung.user.domain.dto.UserDtoRequest import com.gongsung.user.domain.dto.UserDtoResponse import com.gongsung.user.domain.entity.UserEntity import com.gongsung.user.domain.entity.UserRole import com.gongsung.user.domain.enums.Role import com.gongsung.user.repository.UserRoleRepository import com.gongsung.user.repository.UserRepository import jakarta.transaction.Transactional import org.springframework.data.repository.findByIdOrNull import org.springframework.security.authentication.UsernamePasswordAuthenticationToken import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder import org.springframework.stereotype.Service @Service @Transactional class UserService( private val userRepository: UserRepository, private val userRoleRepository: UserRoleRepository, private val authenticationManagerBuilder: AuthenticationManagerBuilder, private val jwtTokenProvider: JwtTokenProvider, ) { fun signUp(userDto: UserDtoRequest): String { var user: UserEntity? = userRepository.findByLoginId(userDto.loginId) if (user != null) { throw InvalidInputException("loginId", "이미 등록된 ID 입니다.") } user = userDto.toEntity() userRepository.save(user) val role = UserRole(null, Role.USER, user) userRoleRepository.save(role) return "회원 가입이 완료되었습니다." } fun signIn(loginDto: LoginDto): TokenInfo { val authenticationToken = UsernamePasswordAuthenticationToken(loginDto.loginId, loginDto.password) val authentication = authenticationManagerBuilder.`object`.authenticate(authenticationToken) return jwtTokenProvider.createToken(authentication) } fun searchMyInfo(id: Long): UserDtoResponse { val user: UserEntity = userRepository.findByIdOrNull(id) ?: throw InvalidInputException("id", "회원($id)가 존재하지 않는 유저입니다") return user.toDto() } fun updateMyInfo(userDto: UserDtoRequest): String { val user = userDto.toEntity() userRepository.save(user) return "수정 완료되었습니다." } }
14
Kotlin
0
1
0f9322f55b2ae1fbfa1d36dadd9310f619afa1a4
2,359
meet-in
Apache License 2.0
app/src/main/java/io/zoemeow/dutschedule/ui/component/settings/dialog/DialogSchoolYearSettings.kt
ZoeMeow1027
504,228,485
false
{"Kotlin": 505302}
package io.zoemeow.dutschedule.ui.component.settings.dialog import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material3.DropdownMenu import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import io.zoemeow.dutschedule.activity.SettingsActivity import io.zoemeow.dutschedule.model.account.SchoolYearItem import io.zoemeow.dutschedule.ui.component.base.DialogBase import io.zoemeow.dutschedule.ui.component.base.OutlinedTextBox @OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsActivity.DialogSchoolYearSettings( isVisible: Boolean = false, dismissRequested: (() -> Unit)? = null, currentSchoolYearItem: SchoolYearItem, onSubmit: ((SchoolYearItem) -> Unit)? = null ) { val currentSettings = remember { mutableStateOf(SchoolYearItem()) } val dropDownSchoolYear = remember { mutableStateOf(false) } val dropDownSemester = remember { mutableStateOf(false) } LaunchedEffect(isVisible) { currentSettings.value = currentSchoolYearItem dropDownSchoolYear.value = false dropDownSemester.value = false } DialogBase( modifier = Modifier .fillMaxWidth() .padding(25.dp), title = "School year settings", isVisible = isVisible, canDismiss = false, isTitleCentered = true, dismissClicked = { dismissRequested?.let { it() } }, content = { Column( horizontalAlignment = Alignment.Start, verticalArrangement = Arrangement.Top, modifier = Modifier.fillMaxWidth(), ) { Text( "Edit your value below to adjust school year variable (careful when changing settings here)", modifier = Modifier.padding(bottom = 10.dp) ) ExposedDropdownMenuBox( expanded = dropDownSchoolYear.value, onExpandedChange = { dropDownSchoolYear.value = !dropDownSchoolYear.value }, content = { OutlinedTextBox( modifier = Modifier .fillMaxWidth() .menuAnchor(), title = "School year", value = String.format("20%d-20%d", currentSettings.value.year, currentSettings.value.year+1) ) DropdownMenu( expanded = dropDownSchoolYear.value, onDismissRequest = { dropDownSchoolYear.value = false }, content = { 23.downTo(10).forEach { DropdownMenuItem( text = { Text(String.format("20%2d-20%2d", it, it+1)) }, onClick = { currentSettings.value = currentSettings.value.clone( year = it ) dropDownSchoolYear.value = false } ) } } ) } ) ExposedDropdownMenuBox( expanded = dropDownSemester.value, onExpandedChange = { dropDownSemester.value = !dropDownSemester.value }, content = { OutlinedTextBox( modifier = Modifier .fillMaxWidth() .menuAnchor(), title = "Semester", value = String.format( "Semester %d%s", if (currentSettings.value.semester <= 2) currentSettings.value.semester else 2, if (currentSettings.value.semester > 2) " (in summer)" else "" ) ) DropdownMenu( expanded = dropDownSemester.value, onDismissRequest = { dropDownSemester.value = false }, content = { 1.rangeTo(3).forEach { DropdownMenuItem( text = { Text(String.format( "Semester %d%s", if (it <= 2) it else 2, if (it > 2) " (in summer)" else "" )) }, onClick = { currentSettings.value = currentSettings.value.clone( semester = it ) dropDownSemester.value = false } ) } } ) } ) } }, actionButtons = { TextButton( onClick = { onSubmit?.let { it(currentSettings.value) } }, content = { Text("Save") }, modifier = Modifier.padding(start = 8.dp), ) TextButton( onClick = { dismissRequested?.let { it() } }, content = { Text("Cancel") }, modifier = Modifier.padding(start = 8.dp), ) } ) }
1
Kotlin
0
1
4ef00cd06ecf3396a2eebba9b320516dbcf81587
6,569
DutSchedule
MIT License
app/src/main/java/in/kaligotla/allpermissionsimpl/presentation/main/permissions/photosVideos/MyPhotosVideosViewModel.kt
deepakkaligotla
722,851,480
false
{"Kotlin": 563021, "JavaScript": 4545}
package `in`.kaligotla.allpermissionsimpl.presentation.main.permissions.photosVideos import android.annotation.SuppressLint import android.content.ContentUris import android.content.Context import android.database.Cursor import android.media.AudioAttributes import android.media.AudioManager import android.media.MediaPlayer import android.net.Uri import android.os.Build import android.provider.MediaStore import android.util.Log import android.webkit.MimeTypeMap import android.widget.Toast import androidx.annotation.RequiresApi import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.core.database.getLongOrNull import androidx.core.database.getStringOrNull import androidx.lifecycle.ViewModel import dagger.hilt.android.lifecycle.HiltViewModel import `in`.kaligotla.allpermissionsimpl.presentation.main.mainCommon.getDateTime import java.io.File import java.io.FileInputStream import java.io.IOException import javax.inject.Inject @HiltViewModel class MyPhotosVideosViewModel @Inject constructor( ) : ViewModel() { private var photoVideosFilesExtensionArray = ArrayList<String>() var photoVideosFilesExtensionList by mutableStateOf(emptyList<String>()) private var filesArray = ArrayList<File>() var photoVideosFilesList by mutableStateOf(emptyList<File>()) val isPhoto = listOf( "bpm", "cr2", "cur", "dds", "dng", "erf", "exr", "fts", "gif", "hdr", "heic", "heif", "ico", "jfif", "jp2", "jpe", "jpeg", "jpg", "jps", "mng", "nef", "nrw", "orf", "pam", "pbm", "pcd", "pcx", "pef", "pes", "pfm", "pgm", "picon", "pict", "png", "pnm", "ppm", "psd", "raf", "ras", "rw2", "sfw", "sgi", "svg", "tga", "tiff", "wbmp", "webp", "wpg", "x3f", "xbm", "xcf", "xpm", "xwd") val isVideo = listOf( "3gp", "asf", "avi", "f4v", "flv", "hevc", "m2ts", "m2v", "m4v", "mjpeg", "mkv", "mov", "mp4", "mpeg", "mpg", "mts", "mxf", "ogv", "rm", "swf", "ts", "vob", "webm", "wmv", "wtv") @RequiresApi(Build.VERSION_CODES.Q) @SuppressLint("Range") fun createCursor(context: Context) { val filesInternal: Cursor? = context.contentResolver.query( MediaStore.Files.getContentUri("internal"), null, null, null, null ) val filesExternal: Cursor? = context.contentResolver.query( MediaStore.Files.getContentUri("external"), null, null, null, null ) combinedResults(filesInternal) combinedResults(filesExternal) } @SuppressLint("Range") private fun combinedResults(cursor: Cursor?) { while(cursor?.moveToNext()==true) { val filePath1 = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA)) val fileExtension = cursor.getString(cursor.getColumnIndex(MediaStore.Files.FileColumns.DISPLAY_NAME)).substringAfterLast('.', "") check(File(filePath1), fileExtension) } cursor?.close() photoVideosFilesList = filesArray.toList() photoVideosFilesExtensionList = photoVideosFilesExtensionArray.toList() } private fun check(temp: File, fileExtension: String) { for(extension in isPhoto+isVideo) { if(extension==fileExtension && !photoVideosFilesExtensionArray.contains(fileExtension)) { photoVideosFilesExtensionArray.add(fileExtension) } } if(photoVideosFilesExtensionArray.contains(fileExtension) && !filesArray.contains(temp)) { filesArray.add(temp) } } }
0
Kotlin
0
0
021aa3376b4a6042c433b06539fdb8f357d12400
3,698
android_permissions
The Unlicense
app/src/main/java/com/app/whakaara/receiver/TimerReceiver.kt
ahudson20
531,856,934
false
{"Kotlin": 466756, "Shell": 761}
package com.app.whakaara.receiver import android.content.Context import android.content.Intent import com.app.whakaara.logic.TimerManagerWrapper import com.app.whakaara.utils.constants.NotificationUtilsConstants.TIMER_RECEIVER_ACTION_PAUSE import com.app.whakaara.utils.constants.NotificationUtilsConstants.TIMER_RECEIVER_ACTION_START import com.app.whakaara.utils.constants.NotificationUtilsConstants.TIMER_RECEIVER_ACTION_STOP import com.app.whakaara.utils.constants.NotificationUtilsConstants.TIMER_RECEIVER_CURRENT_TIME_EXTRA import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.Dispatchers import java.util.Calendar import javax.inject.Inject @AndroidEntryPoint class TimerReceiver : HiltBroadcastReceiver() { @Inject lateinit var timerManagerWrapper: TimerManagerWrapper override fun onReceive(context: Context, intent: Intent) { super.onReceive(context, intent) val actionsList = listOf(TIMER_RECEIVER_ACTION_PAUSE, TIMER_RECEIVER_ACTION_STOP, TIMER_RECEIVER_ACTION_START) if (!actionsList.contains(intent.action)) return val currentTime = intent.getLongExtra(TIMER_RECEIVER_CURRENT_TIME_EXTRA, 0L) goAsync( coroutineContext = Dispatchers.Main ) { when (intent.action) { TIMER_RECEIVER_ACTION_START -> { startTimer( currentTime = currentTime ) } TIMER_RECEIVER_ACTION_PAUSE -> { pauseTimer() } TIMER_RECEIVER_ACTION_STOP -> { stopTimer() } } } } private fun startTimer( currentTime: Long ) { timerManagerWrapper.startTimer() timerManagerWrapper.startTimerNotificationCountdown(milliseconds = currentTime + Calendar.getInstance().timeInMillis) } private fun pauseTimer() { timerManagerWrapper.pauseTimer() timerManagerWrapper.pauseTimerNotificationCountdown() } private fun stopTimer() { timerManagerWrapper.resetTimer() } }
2
Kotlin
3
23
80bd00189b5356d71dd97cf9267aa5ecedd33afa
2,141
whakaara
MIT License
app/src/main/java/com/example/taskmanager/AddTodoActivity.kt
IT22070180
799,426,151
false
{"Kotlin": 20741, "Java": 129}
package com.example.taskmanager import android.content.Intent import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.ImageButton import android.widget.ImageView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import com.example.taskmanager.models.ToDoEntity import java.text.SimpleDateFormat import java.util.* import android.app.DatePickerDialog import android.app.TimePickerDialog import android.content.Context import android.widget.DatePicker import android.widget.TimePicker class AddTodoActivity : AppCompatActivity() { private lateinit var etTitle: EditText private lateinit var etNote: EditText private lateinit var imgCheck: ImageView private lateinit var imgDelete: ImageView private lateinit var imgBackArrow: ImageView private lateinit var calendarBtn: ImageButton private lateinit var todo: ToDoEntity private lateinit var oldTodo: ToDoEntity private var isUpdate = false private var deadline = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_todo) etTitle = findViewById(R.id.et_title) etNote = findViewById(R.id.et_note) imgCheck = findViewById(R.id.img_check) imgDelete = findViewById(R.id.img_delete) imgBackArrow = findViewById(R.id.img_back_arrow) calendarBtn = findViewById(R.id.calendarBtn) try { oldTodo = intent.getSerializableExtra("current_todo") as ToDoEntity etTitle.setText(oldTodo.title) etNote.setText(oldTodo.note) isUpdate = true } catch (e: Exception) { e.printStackTrace() } if (isUpdate) { imgDelete.visibility = View.VISIBLE } else { imgDelete.visibility = View.INVISIBLE } imgCheck.setOnClickListener { val title = etTitle.text.toString() val todoDescription = etNote.text.toString() if (title.isNotEmpty() && todoDescription.isNotEmpty()) { val formatter = SimpleDateFormat("EEE, d MMM yyyy HH:mm a") todo = if (isUpdate) { ToDoEntity(oldTodo.id, title, todoDescription, formatter.format(Date()),deadline,false) } else { ToDoEntity(null, title, todoDescription, formatter.format(Date()),deadline,false) } val intent = Intent() intent.putExtra("todo", todo) setResult(RESULT_OK, intent) finish() } else { Toast.makeText(this@AddTodoActivity, "Please enter some data", Toast.LENGTH_LONG).show() } } imgDelete.setOnClickListener { val intent = Intent() intent.putExtra("todo", oldTodo) intent.putExtra("delete_todo", true) setResult(RESULT_OK, intent) finish() } imgBackArrow.setOnClickListener { onBackPressed() } calendarBtn.setOnClickListener { showDateTimePickerDialog(this) } } private fun showDateTimePickerDialog(context: Context) { val calendar = Calendar.getInstance() val year = calendar.get(Calendar.YEAR) val month = calendar.get(Calendar.MONTH) val day = calendar.get(Calendar.DAY_OF_MONTH) // Date Picker Dialog val datePickerDialog = DatePickerDialog( context, { _, year, monthOfYear, dayOfMonth -> val selectedDate = SimpleDateFormat("EEE, d MMM yyyy", Locale.getDefault()).format( Calendar.getInstance().apply { set(year, monthOfYear, dayOfMonth) }.time ) showTimePickerDialog(context, selectedDate) }, year, month, day ) // Show the Date Picker Dialog datePickerDialog.show() } private fun showTimePickerDialog(context: Context, selectedDate: String) { val calendar = Calendar.getInstance() val hour = calendar.get(Calendar.HOUR_OF_DAY) val minute = calendar.get(Calendar.MINUTE) // Time Picker Dialog val timePickerDialog = TimePickerDialog( context, { _, hourOfDay, minute -> val selectedTime = SimpleDateFormat("HH:mm a", Locale.getDefault()).format( Calendar.getInstance().apply { set(Calendar.HOUR_OF_DAY, hourOfDay) set(Calendar.MINUTE, minute) }.time ) deadline = "$selectedDate $selectedTime" Toast.makeText(context, "Selected Date and Time: $deadline", Toast.LENGTH_LONG).show() // Assuming dateTxt is your TextView where you want to display the date and time // dateTxt.text = selectedDateTime }, hour, minute, false ) // Show the Time Picker Dialog timePickerDialog.show() } }
0
Kotlin
0
0
8f9e6c6b43f07e8ecc708ff68919060a747dd21a
5,201
Task-Management-App
Apache License 2.0
app/src/main/java/com/kishorebabu/android/commitstrip/injection/component/ActivityComponent.kt
KishoreBabuIN
105,754,517
false
null
package com.kishorebabu.android.commitstrip.injection.component import com.kishorebabu.android.commitstrip.features.base.BaseActivity import com.kishorebabu.android.commitstrip.features.main.MainActivity import com.kishorebabu.android.commitstrip.features.splash.SplashActivity import com.kishorebabu.android.commitstrip.injection.PerActivity import com.kishorebabu.android.commitstrip.injection.module.ActivityModule import dagger.Subcomponent @PerActivity @Subcomponent(modules = arrayOf(ActivityModule::class)) interface ActivityComponent { fun inject(baseActivity: BaseActivity) fun inject(mainActivity: MainActivity) fun inject(splashActivity: SplashActivity) fun inject(comicFragment: MainActivity.ComicFragment) }
1
Kotlin
0
0
dc243aff8ac5a6d8dacdcda04ca8d99359757ef3
741
CommitStripAndroid
The Unlicense
feature/subscription/dialog/src/main/kotlin/ru/resodostudios/cashsense/feature/subscription/dialog/SubscriptionDialogViewModel.kt
f33lnothin9
674,320,726
false
{"Kotlin": 293526}
package ru.resodostudios.cashsense.feature.subscription.dialog import android.app.AlarmManager import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.datetime.Clock import kotlinx.datetime.DateTimeUnit import kotlinx.datetime.Instant import kotlinx.datetime.LocalDateTime import kotlinx.datetime.LocalTime import kotlinx.datetime.TimeZone import kotlinx.datetime.minus import kotlinx.datetime.toInstant import kotlinx.datetime.toLocalDateTime import ru.resodostudios.cashsense.core.data.repository.SubscriptionsRepository import ru.resodostudios.cashsense.core.model.data.Currency import ru.resodostudios.cashsense.core.model.data.Reminder import ru.resodostudios.cashsense.core.model.data.Subscription import java.util.UUID import javax.inject.Inject @HiltViewModel class SubscriptionDialogViewModel @Inject constructor( private val subscriptionsRepository: SubscriptionsRepository, ) : ViewModel() { private val _subscriptionDialogUiState = MutableStateFlow(SubscriptionDialogUiState()) val subscriptionDialogUiState = _subscriptionDialogUiState.asStateFlow() fun onSubscriptionEvent(event: SubscriptionDialogEvent) { when (event) { SubscriptionDialogEvent.Save -> { val subscriptionId = _subscriptionDialogUiState.value.id.ifEmpty { UUID.randomUUID().toString() } var reminder: Reminder? = null if (_subscriptionDialogUiState.value.isReminderEnabled) { val timeZone = TimeZone.currentSystemDefault() val currentInstant = _subscriptionDialogUiState.value.paymentDate val currentDateTime = currentInstant.toLocalDateTime(timeZone) val previousDate = currentDateTime.date.minus(1, DateTimeUnit.DAY) val notificationDate = LocalDateTime(previousDate, LocalTime(9, 0)) .toInstant(timeZone) reminder = Reminder( id = subscriptionId.hashCode(), notificationDate = notificationDate, repeatingInterval = 7 * AlarmManager.INTERVAL_DAY, ) } val subscription = Subscription( id = subscriptionId, title = _subscriptionDialogUiState.value.title, amount = _subscriptionDialogUiState.value.amount.toBigDecimal(), paymentDate = _subscriptionDialogUiState.value.paymentDate, currency = _subscriptionDialogUiState.value.currency, reminder = reminder, ) viewModelScope.launch { subscriptionsRepository.upsertSubscription(subscription) } _subscriptionDialogUiState.update { SubscriptionDialogUiState() } } is SubscriptionDialogEvent.UpdateId -> { _subscriptionDialogUiState.update { it.copy(id = event.id) } loadSubscription() } is SubscriptionDialogEvent.UpdateTitle -> { _subscriptionDialogUiState.update { it.copy(title = event.title) } } is SubscriptionDialogEvent.UpdateAmount -> { _subscriptionDialogUiState.update { it.copy(amount = event.amount) } } is SubscriptionDialogEvent.UpdateCurrency -> { _subscriptionDialogUiState.update { it.copy(currency = event.currency) } } is SubscriptionDialogEvent.UpdatePaymentDate -> { _subscriptionDialogUiState.update { it.copy(paymentDate = event.paymentDate) } } is SubscriptionDialogEvent.UpdateReminderSwitch -> { _subscriptionDialogUiState.update { it.copy(isReminderEnabled = event.isReminderActive) } } } } private fun loadSubscription() { viewModelScope.launch { subscriptionsRepository.getSubscription(_subscriptionDialogUiState.value.id) .onStart { _subscriptionDialogUiState.value = SubscriptionDialogUiState(isLoading = true) } .catch { _subscriptionDialogUiState.value = SubscriptionDialogUiState() } .collect { _subscriptionDialogUiState.value = SubscriptionDialogUiState( id = it.id, title = it.title, amount = it.amount.toString(), paymentDate = it.paymentDate, currency = it.currency, isReminderEnabled = it.reminder != null, isLoading = false, ) } } } } data class SubscriptionDialogUiState( val id: String = "", val title: String = "", val amount: String = "", val paymentDate: Instant = Clock.System.now(), val currency: String = Currency.USD.name, val isReminderEnabled: Boolean = false, val isLoading: Boolean = false, )
0
Kotlin
2
26
a89733b3413ad2170b6395dd0d8024882c5bb159
5,635
cashsense
Apache License 2.0
m-gles20-pipeline/src/main/java/org/frikadelki/deepv/pipeline/math/WorldUtils.kt
frikadelki
122,027,202
false
null
/* * Deep Venture K3D * Copyright 2018 -*- frikadelki-corps -*- * Created by frikadelki on 2018/2/11 */ package org.frikadelki.deepv.pipeline.math object World { const val C0: Float = 0.0f const val C1: Float = 1.0f val center: Vector4RO = v4Point() val axisX: Vector4RO = v4Vector(x = C1) val axisY: Vector4RO = v4Vector(y = C1) val axisZ: Vector4RO = v4Vector(z = C1) const val ARC_000: Float = 0.0f const val ARC_045: Float = 45.0f const val ARC_090: Float = 90.0f const val ARC_180: Float = 180.0f const val ARC_270: Float = 270.0f const val ARC_360: Float = 360.0f } fun v4Point(x: Float = World.C0, y: Float = World.C0, z: Float = World.C0) = Vector4().setPoint(x, y, z) fun v4Vector(x: Float = World.C0, y: Float = World.C0, z: Float = World.C0, w: Float = World.C0) = Vector4().set(x, y, z, w) fun v4Color(r: Float = World.C0, g: Float = World.C0, b: Float = World.C0, a: Float = World.C1) = Vector4().set(r, g, b, a)
0
Kotlin
0
0
fd8350e61b360fe60ddd06438e3405c683f4813a
1,084
deep-venture-k3d
MIT License
engine/src/main/kotlin/com/delphix/sdk/objects/Credential.kt
CloudSurgeon
212,463,880
true
{"Kotlin": 586314, "Shell": 46347, "Java": 9931, "Dockerfile": 904}
/** * Copyright (c) 2019 by Delphix. All rights reserved. */ package com.delphix.sdk.objects /** * The security credential. */ interface Credential : TypedObject { override val type: String override fun toMap(): Map<String, Any?> }
0
Kotlin
0
1
819f7e9ea1bb0c675e0d04d61cf05302c488d74f
245
titan-server
Apache License 2.0
app/src/main/java/com/plussoft/testannotation/NoAndroid.kt
PanyaNaknoppakun
830,208,054
false
{"Kotlin": 22080}
package com.plussoft.testannotation import android.content.Context import com.pls.annotation.GenerateEntryPointHiltModule import com.pls.autohilt.NonAndroid_HiltEntryPoint import com.plussoft.testannotation.extension.getEntryPoint import javax.inject.Inject @GenerateEntryPointHiltModule class NoAndroid(context: Context) { init { context.getEntryPoint(NonAndroid_HiltEntryPoint::class.java).inject(this) } @Inject lateinit var testForProvideObject: TestForProvideObject @Inject lateinit var myRepository: MyRepository fun getStatusTest(): String { return myRepository.doSomething() } }
0
Kotlin
0
4
209512b95b6f5cc0ad05715fb59f2ad8ced62df5
638
HiltAnnotationExtension
MIT License
app/src/main/java/com/alex/bioauth/App.kt
MinghuiWang-TT
173,919,272
false
null
package com.alex.bioauth import android.app.Application class App : Application() { override fun onCreate() { super.onCreate() Preference.getInstance(applicationContext) } }
11
Kotlin
0
0
a40c21cf5b656b0b7a8014232a4f5ae8172d86a3
200
BiometicAuthClient
Apache License 2.0
app/src/main/kotlin/jp/co/yumemi/android/codecheck/data/history/room/HistoryDatabase.kt
mickie895
633,669,896
false
null
package jp.co.yumemi.android.codecheck.data.history.room import androidx.room.Database import androidx.room.RoomDatabase import androidx.room.TypeConverters import jp.co.yumemi.android.codecheck.data.history.SearchHistory @Database(entities = [SearchHistory::class], version = 1, exportSchema = false) @TypeConverters(Converters::class) abstract class HistoryDatabase : RoomDatabase() { abstract fun historyDao(): HistoryDao }
9
Kotlin
0
0
507c1dac2aa6960faf493d29e14c2dd082c30f3b
433
yumemi_codecheck
Apache License 2.0
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/CycleIndexPolynomial.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: CycleIndexPolynomial * * Full name: System`CycleIndexPolynomial * * CycleIndexPolynomial[perm, {x , …, x }] constructs the cycle index monomial of the permutation perm in the variables x . * 1 n i * CycleIndexPolynomial[group, {x , …, x }] constructs the cycle index polynomial of group in the variables x . * Usage: 1 n i * * Options: None * * Protected * Attributes: ReadProtected * * local: paclet:ref/CycleIndexPolynomial * Documentation: web: http://reference.wolfram.com/language/ref/CycleIndexPolynomial.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun cycleIndexPolynomial(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("CycleIndexPolynomial", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,498
mathemagika
Apache License 2.0
src/main/kotlin/no/nav/medlemskap/popp/services/PoppService.kt
navikt
863,386,411
false
{"Kotlin": 33074, "Dockerfile": 66}
package no.nav.medlemskap.popp.services import no.nav.medlemskap.popp.domain.Medlemperioder import no.nav.medlemskap.popp.domain.PoppRequest import no.nav.medlemskap.popp.domain.PoppRespons import no.nav.medlemskap.popp.domain.Status import java.time.LocalDate import java.util.* import kotlin.random.Random class PoppService:IJegKanHåndterePoppRequest { override fun handleRequest(PoppRequest: PoppRequest):PoppRespons { if (Random.nextBoolean()){ return PoppRespons( fnr = "01987654321", referanse = UUID.randomUUID().toString(), medlemperioder = listOf( Medlemperioder( fom = LocalDate.parse("2019-09-01"), tom = LocalDate.parse("2019-09-30"), status = Status.JA ), Medlemperioder( fom = LocalDate.parse("2019-10-01"), tom = LocalDate.parse("2019-10-25"), status = Status.NEI ), Medlemperioder( fom = LocalDate.parse("2019-10-26"), tom = LocalDate.parse("2019-11-30"), status = Status.UAVKLART ) ), årsaker = listOf("REGEL_19","REGEL_21"), status = Status.UAVKLART, ) } return PoppRespons( fnr = "01987654321", referanse = UUID.randomUUID().toString(), medlemperioder = listOf( Medlemperioder( fom = LocalDate.parse("2019-09-01"), tom = LocalDate.parse("2019-09-30"), status = Status.JA ), Medlemperioder( fom = LocalDate.parse("2019-10-01"), tom = LocalDate.parse("2019-10-25"), status = Status.JA ), Medlemperioder( fom = LocalDate.parse("2019-10-26"), tom = LocalDate.parse("2019-11-30"), status = Status.JA ) ), årsaker = emptyList(), status = Status.JA, ) } }
0
Kotlin
0
0
733a26e998a4380b6cd461c2ce50a5751423761c
2,315
medlemskap-popp
MIT License
app/src/main/java/com/ethermail/androidchallenge/data/CoincapService.kt
Ethersuite
775,439,375
false
{"Kotlin": 12906}
package com.ethermail.androidchallenge.data import com.ethermail.androidchallenge.data.model.assets.AssetsApiData import com.ethermail.androidchallenge.data.model.markets.MarketsApiData import retrofit2.http.GET const val HOST_COINCAP = "https://api.coincap.io/" interface CoincapService { @GET("/v2/assets") suspend fun getAssets(): AssetsApiData @GET("/v2/markets") suspend fun getMarkets(): MarketsApiData }
0
Kotlin
0
1
dc15d2fcaf900c87e3cbc515fe2086e6e52ecbad
432
android-challenge
MIT License
newm-server/src/main/kotlin/io/newm/server/features/minting/MintingStatusSqsMessage.kt
projectNEWM
447,979,150
false
{"Kotlin": 2426137, "HTML": 185244, "Dockerfile": 2535, "Shell": 1986, "Procfile": 60}
package io.newm.server.features.minting import io.newm.server.features.song.model.MintingStatus import io.newm.server.typealiases.SongId import kotlinx.serialization.Contextual import kotlinx.serialization.Serializable @Serializable data class MintingStatusSqsMessage( @Contextual val songId: SongId, val mintingStatus: MintingStatus, )
1
Kotlin
4
10
4dc2c689eb5518d1bbd25ba69d1d57839ad16f0d
351
newm-server
Apache License 2.0
src/app/src/main/java/jp/kaleidot725/sample/room/AppDatabase.kt
kaleidot725-android
263,554,854
false
null
package jp.kaleidot725.sample.room import androidx.room.Database import androidx.room.RoomDatabase import jp.kaleidot725.sample.room.dao.RepoDao import jp.kaleidot725.sample.room.data.User import jp.kaleidot725.sample.room.dao.UserDao import jp.kaleidot725.sample.room.dao.UserRepoDao import jp.kaleidot725.sample.room.data.Repo import jp.kaleidot725.sample.room.view.UserRepo @Database(entities = [User::class, Repo::class], views = [UserRepo::class], version = 4) abstract class AppDatabase : RoomDatabase() { abstract fun userDao(): UserDao abstract fun repoDao(): RepoDao abstract fun userRepoDao(): UserRepoDao }
0
Kotlin
0
0
c2ad5c579bc67fa27f8d28ce4515d39837c22d6a
632
room
MIT License
plugins/playerinfo/src/main/kotlin/Plugin.kt
pluginloader
354,578,063
false
null
package playerinfo import configs.Conf import kotlinx.serialization.Serializable import org.bukkit.Bukkit import pluginloader.api.Load import pluginloader.api.Plugin import provide.Provider import provide.registerProvider import java.util.* fun interface PlayerReadable{ fun readable(uuid: UUID): String companion object{ operator fun invoke(uuid: UUID) = full.actual.readable(uuid) } } fun interface PlayerNick{ fun nick(uuid: UUID): String? companion object{ operator fun invoke(uuid: UUID) = nick.actual.nick(uuid) } } fun interface PlayerColor{ fun color(uuid: UUID): String companion object{ operator fun invoke(uuid: UUID) = color.actual.color(uuid) } } fun interface PlayerPrefix{ fun prefix(uuid: UUID): String companion object{ operator fun invoke(uuid: UUID) = prefix.actual.prefix(uuid) } } fun interface PlayerSuffix { fun suffix(uuid: UUID): String companion object{ operator fun invoke(uuid: UUID) = suffix.actual.suffix(uuid) } } fun interface PlayerUUIDByNick: (String) -> UUID?{ companion object{ operator fun invoke(nick: String) = uuidByNick.actual(nick) } } private lateinit var full: Provider<PlayerReadable> private lateinit var nick: Provider<PlayerNick> private lateinit var color: Provider<PlayerColor> private lateinit var prefix: Provider<PlayerPrefix> private lateinit var suffix: Provider<PlayerSuffix> private lateinit var uuidByNick: Provider<PlayerUUIDByNick> @Conf internal var config = Config() @Load internal fun load(plugin: Plugin){ full = plugin.registerProvider(PlayerReadable::class, PlayerReadable { uuid -> val color = PlayerColor(uuid) val prefix = PlayerPrefix(uuid) val suffix = PlayerSuffix(uuid) "${if (prefix.isEmpty()) "" else "$prefix "}${if(color.isEmpty()) config.defaultColor else color}${PlayerNick(uuid)}${if (suffix.isEmpty()) "" else " $suffix"}" }) nick = plugin.registerProvider(PlayerNick::class, PlayerNick{Bukkit.getPlayer(it)?.name}) color = plugin.registerProvider(PlayerColor::class, PlayerColor{config.defaultColor}) prefix = plugin.registerProvider( PlayerPrefix::class, PlayerPrefix{""}) suffix = plugin.registerProvider(PlayerSuffix::class, PlayerSuffix{""}) uuidByNick = plugin.registerProvider(PlayerUUIDByNick::class, object: PlayerUUIDByNick{ override fun invoke(nick: String): UUID? { Bukkit.getOfflinePlayers().forEach{if(it.name == nick)return it.uniqueId} return null } }) } @Serializable internal class Config(val defaultColor: String = "§7")
0
Kotlin
0
0
85942ebdb9f65a5c57ec93285703464cac41a4b8
2,658
mono
MIT License
android/app/src/main/kotlin/com/example/gamerev/MainActivity.kt
sinbaddoraji
383,593,300
false
{"Dart": 46904, "HTML": 3693, "Swift": 404, "Kotlin": 124, "Objective-C": 38}
package com.example.gamerev import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
9a5279335373c18ac627740176041ca72f1aeb02
124
GameRev
MIT License
src/test/kotlin/eZmaxApi/models/EzsigntemplateCreateObjectV2ResponseMPayloadTest.kt
eZmaxinc
271,950,932
false
{"Kotlin": 6909939}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package eZmaxApi.models import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import eZmaxApi.models.EzsigntemplateCreateObjectV2ResponseMPayload class EzsigntemplateCreateObjectV2ResponseMPayloadTest : ShouldSpec() { init { // uncomment below to create an instance of EzsigntemplateCreateObjectV2ResponseMPayload //val modelInstance = EzsigntemplateCreateObjectV2ResponseMPayload() // to test the property `aPkiEzsigntemplateID` - An array of unique IDs representing the object that were requested to be created. They are returned in the same order as the array containing the objects to be created that was sent in the request. should("test aPkiEzsigntemplateID") { // uncomment below to test the property //modelInstance.aPkiEzsigntemplateID shouldBe ("TODO") } } }
0
Kotlin
0
0
961c97a9f13f3df7986ea7ba55052874183047ab
1,133
eZmax-SDK-kotlin
MIT License
common/ui/compose/src/main/java/app/tivi/common/compose/TiviPreferenceExtensions.kt
chrisbanes
100,624,553
false
null
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.common.compose import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import app.tivi.settings.TiviPreferences @Composable fun TiviPreferences.shouldUseDarkColors(): Boolean { val themePreference = observeTheme().collectAsState(initial = TiviPreferences.Theme.SYSTEM) return when (themePreference.value) { TiviPreferences.Theme.LIGHT -> false TiviPreferences.Theme.DARK -> true else -> isSystemInDarkTheme() } }
39
null
792
5,749
5dc4d831fd801afab556165d547042c517f98875
1,152
tivi
Apache License 2.0
src/main/kotlin/io/openfuture/chain/network/server/TcpServer.kt
OpenFuturePlatform
135,143,034
false
null
package io.openfuture.chain.network.server import io.netty.bootstrap.ServerBootstrap import io.openfuture.chain.network.property.NodeProperties import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.boot.context.event.ApplicationReadyEvent import org.springframework.context.ApplicationListener import org.springframework.stereotype.Component @Component class TcpServer( private val bootstrap: ServerBootstrap, private val properties: NodeProperties ) : ApplicationListener<ApplicationReadyEvent> { companion object { private val log: Logger = LoggerFactory.getLogger(TcpServer::class.java) private const val LOGO = """ ______ _ _ _ _____ ______ _____ ______ _ / _____) _ | | | || | _ / ___ \ / __ | / ___ \ / __ | | | | / ___ ___ | |_ ___ | | ___ ____ ____ | || | _ ___ ___ | |_ _ ( ( ) )| | //| |( ( ) )| | //| | / / | | (___) / _ \ | _) / _ \ | | / _ \ / ___) / _ || || || \ / _ \ /___)| _) (_) > > < < | |// | | > > < < | |// | | / / | \____/|| |_| | | |__ | |_| | | || |_| |( (___ ( ( | || || | | || |_| ||___ || |__ _ ( (___) )| /__| |( (___) )| /__| | / / \_____/ \___/ \___) \___/ |_| \___/ \____) \_||_||_||_| |_| \___/ (___/ \___)(_) \_____/ \_____/ \_____/ \_____/ |_| """ } override fun onApplicationEvent(event: ApplicationReadyEvent) { try { val channelFuture = bootstrap.bind(properties.port!!).sync() log.info("Netty started on port: ${properties.port}") log.info(LOGO) channelFuture.channel().closeFuture().sync() } catch (e: InterruptedException) { log.error("Server in trouble", e) } } }
2
null
16
64
f7e511b3ba17cc75d7f23618008dd89a7b83c4c0
2,050
open-chain
MIT License
src/main/kotlin/ru/itis/kotlin/news_api/model/Place.kt
feduuusha
857,301,669
false
{"Kotlin": 27021}
package ru.itis.kotlin.news_api.model import kotlinx.serialization.Serializable @Serializable data class Place(val id: Long)
0
Kotlin
0
0
f069992b2f22b2ea2015653625199b7173fe5b58
127
KudaGo-API-Kotlin
MIT License