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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
activity/activity-compose/src/androidTest/java/androidx/activity/compose/ActivityResultRegistryTest.kt
|
virendersran01
| 343,676,031 | false | null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.activity.compose
import android.content.Intent
import androidx.activity.ComponentActivity
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.ActivityResultRegistry
import androidx.activity.result.ActivityResultRegistryOwner
import androidx.activity.result.contract.ActivityResultContract
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.core.app.ActivityOptionsCompat
import androidx.lifecycle.Lifecycle
import androidx.test.core.app.ActivityScenario
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertWithMessage
import org.junit.Assert.fail
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@MediumTest
@RunWith(AndroidJUnit4::class)
class ActivityResultRegistryTest {
@get:Rule
val composeTestRule = createComposeRule()
var launchCount = 0
val registryOwner = ActivityResultRegistryOwner {
object : ActivityResultRegistry() {
override fun <I : Any?, O : Any?> onLaunch(
requestCode: Int,
contract: ActivityResultContract<I, O>,
input: I,
options: ActivityOptionsCompat?
) {
launchCount++
}
}
}
@Test
fun testRegisterForActivityResult() {
var launcher: ActivityResultLauncher<Intent>? by mutableStateOf(null)
composeTestRule.setContent {
CompositionLocalProvider(
LocalActivityResultRegistryOwner.asProvidableCompositionLocal()
provides registryOwner
) {
launcher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {}
}
}
composeTestRule.runOnIdle {
launcher?.launch(Intent()) ?: fail("launcher was not composed")
assertWithMessage("the registry was not invoked")
.that(launchCount)
.isEqualTo(1)
}
}
@Test
fun testRegisterForActivityResultAfterRestoration() {
val activityScenario: ActivityScenario<ComponentActivity> =
ActivityScenario.launch(ComponentActivity::class.java)
activityScenario.moveToState(Lifecycle.State.RESUMED)
var launcher: ActivityResultLauncher<Intent>? by mutableStateOf(null)
activityScenario.onActivity { activity ->
(activity as ComponentActivity).setContent {
CompositionLocalProvider(
LocalActivityResultRegistryOwner.asProvidableCompositionLocal()
provides registryOwner
) {
launcher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {}
}
}
}
activityScenario.recreate()
activityScenario.onActivity {
launcher?.launch(Intent()) ?: fail("launcher was not composed")
assertWithMessage("the registry was not invoked")
.that(launchCount)
.isEqualTo(1)
}
}
}
| 0 | null |
0
| 1 |
d013398a743b10a8202e24c3a1d3def900a78f8f
| 4,118 |
androidx
|
Apache License 2.0
|
lib-universalAdapter/src/main/java/com/llj/adapter/converter/ViewGroupAdapterConverter.kt
|
liulinjie1990823
| 133,350,610 | false |
{"Gradle": 94, "Python": 7, "JSON": 2, "Java Properties": 40, "Shell": 54, "Text": 149, "JavaScript": 32, "Ignore List": 72, "Markdown": 59, "Java": 651, "INI": 17, "Proguard": 56, "XML": 352, "Groovy": 16, "CMake": 13, "C++": 49, "C": 704, "Kotlin": 304, "Roff Manpage": 30, "YAML": 11, "CSS": 6, "JAR Manifest": 1, "HTML": 65, "Rich Text Format": 2, "SQL": 1, "Assembly": 94, "Pascal": 3, "Unix Assembly": 3, "Dart": 96, "AIDL": 4, "SVG": 4, "Gradle Kotlin DSL": 1, "GLSL": 24, "Makefile": 27, "M4Sugar": 119, "sed": 11, "Batchfile": 6, "Roff": 1, "Texinfo": 1, "M4": 1, "Diff": 2, "Gettext Catalog": 37}
|
package com.llj.adapter.converter
import android.os.Build
import android.util.Log
import android.view.View
import android.view.ViewGroup
import com.llj.adapter.UniversalAdapter
import com.llj.adapter.UniversalConverter
import com.llj.adapter.XViewHolder
import com.llj.adapter.listener.ItemClickListener
import com.llj.adapter.listener.ItemClickWrapper
import com.llj.adapter.listener.ItemListenerAdapter
import com.llj.adapter.observable.ListObserver
import com.llj.adapter.observable.ListObserverListener
import com.llj.adapter.observable.SimpleListObserverListener
import com.llj.adapter.util.UniversalAdapterUtils
import java.lang.reflect.Field
/**
* ViewGroupAdapterConverter
*
* @author liulinjie
* @date 2017/2/11
*/
class ViewGroupAdapterConverter<Item, Holder : XViewHolder>
internal constructor(adapter: UniversalAdapter<Item, Holder>, private val mViewGroup: ViewGroup) :
ItemListenerAdapter<Item, Holder>,
UniversalConverter<Item, Holder> {
private var mUniversalAdapter: UniversalAdapter<Item, Holder>? = null
private val mItemClickWrapper: ItemClickWrapper<Item, Holder> = ItemClickWrapper(this)
private val mObserverListener: ListObserverListener<Item>
init {
this.mObserverListener = object : SimpleListObserverListener<Item>() {
override fun onGenericChange(observer: ListObserver<Item>) {
populateAll()
}
override fun onItemRangeChanged(observer: ListObserver<Item>, startPosition: Int, count: Int) {
for (i in startPosition until startPosition + count) {
val childAt = mViewGroup.getChildAt(i) as ViewGroup
getAdapter().bindViewHolder(UniversalAdapterUtils.getViewHolder(childAt), i)
}
}
}
adapter.checkIfBoundAndSet()
setAdapter(adapter)
populateAll()
}
///////////////////////////////////////////////////////////////////////////
//
///////////////////////////////////////////////////////////////////////////
override fun setItemClickedListener(listener: ItemClickListener<Item, Holder>) {
getAdapter().setItemClickedListener(listener)
}
override fun setAdapter(listAdapter: UniversalAdapter<Item, Holder>) {
if (mUniversalAdapter != null) {
mUniversalAdapter!!.mListObserver.removeListener(mObserverListener)
}
mUniversalAdapter = listAdapter
getAdapter().mListObserver.addListener(mObserverListener)
populateAll()
}
override fun getAdapter(): UniversalAdapter<Item, Holder> {
return mUniversalAdapter!!
}
override fun cleanup() {
getAdapter().mListObserver.removeListener(mObserverListener)
}
private fun clear() {
mViewGroup.removeAllViews()
}
private fun populateAll() {
clear()
val count = getAdapter().internalCount
for (i in 0 until count) {
addItem(i)
}
}
private fun addItem(position: Int) {
val holder = getAdapter()
.createViewHolder(mViewGroup, mUniversalAdapter!!.getInternalItemViewType(position))
getAdapter().bindViewHolder(holder, position)
val view = holder.itemView
UniversalAdapterUtils.setViewHolder(view, holder)
if (!hasOnClickListeners(view)) {
mItemClickWrapper.register(view)
}
mViewGroup.addView(view, position)
}
private fun hasOnClickListeners(view: View): Boolean {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
getOnClickListenerV14(view) != null
} else {
getOnClickListenerV(view) != null
}
}
//Used for APIs lower than ICS (API 14)
private fun getOnClickListenerV(view: View): View.OnClickListener? {
var retrievedListener: View.OnClickListener? = null
val viewStr = "android.view.View"
val field: Field
try {
field = Class.forName(viewStr).getDeclaredField("mOnClickListener")
retrievedListener = field[view] as View.OnClickListener
} catch (ex: NoSuchFieldException) {
Log.e("Reflection", "No Such Field.")
} catch (ex: IllegalAccessException) {
Log.e("Reflection", "Illegal Access.")
} catch (ex: ClassNotFoundException) {
Log.e("Reflection", "Class Not Found.")
}
return retrievedListener
}
//Used for new ListenerInfo class structure used beginning with API 14 (ICS)
private fun getOnClickListenerV14(view: View): View.OnClickListener? {
var retrievedListener: View.OnClickListener? = null
val viewStr = "android.view.View"
val lInfoStr = "android.view.View\$ListenerInfo"
try {
var listenerInfo: Any? = null
val listenerField = Class.forName(viewStr).getDeclaredField("mListenerInfo")
if (listenerField != null) {
listenerField.isAccessible = true
listenerInfo = listenerField[view]
}
val clickListenerField = Class.forName(lInfoStr).getDeclaredField("mOnClickListener")
if (clickListenerField != null && listenerInfo != null) {
retrievedListener = clickListenerField[listenerInfo] as View.OnClickListener?
}
} catch (ex: NoSuchFieldException) {
Log.e("Reflection", "No Such Field.")
} catch (ex: IllegalAccessException) {
Log.e("Reflection", "Illegal Access.")
} catch (ex: ClassNotFoundException) {
Log.e("Reflection", "Class Not Found.")
}
return retrievedListener
}
}
| 1 | null |
1
| 1 |
7c5d7fe1e5e594baba19778e0ed857325ce58095
| 5,256 |
ArchitectureDemo
|
Apache License 2.0
|
app-mvp/feature-user-profile/src/main/java/com/bubbble/userprofile/followers/UserFollowersPresenter.kt
|
ImangazalievM
| 101,416,083 | false |
{"Gradle Kotlin DSL": 23, "Markdown": 1, "Java Properties": 2, "Shell": 1, "Ignore List": 14, "Batchfile": 1, "XML": 87, "Kotlin": 160, "Java": 33, "INI": 3, "Proguard": 4, "HTML": 2, "SVG": 2}
|
package com.bubbble.userprofile.followers
import com.bubbble.core.models.user.Follow
import com.bubbble.core.models.user.UserFollowersParams
import com.bubbble.core.network.NoNetworkException
import com.bubbble.coreui.mvp.BasePresenter
import com.bubbble.data.users.FollowersRepository
import com.bubbble.userprofile.api.UserProfileScreen
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import moxy.InjectViewState
import java.util.*
@InjectViewState
class UserFollowersPresenter @AssistedInject constructor(
private val followersRepository: FollowersRepository,
@Assisted private val userName: String
) : BasePresenter<UserFollowersView>() {
private var currentMaxPage = 1
private val followers: MutableList<Follow> = ArrayList()
private var isFollowersLoading = false
private val isFirstLoading: Boolean
private get() = currentMaxPage == 1
override fun onFirstViewAttach() {
viewState.showFollowersLoadingProgress(true)
loadMoreFollowers(currentMaxPage)
}
private fun loadMoreFollowers(page: Int) = launchSafe {
isFollowersLoading = true
val requestParams = UserFollowersParams(userName, page, PAGE_SIZE)
try {
val newFollowers = followersRepository.getUserFollowers(requestParams)
followers.addAll(newFollowers)
viewState.showNewFollowers(newFollowers)
} catch (throwable: NoNetworkException) {
if (isFirstLoading) {
viewState.showNoNetworkLayout(true)
} else {
viewState.showLoadMoreError()
}
} finally {
viewState.showFollowersLoadingProgress(false)
isFollowersLoading = false
}
}
fun onLoadMoreFollowersRequest() {
if (isFollowersLoading) {
return
}
viewState.showFollowersLoadingMoreProgress(true)
currentMaxPage++
loadMoreFollowers(currentMaxPage)
}
fun retryLoading() {
if (isFirstLoading) {
viewState.showNoNetworkLayout(false)
viewState.showFollowersLoadingProgress(true)
} else {
viewState.showFollowersLoadingMoreProgress(true)
}
loadMoreFollowers(currentMaxPage)
}
fun onFollowerClick(follow: Follow) {
router.navigateTo(UserProfileScreen(follow.follower.userName))
}
@AssistedFactory
interface Factory {
fun create(userName: String): UserFollowersPresenter
}
companion object {
private const val PAGE_SIZE = 20
}
}
| 1 | null |
1
| 1 |
7e89e69b855435a58efba724bbd4625582329505
| 2,629 |
Bubbble
|
The Unlicense
|
app/src/main/java/github/znzsofficial/widget/tab/FileTabLayout.kt
|
znzsofficial
| 736,991,346 | false |
{"Gradle Kotlin DSL": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "TOML": 1, "Proguard": 1, "JSON": 1, "Kotlin": 25, "XML": 27, "Java": 109}
|
package github.znzsofficial.widget.tab
import android.content.Context
import android.util.AttributeSet
import com.google.android.material.tabs.TabLayout
import java.io.File
class FileTabLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : TabLayout(context, attrs) {
private var onRemovedListener: OnTabRemovedListener? = null
init {
tabGravity = GRAVITY_START
}
fun addOnTabRemovedListener(listener: OnTabRemovedListener) {
onRemovedListener = listener
}
private fun newTab(file: File): Tab {
val tab = newTab()
tab.text = file.name
tab.tag = file
return tab
}
// 添加文件到 TabLayout.Tab,并添加到 TabLayout 中
fun addFile(file: File): Tab? {
val possibleTab = getTabByFile(file)
if (possibleTab != null) {
selectTab(possibleTab)
return null
}
val tab = newTab(file)
addTab(tab)
return tab
}
// 使用路径添加文件到 TabLayout.Tab,并添加到 TabLayout 中
fun addFile(path: String): Tab? {
return addFile(File(path))
}
fun getPositionByTab(tab: Tab): Int {
for (i in 0..<tabCount) {
val currentTab = getTabAt(i)
if (currentTab == tab) {
return i
}
}
return 0
}
fun getTabByFile(file: File?): Tab? {
for (i in 0..<tabCount) {
val currentTab = getTabAt(i)
if (currentTab?.tag == file) {
return currentTab
}
}
return null
}
fun selectTabAt(index: Int, animate: Boolean = false) {
selectTab(getTabAt(index), animate)
}
override fun removeTab(tab: Tab) {
onRemovedListener
?.onTabRemoved(tab, getPositionByTab(tab))
super.removeTab(tab)
}
override fun removeTabAt(position: Int) {
getTabAt(position)?.let {
onRemovedListener
?.onTabRemoved(it, position)
}
super.removeTabAt(position)
}
fun removeTabByPath(path: String) {
val position = 0
for (i in 0 until tabCount) {
val currentTab = getTabAt(i)
if ((currentTab?.tag as File).path == path) {
onRemovedListener
?.onTabRemoved(currentTab, position)
removeTabAt(i)
break
}
}
}
interface OnTabRemovedListener {
fun onTabRemoved(tab: Tab, position: Int)
}
}
| 0 |
Java
|
0
| 0 |
8b47ce11ec0128d3a1048e78bce0db461217aef9
| 2,532 |
LuaKt-Android
|
Apache License 2.0
|
clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/model/RunStepDeltaObject.kt
|
oapicf
| 529,246,487 | false |
{"Markdown": 6348, "YAML": 73, "Text": 16, "Ignore List": 52, "JSON": 1138, "Makefile": 3, "JavaScript": 1042, "F#": 585, "XML": 468, "Shell": 47, "Batchfile": 10, "Scala": 2313, "INI": 31, "Dockerfile": 17, "Maven POM": 22, "Java": 6356, "Emacs Lisp": 1, "Haskell": 39, "Swift": 263, "Ruby": 555, "OASv3-yaml": 19, "Cabal Config": 2, "Go": 1036, "Go Checksums": 1, "Go Module": 4, "CMake": 11, "C++": 3617, "TOML": 5, "Rust": 268, "Nim": 253, "Perl": 252, "Microsoft Visual Studio Solution": 2, "C#": 778, "HTML": 257, "Xojo": 507, "Gradle": 20, "R": 503, "JSON with Comments": 8, "QMake": 1, "Kotlin": 1548, "Python": 1600, "Crystal": 486, "ApacheConf": 2, "PHP": 1715, "Gradle Kotlin DSL": 1, "Protocol Buffer": 250, "C": 752, "Ada": 16, "Objective-C": 522, "Java Properties": 2, "Erlang": 521, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 501, "SQL": 242, "AsciiDoc": 1, "CSS": 3, "PowerShell": 507, "Elixir": 5, "Apex": 426, "Gemfile.lock": 1, "Option List": 2, "Eiffel": 277, "Gherkin": 1, "Dart": 500, "Groovy": 251, "Elm": 13}
|
/**
* OpenAI API
* The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details.
*
* The version of the OpenAPI document: 2.0.0
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.api.model
import org.openapitools.server.api.model.RunStepDeltaObjectDelta
import com.google.gson.annotations.SerializedName
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
/**
* Represents a run step delta i.e. any changed fields on a run step during streaming.
* @param id The identifier of the run step, which can be referenced in API endpoints.
* @param `object` The object type, which is always `thread.run.step.delta`.
* @param delta
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
data class RunStepDeltaObject (
/* The identifier of the run step, which can be referenced in API endpoints. */
@SerializedName("id") private val _id: kotlin.String?,
/* The object type, which is always `thread.run.step.delta`. */
@SerializedName("`object`") private val _`object`: RunStepDeltaObject.`Object`?,
@SerializedName("delta") private val _delta: RunStepDeltaObjectDelta?
) {
/**
* The object type, which is always `thread.run.step.delta`.
* Values: threadPeriodRunPeriodStepPeriodDelta
*/
enum class `Object`(val value: kotlin.String){
threadPeriodRunPeriodStepPeriodDelta("thread.run.step.delta");
}
val id get() = _id ?: throw IllegalArgumentException("id is required")
val `object` get() = _`object` ?: throw IllegalArgumentException("`object` is required")
val delta get() = _delta ?: throw IllegalArgumentException("delta is required")
}
| 2 |
Java
|
0
| 4 |
c04dc03fa17b816be6e9a262c047840301c084b6
| 2,027 |
openapi-openai
|
MIT License
|
purchases/src/main/kotlin/com/revenuecat/purchases/common/durationExtensions.kt
|
RevenueCat
| 127,346,826 | false |
{"Gemfile.lock": 1, "Gradle": 21, "Markdown": 16, "Java Properties": 10, "Ruby": 3, "Shell": 5, "Text": 1, "Ignore List": 17, "Batchfile": 4, "YAML": 6, "XML": 223, "INI": 5, "Proguard": 14, "Kotlin": 685, "JSON": 5, "TOML": 4, "Java": 44, "Gradle Kotlin DSL": 2, "HTML": 1}
|
package com.revenuecat.purchases.common
import java.util.Date
import kotlin.time.Duration
internal fun Duration.Companion.between(startTime: Date, endTime: Date): Duration {
return (endTime.time - startTime.time).milliseconds
}
internal fun min(duration1: Duration, duration2: Duration): Duration {
return if (duration1 < duration2) duration1 else duration2
}
| 1 | null |
1
| 1 |
5deff6cbebe4712ef3633053ceb6d217179f4fa6
| 371 |
purchases-android
|
MIT License
|
ontrack-common/src/main/java/net/nemerosa/ontrack/common/_KTUtils.kt
|
nemerosa
| 19,351,480 | false | null |
package net.nemerosa.ontrack.common
import java.util.*
import kotlin.reflect.KCallable
/**
* Combination of predicates
*/
infix fun <T> ((T) -> Boolean).and(other: (T) -> Boolean): (T) -> Boolean = { t ->
this.invoke(t) && other.invoke(t)
}
/**
* Creating an optional from a nullable reference
*/
fun <T> T?.asOptional(): Optional<T & Any> = Optional.ofNullable(this)
/**
* Optional to nullable
*/
fun <T> Optional<T>.getOrNull(): T? = orElse(null)
/**
* Converts a POJO as a map, using properties as index.
*/
fun <T : Any> T.asMap(vararg properties: KCallable<Any?>): Map<String, Any?> =
properties.associate { property ->
property.name to property.call()
}
/**
* Runs the code if the condition is met.
*/
fun <T> T.runIf(condition: Boolean, code: T.() -> T) = if (condition) {
code(this)
} else {
this
}
| 57 |
Kotlin
|
27
| 97 |
7c71a3047401e088ba0c6d43aa3a96422024857f
| 851 |
ontrack
|
MIT License
|
S04-ClasesYObjetos/CL08-InlineClasses/src/Programa.kt
|
thegoodcoders
| 258,229,039 | false | null |
fun main(args: Array<String>) {
// No se va a cargar un objeto de tipo Persona
// en tiempo de ejecución la variable "persona" va a contener es directamente el String
val persona = Persona("María")
println(persona)
}
inline class Persona(val nombre: String)
| 0 |
Kotlin
|
0
| 2 |
d7690911af92f9d30444b85bab78c79a5a9f117c
| 278 |
kotlin-introduccion
|
MIT License
|
src/main/kotlin/com/mparticle/kits/AdobeApi.kt
|
mparticle-integrations
| 209,084,952 | false | null |
package com.mparticle.kits
class AdobeApi(val marketingCloudID: String?)
| 4 |
Kotlin
|
4
| 0 |
ec160e63395cb9fe6c5c4e874c9e401ba6b6298c
| 73 |
mparticle-android-integration-adobe-media
|
Apache License 2.0
|
app/src/main/java/com/petnagy/navigatordemo/modules/signup/SignUpActivity.kt
|
petnagy
| 185,669,652 | false | null |
package com.petnagy.navigatordemo.modules.signup
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.petnagy.navigatordemo.R
import dagger.android.support.DaggerAppCompatActivity
class SignUpActivity : DaggerAppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_signup)
openFragment(SignupFragment())
}
fun openFragment(fragment: Fragment) {
val transaction = supportFragmentManager.beginTransaction()
.replace(R.id.signup_container, fragment)
.commit()
}
}
| 0 |
Kotlin
|
0
| 0 |
5e62c771dc4c7a3d606d079c3ea7e6987b15f263
| 644 |
navigator
|
Apache License 2.0
|
android/app/src/main/kotlin/com/example/traffic_weather/MainActivity.kt
|
stcojo
| 321,071,508 | false |
{"Dart": 64272, "Swift": 404, "Kotlin": 132, "Objective-C": 38}
|
package com.example.traffic_weather
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 |
Dart
|
0
| 0 |
af067255540a61e7a3c417b4c02a95e344671d7d
| 132 |
WeatherInfoFlutter
|
MIT License
|
customdata-gender/src/main/java/contacts/entities/custom/gender/GenderMimeType.kt
|
vestrel00
| 223,332,584 | false | null |
package contacts.entities.custom.gender
import contacts.core.entities.MimeType
internal object GenderMimeType : MimeType.Custom() {
// Following Contacts Provider convention of "vnd.package.cursor.item/mimetype"
override val value: String = "vnd.contacts.entities.custom.cursor.item/gender"
}
| 68 |
Kotlin
|
15
| 230 |
c4cad327dbe311d6c7d561e50ebff2f04297aaa2
| 303 |
contacts-android
|
Apache License 2.0
|
app/src/main/java/toy/narza/clonetracker/network/ApiService.kt
|
Yoon-SeungHwan
| 493,072,561 | false |
{"Kotlin": 15143}
|
package toy.narza.clonetracker.network
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import toy.narza.clonetracker.network.`interface`.IClient
object ApiService {
private val interceptor : HttpLoggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
private val client : OkHttpClient = OkHttpClient.Builder().apply {
addInterceptor(interceptor)
}.build()
private val retrofit: IClient by lazy {
Retrofit
.Builder()
.baseUrl(IClient.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build()
.create(IClient::class.java)
}
fun getProgress() = retrofit.getData()
}
| 0 |
Kotlin
|
0
| 0 |
6b33391c4ef863e34a9c04de5cd467d5ff6fdfda
| 868 |
clonetracker
|
MIT License
|
app/src/main/java/com/tradistonks/app/components/charts/pie/Utils.kt
|
tradistonks
| 360,664,184 | false | null |
package com.tradistonks.app.components.charts.pie
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.unit.Dp
import com.tradistonks.app.components.charts.ChartShape
import com.tradistonks.app.components.charts.internal.DEG2RAD
import com.tradistonks.app.components.charts.internal.FDEG2RAD
import com.tradistonks.app.components.charts.internal.safeGet
import com.tradistonks.app.components.charts.legend.LegendEntry
import kotlin.math.cos
import kotlin.math.pow
import kotlin.math.sin
import kotlin.math.sqrt
import kotlin.math.tan
internal fun PieChartData.createLegendEntries(
shapeSize: Dp,
): List<LegendEntry> =
entries.mapIndexed { index, item ->
LegendEntry(
text = item.label,
value = item.value,
percent = item.value * 100f / entries.map { it.value }.reduce { acc, i -> acc + i },
shape = ChartShape(
color = item.color ?: colors.safeGet(index),
shape = legendShape,
size = shapeSize,
)
)
}
internal fun PieChartData.calculateFractions(
minAngle: Float = 16f,
maxAngle: Float = 360f
): List<Float> {
val total = entries.sumByDouble { it.value.toDouble() }.toFloat()
val entryCount = entries.size
val hasMinAngle = minAngle != 0f && entryCount * minAngle <= maxAngle
val minAngles = MutableList(entryCount) { 0f }
val fractions = entries
.map { it.value / total }
.map { it * 360f }
var offset = 0f
var diff = 0f
if (hasMinAngle) {
fractions.forEachIndexed { idx, angle ->
val temp = angle - minAngle
if (temp <= 0) {
offset += -temp
minAngles[idx] = minAngle
} else {
minAngles[idx] = angle
diff += temp
}
}
fractions.forEachIndexed { idx, _ ->
minAngles[idx] -= (minAngles[idx] - minAngle) / diff * offset
}
return minAngles
}
return fractions
}
internal fun calculateMinimumRadiusForSpacedSlice(
center: Offset,
radius: Float,
angle: Float,
arcStartPointX: Float,
arcStartPointY: Float,
startAngle: Float,
sweepAngle: Float
): Float {
val angleMiddle = startAngle + sweepAngle / 2f
// Other point of the arc
val arcEndPointX: Float = center.x + radius * cos((startAngle + sweepAngle) * FDEG2RAD)
val arcEndPointY: Float = center.y + radius * sin((startAngle + sweepAngle) * FDEG2RAD)
// Middle point on the arc
val arcMidPointX: Float = center.x + radius * cos(angleMiddle * FDEG2RAD)
val arcMidPointY: Float = center.y + radius * sin(angleMiddle * FDEG2RAD)
// This is the base of the contained triangle
val basePointsDistance = sqrt(
(arcEndPointX - arcStartPointX).toDouble().pow(2.0) +
(arcEndPointY - arcStartPointY).toDouble().pow(2.0)
)
// After reducing space from both sides of the "slice",
// the angle of the contained triangle should stay the same.
// So let's find out the height of that triangle.
val containedTriangleHeight =
(basePointsDistance / 2.0 * tan((180.0 - angle) / 2.0 * DEG2RAD)).toFloat()
// Now we subtract that from the radius
var spacedRadius = radius - containedTriangleHeight
// And now subtract the height of the arc that's between the triangle and the outer circle
spacedRadius -= sqrt(
(arcMidPointX - (arcEndPointX + arcStartPointX) / 2f).toDouble().pow(2.0) +
(arcMidPointY - (arcEndPointY + arcStartPointY) / 2f).toDouble().pow(2.0)
).toFloat()
return spacedRadius
}
| 6 |
Kotlin
|
0
| 0 |
7043782ef4c703d5d496eabe30e8feed9db47190
| 3,417 |
tradistonks-mobile
|
MIT License
|
commons/ui/src/main/kotlin/com/trilobitech/commons/ui/ext/Typography.kt
|
pedrox-hs
| 689,138,926 | false |
{"Kotlin": 29077}
|
package com.trilobitech.commons.ui.ext
import androidx.compose.material3.Typography
import androidx.compose.ui.text.font.FontFamily
internal fun Typography.applyFontFamily(fontFamily: FontFamily): Typography =
Typography(
displayLarge = displayLarge.copy(fontFamily = fontFamily),
displayMedium = displayMedium.copy(fontFamily = fontFamily),
displaySmall = displaySmall.copy(fontFamily = fontFamily),
headlineLarge = headlineLarge.copy(fontFamily = fontFamily),
headlineMedium = headlineMedium.copy(fontFamily = fontFamily),
headlineSmall = headlineSmall.copy(fontFamily = fontFamily),
titleLarge = titleLarge.copy(fontFamily = fontFamily),
titleMedium = titleMedium.copy(fontFamily = fontFamily),
titleSmall = titleSmall.copy(fontFamily = fontFamily),
bodyLarge = bodyLarge.copy(fontFamily = fontFamily),
bodyMedium = bodyMedium.copy(fontFamily = fontFamily),
bodySmall = bodySmall.copy(fontFamily = fontFamily),
labelLarge = labelLarge.copy(fontFamily = fontFamily),
labelMedium = labelMedium.copy(fontFamily = fontFamily),
labelSmall = labelSmall.copy(fontFamily = fontFamily),
)
| 7 |
Kotlin
|
0
| 2 |
753518ed94fa319cc742ea2e37f711eb8fd6b685
| 1,213 |
TuneBlend
|
MIT License
|
src/test/kotlin/com/example/setintersection/TestOverridenConfiguration.kt
|
chut89
| 713,037,969 | false |
{"Kotlin": 39500}
|
package com.example.setintersection
import org.mockito.kotlin.mock
import org.springframework.boot.test.context.TestConfiguration
import org.springframework.context.annotation.Bean
import org.springframework.test.web.reactive.server.WebTestClient
@TestConfiguration
class TestOverridenConfiguration {
@Bean
fun mockSetIntersectionService(): SetIntersectionService = mock<SetIntersectionService>()
@Bean
fun mockWebTestClient(): WebTestClient = mock<WebTestClient>()
}
| 0 |
Kotlin
|
0
| 0 |
95f640836a7aa5493dbb4dfd62ea97decd567959
| 487 |
demo-set-intersection
|
The Unlicense
|
sphinx/screens/add-sats/add-sats/src/main/java/chat/sphinx/add_sats/navigation/ToAddSatsScreen.kt
|
stakwork
| 340,103,148 | false |
{"Kotlin": 4008358, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453}
|
package chat.sphinx.add_sats.navigation
import androidx.navigation.NavController
import chat.sphinx.add_sats.R
import io.matthewnelson.android_feature_navigation.DefaultNavOptions
import io.matthewnelson.concept_navigation.NavigationRequest
class ToAddSatsScreen: NavigationRequest<NavController>() {
override fun navigate(controller: NavController) {
controller.navigate(
R.id.add_sats_nav_graph,
null,
DefaultNavOptions.defaultAnimsBuilt
)
}
}
| 90 |
Kotlin
|
11
| 18 |
7811b4f4e5a0cf8a26f343704cfced011b1f9bad
| 508 |
sphinx-kotlin
|
MIT License
|
MulatschakTracker/app/src/main/java/com/example/mulatschaktracker/ui/home/HomeFragment.kt
|
sw21-tug
| 350,438,678 | false | null |
package com.example.mulatschaktracker.ui.home
import android.content.Context.MODE_PRIVATE
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.INVISIBLE
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.mulatschaktracker.R
import com.example.mulatschaktracker.StartNewGame
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.mulatschaktracker.*
class HomeFragment : Fragment() {
private lateinit var homeViewModel: HomeViewModel
private lateinit var recyclerView: RecyclerView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// homeViewModel =
// ViewModelProvider(this).get(HomeViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_games, container, false)
val textView: TextView = root.findViewById(R.id.text_game)
// homeViewModel.text.observe(viewLifecycleOwner, Observer {
// textView.text = it
// })
recyclerView = root.findViewById(R.id.gamesRecyclerView)
recyclerView.layoutManager = LinearLayoutManager(root.context)
val userRepository = UserRepository(root.context)
val gameRepository = GameRepository(root.context)
val preferences = this.activity?.getSharedPreferences(PREFERENCENAME, MODE_PRIVATE)
val userName = preferences?.getString(LASTUSER, "")
var gameList: List<GameObject> = ArrayList()
if(!userName.equals("")){
try {
val user = userName?.let { userRepository.getUser(it) }
gameList = user?.let { gameRepository.getGames(it.id, false) }!!
} catch (e: Exception) {
// no handling now
}
}
if(gameList.isNotEmpty()){
textView.text = ""
} else {
textView.text = root.context.getString(R.string.no_running_games)
}
recyclerView.adapter = GameRecyclerAdapter(gameList as ArrayList<GameObject>)
return root
}
}
| 5 | null |
10
| 3 |
e10ca45b5351aee4b23651db648ee8e315f8df42
| 2,384 |
Team_29
|
MIT License
|
src/test/kotlin/io/offscale/openfoodfacts/client/models/WarningOrErrorMessageTest.kt
|
SamuelMarks
| 866,322,014 | false |
{"Kotlin": 537174}
|
/**
*
* 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 io.offscale.openfoodfacts.client.models
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import io.offscale.openfoodfacts.client.models.WarningOrErrorMessage
import io.offscale.openfoodfacts.client.models.WarningOrErrorMessageField
import io.offscale.openfoodfacts.client.models.WarningOrErrorMessageImpact
import io.offscale.openfoodfacts.client.models.WarningOrErrorMessageMessage
class WarningOrErrorMessageTest : ShouldSpec() {
init {
// uncomment below to create an instance of WarningOrErrorMessage
//val modelInstance = WarningOrErrorMessage()
// to test the property `message`
should("test message") {
// uncomment below to test the property
//modelInstance.message shouldBe ("TODO")
}
// to test the property ``field``
should("test `field`") {
// uncomment below to test the property
//modelInstance.`field` shouldBe ("TODO")
}
// to test the property `impact`
should("test impact") {
// uncomment below to test the property
//modelInstance.impact shouldBe ("TODO")
}
}
}
| 0 |
Kotlin
|
0
| 1 |
0ba56f72b5d3ac32b20083ea70c28ca26c6bbdeb
| 1,455 |
openfoodfacts-kotlin-openapi
|
Apache License 2.0
|
tgbotapi.extensions.api/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/api/send/SendMessage.kt
|
Djaler
| 311,091,197 | true |
{"Kotlin": 816932, "Shell": 373}
|
package dev.inmo.tgbotapi.extensions.api.send
import dev.inmo.tgbotapi.CommonAbstracts.TextSource
import dev.inmo.tgbotapi.bot.TelegramBot
import dev.inmo.tgbotapi.requests.send.SendTextMessage
import dev.inmo.tgbotapi.types.ChatIdentifier
import dev.inmo.tgbotapi.types.MessageIdentifier
import dev.inmo.tgbotapi.types.ParseMode.ParseMode
import dev.inmo.tgbotapi.types.buttons.KeyboardMarkup
import dev.inmo.tgbotapi.types.chat.abstracts.Chat
import dev.inmo.tgbotapi.types.message.abstracts.Message
suspend fun TelegramBot.sendMessage(
chatId: ChatIdentifier,
text: String,
parseMode: ParseMode? = null,
disableWebPagePreview: Boolean? = null,
disableNotification: Boolean = false,
replyToMessageId: MessageIdentifier? = null,
allowSendingWithoutReply: Boolean? = null,
replyMarkup: KeyboardMarkup? = null
) = execute(
SendTextMessage(chatId, text, parseMode, disableWebPagePreview, disableNotification, replyToMessageId, allowSendingWithoutReply, replyMarkup)
)
suspend fun TelegramBot.sendTextMessage(
chatId: ChatIdentifier,
text: String,
parseMode: ParseMode? = null,
disableWebPagePreview: Boolean? = null,
disableNotification: Boolean = false,
replyToMessageId: MessageIdentifier? = null,
allowSendingWithoutReply: Boolean? = null,
replyMarkup: KeyboardMarkup? = null
) = sendMessage(
chatId, text, parseMode, disableWebPagePreview, disableNotification, replyToMessageId, allowSendingWithoutReply, replyMarkup
)
suspend fun TelegramBot.sendMessage(
chat: Chat,
text: String,
parseMode: ParseMode? = null,
disableWebPagePreview: Boolean? = null,
disableNotification: Boolean = false,
replyToMessageId: MessageIdentifier? = null,
allowSendingWithoutReply: Boolean? = null,
replyMarkup: KeyboardMarkup? = null
) = sendMessage(chat.id, text, parseMode, disableWebPagePreview, disableNotification, replyToMessageId, allowSendingWithoutReply, replyMarkup)
suspend fun TelegramBot.sendTextMessage(
chat: Chat,
text: String,
parseMode: ParseMode? = null,
disableWebPagePreview: Boolean? = null,
disableNotification: Boolean = false,
replyToMessageId: MessageIdentifier? = null,
allowSendingWithoutReply: Boolean? = null,
replyMarkup: KeyboardMarkup? = null
) = sendTextMessage(chat.id, text, parseMode, disableWebPagePreview, disableNotification, replyToMessageId, allowSendingWithoutReply, replyMarkup)
suspend fun TelegramBot.sendMessage(
chatId: ChatIdentifier,
entities: List<TextSource>,
disableWebPagePreview: Boolean? = null,
disableNotification: Boolean = false,
replyToMessageId: MessageIdentifier? = null,
allowSendingWithoutReply: Boolean? = null,
replyMarkup: KeyboardMarkup? = null
) = execute(
SendTextMessage(chatId, entities, disableWebPagePreview, disableNotification, replyToMessageId, allowSendingWithoutReply, replyMarkup)
)
suspend fun TelegramBot.sendTextMessage(
chatId: ChatIdentifier,
entities: List<TextSource>,
disableWebPagePreview: Boolean? = null,
disableNotification: Boolean = false,
replyToMessageId: MessageIdentifier? = null,
allowSendingWithoutReply: Boolean? = null,
replyMarkup: KeyboardMarkup? = null
) = sendMessage(
chatId, entities, disableWebPagePreview, disableNotification, replyToMessageId, allowSendingWithoutReply, replyMarkup
)
suspend fun TelegramBot.sendMessage(
chat: Chat,
entities: List<TextSource>,
disableWebPagePreview: Boolean? = null,
disableNotification: Boolean = false,
replyToMessageId: MessageIdentifier? = null,
allowSendingWithoutReply: Boolean? = null,
replyMarkup: KeyboardMarkup? = null
) = sendMessage(chat.id, entities, disableWebPagePreview, disableNotification, replyToMessageId, allowSendingWithoutReply, replyMarkup)
suspend fun TelegramBot.sendTextMessage(
chat: Chat,
entities: List<TextSource>,
disableWebPagePreview: Boolean? = null,
disableNotification: Boolean = false,
replyToMessageId: MessageIdentifier? = null,
allowSendingWithoutReply: Boolean? = null,
replyMarkup: KeyboardMarkup? = null
) = sendTextMessage(chat.id, entities, disableWebPagePreview, disableNotification, replyToMessageId, allowSendingWithoutReply, replyMarkup)
suspend inline fun TelegramBot.reply(
to: Message,
text: String,
parseMode: ParseMode? = null,
disableWebPagePreview: Boolean? = null,
disableNotification: Boolean = false,
allowSendingWithoutReply: Boolean? = null,
replyMarkup: KeyboardMarkup? = null
) = sendTextMessage(
to.chat,
text,
parseMode,
disableWebPagePreview,
disableNotification,
to.messageId,
allowSendingWithoutReply,
replyMarkup
)
suspend inline fun TelegramBot.reply(
to: Message,
entities: List<TextSource>,
disableWebPagePreview: Boolean? = null,
disableNotification: Boolean = false,
allowSendingWithoutReply: Boolean? = null,
replyMarkup: KeyboardMarkup? = null
) = sendTextMessage(
to.chat,
entities,
disableWebPagePreview,
disableNotification,
to.messageId,
allowSendingWithoutReply,
replyMarkup
)
| 0 | null |
0
| 0 |
83edda2dfe370fbc35f2e73283cd71e79f101e3c
| 5,167 |
TelegramBotAPI
|
Apache License 2.0
|
src/main/kotlin/org/urielserv/uriel/core/database/schemas/users/UsersSchema.kt
|
UrielHabboServer
| 729,131,075 | false |
{"Kotlin": 299445}
|
package org.urielserv.uriel.core.database.schemas.users
import org.ktorm.schema.*
import org.urielserv.uriel.core.database.schemas.ranks.RanksSchema
import org.urielserv.uriel.game.habbos.HabboGender
import org.urielserv.uriel.game.habbos.HabboInfo
@Suppress("unused")
object UsersSchema : Table<HabboInfo>("users") {
val id = int("id").primaryKey().bindTo { it.id }
val username = varchar("username").bindTo { it.username }
val password = text("password").bindTo { it.password }
val ssoTicket = varchar("sso_ticket").bindTo { it.ssoTicket }
val email = varchar("email").bindTo { it.email }
val isEmailVerified = boolean("is_email_verified").bindTo { it.isEmailVerified }
val rankId = int("rank_id").references(RanksSchema) { it.rank }
val accountCreation = int("account_creation_timestamp").bindTo { it.accountCreation }
val lastLogin = int("last_login_timestamp").bindTo { it.lastLogin }
val lastOnline = int("last_online_timestamp").bindTo { it.lastOnline }
val isOnline = boolean("is_online").bindTo { it.isOnline }
val motto = varchar("motto").bindTo { it.motto }
val look = text("look").bindTo { it.look }
val gender = enum<HabboGender>("gender").bindTo { it.gender }
val registrationIp = varchar("registration_ip").bindTo { it.registrationIp }
val currentIp = varchar("current_ip").bindTo { it.currentIp }
val homeRoomId = int("home_room_id").bindTo { it.homeRoomId }
}
| 0 |
Kotlin
|
0
| 7 |
3c2ca62e01e958fb21d86bef45b1928e05b53e23
| 1,457 |
Uriel
|
MIT License
|
sample/src/main/java/com/haroncode/gemini/sample/domain/model/auth/AuthResponse.kt
|
Hukumister
| 237,633,280 | false | null |
package com.haroncode.gemini.sample.domain.model.auth
data class AuthResponse(
val token: String
)
| 9 |
Kotlin
|
4
| 24 |
5173514d49667a0a60beac4930ea0848dea71f97
| 104 |
Gemini
|
MIT License
|
src/main/kotlin/uk/bfi/uvaudit/security/AuditUserService.kt
|
bfidatadigipres
| 339,780,686 | false | null |
package uk.bfi.uvaudit.security
import org.springframework.dao.support.DataAccessUtils
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
import org.springframework.jdbc.support.GeneratedKeyHolder
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService
import org.springframework.security.oauth2.core.OAuth2AuthenticationException
import org.springframework.security.oauth2.core.oidc.user.OidcUser
import javax.sql.DataSource
class AuditUserService(
dataSource: DataSource,
private val delegate: OidcUserService = OidcUserService()
) : OidcUserService() {
private val jdbcTemplate = NamedParameterJdbcTemplate(dataSource)
@Throws(OAuth2AuthenticationException::class)
override fun loadUser(userRequest: OidcUserRequest): AuditUser {
val oidcUser = delegate.loadUser(userRequest)
val auditUser = fetchUser(oidcUser)
return auditUser?.let { updateUser(oidcUser, it) } ?: createUser(oidcUser)
}
private fun fetchUser(oidcUser: OidcUser): AuditUser? {
val sql = "SELECT id FROM user where sub = :sub"
val params = MapSqlParameterSource(
mapOf("sub" to oidcUser.subject)
)
val dbUserIds = jdbcTemplate.queryForList(sql, params, Long::class.java)
return DataAccessUtils.uniqueResult(dbUserIds)?.let { AuditUser(it, oidcUser) }
}
private fun createUser(oidcUser: OidcUser): AuditUser {
val sql = "INSERT INTO user (sub, email, department) VALUES (:sub, :email, :department)"
val params = MapSqlParameterSource(
mapOf(
"sub" to oidcUser.subject,
"email" to oidcUser.email,
"department" to extractDepartmentClaim(oidcUser)
)
)
val keyHolder = GeneratedKeyHolder()
jdbcTemplate.update(sql, params, keyHolder)
return AuditUser(keyHolder.key!!.toLong(), oidcUser)
}
private fun updateUser(oidcUser: OidcUser, auditUser: AuditUser): AuditUser {
val sql = "UPDATE user SET email = :email, department = :department WHERE id = :id"
val params = MapSqlParameterSource(
mapOf(
"email" to oidcUser.email,
"department" to extractDepartmentClaim(oidcUser),
"id" to auditUser.id
)
)
jdbcTemplate.update(sql, params)
return AuditUser(auditUser.id, oidcUser)
}
private fun extractDepartmentClaim(oidcUser: OidcUser): String? {
val customClaims = oidcUser.getClaimAsMap("https://bfi.org.uk/")
return customClaims?.get("department") as String?
}
}
| 4 |
Kotlin
|
0
| 4 |
b09609f91f5f4e5072b82dfbec443648aac46194
| 2,814 |
bfi-iiif-logging
|
MIT License
|
android/measure/src/test/java/sh/measure/android/attributes/ComputeOnceAttributeProcessorTest.kt
|
measure-sh
| 676,897,841 | false |
{"Kotlin": 890104, "Go": 615450, "Swift": 379937, "TypeScript": 350495, "Shell": 26060, "Objective-C": 17998, "C": 9958, "Python": 7639, "Lua": 1206, "JavaScript": 1053, "CMake": 479, "CSS": 461, "C++": 445}
|
package sh.measure.android.attributes
import org.junit.Assert
import org.junit.Test
import sh.measure.android.events.EventType
import sh.measure.android.fakes.TestData
import sh.measure.android.fakes.TestData.toEvent
class ComputeOnceAttributeProcessorTest {
@Test
fun `compute attributes is only called once when appending attributes`() {
var computeAttributesCalledCount = 0
// Given
val processor = object : ComputeOnceAttributeProcessor() {
override fun computeAttributes(): Map<String, Any?> {
computeAttributesCalledCount++
return mapOf("key" to "value")
}
}
val event = TestData.getExceptionData().toEvent(type = EventType.EXCEPTION)
// When
processor.appendAttributes(event.attributes)
processor.appendAttributes(event.attributes)
processor.appendAttributes(event.attributes)
// Then
Assert.assertEquals(1, computeAttributesCalledCount)
}
}
| 75 |
Kotlin
|
25
| 484 |
86b1a2363fcb9abd876151dacc4f9fa15fc1f7ba
| 1,011 |
measure
|
Apache License 2.0
|
src/main/kotlin/io/github/eendroroy/exposed/demo/controller/api/BaseApiController.kt
|
eendroroy
| 719,427,531 | false |
{"Kotlin": 34877}
|
package io.github.eendroroy.exposed.demo.controller.api
import io.github.eendroroy.exposed.demo.persistence.user.User
import io.github.eendroroy.exposed.demo.security.model.UserDetail
import jakarta.servlet.http.HttpServletRequest
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpHeaders
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContextHolder
import java.security.Principal
open class BaseApiController {
@Autowired
private lateinit var httpRequest: HttpServletRequest
fun agent(): String? = httpRequest.getHeader(HttpHeaders.USER_AGENT)
fun token(): String? = httpRequest.getHeader(HttpHeaders.AUTHORIZATION).ifBlank { null }
fun currentUser(): User {
val auth: Authentication = SecurityContextHolder.getContext().authentication
return (auth.principal as UserDetail).user
}
}
| 0 |
Kotlin
|
0
| 1 |
fdd5973868238269630622622fc8d2ae8b4497cd
| 942 |
exposed.demo
|
MIT License
|
src/main/kotlin/com/baulsupp/oksocial/services/google/firebase/FirebaseCompleter.kt
|
fkorotkov
| 116,174,513 | true |
{"Kotlin": 375382, "Shell": 8328}
|
package com.baulsupp.oksocial.services.google.firebase
import com.baulsupp.oksocial.completion.ApiCompleter
import com.baulsupp.oksocial.completion.DirCompletionVariableCache
import com.baulsupp.oksocial.completion.HostUrlCompleter
import com.baulsupp.oksocial.completion.UrlList
import com.baulsupp.oksocial.kotlin.queryOptionalMap
import com.baulsupp.oksocial.kotlin.request
import com.baulsupp.oksocial.util.FileUtil
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import java.util.logging.Logger
class FirebaseCompleter(private val client: OkHttpClient) : ApiCompleter {
suspend override fun prefixUrls(): UrlList = UrlList(UrlList.Match.HOSTS, HostUrlCompleter.hostUrls(hosts(), false))
suspend override fun siteUrls(url: HttpUrl): UrlList {
val results = siblings(url) + children(url)
val candidates = results.map { url.newBuilder().encodedPath(it).build().toString() }
logger.fine("candidates $candidates")
return UrlList(UrlList.Match.EXACT, dedup(candidates + thisNode(url)))
}
private fun dedup(candidates: List<String>) = candidates.toSortedSet().toList()
suspend fun thisNode(url: HttpUrl): List<String> {
val path = url.encodedPath()
if (path.endsWith("/")) {
return listOf("$url.json")
} else if (path.endsWith(".json") || url.querySize() > 0) {
return listOf(url.toString())
} else if (path.contains('.')) {
return listOf(url.toString().replaceAfterLast(".", "json"))
} else {
return listOf()
}
}
suspend fun siblings(url: HttpUrl): List<String> {
if (url.encodedPath() == "/" || url.querySize() > 1 || url.encodedPath().contains(".")) {
return listOf()
} else {
val parentPath = url.encodedPath().replaceAfterLast("/", "")
val encodedPath = url.newBuilder().encodedPath("$parentPath.json")
var siblings = keyList(encodedPath)
return siblings.toList().flatMap { listOf("$parentPath$it", "$parentPath$it.json") }
}
}
suspend fun keyList(encodedPath: HttpUrl.Builder): List<String> {
val request = encodedPath.addQueryParameter("shallow", "true").build().request()
return client.queryOptionalMap<Any>(request)?.keys?.toList().orEmpty()
}
suspend fun children(url: HttpUrl): List<String> {
if (url.querySize() > 1 || url.encodedPath().contains(".")) {
return listOf()
} else {
val path = url.encodedPath()
val encodedPath = url.newBuilder().encodedPath("$path.json")
var children = keyList(encodedPath)
val prefixPath = if (path.endsWith("/")) path else path + "/"
return children.toList().flatMap { listOf(prefixPath + it + "/", prefixPath + it + ".json") }
}
}
fun hosts(): List<String> = knownHosts()
companion object {
private val logger = Logger.getLogger(FirebaseCompleter::class.java.name)
val firebaseCache = DirCompletionVariableCache(FileUtil.oksocialSettingsDir)
fun knownHosts(): List<String> = firebaseCache["firebase", "hosts"].orEmpty()
fun registerKnownHost(host: String) {
val previous = firebaseCache["firebase", "hosts"]
if (previous == null || !previous.contains(host)) {
firebaseCache["firebase", "hosts"] = listOf(host) + (previous ?: listOf())
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
f7e496f47500a1c3bb0b86d0ac239f4fb46e15f3
| 3,249 |
oksocial
|
Apache License 2.0
|
src/test/kotlin/reactivecircus/firestorm/TestProjectCreator.kt
|
ReactiveCircus
| 205,325,547 | false | null |
package reactivecircus.firestorm
import org.gradle.api.Action
import org.gradle.api.Project
import java.io.File
fun Project.createAndroidAppProject(hasProductFlavor: Boolean) {
appExtension.apply {
compileSdkVersion(30)
if (hasProductFlavor) {
flavorDimensions("environment")
productFlavors {
it.create("mock")
it.create("prod")
}
}
}
File(projectDir, "src/main/AndroidManifest.xml").apply {
parentFile.mkdirs()
writeText("""<manifest package="com.foo.bar"/>""")
}
}
fun Project.createAndroidLibraryProject(hasProductFlavor: Boolean) {
libraryExtension.apply {
compileSdkVersion(30)
if (hasProductFlavor) {
flavorDimensions("environment")
productFlavors(
Action {
it.create("mock")
it.create("prod")
}
)
}
}
File(projectDir, "src/main/AndroidManifest.xml").apply {
parentFile.mkdirs()
writeText("""<manifest package="com.foo.bar"/>""")
}
}
| 0 |
Kotlin
|
0
| 8 |
9298fe5f47deb24d0f463566a70864042ac6ccdd
| 1,133 |
Firestorm
|
Apache License 2.0
|
src/main/java/tpoomlmly/blockround/block/BarSignBlock.kt
|
tpoomlmly
| 379,071,851 | false | null |
package tpoomlmly.blockround.block
import net.fabricmc.fabric.api.`object`.builder.v1.block.FabricBlockSettings
import net.minecraft.block.*
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.fluid.Fluids
import net.minecraft.item.ItemPlacementContext
import net.minecraft.sound.BlockSoundGroup
import net.minecraft.state.StateManager
import net.minecraft.state.property.DirectionProperty
import net.minecraft.util.*
import net.minecraft.util.hit.BlockHitResult
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import net.minecraft.world.BlockView
import net.minecraft.world.World
import net.minecraft.world.WorldAccess
import net.minecraft.world.WorldView
import tpoomlmly.blockround.entity.BarSignBlockEntity
class BarSignBlock : AbstractSignBlock(
FabricBlockSettings.of(Material.DECORATION).noCollision().strength(1F).sounds(BlockSoundGroup.WOOD),
SignType.OAK
) {
companion object {
val FACING: DirectionProperty = HorizontalFacingBlock.FACING // TODO allow all sign directions
private val OUTLINES = mapOf(
Direction.NORTH to createCuboidShape(0.0, 0.0, 7.0, 16.0, 20.0, 9.0),
Direction.SOUTH to createCuboidShape(0.0, 0.0, 7.0, 16.0, 20.0, 9.0),
Direction.EAST to createCuboidShape(7.0, 0.0, 0.0, 9.0, 20.0, 16.0),
Direction.WEST to createCuboidShape(7.0, 0.0, 0.0, 9.0, 20.0, 16.0),
)
}
init {
this.defaultState =
this.stateManager.defaultState
.with(FACING, Direction.NORTH)
.with(WATERLOGGED, false)
}
/**
* Gets the shape of the outline that appears when someone looks at this block.
*/
override fun getOutlineShape(state: BlockState, world: BlockView?, pos: BlockPos?, context: ShapeContext?) =
OUTLINES[state.get(FACING)]
/**
* Can this sign be placed at the given position?
* @return true if the block underneath is solid.
*/
override fun canPlaceAt(state: BlockState, world: WorldView, pos: BlockPos) =
world.getBlockState(pos.down()).material.isSolid
/**
* Calculates the state of this sign when it's placed.
*/
override fun getPlacementState(context: ItemPlacementContext): BlockState? {
val directions = context.placementDirections.filter { it.axis.isHorizontal }
return if (directions.isEmpty()) null
else defaultState
.with(FACING, directions[0].opposite)
.with(WATERLOGGED, context.world.getFluidState(context.blockPos).fluid === Fluids.WATER)
}
/**
* AbstractSignBlock tries to dye the sign. This is the same as the superclass but without dye logic.
*/
override fun onUse(
state: BlockState,
world: World,
pos: BlockPos,
player: PlayerEntity,
hand: Hand,
hitResult: BlockHitResult
) = if (world.isClient()) ActionResult.CONSUME else ActionResult.SUCCESS
/**
* Gets the new state for this block when a neighbour has updated.
*/
override fun getStateForNeighborUpdate(
state: BlockState,
direction: Direction,
neighborState: BlockState?,
world: WorldAccess?,
pos: BlockPos?,
neighborPos: BlockPos?
): BlockState? = if (direction == Direction.DOWN && !state.canPlaceAt(world, pos))
Blocks.AIR.defaultState
else super.getStateForNeighborUpdate(
state,
direction,
neighborState,
world,
pos,
neighborPos
)
override fun rotate(state: BlockState, rotation: BlockRotation): BlockState =
state.with(FACING, rotation.rotate(state.get(FACING)))
override fun mirror(state: BlockState, mirror: BlockMirror): BlockState =
state.rotate(mirror.getRotation(state.get(FACING)))
override fun appendProperties(builder: StateManager.Builder<Block?, BlockState?>) {
builder.add(FACING, WATERLOGGED)
}
override fun createBlockEntity(pos: BlockPos, state: BlockState) = BarSignBlockEntity(pos, state)
override fun canMobSpawnInside() = false
override fun getRenderType(state: BlockState?) = BlockRenderType.MODEL // TODO ENTITYBLOCK_ANIMATED might be the key to making it swing
}
| 0 |
Kotlin
|
0
| 0 |
af368ddf4ac0df5c8fa51262a39b4c07a907bbfe
| 4,274 |
blockround
|
MIT License
|
android/koin-android/src/main/java/org/koin/android/contextaware/ContextAwareComponent.kt
|
prpgleto
| 112,472,267 | true |
{"Kotlin": 79464, "Shell": 462}
|
package org.koin.android.contextaware
/**
* Context Aware interface
*/
interface ContextAwareComponent {
val contextName: String
val contextDrop: ContextDropMethod
}
/**
* Context Aware drop methods
*/
enum class ContextDropMethod {
OnPause, OnDestroy
}
/**
* Default configuration for ContextAwareComponent
*/
object ContextAwareConfig {
var defaultContextDrop = ContextDropMethod.OnPause
}
| 0 |
Kotlin
|
0
| 0 |
6850bba2477840382093a095fac31045b1d56c2e
| 416 |
koin
|
Apache License 2.0
|
video-common-ui/src/main/java/com/kaleyra/video_common_ui/mapper/ParticipantMapper.kt
|
KaleyraVideo
| 686,975,102 | false |
{"Kotlin": 5207104, "Shell": 7470, "Python": 6799, "Java": 2583}
|
/*
* Copyright 2023 Kaleyra @ https://www.kaleyra.com
*
* 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.kaleyra.video_common_ui.mapper
import com.kaleyra.video.conference.Call
import com.kaleyra.video.conference.CallParticipant
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.transform
/**
* Utility functions for the call participants
*/
object ParticipantMapper {
/**
* Utility function to retrieve my participant
* @receiver Flow<Call> the call flow
* @return Flow<CallParticipant.Me> flow emitting my participant whenever is available
*/
fun Call.toMe(): Flow<CallParticipant.Me> =
this.participants
.mapNotNull { it.me }
.distinctUntilChanged()
/**
* Utility function to retrieve the participants that are in-call
* @receiver Flow<Call> the call flow
* @return Flow<CallParticipant.Me> flow emitting all the participants that are in-call
*/
fun Call.toInCallParticipants(): Flow<List<CallParticipant>> =
this.participants
.mapNotNull { participants -> participants.me?.let { Pair(it, participants.others) }}
.flatMapLatest { (me, others) ->
val inCallMap = mutableMapOf<String, CallParticipant>(me.userId to me)
val notInCallMap = mutableMapOf<String, CallParticipant>()
if (others.isEmpty()) flowOf<List<CallParticipant>>(listOf(me))
else others
.map { participant ->
combine(participant.state, participant.streams) { state, streams ->
val isInCall = state == CallParticipant.State.InCall || streams.isNotEmpty()
Pair(participant, isInCall)
}
}
.merge()
.transform { (participant, isInCall) ->
if (isInCall) {
inCallMap[participant.userId] = participant
notInCallMap.remove(participant.userId)
} else {
notInCallMap[participant.userId] = participant
inCallMap.remove(participant.userId)
}
val values = (inCallMap.values + notInCallMap.values).toList()
if (values.size == others.size + 1) {
emit(inCallMap.values.toList())
}
}
}
.distinctUntilChanged()
fun Call.areOtherParticipantsRinging(): Flow<Boolean> {
return participants
.map { it.others }
.flatMapLatest { participants ->
val map = mutableMapOf<String, CallParticipant.State>()
if (participants.isEmpty()) flowOf( false)
else participants
.map { participant ->
participant.state.map { participant.userId to it }
}
.merge()
.transform { (userId, state) ->
map[userId] = state
val values = map.values.toList()
if (values.size == participants.size) {
val isAnyRinging = values.any { it is CallParticipant.State.NotInCall.Ringing }
val isNoneInCall = values.none { it is CallParticipant.State.InCall }
emit(isAnyRinging && isNoneInCall)
}
}
}
.distinctUntilChanged()
}
}
| 0 |
Kotlin
|
0
| 1 |
9faa41e5903616889f2d0cd79ba21e18afe800ed
| 4,483 |
VideoAndroidSDK
|
Apache License 2.0
|
Movies/app/src/main/java/com/daresay/movies/data/local/MovieDao.kt
|
Ezzpify
| 346,202,639 | false | null |
package com.daresay.movies.data.local
import androidx.lifecycle.LiveData
import androidx.room.*
import com.daresay.movies.data.models.favorites.Favorite
import com.daresay.movies.data.models.favorites.FavoriteWithMovieDetails
import com.daresay.movies.data.models.moviedetails.MovieDetails
@Dao
interface MovieDao {
@Query("SELECT * FROM MovieDetails WHERE id = :movieId")
fun getMovie(movieId: Int) : LiveData<MovieDetails>
@Query("SELECT * FROM Favorites WHERE movieId = :movieId")
fun getFavorite(movieId: Int) : LiveData<Favorite>
@Query("SELECT * FROM Favorites WHERE favorite = 1")
fun getAllFavorites() : LiveData<List<FavoriteWithMovieDetails>>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(movie: MovieDetails)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(favorite: Favorite)
}
| 0 |
Kotlin
|
0
| 0 |
9b667638bdf81db4cb4e81d9de3bd561e4d36b30
| 877 |
DaresayMovies
|
MIT License
|
data/src/main/java/com/aconno/sensorics/data/repository/devices/DeviceEntity.kt
|
recreational-snacker
| 163,322,239 | false | null |
package com.aconno.sensorics.data.repository.devices
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
@Entity(tableName = "devices")
data class DeviceEntity(
var name: String,
var alias: String,
@PrimaryKey var macAddress: String,
var icon: String,
var connectable: Boolean = false
)
| 0 |
Kotlin
|
0
| 0 |
18530c7272e685744f1b25f223124e9f67bfdd0b
| 348 |
Sensorics
|
Apache License 2.0
|
lib/examples/src/jsMain/kotlin/zakadabar/lib/examples/frontend/dock/DockBasicExample.kt
|
wiltonlazary
| 378,492,647 | true |
{"Kotlin": 1162402, "JavaScript": 2042, "HTML": 1390, "Shell": 506}
|
/*
* Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.lib.examples.frontend.dock
import org.w3c.dom.HTMLElement
import zakadabar.stack.frontend.builtin.ZkElement
import zakadabar.stack.frontend.builtin.button.buttonSecondary
import zakadabar.stack.frontend.resources.ZkIcons
class DockBasicExample(
element: HTMLElement
) : ZkElement(element) {
override fun onCreate() {
+ buttonSecondary("Try It!") {
zke { + "Hello World!" }.dock(ZkIcons.account_box, "hello")
}
}
}
| 0 | null |
0
| 0 |
1eabec93db32f09cf715048c6cffd0a7948f4d9c
| 596 |
zakadabar-stack
|
Apache License 2.0
|
lib/examples/src/jsMain/kotlin/zakadabar/lib/examples/frontend/dock/DockBasicExample.kt
|
wiltonlazary
| 378,492,647 | true |
{"Kotlin": 1162402, "JavaScript": 2042, "HTML": 1390, "Shell": 506}
|
/*
* Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.lib.examples.frontend.dock
import org.w3c.dom.HTMLElement
import zakadabar.stack.frontend.builtin.ZkElement
import zakadabar.stack.frontend.builtin.button.buttonSecondary
import zakadabar.stack.frontend.resources.ZkIcons
class DockBasicExample(
element: HTMLElement
) : ZkElement(element) {
override fun onCreate() {
+ buttonSecondary("Try It!") {
zke { + "Hello World!" }.dock(ZkIcons.account_box, "hello")
}
}
}
| 0 | null |
0
| 0 |
1eabec93db32f09cf715048c6cffd0a7948f4d9c
| 596 |
zakadabar-stack
|
Apache License 2.0
|
sandbox/src/jsMain/showcases/MDCList.kt
|
mpetuska
| 430,798,310 | false | null |
package showcases
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import dev.petuska.katalog.runtime.Showcase
import dev.petuska.katalog.runtime.layout.InteractiveShowcase
import dev.petuska.kmdc.list.*
import dev.petuska.kmdc.list.item.*
import sandbox.control.BooleanControl
import sandbox.control.ChoiceControl
import sandbox.util.NamedGroup
private class MDCListVM {
var type by mutableStateOf(MDCListType.Default)
var size by mutableStateOf(MDCListSize.SingleLine)
var selection by mutableStateOf(MDCListSelection.Single)
var dense by mutableStateOf(false)
var wrapFocus by mutableStateOf(false)
var divider by mutableStateOf(false)
var inset by mutableStateOf(MDCListDividerInset.None)
val items = listOf("Java", "Kotlin", "Scala", "Groovy", "JavaScript", "TypeScript")
}
@Composable
@Showcase(id = "MDCList")
fun MDCList() = InteractiveShowcase(
viewModel = { MDCListVM() },
controls = {
ChoiceControl("Type", MDCListType.values().associateBy(MDCListType::name), ::type)
ChoiceControl("Size", MDCListSize.values().associateBy(MDCListSize::name), ::size)
ChoiceControl("Selection", MDCListSelection.values().associateBy(MDCListSelection::name), ::selection)
BooleanControl("Dense", ::dense)
BooleanControl("Wrap Focus", ::wrapFocus)
NamedGroup("Divider") {
BooleanControl("Enabled", ::divider)
ChoiceControl("Inset", MDCListDividerInset.values().associateBy(MDCListDividerInset::name), ::inset)
}
},
) {
MDCList(
type = type,
size = size,
selection = selection,
attrs = {
registerEvents()
}
) {
items.chunked(2).forEachIndexed { i, group ->
MDCListGroup {
Subheader("Group $i")
MDCList(
type = type,
size = size,
selection = selection,
dense = dense,
wrapFocus = wrapFocus,
) {
group.forEachIndexed { j, item ->
ListItem {
val id = "kmdc-list-item-${i * 2 + j}"
when (selection) {
MDCListSelection.SingleRadio -> RadioGraphic(false, id)
MDCListSelection.MultiCheckbox -> CheckboxGraphic(false, id)
else -> {}
}
if (size == MDCListSize.TwoLine) {
Label(forId = id) {
Primary(item)
Secondary("$item description")
}
} else {
Label(text = item, forId = id)
}
}
if (divider && j == 0) Divider(inset = inset)
}
}
if (divider && i % 2 == 0) Divider(inset = inset)
}
}
}
}
private fun MDCListAttrsScope<*>.registerEvents() {
onAction { console.log("MDCList#onAction", it.detail) }
onSelectionChanged { console.log("MDCList#onSelectionChanged", it.detail) }
}
| 9 |
Kotlin
|
13
| 99 |
c1ba9cf15d091916f1e253c4c37cc9f9c643f5e3
| 2,967 |
kmdc
|
Apache License 2.0
|
app/src/main/java/com/nawrot/mateusz/compass/home/CompassActivityModule.kt
|
mateusz-nawrot
| 111,402,545 | false | null |
package com.nawrot.mateusz.compass.home
import dagger.Module
@Module
class CompassActivityModule
| 0 |
Kotlin
|
0
| 1 |
fca6ca190a3cf16141726bfb955bd2cff1a8bb33
| 99 |
compass
|
Apache License 2.0
|
app/src/main/java/com/permissionx/app/MainActivity.kt
|
android-little-boy
| 306,526,312 | false | null |
package com.permissionx.app
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.permissionx.androidLittleBoy.PermissionX
import kotlinx.android.synthetic.main.activity_main.*
import java.util.jar.Manifest
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
makeCallBtn.setOnClickListener {
PermissionX.request(this,android.Manifest.permission.CALL_PHONE){ allGranted,deniedList->
if (allGranted){
call()
}else{
Toast.makeText(this,"You denied $deniedList",Toast.LENGTH_SHORT).show()
}
}
}
}
private fun call(){
val intent= Intent(Intent.ACTION_CALL)
intent.data= Uri.parse("tel:10086")
startActivity(intent)
}
}
| 0 |
Kotlin
|
0
| 0 |
25d4be320e1476d00364936a79a03364e6a4c23b
| 1,028 |
PermissionX
|
Apache License 2.0
|
src/test/kotlin/at/cpickl/gadsu/view/machandler.kt
|
christophpickl
| 56,092,216 | false | null |
package at.cpickl.gadsu.view
object TestMacHandler : MacHandler {
override fun isEnabled() = false
override fun registerAbout(onAbout: () -> Unit) { }
override fun registerPreferences(onPreferences: () -> Unit) { }
override fun registerQuit(onQuit: () -> Unit) { }
}
| 43 |
Kotlin
|
1
| 2 |
f6a84c42e1985bc53d566730ed0552b3ae71d94b
| 284 |
gadsu
|
Apache License 2.0
|
magic/core/src/main/java/link/magic/android/modules/connect/response/ShowWalletResponse.kt
|
magiclabs
| 589,703,550 | false | null |
package link.magic.android.modules.connect.response
import org.web3j.protocol.core.Response
import androidx.annotation.Keep
@Keep
class ShowWalletResponse: Response<Boolean>()
| 0 |
Kotlin
|
0
| 2 |
676f89d138cbe76f72b289fdd164e72ffc796e32
| 179 |
magic-android
|
MIT License
|
app/src/main/java/com/sbma/linkup/api/RetrofitFactory.kt
|
ericaskari-metropolia
| 694,027,591 | false |
{"Kotlin": 323836, "HTML": 71958, "TypeScript": 19773, "Dockerfile": 577, "JavaScript": 256}
|
package com.sbma.linkup.api
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitFactory {
fun makeApiService(): ApiService {
return Retrofit.Builder()
.baseUrl("https://sbma.ericaskari.com/")
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(ResultCallAdapterFactory())
.build().create(ApiService::class.java)
}
}
| 0 |
Kotlin
|
1
| 1 |
436d8f46fc76a9d6af2ab5e997dc673d9ee1bf08
| 447 |
sbma
|
MIT License
|
src/commonMain/kotlin/de/robolab/client/renderer/events/ScrollEvent.kt
|
pixix4
| 243,975,894 | false | null |
package de.robolab.client.renderer.events
import de.robolab.common.utils.Dimension
import de.robolab.common.utils.Vector
import de.robolab.common.utils.Rectangle
import de.robolab.common.utils.dimension
class ScrollEvent(
mousePoint: Vector,
val delta: Vector,
screen: Dimension,
ctrlKey: Boolean = false,
altKey: Boolean = false,
shiftKey: Boolean = false
) : PointerEvent(mousePoint, screen, ctrlKey, altKey, shiftKey) {
override fun clip(clip: Rectangle): ScrollEvent {
return ScrollEvent(
mousePoint - clip.topLeft,
delta,
clip.dimension,
ctrlKey,
altKey,
shiftKey
)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
if (!super.equals(other)) return false
other as ScrollEvent
if (delta != other.delta) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + delta.hashCode()
return result
}
}
| 4 |
Kotlin
|
0
| 2 |
1f20731971a9b02f971f01ab8ae8f4e506ff542b
| 1,160 |
robolab-renderer
|
MIT License
|
reveal-shapes/src/main/kotlin/com/svenjacobs/reveal/shapes/balloon/Arrow.kt
|
svenjacobs
| 568,775,557 | false | null |
package com.svenjacobs.reveal.shapes.balloon
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.ui.Alignment
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import com.svenjacobs.reveal.shapes.balloon.Arrow.Companion.bottom
import com.svenjacobs.reveal.shapes.balloon.Arrow.Companion.end
import com.svenjacobs.reveal.shapes.balloon.Arrow.Companion.start
import com.svenjacobs.reveal.shapes.balloon.Arrow.Companion.top
/**
* An arrow pointing to start, top, end or bottom to be used with [Balloon].
*
* @see [start]
* @see [top]
* @see [end]
* @see [bottom]
* @see Balloon
*/
public sealed interface Arrow {
public companion object {
private val DefaultHorizontalWidth = 8.dp
private val DefaultHorizontalHeight = 12.dp
@Composable
@ReadOnlyComposable
public fun start(
width: Dp = DefaultHorizontalWidth,
height: Dp = DefaultHorizontalHeight,
verticalAlignment: Alignment.Vertical = Alignment.CenterVertically,
): Arrow = when (LocalLayoutDirection.current) {
LayoutDirection.Ltr -> ::StartInternal
LayoutDirection.Rtl -> ::EndInternal
}(width, height, verticalAlignment)
@Composable
@ReadOnlyComposable
public fun top(
width: Dp = DefaultHorizontalHeight,
height: Dp = DefaultHorizontalWidth,
horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally,
): Arrow = TopInternal(
width = width,
height = height,
horizontalAlignment = horizontalAlignment,
)
@Composable
@ReadOnlyComposable
public fun end(
width: Dp = DefaultHorizontalWidth,
height: Dp = DefaultHorizontalHeight,
verticalAlignment: Alignment.Vertical = Alignment.CenterVertically,
): Arrow = when (LocalLayoutDirection.current) {
LayoutDirection.Ltr -> ::EndInternal
LayoutDirection.Rtl -> ::StartInternal
}(width, height, verticalAlignment)
@Composable
@ReadOnlyComposable
public fun bottom(
width: Dp = DefaultHorizontalHeight,
height: Dp = DefaultHorizontalWidth,
horizontalAlignment: Alignment.Horizontal = Alignment.CenterHorizontally,
): Arrow = BottomInternal(
width = width,
height = height,
horizontalAlignment = horizontalAlignment,
)
private fun Alignment.Horizontal.cornerRadiusOffset(
cornerRadius: Float,
layoutDirection: LayoutDirection,
): Float = when (this) {
Alignment.Start -> cornerRadius
Alignment.End -> -cornerRadius
else -> 0f
}.let { if (layoutDirection == LayoutDirection.Rtl) -it else it }
private fun Alignment.Vertical.cornerRadiusOffset(cornerRadius: Float): Float = when (this) {
Alignment.Top -> cornerRadius
Alignment.Bottom -> -cornerRadius
else -> 0f
}
}
public val width: Dp
public val height: Dp
/**
* [PaddingValues] that must be applied to Balloon content to account for arrow.
*/
public val padding: PaddingValues
/**
* Returns [Path] that renders arrow.
*/
public fun path(density: Density): Path
/**
* Returns [Offset] which must be applied to [Path] returned by [path] when shape is rendered.
*/
public fun offset(
density: Density,
size: Size,
cornerRadius: Float,
layoutDirection: LayoutDirection,
): Offset
private class StartInternal(
override val width: Dp,
override val height: Dp,
private val verticalAlignment: Alignment.Vertical,
) : Arrow {
override val padding: PaddingValues = PaddingValues.Absolute(left = width)
override fun path(density: Density): Path = with(density) {
Path().apply {
moveTo(0f, height.toPx() / 2f)
lineTo(width.toPx(), 0f)
lineTo(width.toPx(), height.toPx())
close()
}
}
override fun offset(
density: Density,
size: Size,
cornerRadius: Float,
layoutDirection: LayoutDirection,
): Offset = with(density) {
Offset(
x = 0f,
y = verticalAlignment.align(
size = height.roundToPx(),
space = size.height.toInt(),
).toFloat() + verticalAlignment.cornerRadiusOffset(cornerRadius),
)
}
}
private class TopInternal(
override val width: Dp,
override val height: Dp,
private val horizontalAlignment: Alignment.Horizontal,
) : Arrow {
override val padding: PaddingValues = PaddingValues.Absolute(top = height)
override fun path(density: Density): Path = with(density) {
Path().apply {
moveTo(0f, height.toPx())
lineTo(width.toPx() / 2f, 0f)
lineTo(width.toPx(), height.toPx())
close()
}
}
override fun offset(
density: Density,
size: Size,
cornerRadius: Float,
layoutDirection: LayoutDirection,
): Offset = with(density) {
Offset(
x = horizontalAlignment.align(
size = width.roundToPx(),
space = size.width.toInt(),
layoutDirection = layoutDirection,
).toFloat() + horizontalAlignment.cornerRadiusOffset(
cornerRadius,
layoutDirection,
),
y = 0f,
)
}
}
private class EndInternal(
override val width: Dp,
override val height: Dp,
private val verticalAlignment: Alignment.Vertical,
) : Arrow {
override val padding: PaddingValues = PaddingValues.Absolute(right = width)
override fun path(density: Density): Path = with(density) {
Path().apply {
lineTo(width.toPx(), height.toPx() / 2f)
lineTo(0f, height.toPx())
close()
}
}
override fun offset(
density: Density,
size: Size,
cornerRadius: Float,
layoutDirection: LayoutDirection,
): Offset = with(density) {
Offset(
x = size.width - width.toPx(),
y = verticalAlignment.align(
size = height.roundToPx(),
space = size.height.toInt(),
).toFloat() + verticalAlignment.cornerRadiusOffset(cornerRadius),
)
}
}
private class BottomInternal(
override val width: Dp,
override val height: Dp,
private val horizontalAlignment: Alignment.Horizontal,
) : Arrow {
override val padding: PaddingValues = PaddingValues.Absolute(bottom = height)
override fun path(density: Density): Path = with(density) {
Path().apply {
lineTo(width.toPx() / 2f, height.toPx())
lineTo(width.toPx(), 0f)
close()
}
}
override fun offset(
density: Density,
size: Size,
cornerRadius: Float,
layoutDirection: LayoutDirection,
): Offset = with(density) {
Offset(
x = horizontalAlignment.align(
width.roundToPx(),
size.width.toInt(),
layoutDirection,
).toFloat() + horizontalAlignment.cornerRadiusOffset(
cornerRadius,
layoutDirection,
),
y = size.height - height.toPx(),
)
}
}
}
| 1 |
Kotlin
|
3
| 95 |
371cd5803f722ec415679a9289d5b1043c655df8
| 6,819 |
reveal
|
MIT License
|
app/src/main/java/com/charlezz/opencvtutorial/presentation/screen/basic/BackProjectContent.kt
|
Charlezz
| 343,679,405 | false |
{"C++": 5307900, "Java": 2997356, "C": 360745, "CMake": 270863, "Kotlin": 263062, "Objective-C": 8344, "HTML": 6526, "Makefile": 4817, "AIDL": 995}
|
package com.charlezz.opencvtutorial.presentation.screen.basic
import android.view.MotionEvent
import android.widget.Space
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.input.pointer.pointerInteropFilter
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.layout.onSizeChanged
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.charlezz.opencvtutorial.R
import com.charlezz.opencvtutorial.toBitmap
import org.opencv.android.Utils
import org.opencv.core.*
import org.opencv.imgproc.Imgproc
import timber.log.Timber
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.min
/**
* @author soohwan.ok
*/
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun BackProjectContent() {
val context = LocalContext.current
val src by remember { mutableStateOf(Utils.loadResource(context, R.drawable.runa).also { Imgproc.cvtColor(it, it, Imgproc.COLOR_BGR2RGB) }) }
var dst by remember { mutableStateOf(src) }
var isDone by remember { mutableStateOf(false) }
var initPoint by remember { mutableStateOf(Point(0.0, 0.0)) }
var imageSize by remember { mutableStateOf(Size(0.0, 0.0)) }
Column(horizontalAlignment = Alignment.CenterHorizontally) {
TextButton(
modifier = Modifier.align(alignment = Alignment.CenterHorizontally),
enabled = isDone,
onClick = {
isDone = false
dst = src
}
) {
Text(text = if (isDone) "Reset" else "Drag to select area")
}
Image(
modifier = Modifier
.width(IntrinsicSize.Max)
.height(IntrinsicSize.Max)
.aspectRatio(
ratio = src
.width()
.toFloat() / src
.height()
.toFloat()
)
.onSizeChanged {
imageSize = Size(it.width.toDouble(), it.height.toDouble())
}
.pointerInteropFilter { event ->
if (isDone) {
return@pointerInteropFilter true
}
when (event.action) {
MotionEvent.ACTION_DOWN -> {
Timber.d("ACTION_DOWN")
initPoint = Point(event.x.toDouble(), event.y.toDouble())
}
MotionEvent.ACTION_MOVE -> {
Timber.d("ACTION_MOVE")
val newDst = Mat()
src.copyTo(newDst)
val ratio = src
.width()
.toDouble() / imageSize.width
Imgproc.rectangle(
newDst,
Point(initPoint.x * ratio, initPoint.y * ratio),
Point(event.x.toDouble() * ratio, event.y.toDouble() * ratio),
Scalar(0.0, 0.0, 255.0)
)
dst = newDst
}
MotionEvent.ACTION_UP -> {
Timber.d("ACTION_UP")
if (abs(initPoint.x - event.x) < 1.0f ||
abs(initPoint.y - event.y) < 1.0f
) {
Toast
.makeText(
context,
"Drag to select area again",
Toast.LENGTH_SHORT
)
.show()
return@pointerInteropFilter true
}
val x = min(max(event.x, 0f), imageSize.width.toFloat())
val y = min(max(event.y, 0f), imageSize.height.toFloat())
val ratio = src.width() / imageSize.width
val srcWithRoi = Mat(
src,
Rect(
Point(initPoint.x * ratio, initPoint.y * ratio),
Point(x.toDouble() * ratio, y.toDouble() * ratio)
)
)
val srcYCrCb = Mat()
Imgproc.cvtColor(srcWithRoi, srcYCrCb, Imgproc.COLOR_BGR2YCrCb)
val channels = MatOfInt(1, 2)
val ranges = MatOfFloat(0f, 256f, 0f, 256f)
val hist = Mat()
Imgproc.calcHist(
listOf(srcWithRoi),
channels,
Mat(),
hist,
MatOfInt(128, 128),
ranges
)
val backProject = Mat()
Imgproc.calcBackProject(
listOf(src),
channels,
hist,
backProject,
ranges,
1.0
)
val newDst = Mat()
Core.copyTo(src, newDst, backProject)
isDone = true
dst = newDst
}
}
true
}
.align(Alignment.CenterHorizontally)
,
bitmap = dst.toBitmap().asImageBitmap(),
contentDescription = null,
contentScale = ContentScale.FillBounds
)
}
}
| 0 |
C++
|
4
| 6 |
ee62c1f7ef684a87a5be26ba2de84d7ecf422202
| 6,484 |
OpenCVTutorial
|
Apache License 2.0
|
src/com/blogspot/kotlinstudy/graphnote/HelpDialog.kt
|
cdcsgit
| 400,042,410 | false | null |
package com.blogspot.kotlinstudy.graphnote
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import javax.swing.*
import javax.swing.plaf.basic.BasicScrollBarUI
class HelpDialog(parent: JFrame) : JDialog(parent, "Help", true), ActionListener {
private var mHelpTextPane: JTextPane
private var mCloseBtn : ColorButton
init {
mCloseBtn = ColorButton("Close")
mCloseBtn.addActionListener(this)
mHelpTextPane = JTextPane()
mHelpTextPane.contentType = "text/html"
mHelpTextPane.text = HelpText.text
val scrollPane = JScrollPane(mHelpTextPane)
val aboutPanel = JPanel()
scrollPane.preferredSize = Dimension(850, 800)
scrollPane.verticalScrollBar.ui = BasicScrollBarUI()
scrollPane.horizontalScrollBar.ui = BasicScrollBarUI()
aboutPanel.add(scrollPane)
val panel = JPanel()
panel.layout = BorderLayout()
panel.add(aboutPanel, BorderLayout.CENTER)
val btnPanel = JPanel()
btnPanel.add(mCloseBtn)
panel.add(btnPanel, BorderLayout.SOUTH)
contentPane.add(panel)
pack()
}
override fun actionPerformed(e: ActionEvent?) {
if (e?.source == mCloseBtn) {
dispose()
}
}
}
private class HelpText() {
companion object {
val text =
"""
<html>
<body>
<center><font size=7>graph view utility</font><br>
<font size=5>==================================================================================</font></center>
<b>Data format</b><br>
TITLE|title string <br>
SETTINGS|Y Name|X Name|X Range|Y Min value|Min annotation <br>
Xval|Line name#Yval#Description1(Can be omitted)|Line name2#Yval2#Description2 ...
<pre>
Example
TITLE|Show CPU Usage : top -b -d 1
SETTINGS|CPU|TIME|160|0.1|0.5
1631165418|Total#7.3|999982-top#2.3|6558-Xorg#0.8|6889-cinnamon#0.8|8784-terminator#0.8
1631165419|Total#0.9|688631-java#0.4|999230-chrome#0.2|6889-cinnamon#0.1
</pre>
</body>
</html>
""".trimIndent()
}
}
| 0 |
Kotlin
|
0
| 0 |
7796480da6344d6c2681e64e3b6a39c61d770b7c
| 2,174 |
graphnote
|
Apache License 2.0
|
shared/src/commonTest/kotlin/co/touchlab/kampkit/SqlDelightTest.kt
|
anhtuanBk
| 840,141,057 | false |
{"Kotlin": 87492, "Swift": 12925}
|
package co.touchlab.kampkit
import co.touchlab.kampkit.db.User
import co.touchlab.kampkit.db.UserDetails
import co.touchlab.kermit.Logger
import co.touchlab.kermit.StaticConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class SqlDelightTest {
private lateinit var dbHelper: DatabaseHelper
private suspend fun DatabaseHelper.insertUsers(users: List<User>) {
insertUsers(users)
}
private val page: Long = 1
private val login = "cdc"
private val mockUsers: List<User> = listOf(
User(
"aaa",
"mkdc.com",
"ikdkc.asa",
page
),
User(
"dsdd",
"mksddc.com",
"ikwewdkc.asa",
page
)
)
private val mockUserDetails = UserDetails(
login,
"dmck.cjdnc",
"cjndjc.ncjdnc",
"jandc",
1212,
12313
)
@BeforeTest
fun setup() = runTest {
dbHelper = DatabaseHelper(
testDbConnection(),
Logger(StaticConfig()),
Dispatchers.Default
)
dbHelper.deleteAll()
dbHelper.insertUsers(mockUsers)
dbHelper.insertUserDetail(mockUserDetails)
}
@Test
fun `Select Users by page Success`() = runTest {
val users = dbHelper.selectUsersByPage(page.toInt()).first()
assertEquals(
users,
mockUsers
)
}
@Test
fun `Select UserDetails by login Success`() = runTest {
val userDetails = dbHelper.selectUserDetailsByLogin(login).first()
assertEquals(
userDetails,
mockUserDetails
)
}
@Test
fun `Delete All Success`() = runTest {
assertTrue(dbHelper.selectUsersByPage(page.toInt()).first().isNotEmpty())
dbHelper.deleteAll()
assertTrue(
dbHelper.selectUsersByPage(page.toInt()).first().isEmpty(),
"Delete All did not work"
)
}
}
| 0 |
Kotlin
|
0
| 0 |
c7d9b40f9d0e7a382703a6270aa395600c23f290
| 2,171 |
github-users
|
Apache License 2.0
|
data/src/main/java/com/m3u/data/remote/api/dto/Content.kt
|
realOxy
| 592,741,804 | false |
{"Kotlin": 470914}
|
@file:Suppress("unused")
package com.m3u.data.remote.api.dto
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Content(
@SerialName("_links")
val links: Links,
@SerialName("download_url")
val downloadUrl: String,
@SerialName("git_url")
val gitUrl: String,
@SerialName("html_url")
val htmlUrl: String,
@SerialName("name")
val name: String,
@SerialName("path")
val path: String,
@SerialName("sha")
val sha: String,
@SerialName("size")
val size: Int,
@SerialName("type")
val type: String,
@SerialName("url")
val url: String
) {
@Serializable
data class Links(
@SerialName("git")
val git: String,
@SerialName("html")
val html: String,
@SerialName("self")
val self: String
)
companion object {
const val TYPE_DIR = "dir"
const val TYPE_FILE = "file"
}
}
| 0 |
Kotlin
|
2
| 25 |
c4b88978c36fbd254414d81aa8926fcf3223d185
| 973 |
M3UAndroid
|
Apache License 2.0
|
app/src/main/java/com/hsf1002/sky/wanandroid/presenter/HomeFragmentPresenterImpl.kt
|
hafitzrizki
| 129,183,302 | false | null |
package com.hsf1002.sky.wanandroid.presenter
import com.hsf1002.sky.wanandroid.bean.BannerResponse
import com.hsf1002.sky.wanandroid.bean.HomeListResponse
import com.hsf1002.sky.wanandroid.model.CollectArticleModel
import com.hsf1002.sky.wanandroid.model.HomeModel
import com.hsf1002.sky.wanandroid.model.HomeModelImpl
import com.hsf1002.sky.wanandroid.view.CollectArticleView
import com.hsf1002.sky.wanandroid.view.HomeFragmentView
/**
* Created by hefeng on 18-3-24.
*/
class HomeFragmentPresenterImpl(private val homeFragmentView: HomeFragmentView,
private val collectArticleView: CollectArticleView
):HomePresenter.OnHomeListListener, HomePresenter.OnCollectArticleListener, HomePresenter.OnBannerListener
{
private val homeModel:HomeModel = HomeModelImpl()
private val collectArticleModel:CollectArticleModel = HomeModelImpl()
override fun getHomeList(page: Int) {
homeModel.getHomeList(this, page)
}
override fun getHomeListSuccess(result: HomeListResponse) {
if (result.errorCode != 0) {
homeFragmentView.getHomeListFailed(result.errorMsg)
return
}
val total = result.data.total
if (total == 0) {
homeFragmentView.getHomeListZero()
return
} else if (total < result.data.size) {
homeFragmentView.getHomeListSmall(result)
return
}
else
{
homeFragmentView.getHomeListSuccess(result)
}
}
override fun getHomeListFailed(errorMsg: String?) {
homeFragmentView.getHomeListFailed(errorMsg)
}
override fun collectArticle(id: Int, isAdd: Boolean) {
collectArticleModel.collectArticle(this, id, isAdd)
}
override fun collectArticleSuccess(result: HomeListResponse, isAdd: Boolean) {
if (result.errorCode != 0)
{
collectArticleView.collectArticleFailed(result.errorMsg, isAdd)
}
else
{
collectArticleView.collectArticleSuccess(result, isAdd)
}
}
override fun collectArticleFailed(errorMsg: String, isAdd: Boolean) {
collectArticleView.collectArticleFailed(errorMsg, isAdd)
}
override fun getBanner() {
homeModel.getBanner(this)
}
override fun getBannerSuccess(result: BannerResponse) {
if (result.errorCode != 0)
{
homeFragmentView.getBannerFailed(result.errorMsg)
return
}
result.data?:let {
homeFragmentView.getBannerZero()
return
}
homeFragmentView.getBannerSuccess(result)
}
override fun getBannerFailed(errorMsg: String) {
homeFragmentView.getBannerFailed(errorMsg)
}
fun cancelRequest()
{
homeModel.cancelBannerRequest()
homeModel.cancelHomeListRequest()
collectArticleModel.cancelCollectRequest()
}
}
| 0 |
Kotlin
|
0
| 0 |
9cf96fc9d6bcfade72d1f94046bde7373b7d038d
| 2,940 |
WanAndroid
|
Apache License 2.0
|
src/jsMain/kotlin/EventJs.kt
|
Kotlin
| 33,301,379 | false | null |
package org.w3c.dom.events // ktlint-disable filename
import org.w3c.dom.*
public actual external interface Event {
val type: String
val target: EventTarget?
val currentTarget: EventTarget?
val eventPhase: Short
val bubbles: Boolean
val cancelable: Boolean
val defaultPrevented: Boolean
val composed: Boolean
val isTrusted: Boolean
val timeStamp: Number
fun stopImmediatePropagation()
fun composedPath(): Array<EventTarget>
actual fun stopPropagation()
actual fun preventDefault()
actual fun initEvent(eventTypeArg: String, canBubbleArg: Boolean, cancelableArg: Boolean)
}
| 72 |
Kotlin
|
113
| 1,271 |
c2f8ee0df425e5188681ac821034c8781ee2a146
| 637 |
kotlinx.html
|
Apache License 2.0
|
beckon-mesh/src/main/java/com/technocreatives/beckon/mesh/model/UnprovisionedScanResult.kt
|
technocreatives
| 364,517,134 | false | null |
package com.technocreatives.beckon.mesh.model
import android.os.Parcelable
import com.technocreatives.beckon.MacAddress
import kotlinx.parcelize.Parcelize
import java.util.*
@Parcelize
data class UnprovisionedScanResult(
val macAddress: MacAddress,
val name: String?,
val rssi: Int,
val uuid: UUID
) : Parcelable
| 1 |
Kotlin
|
1
| 8 |
2e252df19c02104821c393225ee8d5abefa07b74
| 330 |
beckon-android
|
Apache License 2.0
|
src/commonMain/kotlin/org/snakeyaml/engine/v2/constructor/core/ConstructYamlCoreFloat.kt
|
krzema12
| 642,543,787 | false | null |
/*
* Copyright (c) 2018, SnakeYAML
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.snakeyaml.engine.v2.constructor.core
import org.snakeyaml.engine.v2.constructor.json.ConstructYamlJsonFloat
import org.snakeyaml.engine.v2.nodes.Node
import org.snakeyaml.engine.v2.nodes.ScalarNode
/**
* Create Double instances for float
*/
class ConstructYamlCoreFloat : ConstructYamlJsonFloat() {
override fun constructScalar(node: Node?): String {
// to lower case to parse the special values in any case
return (node as ScalarNode).value.lowercase()
}
}
| 9 |
Kotlin
|
0
| 3 |
ff5fc9f1f6962145007d8d10079857bd8d9c2652
| 1,086 |
snakeyaml-engine-kmp
|
Apache License 2.0
|
detectors/src/main/kotlin/com/serchinastico/lin/detectors/noDataFrameworksFromAndroidClassDetector.kt
|
Serchinastico
| 158,760,415 | false | null |
package com.serchinastico.lin.detectors
import com.android.tools.lint.detector.api.Scope
import com.serchinastico.lin.annotations.Detector
import com.serchinastico.lin.dsl.detector
import com.serchinastico.lin.dsl.isAndroidFrameworkType
import com.serchinastico.lin.dsl.isFrameworkLibraryImport
import com.serchinastico.lin.dsl.issue
@Detector
fun noDataFrameworksFromAndroidClass() = detector(
issue(
Scope.JAVA_FILE_SCOPE,
"""Framework classes to get or store data should never be called from Activities, Fragments or any other
| Android related view.""".trimMargin(),
"""Your Android classes should not be responsible for retrieving or storing information, that should be
| responsibility of another classes.""".trimMargin()
)
) {
import { suchThat { it.isFrameworkLibraryImport } }
type { suchThat { node -> node.uastSuperTypes.any { it.isAndroidFrameworkType } } }
}
| 10 |
Kotlin
|
7
| 235 |
964f00f40e544e61f96e80065c71d5d91adefb3d
| 945 |
Lin
|
Apache License 2.0
|
app/src/main/kotlin/app/lawnchair/lawnicons/viewmodel/LawniconsViewModel.kt
|
LawnchairLauncher
| 423,607,805 | false |
{"Kotlin": 256343, "Python": 16278, "JavaScript": 6611}
|
package app.lawnchair.lawnicons.viewmodel
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import app.lawnchair.lawnicons.model.IconInfoModel
import app.lawnchair.lawnicons.model.IconRequestModel
import app.lawnchair.lawnicons.model.SearchMode
import app.lawnchair.lawnicons.repository.IconRepository
import app.lawnchair.lawnicons.repository.NewIconsRepository
import app.lawnchair.lawnicons.ui.util.SampleData
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
interface LawniconsViewModel {
val iconInfoModel: StateFlow<IconInfoModel>
val searchedIconInfoModel: StateFlow<IconInfoModel>
val iconRequestModel: StateFlow<IconRequestModel?>
val newIconsInfoModel: StateFlow<IconInfoModel>
var expandSearch: Boolean
val searchMode: SearchMode
val searchTerm: String
fun searchIcons(query: String)
fun changeMode(mode: SearchMode)
fun clearSearch()
}
@HiltViewModel
class LawniconsViewModelImpl @Inject constructor(
private val iconRepository: IconRepository,
private val newIconsRepository: NewIconsRepository,
) : LawniconsViewModel, ViewModel() {
override val iconInfoModel = iconRepository.iconInfoModel
override val searchedIconInfoModel = iconRepository.searchedIconInfoModel
override val iconRequestModel = iconRepository.iconRequestList
override val newIconsInfoModel = newIconsRepository.newIconsInfoModel
override var expandSearch by mutableStateOf(false)
private var _searchMode by mutableStateOf(SearchMode.LABEL)
private var _searchTerm by mutableStateOf("")
override val searchMode: SearchMode
get() = _searchMode
override val searchTerm: String
get() = _searchTerm
override fun searchIcons(query: String) {
_searchTerm = query
viewModelScope.launch {
iconRepository.search(searchMode, searchTerm)
}
}
override fun changeMode(mode: SearchMode) {
_searchMode = mode
viewModelScope.launch {
iconRepository.search(searchMode, searchTerm)
}
}
override fun clearSearch() {
_searchTerm = ""
viewModelScope.launch {
iconRepository.clearSearch()
}
}
}
class DummyLawniconsViewModel : LawniconsViewModel {
private val list = SampleData.iconInfoList
override val iconInfoModel = MutableStateFlow(IconInfoModel(iconInfo = list, iconCount = list.size)).asStateFlow()
override val searchedIconInfoModel = MutableStateFlow(IconInfoModel(iconInfo = list, iconCount = list.size)).asStateFlow()
override val iconRequestModel = MutableStateFlow(IconRequestModel(list = listOf(), iconCount = 0)).asStateFlow()
override val newIconsInfoModel = MutableStateFlow(IconInfoModel(iconInfo = list, iconCount = list.size)).asStateFlow()
override var expandSearch by mutableStateOf(false)
override val searchMode = SearchMode.LABEL
override val searchTerm = ""
override fun searchIcons(query: String) {}
override fun changeMode(mode: SearchMode) {}
override fun clearSearch() {}
}
| 32 |
Kotlin
|
459
| 1,355 |
d126cb719b82a0ccebf7fe5295019356ec3df70b
| 3,410 |
lawnicons
|
Apache License 2.0
|
src/main/kotlin/me/fzzyhmstrs/amethyst_imbuement/spells/LightningStormAugment.kt
|
fzzyhmstrs
| 461,338,617 | false | null |
package me.fzzyhmstrs.amethyst_imbuement.spells
import me.fzzyhmstrs.amethyst_core.augments.AugmentHelper
import me.fzzyhmstrs.amethyst_core.augments.ScepterAugment
import me.fzzyhmstrs.amethyst_core.augments.SpellActionResult
import me.fzzyhmstrs.amethyst_core.augments.base.EntityAoeAugment
import me.fzzyhmstrs.amethyst_core.augments.base.ProjectileAugment
import me.fzzyhmstrs.amethyst_core.augments.data.AugmentDatapoint
import me.fzzyhmstrs.amethyst_core.augments.paired.AugmentType
import me.fzzyhmstrs.amethyst_core.augments.paired.DamageSourceBuilder
import me.fzzyhmstrs.amethyst_core.augments.paired.PairedAugments
import me.fzzyhmstrs.amethyst_core.augments.paired.ProcessContext
import me.fzzyhmstrs.amethyst_core.interfaces.SpellCastingEntity
import me.fzzyhmstrs.amethyst_core.modifier.AugmentEffect
import me.fzzyhmstrs.amethyst_core.modifier.addLang
import me.fzzyhmstrs.amethyst_core.scepter.LoreTier
import me.fzzyhmstrs.amethyst_core.scepter.ScepterTier
import me.fzzyhmstrs.amethyst_core.scepter.SpellType
import me.fzzyhmstrs.amethyst_imbuement.AI
import me.fzzyhmstrs.amethyst_imbuement.entity.PlayerLightningEntity
import me.fzzyhmstrs.amethyst_imbuement.spells.pieces.ApplyTaskAugmentData
import me.fzzyhmstrs.amethyst_imbuement.spells.pieces.ContextData
import me.fzzyhmstrs.amethyst_imbuement.spells.pieces.SpellAdvancementChecks
import me.fzzyhmstrs.amethyst_imbuement.spells.pieces.SpellHelper
import me.fzzyhmstrs.fzzy_core.coding_util.PerLvlI
import me.fzzyhmstrs.fzzy_core.coding_util.PersistentEffectHelper
import me.fzzyhmstrs.fzzy_core.raycaster_util.RaycasterUtil
import net.minecraft.entity.Entity
import net.minecraft.entity.LivingEntity
import net.minecraft.entity.damage.DamageTypes
import net.minecraft.item.Items
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.server.world.ServerWorld
import net.minecraft.sound.SoundCategory
import net.minecraft.sound.SoundEvents
import net.minecraft.text.Text
import net.minecraft.util.Hand
import net.minecraft.util.hit.EntityHitResult
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import net.minecraft.world.World
@Suppress("SpellCheckingInspection")
class LightningStormAugment: EntityAoeAugment(ScepterTier.THREE, AugmentType.AREA_DAMAGE), PersistentEffectHelper.PersistentEffect{
override val augmentData: AugmentDatapoint =
AugmentDatapoint(
AI.identity("lightning_storm"),SpellType.FURY,400,80,
23,3,1,10,LoreTier.HIGH_TIER, Items.COPPER_BLOCK)
//ml 3
override val baseEffect: AugmentEffect
get() = super.baseEffect.withRange(8.0,1.0,0.0)
.withDuration(0,120,0)
.withDamage(5.0f,1.0f)
override fun <T> canTarget(
entityHitResult: EntityHitResult,
context: ProcessContext,
world: World,
user: T,
hand: Hand,
spells: PairedAugments
): Boolean where T : SpellCastingEntity,T : LivingEntity {
return SpellHelper.hostileTarget(entityHitResult.entity,user,this)
}
override fun appendDescription(description: MutableList<Text>, other: ScepterAugment, othersType: AugmentType) {
description.addLang("amethyst_imbuement.todo")
}
override fun filter(list: List<Entity>, user: LivingEntity): MutableList<EntityHitResult> {
return SpellHelper.hostileFilter(list,user,this)
}
override fun provideArgs(pairedSpell: ScepterAugment): Array<Text> {
return arrayOf(pairedSpell.provideNoun(this))
}
override fun onPaired(player: ServerPlayerEntity, pair: PairedAugments) {
SpellAdvancementChecks.uniqueOrDouble(player, pair)
}
override val delay = PerLvlI(21,-3,0)
override fun damageSourceBuilder(world: World, source: Entity?, attacker: LivingEntity?): DamageSourceBuilder {
return super.damageSourceBuilder(world, source, attacker).set(DamageTypes.LIGHTNING_BOLT)
}
override fun <T> applyTasks(world: World, context: ProcessContext, user: T, hand: Hand, level: Int, effects: AugmentEffect, spells: PairedAugments)
:
SpellActionResult
where
T: LivingEntity,
T: SpellCastingEntity
{
val onCastResults = spells.processOnCast(context,world,null,user, hand, level, effects)
if (!onCastResults.success()) return FAIL
if (onCastResults.overwrite()) return onCastResults
val hit = RaycasterUtil.raycastBlock(effects.range(level),user)
val entityList = RaycasterUtil.raycastEntityArea(effects.range(level), user, if (hit != null) Vec3d.of(hit) else null)
val filteredList = filter(entityList,user)
if (filteredList.isEmpty()) return FAIL
val list = spells.processMultipleEntityHits(filteredList,context,world,null,user, hand, level, effects)
list.addAll(onCastResults.results())
return if (list.isEmpty()) {
FAIL
} else {
if (!context.get(ContextData.PERSISTENT)) {
context.set(ContextData.PERSISTENT,true)
(world as ServerWorld).setWeather(0, 1200, true, true)
val data = ApplyTaskAugmentData(world, context.copy(), user, hand, level, effects, spells)
PersistentEffectHelper.setPersistentTickerNeed(this,delay.value(level),effects.duration(level),data)
castSoundEvent(world,user.blockPos,context)
}
SpellActionResult.success(list)
}
}
override fun <T> entityEffects(
entityHitResult: EntityHitResult,
context: ProcessContext,
world: World,
source: Entity?,
user: T,
hand: Hand,
level: Int,
effects: AugmentEffect,
othersType: AugmentType,
spells: PairedAugments
): SpellActionResult where T : SpellCastingEntity, T : LivingEntity {
if (othersType.empty && context.get(ProcessContext.FROM_ENTITY)){
if (!canTarget(entityHitResult, context, world, user, hand, spells)) return FAIL
val amount = spells.provideDealtDamage(effects.damage(level), context, entityHitResult, user, world, hand, level, effects)
val damageSource = spells.provideDamageSource(context,entityHitResult, source, user, world, hand, level, effects)
val bl = entityHitResult.entity.damage(damageSource, amount)
return if(bl) {
user.applyDamageEffects(user,entityHitResult.entity)
spells.hitSoundEvents(world, entityHitResult.entity.blockPos,context)
if (entityHitResult.entity.isAlive) {
SpellActionResult.success(AugmentHelper.DAMAGED_MOB, AugmentHelper.PROJECTILE_HIT)
} else {
spells.processOnKill(entityHitResult, context, world, source, user, hand, level, effects)
SpellActionResult.success(AugmentHelper.DAMAGED_MOB, AugmentHelper.PROJECTILE_HIT, AugmentHelper.KILLED_MOB)
}
} else {
FAIL
}
} else if (othersType.empty){
val ple = PlayerLightningEntity(world,user)
ple.passEffects(spells,effects,level)
ple.refreshPositionAfterTeleport(Vec3d.ofBottomCenter(entityHitResult.entity.blockPos))
ple.passContext(ProjectileAugment.projectileContext(context.copy()))
return if (world.spawnEntity(ple)) SpellActionResult.success(AugmentHelper.PROJECTILE_FIRED) else FAIL
}
return SUCCESSFUL_PASS
}
@Suppress("KotlinConstantConditions")
override fun persistentEffect(data: PersistentEffectHelper.PersistentEffectData) {
if (data !is ApplyTaskAugmentData<*>) return
if (data.user !is LivingEntity) return
this.applyTasks(data.world,data.context,data.user,data.hand,data.level,data.effects,data.spells)
}
override fun castSoundEvent(world: World, blockPos: BlockPos, context: ProcessContext) {
world.playSound(null, blockPos, SoundEvents.ITEM_TRIDENT_THUNDER, SoundCategory.PLAYERS,1f,1f)
}
}
| 16 |
Kotlin
|
7
| 3 |
9971606dfafa9422e9558238c7783f8e27bd34a3
| 8,092 |
ai
|
MIT License
|
subprojects/android-test/ui-testing-core-app/src/sharedTest/kotlin/com/avito/android/ui/test/MovingButtonTest.kt
|
avito-tech
| 230,265,582 | false | null |
package com.avito.android.ui.test
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.avito.android.test.app.core.screenRule
import com.avito.android.ui.MovingButtonActivity
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class MovingButtonTest {
@get:Rule
val rule = screenRule<MovingButtonActivity>(launchActivity = true)
@Test
fun movingButton_clicked() {
Screen.movingButton.movedButton.click()
Screen.movingButton.movedButtonClickIndicatorView.checks.isDisplayed()
}
}
| 4 |
Kotlin
|
37
| 331 |
44a9f33b2e4ac4607a8269cbf4f7326ba40402fe
| 585 |
avito-android
|
MIT License
|
app/src/main/java/com/nutrition/balanceme/domain/usecases/ProfileUseCases.kt
|
DatTrannn
| 521,896,551 | false | null |
package com.nutrition.balanceme.domain.usecases
import android.net.Uri
import androidx.lifecycle.LiveData
import com.nutrition.balanceme.data.remote.UploadState
import com.nutrition.balanceme.domain.models.Profile
import com.nutrition.balanceme.domain.models.Recipe
import com.nutrition.balanceme.domain.repositories.ProfileRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class ProfileUseCases @Inject constructor(private val profileRepository: ProfileRepository) {
fun clearProgress() = profileRepository.clearProgress()
fun getProfile(): Flow<Profile> = profileRepository.getProfile()
fun getProgress(): LiveData<UploadState> = profileRepository.getProgress()
suspend fun getFavorites(ids: List<String>): List<Recipe> {
return profileRepository.getFavorites(ids)
}
suspend fun getRecipes(id: String): List<Recipe>{
return profileRepository.getRecipes(id)
}
suspend fun updateProfile(update: Profile){
return profileRepository.updateProfile(update)
}
suspend fun uploadImage(directory: String, path: Uri){
return profileRepository.uploadImage(directory, path)
}
suspend fun clearData() {
profileRepository.clearData()
}
}
| 0 |
Kotlin
|
0
| 0 |
f51d0276b1d34e00b27b44689aedf80e1580c542
| 1,251 |
BalanceMeApp
|
MIT License
|
app/src/main/java/com/myweather/app/ui/fragment/landing/LandingFragment.kt
|
a7madwaseem
| 250,847,882 | false | null |
package com.myweather.app.ui.fragment.landing
import android.os.Bundle
import android.view.View
import androidx.navigation.fragment.findNavController
import com.myweather.app.R
import com.myweather.app.ui.fragment.BasicFragment
import kotlinx.android.synthetic.main.fragment_landing.*
/**
* Created by <NAME> on 27/03/2020
*/
class LandingFragment : BasicFragment() {
//region Fragment Methods
override fun getContentResource(): Int {
return R.layout.fragment_landing
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupListeners()
}
//endregion
//region General Methods
private fun setupListeners() {
weatherButton.setOnClickListener { onStep1Clicked() }
forecastButton.setOnClickListener { onStep2Clicked() }
}
//endregion
//region UI Handlers
private fun onStep1Clicked() {
findNavController().navigate(R.id.action_landingFragment_to_step1Fragment)
}
private fun onStep2Clicked() {
findNavController().navigate(R.id.action_landingFragment_to_step2Fragment)
}
//endregion
}
| 0 |
Kotlin
|
0
| 0 |
0a3261bf18935f634c29610e72bf7bc88ce3a2b7
| 1,175 |
My-weather
|
Apache License 2.0
|
kstatemachine/src/test/kotlin/ru/nsk/kstatemachine/CompositionStateMachinesTest.kt
|
nsk90
| 296,142,904 | false | null |
package ru.nsk.kstatemachine
import io.kotest.core.spec.style.StringSpec
import io.mockk.verify
import io.mockk.verifyOrder
/**
* In a parent state machine it is not possible to use as transitions targets states from inner machine and vise versa.
* Inner machine is treated as atomic state by outer one.
* Inner machine is started automatically when outer one enters it.
*/
class CompositionStateMachinesTest : StringSpec({
"composition inner auto start" { composition(false) }
"composition inner manual start" { composition(true) }
})
private fun composition(startInnerMachineOnSetup: Boolean) {
val callbacks = mockkCallbacks()
val outerState1 = DefaultState("Outer state1")
val innerState1 = DefaultState("Inner state1")
val innerState2 = DefaultState("Inner state2")
val innerMachine = createStateMachine("Inner machine", start = startInnerMachineOnSetup) {
logger = StateMachine.Logger { println(it) }
callbacks.listen(this)
onStarted {
callbacks.onStarted(this)
}
addInitialState(innerState1) {
callbacks.listen(this)
transition<SwitchEvent>("Switch") {
targetState = innerState2
callbacks.listen(this)
}
}
addState(innerState2) {
callbacks.listen(this)
}
}
val machine = createStateMachine {
callbacks.listen(this)
addInitialState(outerState1) {
callbacks.listen(this)
transition<SwitchEvent> {
targetState = innerMachine
callbacks.listen(this)
}
}
addState(innerMachine)
}
verifyOrder {
callbacks.onEntryState(machine)
callbacks.onEntryState(outerState1)
}
machine.processEvent(SwitchEvent)
verify {
callbacks.onTriggeredTransition(SwitchEvent)
callbacks.onExitState(outerState1)
callbacks.onStarted(innerMachine)
callbacks.onEntryState(innerMachine)
callbacks.onEntryState(innerState1)
}
innerMachine.processEvent(SwitchEvent)
verifyOrder {
callbacks.onTriggeredTransition(SwitchEvent)
callbacks.onExitState(innerState1)
callbacks.onEntryState(innerState2)
}
}
| 4 |
Kotlin
|
6
| 54 |
6e7887367195fe5e5fd08bcb9664d907764d8150
| 2,304 |
kstatemachine
|
Boost Software License 1.0
|
advent-of-code-2018/src/test/java/aoc/Advent14.kt
|
yuriykulikov
| 159,951,728 | false | null |
package aoc
import org.assertj.core.api.Assertions.assertThat
import org.junit.Ignore
import org.junit.Test
class Advent14 {
@Test
fun `After 9 recipes, the scores of the next ten would be 5158916779`() {
assertThat(scoreAfter(9)).isEqualTo("5158916779")
}
@Test
fun `After 5 recipes, the scores of the next ten would be 0124515891`() {
assertThat(scoreAfter(5)).isEqualTo("0124515891")
}
@Test
fun `After 18 recipes, the scores of the next ten would be 9251071085`() {
assertThat(scoreAfter(18)).isEqualTo("9251071085")
}
@Test
fun `After 2018 recipes, the scores of the next ten would be 5941429882`() {
assertThat(scoreAfter(2018)).isEqualTo("5941429882")
}
@Test
fun `After 793061 recipes, the scores of the next ten would be 4138145721`() {
assertThat(scoreAfter(793061)).isEqualTo("4138145721")
}
@Test
fun `51589 first appears after 9 recipes`() {
assertThat(recipiesToAchieve("51589")).isEqualTo(9)
}
@Test
fun `01245 first appears after 5 recipes`() {
assertThat(recipiesToAchieve("01245")).isEqualTo(5)
}
@Test
fun `92510 first appears after 18 recipes`() {
assertThat(recipiesToAchieve("92510")).isEqualTo(18)
}
@Test
fun `59414 first appears after 2018 recipes`() {
assertThat(recipiesToAchieve("59414")).isEqualTo(2018)
}
@Ignore("Takes 14 seconds")
@Test
fun `793061 first appears after 20276284 recipes`() {
assertThat(recipiesToAchieve("793061")).isEqualTo(20276284)
}
private fun recipiesToAchieve(toMatch: String): Int {
val board = Board()
val elves: List<Elf> = listOf(Elf(board, 0), Elf(board, 1))
fun findMatch(board: Board): Int? {
if (board.tail < toMatch.length) return null
// println("matching $toMatch against ${board.board.joinToString("") { it.toString() }}")
val firstSequenceStartingPoint = board.tail - toMatch.lastIndex
val secondSequenceStartingPoint = firstSequenceStartingPoint - 1
val toMatchLast = board.board
.subList(firstSequenceStartingPoint, board.board.size)
.joinToString("") { it.toString() }
val toMatchSecondToLast = board.board
.subList(secondSequenceStartingPoint, board.board.size - 1)
.joinToString("") { it.toString() }
// println("toMatchLast $toMatchLast")
// println("toMatchSecondToLast $toMatchSecondToLast")
return when (toMatch) {
toMatchLast -> firstSequenceStartingPoint
toMatchSecondToLast -> secondSequenceStartingPoint
else -> null
}
}
return generateSequence(0) { it + 1 }.mapNotNull { iteration ->
board.dump(elves.map { elf -> elf.currentIndex }, iteration)
val currentSum = elves.sumBy { elf -> board[elf.currentIndex] }
if (currentSum < 10) {
board.append(currentSum)
} else {
board.append(currentSum.div(10))
board.append(currentSum.rem(10))
}
elves.forEach { elf -> elf.stepForward() }
assertThat(elves.map { elf -> elf.currentIndex }.distinct().size).isEqualTo(2)
findMatch(board)
}
.first()
}
/*
Only two recipes are on the board: the first recipe got a score of 3, the second, 7. Each of the two Elves has a
current recipe: the first Elf starts with the first recipe, and the second Elf starts with the second recipe.
To create new recipes, the two Elves combine their current recipes. This creates new recipes from the digits of
the sum of the current recipes' scores. With the current recipes' scores of 3 and 7, their sum is 10, and so two
new recipes would be created: the first with score 1 and the second with score 0. If the current recipes' scores
were 2 and 3, the sum, 5, would only create one recipe (with a score of 5) with its single digit.
The new recipes are added to the end of the scoreboard in the order they are created. So, after the first round,
the scoreboard is 3, 7, 1, 0.
After all new recipes are added to the scoreboard, each Elf picks a new current recipe. To do this, the Elf steps
forward through the scoreboard a number of recipes equal to 1 plus the score of their current recipe. So, after the
first round, the first Elf moves forward 1 + 3 = 4 times, while the second Elf moves forward 1 + 7 = 8 times. If
they run out of recipes, they loop back around to the beginning. After the first round, both Elves happen to loop
around until they land on the same recipe that they had in the beginning; in general, they will move to different
recipes.
*/
class Board {
val dbg = false
val board: MutableList<Int> = mutableListOf()
var tail: Int = -1
init {
append(3)
append(7)
}
operator fun get(index: Int): Int {
return when {
index > tail -> throw IllegalStateException("Index $index is not available, tail is $tail")
else -> board[index]
}
}
fun loopTo(index: Int): Int {
return when {
index > tail -> index.rem(tail + 1)
else -> index
}
}
fun append(recipe: Int) {
tail++
board.add(recipe)
}
fun dump(current: List<Int>, iteration: Int) {
if (dbg) {
println("$iteration: " + board
.mapIndexedNotNull { index, value ->
when {
index == current[0] -> "($value)"
index == current[1] -> "[$value]"
index <= tail -> "$value"
else -> null
}
}
.joinToString(""))
}
}
}
// 0: (3)[7]
// 1: (3)[7] 1 0
// 2: 3 7 1 [0](1) 0
// 3: 3 7 1 0 [1] 0 (1)
// 4: (3) 7 1 0 1 0 [1] 2
// 5: 3 7 1 0 (1) 0 1 2 [4]
// 6: 3 7 1 [0] 1 0 (1) 2 4 5
// 7: 3 7 1 0 [1] 0 1 2 (4) 5 1
// 8: 3 (7) 1 0 1 0 [1] 2 4 5 1 5
// 9: 3 7 1 0 1 0 1 2 [4](5) 1 5 8
// 10: 3 (7) 1 0 1 0 1 2 4 5 1 5 8 [9]
// 11: 3 7 1 0 1 0 1 [2] 4 (5) 1 5 8 9 1 6
// 12: 3 7 1 0 1 0 1 2 4 5 [1] 5 8 9 1 (6) 7
// 13: 3 7 1 0 (1) 0 1 2 4 5 1 5 [8] 9 1 6 7 7
// 14: 3 7 [1] 0 1 0 (1) 2 4 5 1 5 8 9 1 6 7 7 9
// 15: 3 7 1 0 [1] 0 1 2 (4) 5 1 5 8 9 1 6 7 7 9 2
private fun scoreAfter(recipies: Int): String {
val board = Board()
val elves: List<Elf> = listOf(Elf(board, 0), Elf(board, 1))
repeat(recipies + 10 - 3) {
board.dump(elves.map { elf -> elf.currentIndex }, it)
val currentSum = elves.sumBy { elf -> board[elf.currentIndex] }
if (currentSum < 10) {
board.append(currentSum)
} else {
board.append(currentSum.div(10))
board.append(currentSum.rem(10))
}
elves.forEach { elf -> elf.stepForward() }
assertThat(elves.map { elf -> elf.currentIndex }.distinct().size).isEqualTo(2)
}
return (recipies..(recipies + 9)).joinToString("") { board[it].toString() }
}
class Elf(private val board: Board, var currentIndex: Int) {
fun stepForward() {
val score = board[currentIndex]
currentIndex = board.loopTo(currentIndex + score + 1)
}
}
}
| 0 |
Kotlin
|
0
| 1 |
20f941bff9c075dbcc325ea1a7012bcaa4324177
| 7,830 |
advent-of-code
|
MIT License
|
app/src/main/java/com/imdvlpr/sobatdompet/activity/auth/AuthInterface.kt
|
Imdvlpr99
| 706,199,527 | false |
{"Kotlin": 148299, "Java": 3626}
|
package com.imdvlpr.sobatdompet.activity.auth
import com.imdvlpr.sobatdompet.model.Login
import com.imdvlpr.sobatdompet.model.OTP
import com.imdvlpr.sobatdompet.model.StatusResponse
import com.imdvlpr.sobatdompet.helper.base.BaseView
interface AuthInterface: BaseView {
fun onProgress()
fun onFinishProgress()
fun onFailed(message: String)
fun onSuccessSendOtp(data: OTP) {}
fun onSuccessVerifyOtp(data: OTP) {}
fun onSuccessLogin(login: Login) {}
fun onSuccessRegister() {}
fun onSuccessCheckUsers(response: StatusResponse) {}
}
| 0 |
Kotlin
|
0
| 1 |
4309a0ae836363e746e08513d86f85afc90b3671
| 571 |
Sobat-Dompet
|
MIT License
|
app/src/main/java/com/kieronquinn/app/discoverkiller/utils/extensions/Extensions+Fragment.kt
|
KieronQuinn
| 273,963,637 | false |
{"Kotlin": 417138, "Java": 18179, "AIDL": 4171}
|
package com.kieronquinn.app.discoverkiller.utils.extensions
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
fun Fragment.childBackStackTopFragment() = callbackFlow {
val listener = FragmentManager.OnBackStackChangedListener {
trySend(getTopFragment())
}
childFragmentManager.addOnBackStackChangedListener(listener)
trySend(getTopFragment())
awaitClose {
childFragmentManager.removeOnBackStackChangedListener(listener)
}
}
fun Fragment.getTopFragment(): Fragment? {
if(!isAdded) return null
return childFragmentManager.fragments.firstOrNull()
}
| 1 |
Kotlin
|
8
| 302 |
8a59868f5de7493b685c20a38239b08f8c1c9259
| 719 |
DiscoverKiller
|
Apache License 2.0
|
core/src/commonMain/kotlin/work/socialhub/kbsky/api/entity/app/bsky/actor/ActorGetProfilesRequest.kt
|
uakihir0
| 735,265,237 | false |
{"Kotlin": 396349, "Shell": 1421, "Makefile": 315}
|
package work.socialhub.kbsky.api.entity.app.bsky.actor
import work.socialhub.kbsky.api.entity.share.AuthRequest
import work.socialhub.kbsky.api.entity.share.MapRequest
import work.socialhub.kbsky.auth.AuthProvider
class ActorGetProfilesRequest(
auth: AuthProvider
) : AuthRequest(auth), MapRequest {
var actors: List<String>? = null
override fun toMap(): Map<String, Any> {
return mutableMapOf<String, Any>().also {
it.addParam("actors", actors)
}
}
}
| 1 |
Kotlin
|
1
| 17 |
2602dd952ab8a81329d0bb0a24b601a4f9a46089
| 500 |
kbsky
|
MIT License
|
src/main/kotlin/tech/relaycorp/relaynet/bindings/pdc/PDCException.kt
|
relaycorp
| 171,718,724 | false |
{"Kotlin": 543225}
|
package tech.relaycorp.relaynet.bindings.pdc
import tech.relaycorp.relaynet.RelaynetException
sealed class PDCException(message: String, cause: Throwable? = null) :
RelaynetException(message, cause)
/**
* Base class for connectivity errors and errors caused by the server.
*/
abstract class ServerException internal constructor(message: String, cause: Throwable?) :
PDCException(message, cause)
/**
* Error before or while connected to the server.
*
* The client should retry later.
*/
class ServerConnectionException(message: String, cause: Throwable? = null) :
ServerException(message, cause)
/**
* The server sent an invalid message or behaved in any other way that violates the binding.
*
* Retrying later is unlikely to make a difference in the short term.
*/
class ServerBindingException(message: String, cause: Throwable? = null) :
ServerException(message, cause)
/**
* The server claims that the client is violating the binding.
*
* Retrying later is unlikely to make a difference.
*/
class ClientBindingException(message: String) : PDCException(message)
/**
* The server refused to accept a parcel due to reasons outside the control of the client.
*
* For example, the sender of the parcel may be untrusted.
*/
class RejectedParcelException(message: String) : PDCException(message)
/**
* The user of the client made a mistake while specifying the nonce signer(s).
*/
class NonceSignerException(message: String) : PDCException(message)
| 10 |
Kotlin
|
0
| 2 |
2fe2212375641592a06f70a2219413168f6ffea5
| 1,488 |
awala-jvm
|
Apache License 2.0
|
app/src/main/java/com/carin/data/remote/RouteService.kt
|
MEI-Grupo-4-CarIn
| 773,390,235 | false |
{"Kotlin": 242704}
|
package com.carin.data.remote
import com.carin.data.remote.dto.RouteDto
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Query
interface RouteService {
@GET("/routes")
fun getRoutes(
@Query("search") search: String? = null,
@Query("status") status: String? = null,
@Query("page") page: Int? = null,
@Query("perPage") perPage: Int? = null
): Call<List<RouteDto>>
}
| 4 |
Kotlin
|
0
| 0 |
0e1d358668dc3d1f25c22d7403ab4669fd740276
| 430 |
CarIn.AndroidApp
|
MIT License
|
app/src/main/java/com/vitorpamplona/amethyst/ui/dal/UserProfileFollowersFeedFilter.kt
|
vitorpamplona
| 587,850,619 | false | null |
package com.vitorpamplona.amethyst.ui.dal
import com.vitorpamplona.amethyst.model.Account
import com.vitorpamplona.amethyst.model.LocalCache
import com.vitorpamplona.amethyst.model.User
class UserProfileFollowersFeedFilter(val user: User, val account: Account) : FeedFilter<User>() {
override fun feedKey(): String {
return account.userProfile().pubkeyHex + "-" + user.pubkeyHex
}
override fun feed(): List<User> {
return LocalCache.users.values.filter { it.isFollowing(user) && !account.isHidden(it) }
}
}
| 157 | null |
141
| 981 |
2de3d19a34b97c012e39b203070d9c1c0b1f0520
| 542 |
amethyst
|
MIT License
|
product/services/push/src/main/java/com/yugyd/quiz/push/PushManagerImpl.kt
|
Yugyd
| 685,349,849 | false |
{"Kotlin": 873471, "FreeMarker": 22968, "Fluent": 18}
|
/*
* Copyright 2023 <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.yugyd.quiz.push
import android.Manifest
import android.annotation.TargetApi
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.media.RingtoneManager
import android.os.Build
import android.os.SystemClock
import androidx.core.app.ActivityCompat
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import com.yugyd.quiz.core.Logger
import com.yugyd.quiz.core.ResIdProvider
import com.yugyd.quiz.uikit.theme.app_color_positive
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
internal class PushManagerImpl @Inject constructor(
@ApplicationContext private val context: Context,
private val logger: Logger,
private val resIdProvider: ResIdProvider
) : PushManager {
private val notificationManager = NotificationManagerCompat.from(context)
private val channelId by lazy {
context.getString(R.string.default_channel_id)
}
private val launchIntent
get() = context.packageManager.getLaunchIntentForPackage(context.packageName)
override fun createChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationManager.createNotificationChannel(createNotificationChannel())
}
logger.print(TAG, "Notification channels is created")
}
override fun processPush(pushMessage: PushMessage) {
if (
notificationManager.areNotificationsEnabled() &&
ActivityCompat.checkSelfPermission(
context,
Manifest.permission.POST_NOTIFICATIONS,
) == PackageManager.PERMISSION_GRANTED
) {
val notification = createNotification(pushMessage)
notificationManager.notify(pushMessage.messageId.hashCode(), notification)
logger.print(
TAG,
"Process notification: $pushMessage.messageId, $pushMessage.title, $pushMessage.message"
)
} else {
logger.print(TAG, "Notification not enabled")
}
}
@TargetApi(Build.VERSION_CODES.O)
private fun createNotificationChannel(): NotificationChannel {
val name = context.getString(R.string.default_channel_name)
val description = context.getString(R.string.default_channel_description)
val importance = NotificationManager.IMPORTANCE_DEFAULT
return NotificationChannel(
channelId,
name,
importance
).apply {
setShowBadge(true)
this.description = description
}
}
private fun createNotification(pushMessage: PushMessage) =
NotificationCompat.Builder(context, channelId)
.setContentTitle(pushMessage.title)
.setContentText(pushMessage.message)
.setSmallIcon(resIdProvider.pushIcon())
.setColor(app_color_positive.value.toInt())
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(createPendingIntent(pushMessage))
.build()
private fun createPendingIntent(pushMessage: PushMessage) = PendingIntent.getActivity(
context,
SystemClock.currentThreadTimeMillis().toInt(),
createLaunchActivityIntent(pushMessage),
PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_ONE_SHOT
)
private fun createLaunchActivityIntent(pushMessage: PushMessage) = Intent(launchIntent).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
for ((key, value) in pushMessage.data.entries) {
putExtra(key, value)
}
}
companion object {
private const val TAG = "PushManager"
}
}
| 0 |
Kotlin
|
1
| 8 |
0192d1ccabe96b7ac9f9a844259cca7a018aa6b5
| 4,564 |
quiz-platform
|
Apache License 2.0
|
feature/authorization/presentation/src/commonMain/kotlin/org/timemates/app/authorization/ui/afterstart/AfterStartScreen.kt
|
timemates
| 575,537,317 | false |
{"Kotlin": 329102}
|
package org.timemates.app.authorization.ui.afterstart
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.rounded.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import io.github.skeptick.libres.compose.painterResource
import org.timemates.app.authorization.ui.afterstart.mvi.AfterStartScreenComponent
import org.timemates.app.authorization.ui.afterstart.mvi.AfterStartScreenComponent.*
import org.timemates.app.feature.common.MVI
import org.timemates.app.localization.compose.LocalStrings
import org.timemates.app.style.system.Resources
import org.timemates.app.style.system.appbar.AppBar
import org.timemates.app.style.system.button.Button
import org.timemates.app.style.system.theme.AppTheme
import pro.respawn.flowmvi.essenty.compose.subscribe
@Composable
fun AfterStartScreen(
mvi: MVI<State, Intent, Action>,
navigateToConfirmation: (String) -> Unit,
navigateToStart: () -> Unit,
) {
val painter: Painter = Resources.image.confirm_authorization_info_image.painterResource()
@Suppress("UNUSED_VARIABLE")
val state = mvi.subscribe { action ->
when (action) {
is Action.NavigateToConfirmation -> navigateToConfirmation(action.verificationHash.string)
Action.OnChangeEmailClicked -> navigateToStart()
}
}
Scaffold(
topBar = {
AppBar(
navigationIcon = {
IconButton(
onClick = { mvi.store.intent(Intent.OnChangeEmailClicked) },
) {
Icon(Icons.AutoMirrored.Rounded.ArrowBack, contentDescription = null)
}
},
title = LocalStrings.current.appName,
)
}
) { rootPaddings ->
Column(
modifier = Modifier.fillMaxSize()
.padding(rootPaddings)
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
Column(
modifier = Modifier.fillMaxWidth().weight(1f),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Icon(
modifier = Modifier,
painter = painter,
contentDescription = null,
)
Spacer(Modifier.height(8.dp))
Text(
text = LocalStrings.current.confirmation,
modifier = Modifier,
style = MaterialTheme.typography.titleLarge,
)
Spacer(Modifier.height(16.dp))
Text(
text = LocalStrings.current.confirmationDescription,
modifier = Modifier.padding(horizontal = 8.dp),
color = AppTheme.colors.secondaryVariant,
style = MaterialTheme.typography.bodyMedium,
textAlign = TextAlign.Center,
)
}
Button(
modifier = Modifier.fillMaxWidth(),
primary = false,
onClick = { mvi.store.intent(Intent.OnChangeEmailClicked) },
) {
Text(LocalStrings.current.changeEmail)
}
Button(
modifier = Modifier.fillMaxWidth(),
primary = true,
onClick = { mvi.store.intent(Intent.NextClicked) },
) {
Text(LocalStrings.current.nextStep)
}
}
}
}
| 19 |
Kotlin
|
0
| 28 |
bec7508d38e87149005c57a98f10a0eb4dbd4891
| 4,394 |
app
|
MIT License
|
app/src/main/java/com/example/abgabe/viewmodels/CatOverviewViewmodel.kt
|
Lumoma
| 804,942,446 | false |
{"Kotlin": 85419, "Java": 55845}
|
package com.example.abgabe.viewmodels
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.abgabe.data.local.Cat
import com.example.abgabe.data.local.CatDao
import com.example.abgabe.data.remote.CatApi
import com.example.abgabe.ui.states.OverviewUiState
import com.example.abgabe.data.util.QrCodeHelper
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class OverviewViewModel @Inject constructor(
private val catDao: CatDao,
private val qrCodeHelper: QrCodeHelper,
private val catApi: CatApi
) : ViewModel() {
val addCatToggle = MutableStateFlow(false)
val uiState: StateFlow<OverviewUiState> = combine(
catDao.getCatsOrderedByName(),
addCatToggle
) { cats, addCatState ->
when {
addCatState -> OverviewUiState.AddCat(
pictureUrl = getRandomCatPictureURL(),
onSaveCat = {
addCatToDatabase(it.copy(it.id, it.name, it.breed, it.temperament, it.origin, it.lifeExpectancy, it.imageUrl, it.qrCodePath, it.qrCodeByteArray))
addCatToggle.value = false
},
generateNewPictureURL = {
viewModelScope.launch {
getRandomCatPictureURL()
}
}
)
cats.isEmpty() -> OverviewUiState.EmptyDatabase
else -> OverviewUiState.Content(
cats = cats,
onAddCat = {
addCatToggle.value = true
}
)
}
}.stateIn(viewModelScope, SharingStarted.WhileSubscribed(), OverviewUiState.Loading)
private fun addCatToDatabase(cat: Cat) {
viewModelScope.launch(Dispatchers.IO) {
cat.qrCodePath = qrCodeHelper.generateQRCodeFromUUID(cat.name, cat.id)
cat.qrCodeByteArray = qrCodeHelper.generateQRCodeByteCodeFromUUID(cat.id)
catDao.insert(cat)
}
}
private suspend fun getRandomCatPictureURL(): String {
return withContext(Dispatchers.IO) {
catApi.getRandomCatPictureUrlFromApi()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
b8218d9d6e7b2bf8bd0aa78701372202893f99ef
| 2,670 |
androidARapp
|
The Unlicense
|
redux/src/main/kotlin/com/grzegorzdyrda/redux/StoreSubscriber.kt
|
GrzegorzDyrda
| 112,115,019 | false | null |
package com.grzegorzdyrda.redux
/**
* All Store subscribers must implement this interface.
*
* Contains the following methods:
* - [onNewState] (required) - called each time the State has changed
* - [onCommandReceived] (optional) - called each time a Command has been sent
*/
interface StoreSubscriber<in STATE> {
/**
* Called each time the State has changed.
*
* @param state current State provided by the Store
*/
fun onNewState(state: STATE)
/**
* Called each time a Command has been sent.
*
* Commands are a way of telling that some one-time side-effect should be performed.
*
* @param command recent Command sent by using [Store.sendCommand]
*/
fun onCommandReceived(command: Any) {
// Default implementation throws an exception
throw NotImplementedError("A Command has been sent, but Target class doesn't implement onCommandReceived()! Please implement the missing method. Command = $command, Target = $this")
}
}
| 5 |
Kotlin
|
0
| 1 |
6880711b846e702443fe84761072537d3b243298
| 1,014 |
redux
|
MIT License
|
app/src/main/java/com/babatunde/pasteltest/room/NewsDatabase.kt
|
babatunde360
| 575,173,937 | false |
{"Kotlin": 26389}
|
package com.babatunde.pasteltest.room
import androidx.room.Database
import androidx.room.RoomDatabase
import com.babatunde.pasteltest.model.Article
@Database(entities = [Article::class], exportSchema = false, version = 1)
abstract class NewsDatabase : RoomDatabase() {
abstract fun dbNewsDao(): NewsDao
// companion object that allow the database name to be called anywhere in the codebase
companion object{
const val db_Name = "newsDB"
}
}
| 0 |
Kotlin
|
0
| 0 |
4a57a44ec650a8b3c5dedf15aafd0850acec67ab
| 468 |
PastelTest
|
Apache License 2.0
|
src/main/kotlin/com/dotori/v2/domain/music/domain/entity/Music.kt
|
Team-Ampersand
| 569,110,809 | false |
{"Kotlin": 404400, "Shell": 827}
|
package com.dotori.v2.domain.music.domain.entity
import com.dotori.v2.domain.member.domain.entity.Member
import com.dotori.v2.global.entity.BaseTimeEntity
import javax.persistence.*
@Entity
@Table(name = "music")
class Music(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "music_id")
val id: Long = 0,
@Column(name = "music_url", nullable = false)
val url: String,
@Column(name = "music_title", nullable = false)
val title: String,
@Column(name = "music_thumbnail", nullable = false)
val thumbnail: String,
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "member_id", nullable = false)
val member: Member
) : BaseTimeEntity()
| 6 |
Kotlin
|
3
| 15 |
11cabbcaf916c763f720be88ba2d9a8bc8cea8fa
| 709 |
Dotori-server-V2
|
Apache License 2.0
|
app/src/main/java/com/sd/demo/ctx/MainActivity.kt
|
zj565061763
| 575,962,624 | false | null |
package com.sd.demo.ctx
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.sd.lib.ctx.fContext
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
logMsg { "Activity onCreate context:$fContext" }
}
}
inline fun logMsg(block: () -> String) {
Log.i("ctx-demo", block())
}
| 0 |
Kotlin
|
0
| 0 |
4aa07e18e2969ed14fa3802bc167e975ed79fffb
| 483 |
ctx
|
MIT License
|
backend/src/main/kotlin/dev/dres/data/model/submissions/DbAnswerType.kt
|
dres-dev
| 248,713,193 | false |
{"Kotlin": 942970, "TypeScript": 466681, "HTML": 192895, "SCSS": 12579, "JavaScript": 1835, "Shell": 925, "Dockerfile": 412}
|
package dev.dres.data.model.submissions
import dev.dres.data.model.admin.DbRole
import jetbrains.exodus.entitystore.Entity
import kotlinx.dnq.XdEnumEntity
import kotlinx.dnq.XdEnumEntityType
import kotlinx.dnq.xdRequiredStringProp
/**
* The type of [DbAnswerSet] with respect to its content
*
* @author Ralph Gasser & Luca Rossetto
* @version 1.1.0
*/
class DbAnswerType(entity: Entity) : XdEnumEntity(entity) {
companion object : XdEnumEntityType<DbAnswerType>() {
val ITEM by enumField { description = AnswerType.ITEM.name }
val TEMPORAL by enumField { description = AnswerType.TEMPORAL.name }
val TEXT by enumField { description = AnswerType.TEXT.name }
/**
* Returns a list of all [DbRole] values.
*
* @return List of all [DbRole] values.
*/
fun values() = listOf(ITEM, TEMPORAL, TEXT)
/**
* Parses a [DbRole] instance from a [String].
*/
fun parse(string: String) = when (string.uppercase()) {
AnswerType.ITEM.name -> ITEM
AnswerType.TEMPORAL.name -> TEMPORAL
AnswerType.TEXT.name -> TEXT
else -> throw IllegalArgumentException("Failed to parse submission type '$string'.")
}
}
/** Name / description of the [DbAnswerType]. */
var description by xdRequiredStringProp(unique = true)
private set
/**
* Converts this [DbAnswerType] to a RESTful API representation [DbAnswerType].
*
* @return [DbAnswerType]
*/
fun toApi() = AnswerType.fromDb(this).toApi()
}
| 37 |
Kotlin
|
3
| 14 |
7fbe29f3d77f105fc6e1ae31c76bac7fd39a6bae
| 1,589 |
DRES
|
MIT License
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/dms/DocDbSettingsPropertyDsl.kt
|
F43nd1r
| 643,016,506 | false | null |
package com.faendir.awscdkkt.generated.services.dms
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.dms.CfnEndpoint
@Generated
public fun buildDocDbSettingsProperty(initializer: @AwsCdkDsl
CfnEndpoint.DocDbSettingsProperty.Builder.() -> Unit): CfnEndpoint.DocDbSettingsProperty =
CfnEndpoint.DocDbSettingsProperty.Builder().apply(initializer).build()
| 1 |
Kotlin
|
0
| 0 |
a1cf8fbfdfef9550b3936de2f864543edb76348b
| 445 |
aws-cdk-kt
|
Apache License 2.0
|
adapter/dtexchange/src/main/java/org/bidon/dtexchange/ext/AdDisplayErrorExt.kt
|
bidon-io
| 504,568,127 | false | null |
package org.bidon.dtexchange.ext
import com.fyber.inneractive.sdk.external.InneractiveUnitController
import org.bidon.dtexchange.DTExchangeDemandId
import org.bidon.sdk.config.BidonError
/**
* Created by <NAME> on 01/03/2023.
*/
internal fun InneractiveUnitController.AdDisplayError?.asBidonError() =
BidonError.Unspecified(demandId = DTExchangeDemandId, sourceError = this)
| 1 |
Kotlin
|
0
| 0 |
a624344c96c08ee05c026daed8ca7634f56daf0f
| 382 |
bidon-sdk-android
|
Apache License 2.0
|
Android/app/src/main/java/com/vigbag/android/model/ChildItemDataClass.kt
|
codervivek5
| 604,109,006 | false |
{"HTML": 179621, "CSS": 159009, "JavaScript": 59072, "Python": 35796, "Kotlin": 25475, "SCSS": 12443, "Shell": 118}
|
package com.vigbag.android.model
data class ChildItemDataClass(val itemImage:Int,val itemName:String,
val itemSpecs:String,val itemRating:Double,val itemReviews:String)
| 26 |
HTML
|
158
| 55 |
114bfa83cffabb83e760ef503b74fa89e1624f3f
| 200 |
VigyBag
|
MIT License
|
Hyperskill/Minesweeper/Main.kt
|
Alphabeater
| 435,048,407 | false | null |
package minesweeper
import java.util.*
import kotlin.system.exitProcess
val s = Scanner(System.`in`)
const val dim = 9
enum class Directions {
N, NE, E, SE, S, SW, W, MW
}
fun main() {
println("The dimension of the board is 9.")
print("How many mines do you want on the field? ")
val bombs = s.nextInt()
val minesweeper = Game(dim)
minesweeper.printBoard()
loop@do {
println("Set/unset mines marks(mine) or claim(free) a cell(row, column):\n" +
"i.e. > 1 3 free OR 2 5 mine")
val row = s.nextInt() - 1
val column = s.nextInt() - 1
val option = s.next()
if (!minesweeper.hasInitialized) {
minesweeper.initialize(bombs, row, column)
minesweeper.hasInitialized = true
}
val cell = minesweeper.board[row][column].value
val marked = minesweeper.board[row][column].marked
when (option) {
"free" -> { // The player makes the assumption that the cell is free
when (cell) {
0 -> minesweeper.revealCells(row, column) // Reveal all surrounding cells that are not bombs
in 1..8 -> minesweeper.revealCell(row, column) // Free only that cell
else -> { // Trigger game lost, also print all bombs on current board
minesweeper.lostGame()
println("You stepped on a mine and failed!")
exitProcess(1)
}
}
}
"mine" -> { // The player marks a cell
minesweeper.board[row][column].marked = marked != true
}
else -> {
println("Invalid option.")
continue@loop
}
}
minesweeper.printBoard()
} while (!minesweeper.checkWin())
println("Congratulations! You found all the mines!")
}
| 0 |
Kotlin
|
0
| 0 |
f06ba54874295d49db99eb58e32ae508838008bc
| 1,928 |
Archive
|
MIT License
|
src/main/kotlin/org/wagham/utils/MessageUtils.kt
|
ilregnodiwagham
| 566,988,243 | false | null |
package org.wagham.utils
import dev.kord.core.behavior.channel.createMessage
import dev.kord.core.entity.channel.MessageChannel
suspend fun MessageChannel.sendTextMessage(message: String) =
message.split("\n")
.fold(listOf("")) { acc, it ->
if((acc.last().length + it.length) < 2000) {
acc.dropLast(1) + ("${acc.last()}\n$it")
} else acc + it
}.forEach {
this.createMessage {
content = it
}
}
| 0 |
Kotlin
|
0
| 0 |
8df43d3985a9152b799be9f390ddef544449e020
| 503 |
wagham-bot
|
MIT License
|
services/csm.cloud.project.api.timeseries/src/test/kotlin/com/bosch/pt/csm/cloud/projectmanagement/project/craft/facade/graphql/TaskCraftGraphQlApiIntegrationTest.kt
|
boschglobal
| 805,348,245 | false |
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
|
/*
* ************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2018 - 2023
*
* ************************************************************************
*/
package com.bosch.pt.csm.cloud.projectmanagement.project.craft.facade.graphql
import com.bosch.pt.csm.cloud.projectmanagement.application.RmsSpringBootTest
import com.bosch.pt.csm.cloud.projectmanagement.application.common.AbstractGraphQlApiIntegrationTest
import com.bosch.pt.csm.cloud.projectmanagement.craft.messages.ProjectCraftAggregateG2Avro
import com.bosch.pt.csm.cloud.projectmanagement.project.event.submitProject
import com.bosch.pt.csm.cloud.projectmanagement.project.event.submitProjectCraftG2
import com.bosch.pt.csm.cloud.projectmanagement.project.event.submitTask
import com.bosch.pt.csm.cloud.projectmanagement.test.eventDate
import com.bosch.pt.csm.cloud.projectmanagement.test.get
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
@RmsSpringBootTest
class TaskCraftGraphQlApiIntegrationTest : AbstractGraphQlApiIntegrationTest() {
val craft = "projects[0].tasks[0].craft"
val query =
"""
query {
projects {
tasks {
craft {
id
version
name
color
eventDate
}
}
}
}
"""
.trimIndent()
lateinit var aggregate: ProjectCraftAggregateG2Avro
@BeforeEach
fun init() {
setAuthentication("csm-user")
eventStreamGenerator.submitProject().submitCsmParticipant()
}
@Test
fun `query craft`() {
submitEvents()
// Execute query and validate payload
val response = graphQlTester.document(query).execute()
response.get("$craft.id").isEqualTo(aggregate.aggregateIdentifier.identifier)
response.get("$craft.version").isEqualTo(aggregate.aggregateIdentifier.version.toString())
response.get("$craft.name").isEqualTo(aggregate.name)
response.get("$craft.color").isEqualTo(aggregate.color)
response.get("$craft.eventDate").isEqualTo(aggregate.eventDate())
}
private fun submitEvents() {
eventStreamGenerator.submitProject().submitCsmParticipant()
aggregate = eventStreamGenerator.submitProjectCraftG2().get("projectCraft")!!
eventStreamGenerator.submitTask()
}
}
| 0 |
Kotlin
|
3
| 9 |
9f3e7c4b53821bdfc876531727e21961d2a4513d
| 2,354 |
bosch-pt-refinemysite-backend
|
Apache License 2.0
|
src/main/kotlin/daniel/mybank/model/Account.kt
|
DanFonseca
| 602,188,054 | false | null |
package daniel.mybank.model
import org.jetbrains.annotations.NotNull
import java.math.BigDecimal
import javax.persistence.*
@Entity
class Account (
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long,
@NotNull ()
var amount: BigDecimal,
@OneToOne(cascade = [CascadeType.ALL])
@JoinColumn(name = "Client_cpf")
val client: Client? = null
) {
}
| 0 |
Kotlin
|
0
| 0 |
b327cd4e8d7735b269708580d02bf865904109b8
| 434 |
mybank
|
MIT License
|
app/src/main/java/gmarques/debtv4/data/room/AppDatabase.kt
|
GilianMarques
| 620,074,123 | false | null |
package gmarques.debtv4.data.room
import androidx.room.Database
import androidx.room.RoomDatabase
import gmarques.debtv4.data.room.dao.DespesaDaoRoom
import gmarques.debtv4.data.room.dao.RecorrenciaDaoRoom
import gmarques.debtv4.data.room.entidades.DespesaEntidade
import gmarques.debtv4.data.room.entidades.RecorrenciaEntidade
const val DATABASE_NAME = "app-database.sql"
@Database(
version = 1,
exportSchema = false,
entities = [DespesaEntidade::class, RecorrenciaEntidade::class]
)
abstract class AppDatabase : RoomDatabase() {
abstract fun getDespesaDao(): DespesaDaoRoom
abstract fun getRecorrenciaDao(): RecorrenciaDaoRoom
}
| 0 |
Kotlin
|
0
| 0 |
c01f817af61fb1da02b27bb21a45b3fb54e03c6e
| 655 |
DebtV4
|
MIT License
|
app/src/main/java/gmarques/debtv4/data/room/AppDatabase.kt
|
GilianMarques
| 620,074,123 | false | null |
package gmarques.debtv4.data.room
import androidx.room.Database
import androidx.room.RoomDatabase
import gmarques.debtv4.data.room.dao.DespesaDaoRoom
import gmarques.debtv4.data.room.dao.RecorrenciaDaoRoom
import gmarques.debtv4.data.room.entidades.DespesaEntidade
import gmarques.debtv4.data.room.entidades.RecorrenciaEntidade
const val DATABASE_NAME = "app-database.sql"
@Database(
version = 1,
exportSchema = false,
entities = [DespesaEntidade::class, RecorrenciaEntidade::class]
)
abstract class AppDatabase : RoomDatabase() {
abstract fun getDespesaDao(): DespesaDaoRoom
abstract fun getRecorrenciaDao(): RecorrenciaDaoRoom
}
| 0 |
Kotlin
|
0
| 0 |
c01f817af61fb1da02b27bb21a45b3fb54e03c6e
| 655 |
DebtV4
|
MIT License
|
src/main/java/catmoe/fallencrystal/moefilter/api/command/CommandManager.kt
|
CatMoe
| 638,486,044 | false | null |
package catmoe.fallencrystal.moefilter.api.command
import catmoe.fallencrystal.moefilter.api.command.annotation.*
import catmoe.fallencrystal.moefilter.api.command.annotation.misc.DescriptionFrom.MESSAGE_PATH
import catmoe.fallencrystal.moefilter.api.command.annotation.misc.DescriptionFrom.STRING
import catmoe.fallencrystal.moefilter.api.command.annotation.parse.ParsedInfo
import catmoe.fallencrystal.moefilter.common.config.ObjectConfig
import com.github.benmanes.caffeine.cache.Caffeine
import net.md_5.bungee.api.CommandSender
import net.md_5.bungee.api.ProxyServer
import java.util.concurrent.CopyOnWriteArrayList
object CommandManager {
private val command = Caffeine.newBuilder().build<String, ICommand>()
private val commands: MutableList<String> = CopyOnWriteArrayList()
private val parseCommand = Caffeine.newBuilder().build<ICommand, ParsedInfo>()
private val console = ProxyServer.getInstance().console
fun register(c: ICommand) {
val iClass = c::class.java
if (iClass.isAnnotationPresent(DebugCommand::class.java) && !(try { ObjectConfig.getConfig().getBoolean("debug") } catch (_: Exception) { false })) { return }
val annotationCommand = ( try { iClass.getAnnotation(Command::class.java).command } catch (_:Exception) { return } )
val annotationPermission = ( try { val permission= iClass.getAnnotation(CommandPermission::class.java).permission; permission.ifEmpty { "" } } catch (_: Exception) { "" } )
val annotationAllowConsole = iClass.isAnnotationPresent(ConsoleCanExecute::class.java)
val annotationDescription = getAnnotationDescription(c)
val annotationUsage = ( try { iClass.getAnnotation(CommandUsage::class.java).usage.toList() } catch (_: Exception) { listOf() } )
if (commands.contains(annotationCommand)) { return }
val parsed = ParsedInfo(annotationCommand, annotationDescription, annotationPermission, annotationUsage, annotationAllowConsole)
parseCommand.put(c, parsed)
command.put(annotationCommand, c)
commands.add(annotationCommand)
}
private fun getAnnotationDescription(c: ICommand): String {
val annotationDescription = c::class.java.getAnnotation(CommandDescription::class.java) ?: return ""
val description = annotationDescription.description
return when (annotationDescription.type) {
STRING -> { description }
MESSAGE_PATH -> { try { ObjectConfig.getMessage().getString(description) } catch (_: Exception) { "" } }
}
}
fun unregister(c: ICommand) {
val iClass = c::class.java
if (!iClass.isAnnotationPresent(Command::class.java)) return
val targetCommand = c::class.java.getAnnotation(Command::class.java).command
val originalCommand = command.getIfPresent(targetCommand)
if (targetCommand.isNotEmpty() && originalCommand != null) {
parseCommand.invalidate(originalCommand)
command.invalidate(targetCommand)
}
commands.remove(targetCommand)
}
fun dropAll() {
parseCommand.invalidateAll()
command.invalidateAll()
commands.clear()
}
fun getCommandList(): MutableList<ICommand> {
val list: MutableList<ICommand> = ArrayList()
commands.forEach {
val iCommand = command.getIfPresent(it)
if (iCommand != null) { list.add(iCommand) }
}
return list
}
fun getICommand(cmd: String): ICommand? { return command.getIfPresent(cmd) }
fun getParsedCommand(c: ICommand): ParsedInfo? { return parseCommand.getIfPresent(c) }
fun getCommandList(sender: CommandSender): MutableList<ICommand> {
val listWithPermission = mutableListOf<ICommand>()
getCommandList().forEach {
val parsedInfo = getParsedCommand(it)!!
if (sender == console) { if (parsedInfo.allowConsole) listWithPermission.add(it) } else if (sender.hasPermission(parsedInfo.permission)) listWithPermission.add(it)
}
return listWithPermission
}
}
| 2 |
Kotlin
|
0
| 2 |
4afea088e12dc89d93dbc54f9c3a30b9c0d6f3f7
| 4,083 |
MoeFilter
|
Apache License 2.0
|
playtest-http/src/main/kotlin/com/uzabase/playtest2/http/proxy/ResponseBodyProxy.kt
|
uzabase
| 723,558,469 | false |
{"Kotlin": 66449}
|
package com.uzabase.playtest2.http.proxy
import com.uzabase.playtest2.core.assertion.ShouldBeString
import com.uzabase.playtest2.core.assertion.ShouldContainsString
import com.uzabase.playtest2.http.zoom.JsonPathProxy
import com.uzabase.playtest2.http.zoom.JsonSerializable
import java.nio.file.Path
class ResponseBodyProxy private constructor(val body: Path) : ShouldBeString, ShouldContainsString, JsonSerializable {
companion object {
fun of(body: Path) = ResponseBodyProxy(body)
}
override fun shouldBe(expected: String): Boolean =
body.toFile().readText(Charsets.UTF_8) == expected
override fun shouldContain(expected: String): Boolean =
body.toFile().readText(Charsets.UTF_8).contains(expected)
override fun toJsonPathProxy(path: String): JsonPathProxy =
body.toFile().readText(Charsets.UTF_8)
.let { JsonPathProxy.of(it, path) }
}
| 10 |
Kotlin
|
0
| 8 |
d922f99502cc181e1a98f163634f140ebfd2f47d
| 906 |
playtest2
|
MIT License
|
sdk/src/main/java/app/knock/client/KnockMessagingService.kt
|
knocklabs
| 712,054,463 | false |
{"Kotlin": 191911}
|
package app.knock.client
import android.annotation.SuppressLint
import app.knock.client.models.messages.KnockMessageStatusUpdateType
import app.knock.client.modules.registerTokenForFCM
import app.knock.client.modules.updateMessageStatus
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
@SuppressLint("MissingFirebaseInstanceTokenRefresh")
open class KnockMessagingService: FirebaseMessagingService() {
/*
This will be called if user receives a push notification with the app in the foreground only, unless it is a "silent notification".
A silent notification removes the `notification` object from the payload, which will not trigger the Android OS to handle the notification for you.
*/
override fun onMessageReceived(message: RemoteMessage) {
super.onMessageReceived(message)
Knock.shared.logDebug(KnockLogCategory.PUSH_NOTIFICATION, "onMessageReceived", "received message: $message")
Knock.shared.logDebug(KnockLogCategory.PUSH_NOTIFICATION, "onMessageReceived", "From: ${message.from}")
message.data.isNotEmpty().let {
Knock.shared.logDebug(KnockLogCategory.PUSH_NOTIFICATION, "onMessageReceived", "Message data payload: " + message.data)
}
message.notification?.let {
Knock.shared.logDebug(KnockLogCategory.PUSH_NOTIFICATION, "onMessageReceived", "Message Notification Body: ${it.body}")
}
fcmRemoteMessageReceived(message)
}
override fun onNewToken(token: String) {
super.onNewToken(token)
Knock.shared.logDebug(KnockLogCategory.PUSH_NOTIFICATION, "onNewToken", token)
try {
val channelId = Knock.shared.environment.getSafePushChannelId()
Knock.shared.registerTokenForFCM(channelId = channelId, token = token) { result ->
result.onSuccess {
Knock.shared.logDebug(KnockLogCategory.PUSH_NOTIFICATION, "onNewToken", "registerTokenForFCM: Success")
}.onFailure {
Knock.shared.logDebug(KnockLogCategory.PUSH_NOTIFICATION, "onNewToken", "registerTokenForFCM: Failure")
}
}
} catch (e: Exception) {
Knock.shared.logDebug(KnockLogCategory.PUSH_NOTIFICATION, "onNewToken", "registerTokenForFCM: Failure. Need to first set PushChannelId with Knock.setup().")
}
}
open fun fcmRemoteMessageReceived(message: RemoteMessage) {
message.data[Knock.KNOCK_MESSAGE_ID_KEY]?.let {
Knock.shared.updateMessageStatus(it, KnockMessageStatusUpdateType.READ) {}
}
}
}
| 0 |
Kotlin
|
1
| 2 |
96707ada2ee0bec439364ef320d5a293e607915e
| 2,651 |
knock-android
|
MIT License
|
app/src/main/java/ttaomae/foodtracker/di/RepositoryModule.kt
|
ttaomae
| 637,206,443 | false | null |
package ttaomae.foodtracker.di
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import ttaomae.foodtracker.data.FoodItemDao
import ttaomae.foodtracker.data.FoodItemDaoRepository
import ttaomae.foodtracker.data.FoodItemRepository
import ttaomae.foodtracker.data.RestaurantDao
import ttaomae.foodtracker.data.RestaurantDaoRepository
import ttaomae.foodtracker.data.RestaurantRepository
@Module
@InstallIn(SingletonComponent::class)
class RepositoryModule {
@Provides
fun provideFoodRepository(foodItemDao: FoodItemDao): FoodItemRepository {
return FoodItemDaoRepository(foodItemDao)
}
@Provides
fun provideRestaurantRepository(restaurantDao: RestaurantDao): RestaurantRepository {
return RestaurantDaoRepository(restaurantDao)
}
}
| 17 |
Kotlin
|
0
| 0 |
e5654bfde67f53896aea170d7bc5341599209397
| 845 |
food-tracker
|
MIT License
|
library/src/main/kotlin/me/proxer/library/api/info/InfoApi.kt
|
proxer
| 43,981,937 | false |
{"Kotlin": 492567}
|
package me.proxer.library.api.info
import retrofit2.Retrofit
/**
* API for the Info class.
*
* @author <NAME>
*/
class InfoApi internal constructor(retrofit: Retrofit) {
private val internalApi = retrofit.create(InternalApi::class.java)
/**
* Returns the respective endpoint.
*/
fun entryCore(entryId: String): EntryCoreEndpoint {
return EntryCoreEndpoint(internalApi, entryId)
}
/**
* Returns the respective endpoint.
*/
fun entry(entryId: String): EntryEndpoint {
return EntryEndpoint(internalApi, entryId)
}
/**
* Returns the respective endpoint.
*/
fun episodeInfo(entryId: String): EpisodeInfoEndpoint {
return EpisodeInfoEndpoint(internalApi, entryId)
}
/**
* Returns the respective endpoint.
*/
fun comments(entryId: String): CommentsEndpoint {
return CommentsEndpoint(internalApi, entryId)
}
/**
* Returns the respective endpoint.
*/
fun relations(entryId: String): RelationsEndpoint {
return RelationsEndpoint(internalApi, entryId)
}
/**
* Returns the respective endpoint.
*/
fun translatorGroup(translatorGroupId: String): TranslatorGroupEndpoint {
return TranslatorGroupEndpoint(internalApi, translatorGroupId)
}
/**
* Returns the respective endpoint.
*/
fun industry(industryId: String): IndustryEndpoint {
return IndustryEndpoint(internalApi, industryId)
}
/**
* Returns the respective endpoint.
*/
fun note(entryId: String): ModifyUserInfoEndpoint {
return ModifyUserInfoEndpoint(internalApi, entryId, UserInfoType.NOTE)
}
/**
* Returns the respective endpoint.
*/
fun markAsFavorite(entryId: String): ModifyUserInfoEndpoint {
return ModifyUserInfoEndpoint(internalApi, entryId, UserInfoType.FAVORITE)
}
/**
* Returns the respective endpoint.
*/
fun markAsFinished(entryId: String): ModifyUserInfoEndpoint {
return ModifyUserInfoEndpoint(internalApi, entryId, UserInfoType.FINISHED)
}
/**
* Returns the respective endpoint.
*/
fun subscribe(entryId: String): ModifyUserInfoEndpoint {
return ModifyUserInfoEndpoint(internalApi, entryId, UserInfoType.SUBSCRIBE)
}
/**
* Returns the respective endpoint.
*/
fun recommendations(entryId: String): RecommendationsEndpoint {
return RecommendationsEndpoint(internalApi, entryId)
}
/**
* Returns the respective endpoint.
*/
fun userInfo(entryId: String): MediaUserInfoEndpoint {
return MediaUserInfoEndpoint(internalApi, entryId)
}
/**
* Returns the respective endpoint.
*/
fun forumDiscussions(entryId: String): ForumDiscussionsEndpoint {
return ForumDiscussionsEndpoint(internalApi, entryId)
}
}
| 0 |
Kotlin
|
2
| 13 |
f55585b485c8eff6da944032690fe4de40a58e65
| 2,898 |
ProxerLibJava
|
MIT License
|
app/src/main/kotlin/dmitry/molchanov/tictactoe/presentation/game/GameOverChecker.kt
|
MolchanovDmitry
| 544,147,571 | false |
{"Kotlin": 18557}
|
package dmitry.molchanov.tictactoe.presentation.game
import dmitry.molchanov.tictactoe.presentation.game.model.CellType
import dmitry.molchanov.tictactoe.presentation.game.model.CellType.BOTTOM
import dmitry.molchanov.tictactoe.presentation.game.model.CellType.CENTER
import dmitry.molchanov.tictactoe.presentation.game.model.CellType.LEFT_BOTTOM
import dmitry.molchanov.tictactoe.presentation.game.model.CellType.LEFT_CENTER
import dmitry.molchanov.tictactoe.presentation.game.model.CellType.LEFT_TOP
import dmitry.molchanov.tictactoe.presentation.game.model.CellType.RIGHT_BOTTOM
import dmitry.molchanov.tictactoe.presentation.game.model.CellType.RIGHT_CENTER
import dmitry.molchanov.tictactoe.presentation.game.model.CellType.RIGHT_TOP
import dmitry.molchanov.tictactoe.presentation.game.model.CellType.TOP
import dmitry.molchanov.tictactoe.presentation.game.model.PlayerType
fun getWinnerCells(gameSnap: Map<CellType, PlayerType>): Pair<PlayerType, List<CellType>>? =
gameSnap.getSinglePlayerWithCellsOrNull(LEFT_TOP, TOP, RIGHT_TOP)
?: gameSnap.getSinglePlayerWithCellsOrNull(LEFT_CENTER, CENTER, RIGHT_CENTER)
?: gameSnap.getSinglePlayerWithCellsOrNull(LEFT_BOTTOM, BOTTOM, RIGHT_BOTTOM)
?: gameSnap.getSinglePlayerWithCellsOrNull(LEFT_TOP, LEFT_CENTER, LEFT_BOTTOM)
?: gameSnap.getSinglePlayerWithCellsOrNull(TOP, CENTER, BOTTOM)
?: gameSnap.getSinglePlayerWithCellsOrNull(RIGHT_TOP, RIGHT_CENTER, RIGHT_BOTTOM)
?: gameSnap.getSinglePlayerWithCellsOrNull(LEFT_TOP, CENTER, RIGHT_BOTTOM)
?: gameSnap.getSinglePlayerWithCellsOrNull(RIGHT_TOP, CENTER, LEFT_BOTTOM)
private fun Map<CellType, PlayerType>.getSinglePlayerWithCellsOrNull(
vararg cellTypes: CellType
): Pair<PlayerType, List<CellType>>? {
var playerType: PlayerType? = null
cellTypes.forEach { cellType ->
val cellPlayer = this[cellType]
when {
cellPlayer == null -> return null
playerType == null -> playerType = cellPlayer
cellPlayer != playerType -> return null
}
}
return playerType?.let { it to cellTypes.toList() }
}
| 0 |
Kotlin
|
0
| 0 |
bdf7d79156cdcdfb2d423895584d9f5241673e2f
| 2,131 |
TicTacToeWearOs
|
Apache License 2.0
|
src/main/kotlin/net/botlify/anticaptchacom/supplier/utils/TaskResponse.kt
|
botlify-net
| 624,862,804 | false |
{"Kotlin": 41548}
|
package net.botlify.anticaptchacom.supplier.utils
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import net.botlify.anticaptchacom.AntiCaptchaComClient
import net.botlify.anticaptchacom.data.response.solution.SolveResponse
import net.botlify.anticaptchacom.enums.TaskStatus
import net.botlify.anticaptchacom.exceptions.AntiCaptchaComException
import org.apache.logging.log4j.LogManager
import java.util.concurrent.TimeoutException
@JsonIgnoreProperties(ignoreUnknown = true)
private data class TaskResult(
@JsonProperty("errorId")
val errorId: Int,
@JsonProperty("status")
val status: TaskStatus,
)
private data class TaskRequest(
@JsonProperty("clientKey")
val clientKey: String,
@JsonProperty("taskId")
val taskId: TaskId,
)
internal class TaskResponse<T>(
private val api: AntiCaptchaComClient,
private val taskId: TaskId,
private val clazz: Class<T>,
) {
companion object {
/**
* The logger of the class.
*/
private val log = LogManager.getLogger(TaskResponse::class.java)
}
@Throws(AntiCaptchaComException::class, TimeoutException::class)
fun getResponse(): SolveResponse<T> {
return (getResponse(1))
}
private fun getResponse(attempt: Int): SolveResponse<T> {
verifyAttemptAndSleep(attempt)
val responseString = sendGetStatus()
val taskResult = mapTaskResult(responseString)
return when (taskResult.status) {
TaskStatus.PROCESSING -> {
log.trace("Task id {} is still processing...", taskId)
getResponse(attempt + 1)
}
TaskStatus.READY -> {
log.trace("Task id {} is ready!", taskId)
mapResponse(responseString)
}
}
}
private fun verifyAttemptAndSleep(attempt: Int) {
val firstSleepTime = api.config.firstSleepBetweenAttemptsMillis
val otherSleepTime = api.config.sleepBetweenAttemptsMillis
val sleepTime = if (attempt == 1) firstSleepTime else otherSleepTime
val maxAttempts = api.config.maxAttempts;
if (attempt > maxAttempts) {
throw TimeoutException("Max attempts reached for anti-captcha.com for task id $taskId")
}
log.trace("Attempt {} of {} for task id {}", attempt, maxAttempts, taskId)
log.trace("Sleeping {} millis before getting captcha solution for task id {}...", sleepTime, taskId)
Thread.sleep(sleepTime.toLong())
}
private fun sendGetStatus(): String {
val mapper = jacksonObjectMapper()
val request = TaskRequest(api.config.apiKey, taskId)
val requestJson = mapper.writeValueAsString(request)
val responseString: String = api.httpRequester.sendPost("/getTaskResult", requestJson)
return responseString;
}
private fun mapTaskResult(json: String): TaskResult {
val mapper = jacksonObjectMapper()
val result = mapper.readValue(json, TaskResult::class.java)
return result
}
private fun mapResponse(response: String): SolveResponse<T> {
val mapper = jacksonObjectMapper()
val type = mapper.typeFactory.constructParametricType(SolveResponse::class.java, clazz)
val result = mapper.readValue<SolveResponse<T>>(response, type)
return result
}
}
| 0 |
Kotlin
|
0
| 0 |
ce971de71e87b03509ee4c06a639972cc98e0d2d
| 3,480 |
anticaptchacom-api
|
Apache License 2.0
|
search/src/main/java/dev/hakanbagci/search/domain/usecase/SearchMeals.kt
|
hakanbagci
| 415,409,117 | false |
{"Kotlin": 16467}
|
package dev.hakanbagci.search.domain.usecase
import dev.hakanbagci.search.domain.entity.SearchMealsResult
import dev.hakanbagci.search.domain.repo.MealRepository
import javax.inject.Inject
class SearchMeals @Inject constructor(
private val mealRepository: MealRepository
) {
suspend operator fun invoke(query: String): SearchMealsResult {
return mealRepository.search(query)
}
}
| 7 |
Kotlin
|
0
| 0 |
f66e4aa25037520480add77c39eccfed344bf2b6
| 402 |
meals-compose
|
Apache License 2.0
|
api/src/commonMain/kotlin/keep/Cacheable.kt
|
aSoft-Ltd
| 629,808,228 | false | null |
@file:JsExport
package keep
import kollections.JsExport
interface Cacheable {
val cache: Cache
}
| 0 |
Kotlin
|
0
| 0 |
2801c388be06f9df5a3ded782b75eab3fc3fd3b9
| 103 |
keep
|
MIT License
|
WorkManagerDemo/app/src/main/java/com/example/workmanagerdemo/UploadWorker.kt
|
iamaydan
| 343,137,358 | false |
{"Kotlin": 149521}
|
package com.example.workmanagerdemo
import android.content.Context
import android.util.Log
import androidx.work.Data
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
class UploadWorker(context: Context,params:WorkerParameters) : Worker(context,params) {
companion object{
const val KEY_WORKER = "key_worker"
}
override fun doWork(): Result {
try {
val count = inputData.getInt(MainActivity.KEY_COUNT_VALUE,0)
for (i in 0 until count) {
Log.i("MYTAG", "Uploading $i")
}
val time = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
val currentDate = time.format(Date())
val outPutData = Data.Builder()
.putString(KEY_WORKER,currentDate)
.build()
return Result.success(outPutData)
} catch (e: Exception){
return Result.failure()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
b6637ea92393a29947f48ed17b01d28ced7477fc
| 1,016 |
IBAR-Training-1
|
Apache License 2.0
|
WorkManagerDemo/app/src/main/java/com/example/workmanagerdemo/UploadWorker.kt
|
iamaydan
| 343,137,358 | false |
{"Kotlin": 149521}
|
package com.example.workmanagerdemo
import android.content.Context
import android.util.Log
import androidx.work.Data
import androidx.work.Worker
import androidx.work.WorkerParameters
import java.lang.Exception
import java.text.SimpleDateFormat
import java.util.*
class UploadWorker(context: Context,params:WorkerParameters) : Worker(context,params) {
companion object{
const val KEY_WORKER = "key_worker"
}
override fun doWork(): Result {
try {
val count = inputData.getInt(MainActivity.KEY_COUNT_VALUE,0)
for (i in 0 until count) {
Log.i("MYTAG", "Uploading $i")
}
val time = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
val currentDate = time.format(Date())
val outPutData = Data.Builder()
.putString(KEY_WORKER,currentDate)
.build()
return Result.success(outPutData)
} catch (e: Exception){
return Result.failure()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
b6637ea92393a29947f48ed17b01d28ced7477fc
| 1,016 |
IBAR-Training-1
|
Apache License 2.0
|
app/src/main/java/com/goudurixx/pokedex/features/pokemon/components/FilterDialog.kt
|
Goudurixx
| 756,872,856 | false |
{"Kotlin": 249861}
|
import android.util.Log
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.SizeTransform
import androidx.compose.animation.animateColor
import androidx.compose.animation.core.EaseInCubic
import androidx.compose.animation.core.EaseOutCubic
import androidx.compose.animation.core.FastOutSlowInEasing
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.scaleIn
import androidx.compose.animation.togetherWith
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.RangeSlider
import androidx.compose.material3.SegmentedButton
import androidx.compose.material3.SegmentedButtonDefaults
import androidx.compose.material3.SingleChoiceSegmentedButtonRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalConfiguration
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.goudurixx.pokedex.core.common.models.FilterByParameter
import com.goudurixx.pokedex.core.ui.theme.PokedexTheme
import com.goudurixx.pokedex.core.ui.theme.TypeFire
import com.goudurixx.pokedex.core.ui.theme.TypeWater
import com.goudurixx.pokedex.features.pokemon.models.BaseFilterItemUiModel
import com.goudurixx.pokedex.features.pokemon.models.BooleanFilterUiModel
import com.goudurixx.pokedex.features.pokemon.models.ListFilterUiModel
import com.goudurixx.pokedex.features.pokemon.models.RangeFilterItemUiModel
import com.goudurixx.pokedex.features.pokemon.models.TypeUiModel
import com.goudurixx.pokedex.features.pokemon.models.updateFilterList
import kotlin.math.roundToInt
@Composable
fun FabContainer(
filterList: List<BaseFilterItemUiModel>,
onFilterListChange: (List<BaseFilterItemUiModel>) -> Unit,
containerState: FabContainerState,
onContainerStateChange: (FabContainerState) -> Unit,
modifier: Modifier = Modifier,
) {
val isCompactdevice = (LocalConfiguration.current.screenWidthDp < 600.dp.value)
val transition = updateTransition(containerState, label = "container transform")
val animatedColor by transition.animateColor(
label = "color",
) { state ->
when (state) {
FabContainerState.Fab -> MaterialTheme.colorScheme.primaryContainer
FabContainerState.Fullscreen -> MaterialTheme.colorScheme.surface
}
}
val cornerRadius by transition.animateDp(
label = "corner radius",
transitionSpec = {
when (targetState) {
FabContainerState.Fab -> tween(
durationMillis = 400,
easing = EaseOutCubic,
)
FabContainerState.Fullscreen -> tween(
durationMillis = 200,
easing = EaseInCubic,
)
}
}
) { state ->
when (state) {
FabContainerState.Fab -> 16.dp
FabContainerState.Fullscreen -> if (isCompactdevice) 0.dp else 16.dp
}
}
val elevation by transition.animateDp(
label = "elevation",
transitionSpec = {
when (targetState) {
FabContainerState.Fab -> tween(
durationMillis = 400,
easing = EaseOutCubic,
)
FabContainerState.Fullscreen -> tween(
durationMillis = 200,
easing = EaseOutCubic,
)
}
}
) { state ->
when (state) {
FabContainerState.Fab -> 6.dp
FabContainerState.Fullscreen -> 6.dp
}
}
val padding by transition.animateDp(
label = "padding",
) { state ->
when (state) {
FabContainerState.Fab -> 16.dp
FabContainerState.Fullscreen -> if (isCompactdevice) 0.dp else 16.dp
}
}
AnimatedVisibility(
visible = containerState == FabContainerState.Fullscreen,
modifier = Modifier.fillMaxSize(),
enter = fadeIn(),
exit = fadeOut()
)
{
Box(
Modifier
.background(Color.Black.copy(0.5f))
.pointerInput(Unit) {
detectTapGestures {
onContainerStateChange(FabContainerState.Fab)
}
}
)
}
transition.AnimatedContent(
contentAlignment = Alignment.Center,
modifier = modifier
.padding(start = padding, end = padding, bottom = padding, top = padding)
.shadow(
elevation = elevation,
shape = RoundedCornerShape(cornerRadius)
)
.drawBehind { drawRect(animatedColor) },
transitionSpec = {
(
fadeIn(animationSpec = tween(220, delayMillis = 90)) +
scaleIn(
initialScale = 0.92f,
animationSpec = tween(220, delayMillis = 90)
)
)
.togetherWith(fadeOut(animationSpec = tween(90)))
.using(SizeTransform(clip = false, sizeAnimationSpec = { _, _ ->
tween(
durationMillis = 500,
easing = FastOutSlowInEasing
)
}))
}
) { state ->
when (state) {
FabContainerState.Fab -> {
Fab(
modifier = Modifier,
onClick = { onContainerStateChange(FabContainerState.Fullscreen) }
)
}
FabContainerState.Fullscreen -> {
FilterContent(
filterList = filterList,
onFilterListChange = onFilterListChange,
onDismiss = { onContainerStateChange(FabContainerState.Fab) },
modifier = Modifier
.widthIn(max = 600.dp)
.fillMaxSize()
)
}
}
}
}
@Composable
fun FilterContent(
filterList: List<BaseFilterItemUiModel>,
onFilterListChange: (List<BaseFilterItemUiModel>) -> Unit,
onDismiss: () -> Unit,
modifier: Modifier = Modifier
) {
LazyColumn(
modifier = modifier
.padding(8.dp)
.clip(RoundedCornerShape(8.dp)),
verticalArrangement = Arrangement.spacedBy(16.dp),
contentPadding = PaddingValues(16.dp)
) {
item {
filterList.forEachIndexed { index, filterItem ->
when (filterItem) {
is RangeFilterItemUiModel -> {
RangeSliderItem(
filterItem = filterItem,
index = index,
filterList = filterList,
onFilterListChange = onFilterListChange,
)
}
is ListFilterUiModel<*> -> {
Text(
text = filterItem.type.parameterName,
modifier = Modifier.fillMaxWidth(),
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center,
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
) {
filterItem.list.forEachIndexed { index, it ->
if (it.first is TypeUiModel) {
val type = it.first as TypeUiModel
TextButton(
onClick = {
onFilterListChange(
filterList.updateFilterList(
index,
filterItem.updateList(
filterItem.list.indexOf(it),
filterItem.list[index].second
)
)
)
},
colors = ButtonDefaults.buttonColors(containerColor = type.color),
border = if (filterItem.list[index].second) BorderStroke(
2.dp,
MaterialTheme.colorScheme.onSurface
) else null,
) {
Text(
text = type.name,
style = MaterialTheme.typography.titleMedium,
)
}
}
}
}
}
is BooleanFilterUiModel -> {
Row(
modifier = Modifier
.padding(vertical = 8.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center
) {
Text(
text = filterItem.type.parameterName,
modifier = Modifier.weight(1f)
)
SingleChoiceBooleanButton(
value = filterItem.value,
onValueChange = {
onFilterListChange(
filterList.updateFilterList(
index,
filterItem.copy(value = it)
)
)
}
)
}
}
}
}
}
item {
Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
OutlinedButton(
onClick = {
onDismiss()
Log.e("FilterContent", "FilterContent: $filterList")
},
modifier = Modifier
) {
Text(
text = "Dismiss"
)
}
}
}
}
}
@Composable
fun RangeSliderItem(
filterItem: RangeFilterItemUiModel,
index: Int,
filterList: List<BaseFilterItemUiModel>,
onFilterListChange: (List<BaseFilterItemUiModel>) -> Unit
) {
Column() {
Text(
text = filterItem.type.parameterName,
modifier = Modifier.fillMaxWidth(),
style = MaterialTheme.typography.titleMedium,
textAlign = TextAlign.Center,
)
RangeSlider(
value = filterItem.value,
onValueChange = { range ->
onFilterListChange(
filterList.updateFilterList(
index,
filterItem.copy(value = range)
)
)
},
steps = filterItem.steps,
valueRange = filterItem.range,
)
Row(Modifier.fillMaxWidth()) {
Text(
text = filterItem.value.start.roundToInt().toString(),
modifier = Modifier.weight(1f),
style = MaterialTheme.typography.titleMedium,
)
Text(
text = filterItem.value.endInclusive.roundToInt().toString(),
style = MaterialTheme.typography.titleMedium,
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SingleChoiceBooleanButton(value: Boolean?, onValueChange: (Boolean?) -> Unit) {
SingleChoiceSegmentedButtonRow {
SegmentedButton(
selected = value == true,
onClick = { onValueChange(if (value == true) null else true) },
shape = SegmentedButtonDefaults.itemShape(index = 0, count = 2)
) {
Text(text = "Yes")
}
SegmentedButton(
selected = value == false,
onClick = { onValueChange(if (value == false) null else false) },
shape = SegmentedButtonDefaults.itemShape(index = 1, count = 2)
) {
Text(text = "No")
}
}
}
@Composable
private fun HotContent() {
Column {
SearchBar(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 12.dp, vertical = 6.dp)
)
HotTakes()
}
}
@Composable
private fun SearchBar(modifier: Modifier = Modifier) {
OutlinedTextField(
modifier = modifier,
value = "",
onValueChange = {},
leadingIcon = {
Icon(
imageVector = Icons.Default.Menu,
contentDescription = null,
)
},
placeholder = {
Text(
text = "Search your hot takes"
)
},
colors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = Color.Transparent,
unfocusedBorderColor = Color.Transparent,
unfocusedContainerColor = MaterialTheme.colorScheme.secondaryContainer,
focusedContainerColor = MaterialTheme.colorScheme.secondaryContainer,
),
shape = RoundedCornerShape(50)
)
}
@Composable
private fun HotTakes() {
LazyColumn(
modifier = Modifier
.fillMaxWidth()
.padding(top = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
items(listOf("ddd", "ddda", "dadad")) {
HotTake(hotTake = it)
}
}
}
@Composable
private fun HotTake(hotTake: String) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 16.dp),
onClick = { },
) {
Column(
modifier = Modifier.padding(16.dp)
) {
Text(
text = hotTake,
style = MaterialTheme.typography.titleMedium,
)
Text(
modifier = Modifier
.padding(top = 6.dp),
maxLines = 3,
text = hotTake,
overflow = TextOverflow.Ellipsis
)
}
}
}
@Composable
private fun Fab(
modifier: Modifier = Modifier,
onClick: () -> Unit
) {
Box(
modifier = modifier
.defaultMinSize(
minWidth = 56.dp,
minHeight = 56.dp,
)
.clickable(
onClick = onClick,
),
contentAlignment = Alignment.Center,
) {
Icon(
painter = rememberVectorPainter(Icons.Filled.Add),
contentDescription = null,
)
}
}
enum class FabContainerState {
Fab,
Fullscreen,
}
@Preview(showBackground = true, widthDp = 700)
@Composable
private fun Preview() {
PokedexTheme {
var fabContainerState by remember { mutableStateOf(FabContainerState.Fullscreen) }
var filterList by remember {
mutableStateOf(
listOf(
RangeFilterItemUiModel(FilterByParameter.ID, 0f..1000f, 0f..1000f),
RangeFilterItemUiModel(FilterByParameter.BASE_EXPERIENCE, 0f..400f, 0f..400f),
RangeFilterItemUiModel(FilterByParameter.ATTACK, 0f..255f, 0f..255f),
ListFilterUiModel<TypeUiModel>(
FilterByParameter.TYPE,
listOf(
Pair(TypeUiModel(id = 1, "fire", TypeFire), false),
Pair(TypeUiModel(id = 2, "water", TypeWater), false)
)
),
BooleanFilterUiModel(
FilterByParameter.IS_LEGENDARY,
false
), //TODO CHECK THE THIRD STATE
BooleanFilterUiModel(
FilterByParameter.IS_LEGENDARY,
false
), //TODO CHECK THE THIRD STATE
)
)
}
Box(
modifier = Modifier
.fillMaxSize(),
) {
HotContent()
FabContainer(
filterList = filterList,
onFilterListChange = {
filterList = it
Log.e("HomeScreen", "HomeScreen: $filterList")
},
modifier = Modifier
.align(Alignment.BottomEnd),
containerState = fabContainerState,
onContainerStateChange = { newContainerState ->
fabContainerState = newContainerState
}
)
}
}
}
| 0 |
Kotlin
|
0
| 2 |
91999438d698d59ca4b510172c72140662ed57a0
| 19,922 |
pokedex-JC
|
MIT License
|
backend/src/test/kotlin/com/denchic45/studiversity/client/course/CourseWithStudyGroupMembershipTest.kt
|
denchic45
| 435,895,363 | false |
{"Kotlin": 2110094, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
|
package com.denchic45.studiversity.client.course
import com.denchic45.studiversity.KtorClientTest
import com.denchic45.stuiversity.api.course.model.CourseResponse
import com.denchic45.stuiversity.api.course.model.CreateCourseRequest
import com.denchic45.stuiversity.api.membership.model.ManualJoinMemberRequest
import com.denchic45.stuiversity.api.membership.model.ScopeMember
import com.denchic45.stuiversity.api.role.model.Role
import com.denchic45.stuiversity.api.studygroup.model.AcademicYear
import com.denchic45.stuiversity.api.studygroup.model.CreateStudyGroupRequest
import com.denchic45.stuiversity.api.studygroup.model.StudyGroupResponse
import com.denchic45.stuiversity.util.toUUID
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.util.*
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class CourseWithStudyGroupMembershipTest : KtorClientTest() {
private lateinit var studyGroup1: StudyGroupResponse
private lateinit var studyGroup2: StudyGroupResponse
private lateinit var course: CourseResponse
private val user1Id = "7a98cdcf-d404-4556-96bd-4ce9137c8cbe".toUUID()
private val user2Id = "77129e28-bf01-4dca-b19f-9fbcf576345e".toUUID()
@BeforeEach
fun initData(): Unit = runBlocking {
studyGroup1 = client.post("/studygroups") {
contentType(ContentType.Application.Json)
setBody(CreateStudyGroupRequest("Test group 1", AcademicYear(2022, 2023), null, null))
}.body<StudyGroupResponse>().apply {
assertEquals(name, "Test group 1")
}
studyGroup2 = client.post("/studygroups") {
contentType(ContentType.Application.Json)
setBody(CreateStudyGroupRequest("Test group 2", AcademicYear(2022, 2025), null, null))
}.body()
course = client.post("/courses") {
contentType(ContentType.Application.Json)
setBody(CreateCourseRequest("Test course 1"))
}.run {
val body = body<CourseResponse>()
assertEquals(body.name, "Test course 1")
body
}
}
@AfterEach
fun clearData(): Unit = runBlocking {
// delete data
assertEquals(
HttpStatusCode.NoContent,
client.delete("/studygroups/${studyGroup1.id}").status
)
assertEquals(
HttpStatusCode.NoContent,
client.delete("/studygroups/${studyGroup2.id}").status
)
assertEquals(
HttpStatusCode.OK,
client.put("/courses/${course.id}/archived").status
)
assertEquals(
HttpStatusCode.NoContent,
client.delete("/courses/${course.id}").status
)
}
@Test
fun testMembersOnAttachDetachStudyGroupsToCourse(): Unit = runBlocking {
attachGroupsToCourse(client, course, studyGroup1, studyGroup2)
client.get("/courses/${course.id}/studygroups")
.body<List<String>>().apply {
assertEquals(
listOf(studyGroup1.id, studyGroup2.id).sorted(),
map(String::toUUID).sorted()
)
}
enrolStudentsToGroups()
syncMembership(course.id)
delay(10000)
client.get("/scopes/${course.id}/members").body<List<ScopeMember>>().apply {
assertEquals(listOf(user1Id, user2Id).sorted(), map { it.user.id }.sorted())
}
// detach first group and check members of course
client.delete("/courses/${course.id}/studygroups/${studyGroup1.id}")
syncMembership(course.id)
delay(12000)
client.get("/scopes/${course.id}/members").body<List<ScopeMember>>().apply {
assertEquals(listOf(user1Id), map { it.user.id })
}
// detach second group and check members of course
client.delete("/courses/${course.id}/studygroups/${studyGroup2.id}")
syncMembership(course.id)
delay(12000)
client.get("/scopes/${course.id}/members").body<List<ScopeMember>>().apply {
assertEquals(emptyList(), map { it.user.id })
}
}
@Test
fun testMembersOnEnrolUnrollFromGroupsInCourse(): Unit = runBlocking {
val user1Id = "7a98cdcf-d404-4556-96bd-4ce9137c8cbe".toUUID()
val user2Id = "77129e28-bf01-4dca-b19f-9fbcf576345e".toUUID()
enrolStudentsToGroups()
attachGroupsToCourse(client, course, studyGroup1, studyGroup2)
syncMembership(course.id)
// assert two attached study groups to course
client.get("/courses/${course.id}/studygroups").body<List<String>>().apply {
assertEquals(
listOf(studyGroup1.id, studyGroup2.id).sorted(),
map(String::toUUID).sorted()
)
}
// assert two users in course membership
client.get("/scopes/${course.id}/members").body<List<ScopeMember>>().apply {
assertEquals(listOf(user1Id, user2Id).sorted(), map { it.user.id }.sorted())
assertTrue(all { it.roles.contains(Role.Student) })
}
// delete first user from first group
client.delete("/scopes/${studyGroup1.id}/members/$user1Id") {
parameter(
"action",
"manual"
)
}
syncMembership(course.id)
delay(12000)
// assert only second member in first group
client.get("/scopes/${studyGroup1.id}/members").body<List<ScopeMember>>().apply {
assertEquals(listOf(user2Id), map { it.user.id })
}
// assert two members of course
client.get("/scopes/${course.id}/members").body<List<ScopeMember>>().apply {
assertEquals(listOf(user1Id, user2Id).sorted(), map { it.user.id }.sorted())
}
// delete second user from first group
client.delete("/scopes/${studyGroup1.id}/members/$user2Id") {
parameter(
"action",
"manual"
)
}
syncMembership(course.id)
delay(10000)
// assert zero members in first group
client.get("/scopes/${studyGroup1.id}/members").body<List<ScopeMember>>().apply {
assertEquals(emptyList(), map { it.user.id })
}
// assert only first member of course
client.get("/scopes/${course.id}/members").body<List<ScopeMember>>().apply {
assertEquals(listOf(user1Id), map { it.user.id })
}
// delete first user from second group
client.delete("/scopes/${studyGroup2.id}/members/$user1Id") {
parameter(
"action",
"manual"
)
}
syncMembership(course.id)
delay(10000)
// assert zero members of course
client.get("/scopes/${course.id}/members").body<List<ScopeMember>>().apply {
assertEquals(emptyList(), map { it.user.id })
}
}
private suspend fun enrolStudentsToGroups(
) {
client.post("/scopes/${studyGroup1.id}/members?action=manual") {
contentType(ContentType.Application.Json)
setBody(ManualJoinMemberRequest(user1Id, roleIds = listOf(3)))
}.apply { assertEquals(HttpStatusCode.Created, status) }
client.post("/scopes/${studyGroup2.id}/members?action=manual") {
contentType(ContentType.Application.Json)
setBody(ManualJoinMemberRequest(user1Id, roleIds = listOf(3)))
}.apply { assertEquals(HttpStatusCode.Created, status) }
client.post("/scopes/${studyGroup1.id}/members?action=manual") {
contentType(ContentType.Application.Json)
setBody(ManualJoinMemberRequest(user2Id, roleIds = listOf(3)))
}.apply { assertEquals(HttpStatusCode.Created, status) }
delay(10000)
}
private suspend fun syncMembership(courseId: UUID) {
client.get("/scopes/${courseId}/memberships") {
parameter("type", "by_group")
}.run {
if (status == HttpStatusCode.OK)
client.post("/scopes/${courseId}/memberships/${bodyAsText()}/sync").apply {
assertEquals(HttpStatusCode.Accepted, status)
}
}
}
private suspend fun attachGroupsToCourse(
client: HttpClient,
course: CourseResponse,
studyGroup1: StudyGroupResponse,
studyGroup2: StudyGroupResponse
) {
client.put("/courses/${course.id}/studygroups/${studyGroup1.id}")
delay(14000)
client.put("/courses/${course.id}/studygroups/${studyGroup2.id}")
delay(10000)
}
}
| 0 |
Kotlin
|
0
| 7 |
9b783fe46d44964f95666641bca9323cd558c11a
| 8,904 |
Studiversity
|
Apache License 2.0
|
app/src/test/java/io/github/wulkanowy/data/repositories/semester/SemesterRepositoryTest.kt
|
AlexxPy
| 244,323,232 | true |
{"Kotlin": 885566, "Shell": 220}
|
package io.github.wulkanowy.data.repositories.semester
import com.github.pwittchen.reactivenetwork.library.rx2.internet.observing.InternetObservingSettings
import io.github.wulkanowy.data.SdkHelper
import io.github.wulkanowy.data.db.entities.Semester
import io.github.wulkanowy.data.db.entities.Student
import io.github.wulkanowy.data.repositories.UnitTestInternetObservingStrategy
import io.reactivex.Maybe
import io.reactivex.Single
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.doNothing
import org.mockito.Mockito.doReturn
import org.mockito.Mockito.verify
import org.mockito.MockitoAnnotations
import org.threeten.bp.LocalDate.now
class SemesterRepositoryTest {
@Mock
private lateinit var semesterRemote: SemesterRemote
@Mock
private lateinit var semesterLocal: SemesterLocal
@Mock
private lateinit var sdkHelper: SdkHelper
@Mock
private lateinit var student: Student
private lateinit var semesterRepository: SemesterRepository
private val settings = InternetObservingSettings.builder()
.strategy(UnitTestInternetObservingStrategy())
.build()
@Before
fun initTest() {
MockitoAnnotations.initMocks(this)
semesterRepository = SemesterRepository(semesterRemote, semesterLocal, settings, sdkHelper)
}
@Test
fun getSemesters_noSemesters() {
val semesters = listOf(
createSemesterEntity(0, 0, now().minusMonths(6), now().minusMonths(3)),
createSemesterEntity(0, 0, now().minusMonths(3), now())
)
doNothing().`when`(sdkHelper).init(student)
doReturn(Maybe.empty<Semester>()).`when`(semesterLocal).getSemesters(student)
doReturn(Single.just(semesters)).`when`(semesterRemote).getSemesters(student)
semesterRepository.getSemesters(student).blockingGet()
verify(semesterLocal).deleteSemesters(emptyList())
verify(semesterLocal).saveSemesters(semesters)
}
@Test
fun getSemesters_noCurrent() {
val semesters = listOf(
createSemesterEntity(0, 0, now().minusMonths(12), now().minusMonths(6)),
createSemesterEntity(0, 0, now().minusMonths( 6), now().minusMonths(1))
)
doNothing().`when`(sdkHelper).init(student)
doReturn(Maybe.just(semesters)).`when`(semesterLocal).getSemesters(student)
val items = semesterRepository.getSemesters(student).blockingGet()
assertEquals(2, items.size)
}
@Test
fun getSemesters_oneCurrent() {
val semesters = listOf(
createSemesterEntity(0, 0, now().minusMonths(6), now().minusMonths(3)),
createSemesterEntity(0, 0, now().minusMonths(3), now())
)
doNothing().`when`(sdkHelper).init(student)
doReturn(Maybe.just(semesters)).`when`(semesterLocal).getSemesters(student)
val items = semesterRepository.getSemesters(student).blockingGet()
assertEquals(2, items.size)
}
@Test
fun getSemesters_doubleCurrent() {
val semesters = listOf(
createSemesterEntity(0, 0, now(), now()),
createSemesterEntity(0, 0, now(), now())
)
doNothing().`when`(sdkHelper).init(student)
doReturn(Maybe.just(semesters)).`when`(semesterLocal).getSemesters(student)
val items = semesterRepository.getSemesters(student).blockingGet()
assertEquals(2, items.size)
}
@Test
fun getSemesters_noSemesters_refreshOnNoCurrent() {
val semesters = listOf(
createSemesterEntity(0, 0, now().minusMonths(6), now().minusMonths(3)),
createSemesterEntity(0, 0, now().minusMonths(3), now())
)
doNothing().`when`(sdkHelper).init(student)
doReturn(Maybe.empty<Semester>()).`when`(semesterLocal).getSemesters(student)
doReturn(Single.just(semesters)).`when`(semesterRemote).getSemesters(student)
semesterRepository.getSemesters(student, refreshOnNoCurrent = true).blockingGet()
verify(semesterLocal).deleteSemesters(emptyList())
verify(semesterLocal).saveSemesters(semesters)
}
@Test
fun getSemesters_noCurrent_refreshOnNoCurrent() {
val semesters = listOf(
createSemesterEntity(0, 0, now().minusMonths(12), now().minusMonths(6)),
createSemesterEntity(0, 0, now().minusMonths( 6), now().minusMonths(1))
)
doNothing().`when`(sdkHelper).init(student)
doReturn(Maybe.just(semesters)).`when`(semesterLocal).getSemesters(student)
doReturn(Single.just(semesters)).`when`(semesterRemote).getSemesters(student)
val items = semesterRepository.getSemesters(student, refreshOnNoCurrent = true).blockingGet()
assertEquals(2, items.size)
}
@Test
fun getSemesters_doubleCurrent_refreshOnNoCurrent() {
val semesters = listOf(
createSemesterEntity(0, 0, now(), now()),
createSemesterEntity(0, 0, now(), now())
)
doNothing().`when`(sdkHelper).init(student)
doReturn(Maybe.just(semesters)).`when`(semesterLocal).getSemesters(student)
val items = semesterRepository.getSemesters(student, refreshOnNoCurrent = true).blockingGet()
assertEquals(2, items.size)
}
@Test(expected = IllegalArgumentException::class)
fun getCurrentSemester_doubleCurrent() {
val semesters = listOf(
createSemesterEntity(0, 0, now(), now()),
createSemesterEntity(0, 0, now(), now())
)
doNothing().`when`(sdkHelper).init(student)
doReturn(Maybe.just(semesters)).`when`(semesterLocal).getSemesters(student)
semesterRepository.getCurrentSemester(student).blockingGet()
}
@Test(expected = RuntimeException::class)
fun getCurrentSemester_emptyList() {
doNothing().`when`(sdkHelper).init(student)
doReturn(Maybe.just(emptyList<Semester>())).`when`(semesterLocal).getSemesters(student)
semesterRepository.getCurrentSemester(student).blockingGet()
}
}
| 0 | null |
0
| 0 |
75c94865e40513e3ccb8930c66910b66562d6639
| 6,115 |
wulkanowy
|
Apache License 2.0
|
data/src/main/java/ch/srg/dataProvider/integrationlayer/data/remote/SearchResultList.kt
|
SRGSSR
| 469,671,723 | false | null |
package ch.srg.dataProvider.integrationlayer.data.remote
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* Copyright (c) SRG SSR. All rights reserved.
* <p>
* License information is available from the LICENSE file.
*/
sealed class SearchResultList : ListResult<SearchResult>() {
abstract val searchTerm: String?
abstract val total: Int?
fun urns(): List<String>? {
return data?.map { it.urn }
}
}
@Serializable
data class SearchResultMediaList(
override val next: String?,
@SerialName("searchResultMediaList")
override val data: List<SearchResult>? = null,
override val searchTerm: String? = null,
override val total: Int? = null,
val aggregations: MediaAggregations? = null,
val exactMatchTotal: Int? = null,
val suggestionList: List<SearchSuggestion>? = null
) : SearchResultList()
@Serializable
data class SearchResultShowList(
override val next: String? = null,
override val total: Int? = null,
@SerialName("searchResultShowList")
override val data: List<SearchResult>? = null,
override val searchTerm: String? = null
) : SearchResultList()
@Serializable
data class SearchResultWithMediaList(
override val next: String? = null,
override val data: List<Media>? = null,
val searchTerm: String? = null,
val total: Int? = null,
val aggregations: MediaAggregations? = null,
val exactMatchTotal: Int? = null,
val suggestionList: List<SearchSuggestion>? = null
) : ListResult<Media>()
@Serializable
data class SearchResultWithShowList(
override val next: String? = null,
val total: Int? = null,
override val data: List<Show>? = null,
val searchTerm: String? = null
) : ListResult<Show>()
| 1 |
Kotlin
|
0
| 0 |
20fc35cbd43aaca36e5f44b8d95de575f3518a6c
| 1,754 |
srgdataprovider-android
|
MIT License
|
src/main/kotlin/io/github/grimmjo/jaxrs_analyzer/JaxRsAnalyserTask.kt
|
grimmjo
| 105,573,383 | false | null |
package io.github.grimmjo.jaxrs_analyzer
import com.sebastian_daschner.jaxrs_analyzer.JAXRSAnalyzer
import com.sebastian_daschner.jaxrs_analyzer.backend.swagger.SwaggerOptions
import org.gradle.api.DefaultTask
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.provider.ListProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.*
import org.gradle.kotlin.dsl.listProperty
import org.gradle.kotlin.dsl.property
import java.nio.file.Path
import kotlin.io.path.deleteIfExists
/**
* JaxRsAnalyserTask
* @author grimmjo
*/
@CacheableTask
abstract class JaxRsAnalyserTask : DefaultTask() {
@get:Input
abstract val mainSourceSet: Property<SourceSet>
@get:Input
abstract val backend: ListProperty<String>
@get:OutputDirectory
abstract val outputDirectory: DirectoryProperty
@get:Input
abstract val outputFileBaseName: Property<String>
@get:Input
abstract val schemes: ListProperty<String>
@get:Input
abstract val domain: Property<String>
@get:Input
abstract val renderTags: Property<Boolean>
@get:Input
abstract val tagPathOffset: Property<Number>
@TaskAction
fun analyse() {
val analysis = JAXRSAnalyzer.Analysis()
analysis.setProjectName(project.name)
analysis.setProjectVersion(project.version.toString())
mainSourceSet.get().compileClasspath.forEach { analysis.addClassPath(it.toPath()) }
mainSourceSet.get().runtimeClasspath.forEach { analysis.addClassPath(it.toPath()) }
mainSourceSet.get().allSource.sourceDirectories.forEach { analysis.addProjectSourcePath(it.toPath()) }
mainSourceSet.get().output.classesDirs.forEach { analysis.addProjectClassPath(it.toPath()) }
backend.get().forEach {
analysis.backend = JAXRSAnalyzer.constructBackend(it)
var config: Map<String, String> = mapOf()
val outputFile: Path
when (it) {
"swagger" -> {
config = mapOf(
SwaggerOptions.SWAGGER_SCHEMES to schemes.get()
.joinToString(separator = ","),
SwaggerOptions.DOMAIN to domain.get(),
SwaggerOptions.RENDER_SWAGGER_TAGS to renderTags.get().toString(),
SwaggerOptions.SWAGGER_TAGS_PATH_OFFSET to tagPathOffset.get().toString()
)
outputFile =
outputDirectory.get().asFile.toPath().resolve(outputFileBaseName.get() + "swagger.json")
}
"plaintext" -> {
outputFile =
outputDirectory.get().asFile.toPath().resolve(outputFileBaseName.get() + "plaintext.txt")
}
"asciidoc" -> {
outputFile =
outputDirectory.get().asFile.toPath().resolve(outputFileBaseName.get() + "asciidoc.adoc")
}
"markdown" -> {
outputFile =
outputDirectory.get().asFile.toPath().resolve(outputFileBaseName.get() + "markdown.md")
}
else -> {
throw IllegalArgumentException("Invalid backend type. Only 'swagger', 'plaintext' and 'asciidoc' are allowed.")
}
}
analysis.configureBackend(config)
analysis.setOutputLocation(outputFile)
outputFile.deleteIfExists()
JAXRSAnalyzer(analysis).analyze()
}
}
}
| 0 |
Kotlin
|
5
| 6 |
93a954a477d9f9791644180fe93256f54d291ed9
| 3,587 |
jaxrs-analyzer-gradle-plugin
|
Apache License 2.0
|
kotlin-antd/antd-samples/src/main/kotlin/samples/Main.kt
|
LuoKevin
| 341,311,901 | true |
{"Kotlin": 1549697, "HTML": 1503}
|
package samples
import kotlinext.js.*
import kotlinx.browser.*
import react.dom.*
fun main() {
require("antd/dist/antd.css")
render(document.getElementById("root")) {
app()
}
}
| 0 | null |
0
| 0 |
9f57507607c3dd5d5452f3cbeb966b6db3d60c76
| 200 |
kotlin-js-wrappers
|
Apache License 2.0
|
data/src/main/java/com/planradar/data/datasource/weather/impl/LocalWeatherDataSourceImpl.kt
|
imTefa
| 448,439,361 | false | null |
package com.planradar.data.datasource.weather.impl
import com.planradar.data.datasource.weather.LocalWeatherDataSource
import com.planradar.data.db.weather.WeatherDao
import com.planradar.data.db.weather.WeatherEntity
import com.planradar.data.models.Weather
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
internal class LocalWeatherDataSourceImpl(
private val weatherDao: WeatherDao,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : LocalWeatherDataSource {
override suspend fun saveWeatherRecord(weather: Weather) {
withContext(dispatcher) {
weatherDao.saveCity(
WeatherEntity(
cityId = weather.cityId,
cityName = weather.cityName,
countryName = weather.countryName,
date = weather.date,
description = weather.description,
temp = weather.temp,
humidity = weather.humidity,
windSpeed = weather.windSpeed,
iconId = weather.iconId
)
)
}
}
override suspend fun getWeatherCallHistory(cityId: Long): Flow<List<Weather>> {
return weatherDao.getCityHistory(cityId).map {
it.map { weatherEntity ->
Weather(
cityId = weatherEntity.cityId,
cityName = weatherEntity.cityName,
countryName = weatherEntity.countryName,
date = weatherEntity.date,
description = weatherEntity.description,
temp = weatherEntity.temp,
humidity = weatherEntity.humidity,
windSpeed = weatherEntity.windSpeed,
iconId = weatherEntity.iconId
)
}
}
}
}
| 0 |
Kotlin
|
0
| 0 |
bd63aee20590e2273568aaa4766e589d9826f869
| 2,008 |
WeatherApp-PlanRadar-Task
|
Apache License 2.0
|
m5-validation/src/main/kotlin/com/finyou/fintrack/backend/validation/ValidationResult.kt
|
otuskotlin
| 377,713,994 | false | null |
package com.finyou.fintrack.backend.validation
data class ValidationResult(
val errors: List<IValidationError>
) {
val isSuccess: Boolean
get() = errors.isEmpty()
companion object {
val SUCCESS = ValidationResult(emptyList())
}
}
| 0 |
Kotlin
|
0
| 0 |
2827e9759ee6ad745c8721316b500015a452f129
| 265 |
ok-202105-finrec-do
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.