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
stripe/src/main/java/com/stripe/android/view/FpxViewModel.kt
Yog8482
274,082,025
false
{"Gradle": 5, "Markdown": 7, "YAML": 2, "INI": 3, "Shell": 4, "Text": 2, "Ignore List": 1, "Batchfile": 3, "Java Properties": 1, "XML": 152, "Kotlin": 460, "Java": 5, "JSON": 1, "Proguard": 1, "EditorConfig": 1, "HTML": 2123, "CSS": 2, "JavaScript": 1, "Ruby": 1}
package com.stripe.android.view import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.liveData import com.stripe.android.ApiRequest import com.stripe.android.PaymentConfiguration import com.stripe.android.StripeApiRepository import com.stripe.android.model.FpxBankStatuses import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancelChildren internal class FpxViewModel @JvmOverloads internal constructor( application: Application, private val workDispatcher: CoroutineDispatcher = Dispatchers.IO ) : AndroidViewModel(application) { private val publishableKey = PaymentConfiguration.getInstance(application).publishableKey private val stripeRepository = StripeApiRepository( application, publishableKey, workDispatcher = workDispatcher ) internal var selectedPosition: Int? = null @JvmSynthetic internal fun getFpxBankStatues() = liveData<FpxBankStatuses>(workDispatcher) { emitSource( runCatching { stripeRepository.getFpxBankStatus(ApiRequest.Options(publishableKey)) }.getOrDefault(MutableLiveData(FpxBankStatuses())) ) } override fun onCleared() { super.onCleared() workDispatcher.cancelChildren() } }
1
null
1
1
bf481f8ee359a4d6f872dfa757ce6ef5809f3cad
1,395
stripe-android
MIT License
stripe/src/main/java/com/stripe/android/view/FpxViewModel.kt
Yog8482
274,082,025
false
{"Gradle": 5, "Markdown": 7, "YAML": 2, "INI": 3, "Shell": 4, "Text": 2, "Ignore List": 1, "Batchfile": 3, "Java Properties": 1, "XML": 152, "Kotlin": 460, "Java": 5, "JSON": 1, "Proguard": 1, "EditorConfig": 1, "HTML": 2123, "CSS": 2, "JavaScript": 1, "Ruby": 1}
package com.stripe.android.view import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.MutableLiveData import androidx.lifecycle.liveData import com.stripe.android.ApiRequest import com.stripe.android.PaymentConfiguration import com.stripe.android.StripeApiRepository import com.stripe.android.model.FpxBankStatuses import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.cancelChildren internal class FpxViewModel @JvmOverloads internal constructor( application: Application, private val workDispatcher: CoroutineDispatcher = Dispatchers.IO ) : AndroidViewModel(application) { private val publishableKey = PaymentConfiguration.getInstance(application).publishableKey private val stripeRepository = StripeApiRepository( application, publishableKey, workDispatcher = workDispatcher ) internal var selectedPosition: Int? = null @JvmSynthetic internal fun getFpxBankStatues() = liveData<FpxBankStatuses>(workDispatcher) { emitSource( runCatching { stripeRepository.getFpxBankStatus(ApiRequest.Options(publishableKey)) }.getOrDefault(MutableLiveData(FpxBankStatuses())) ) } override fun onCleared() { super.onCleared() workDispatcher.cancelChildren() } }
1
null
1
1
bf481f8ee359a4d6f872dfa757ce6ef5809f3cad
1,395
stripe-android
MIT License
service/src/main/kotlin/app/cash/backfila/ui/components/BackfillsTable.kt
cashapp
209,384,085
false
null
package app.cash.backfila.ui.components import app.cash.backfila.dashboard.UiBackfillRun import kotlinx.html.TagConsumer import kotlinx.html.div import kotlinx.html.h1 import kotlinx.html.table import kotlinx.html.tbody import kotlinx.html.td import kotlinx.html.th import kotlinx.html.thead import kotlinx.html.tr fun TagConsumer<*>.BackfillsTable(running: Boolean, backfills: List<UiBackfillRun>) { val title = if (running) "Running" else "Paused" div("px-4 sm:px-6 lg:px-8 py-5") { div("sm:flex sm:items-center") { div("sm:flex-auto") { h1("text-base font-semibold leading-6 text-gray-900") { +"""Backfills ($title)""" } // TODO delete // p("mt-2 text-sm text-gray-700") { +"""A list of all the users in your account including their name, title, email and role.""" } } } div("mt-8 flow-root") { div("-mx-4 -my-2 overflow-x-auto sm:-mx-6 lg:-mx-8") { div("inline-block min-w-full py-2 align-middle sm:px-6 lg:px-8") { table("min-w-full divide-y divide-gray-300") { thead { tr { listOf("ID", "Name", "State", "Dry Run", "Progress", "Created by", "Created at", "Last active at").map { th( classes = "py-3.5 pl-4 pr-3 text-left text-sm font-semibold text-gray-900 sm:pl-0", ) { +it } } } } tbody("divide-y divide-gray-200") { backfills.forEach { tr { listOf(it.id, it.name, it.state, it.dry_run).map { td( "whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-0", ) { +"""$it""" } } td( "whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-0", ) { ProgressBar(it.backfilled_matching_record_count, it.computed_matching_record_count) } listOf(it.created_by_user, it.created_at, it.last_active_at).map { td( "whitespace-nowrap py-4 pl-4 pr-3 text-sm font-medium text-gray-900 sm:pl-0", ) { +"""$it""" } } // TODO delete // td( // "relative whitespace-nowrap py-4 pl-3 pr-4 text-right text-sm font-medium sm:pr-0" // ) { // a(classes = "text-indigo-600 hover:text-indigo-900") { // href = "#" // +"""Edit""" // span("sr-only") { +""", Lindsay Walton""" } // } // } } } } } } } } } }
50
null
47
31
0c2d9dfb934a58c2cc1f572ac5046a70981e2e7b
2,841
backfila
Apache License 2.0
app/src/main/java/com/kickstarter/mock/factories/ProjectEnvironmentalCommitmentFactory.kt
kickstarter
76,278,501
false
null
package com.kickstarter.mock.factories import com.kickstarter.models.EnvironmentalCommitment import type.EnvironmentalCommitmentCategory class ProjectEnvironmentalCommitmentFactory private constructor() { companion object { fun getEnvironmentalCommitments(): List<EnvironmentalCommitment> { return listOf( getLongLastingDesignCategory(), getSustainableMaterialsCategory() ) } private fun getLongLastingDesignCategory() = EnvironmentalCommitment.builder() .id(1L) .description( "No, there is no extra VAT or taxes for backers.\r\n\r\nWe will export the " + "tables to local countries first and forward to respective shipping addresses through local couriers. We will clear the customs for all the desks. \r\n\r\nVAT and taxes are already included in the reward price and no extra payment will be required from backers." ) .category(EnvironmentalCommitmentCategory.LONG_LASTING_DESIGN.name) .build() private fun getSustainableMaterialsCategory() = EnvironmentalCommitment.builder() .id(3L) .description( "No, there is no extra VAT or taxes for backers.\r\n\r\nWe will export the " + "tables to local countries first and forward to respective shipping addresses through local couriers. We will clear the customs for all the desks. \r\n\r\nVAT and taxes are already included in the reward price and no extra payment will be required from backers." ) .category(EnvironmentalCommitmentCategory.SUSTAINABLE_MATERIALS.name) .build() } }
8
null
989
5,752
a9187fb484c4d12137c7919a2a53339d67cab0cb
1,721
android-oss
Apache License 2.0
dsl/camel-kotlin-api/src/generated/kotlin/org/apache/camel/kotlin/components/SnmpUriDsl.kt
obbyK
348,438,030
true
null
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.kotlin.components import kotlin.Boolean import kotlin.Int import kotlin.String import kotlin.Unit import org.apache.camel.kotlin.CamelDslMarker import org.apache.camel.kotlin.UriDsl public fun UriDsl.snmp(i: SnmpUriDsl.() -> Unit) { SnmpUriDsl(this).apply(i) } @CamelDslMarker public class SnmpUriDsl( it: UriDsl, ) { private val it: UriDsl init { this.it = it this.it.component("snmp") } private var host: String = "" private var port: String = "" public fun host(host: String) { this.host = host it.url("$host:$port") } public fun port(port: String) { this.port = port it.url("$host:$port") } public fun port(port: Int) { this.port = port.toString() it.url("$host:$port") } public fun oids(oids: String) { it.property("oids", oids) } public fun protocol(protocol: String) { it.property("protocol", protocol) } public fun retries(retries: String) { it.property("retries", retries) } public fun retries(retries: Int) { it.property("retries", retries.toString()) } public fun snmpCommunity(snmpCommunity: String) { it.property("snmpCommunity", snmpCommunity) } public fun snmpContextEngineId(snmpContextEngineId: String) { it.property("snmpContextEngineId", snmpContextEngineId) } public fun snmpContextName(snmpContextName: String) { it.property("snmpContextName", snmpContextName) } public fun snmpVersion(snmpVersion: String) { it.property("snmpVersion", snmpVersion) } public fun snmpVersion(snmpVersion: Int) { it.property("snmpVersion", snmpVersion.toString()) } public fun timeout(timeout: String) { it.property("timeout", timeout) } public fun timeout(timeout: Int) { it.property("timeout", timeout.toString()) } public fun type(type: String) { it.property("type", type) } public fun delay(delay: String) { it.property("delay", delay) } public fun sendEmptyMessageWhenIdle(sendEmptyMessageWhenIdle: String) { it.property("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle) } public fun sendEmptyMessageWhenIdle(sendEmptyMessageWhenIdle: Boolean) { it.property("sendEmptyMessageWhenIdle", sendEmptyMessageWhenIdle.toString()) } public fun treeList(treeList: String) { it.property("treeList", treeList) } public fun treeList(treeList: Boolean) { it.property("treeList", treeList.toString()) } public fun bridgeErrorHandler(bridgeErrorHandler: String) { it.property("bridgeErrorHandler", bridgeErrorHandler) } public fun bridgeErrorHandler(bridgeErrorHandler: Boolean) { it.property("bridgeErrorHandler", bridgeErrorHandler.toString()) } public fun exceptionHandler(exceptionHandler: String) { it.property("exceptionHandler", exceptionHandler) } public fun exchangePattern(exchangePattern: String) { it.property("exchangePattern", exchangePattern) } public fun pollStrategy(pollStrategy: String) { it.property("pollStrategy", pollStrategy) } public fun lazyStartProducer(lazyStartProducer: String) { it.property("lazyStartProducer", lazyStartProducer) } public fun lazyStartProducer(lazyStartProducer: Boolean) { it.property("lazyStartProducer", lazyStartProducer.toString()) } public fun backoffErrorThreshold(backoffErrorThreshold: String) { it.property("backoffErrorThreshold", backoffErrorThreshold) } public fun backoffErrorThreshold(backoffErrorThreshold: Int) { it.property("backoffErrorThreshold", backoffErrorThreshold.toString()) } public fun backoffIdleThreshold(backoffIdleThreshold: String) { it.property("backoffIdleThreshold", backoffIdleThreshold) } public fun backoffIdleThreshold(backoffIdleThreshold: Int) { it.property("backoffIdleThreshold", backoffIdleThreshold.toString()) } public fun backoffMultiplier(backoffMultiplier: String) { it.property("backoffMultiplier", backoffMultiplier) } public fun backoffMultiplier(backoffMultiplier: Int) { it.property("backoffMultiplier", backoffMultiplier.toString()) } public fun greedy(greedy: String) { it.property("greedy", greedy) } public fun greedy(greedy: Boolean) { it.property("greedy", greedy.toString()) } public fun initialDelay(initialDelay: String) { it.property("initialDelay", initialDelay) } public fun initialDelay(initialDelay: Int) { it.property("initialDelay", initialDelay.toString()) } public fun repeatCount(repeatCount: String) { it.property("repeatCount", repeatCount) } public fun repeatCount(repeatCount: Int) { it.property("repeatCount", repeatCount.toString()) } public fun runLoggingLevel(runLoggingLevel: String) { it.property("runLoggingLevel", runLoggingLevel) } public fun scheduledExecutorService(scheduledExecutorService: String) { it.property("scheduledExecutorService", scheduledExecutorService) } public fun scheduler(scheduler: String) { it.property("scheduler", scheduler) } public fun schedulerProperties(schedulerProperties: String) { it.property("schedulerProperties", schedulerProperties) } public fun startScheduler(startScheduler: String) { it.property("startScheduler", startScheduler) } public fun startScheduler(startScheduler: Boolean) { it.property("startScheduler", startScheduler.toString()) } public fun timeUnit(timeUnit: String) { it.property("timeUnit", timeUnit) } public fun useFixedDelay(useFixedDelay: String) { it.property("useFixedDelay", useFixedDelay) } public fun useFixedDelay(useFixedDelay: Boolean) { it.property("useFixedDelay", useFixedDelay.toString()) } public fun authenticationPassphrase(authenticationPassphrase: String) { it.property("authenticationPassphrase", authenticationPassphrase) } public fun authenticationProtocol(authenticationProtocol: String) { it.property("authenticationProtocol", authenticationProtocol) } public fun privacyPassphrase(privacyPassphrase: String) { it.property("privacyPassphrase", privacyPassphrase) } public fun privacyProtocol(privacyProtocol: String) { it.property("privacyProtocol", privacyProtocol) } public fun securityLevel(securityLevel: String) { it.property("securityLevel", securityLevel) } public fun securityLevel(securityLevel: Int) { it.property("securityLevel", securityLevel.toString()) } public fun securityName(securityName: String) { it.property("securityName", securityName) } }
0
Java
0
0
36f6936623eb745b884fd2d9093a4653f70ec880
7,341
camel
Apache License 2.0
app/src/main/kotlin/com/werb/g_trending/extensions/KeyBoardExtension.kt
werbhelius
102,488,412
false
null
package com.werb.g_trending.extensions import android.content.Context import android.view.inputmethod.InputMethodManager import android.widget.EditText /** * Created by wanbo on 2017/2/4. */ fun EditText.showKeyboard() { requestFocus() val inputManager = context.getSystemService( Context.INPUT_METHOD_SERVICE) as InputMethodManager inputManager.showSoftInput(this, 0) } fun EditText.hideKeyboard() { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(windowToken, 0) }
1
null
8
46
f0fb0ea825c8fb96603565e0bfc673ccaf714639
574
G-Trending
Apache License 2.0
picshare/src/main/java/ch/liip/picshare/helpers/IoHelper.kt
liip
166,997,768
false
null
package ch.liip.picshare.helpers import android.content.Context import android.net.Uri import androidx.core.content.FileProvider import androidx.core.net.toFile import java.io.File private const val SHARED_FOLDER = "picshareprovider" private const val SHARED_IMAGE_NAME = "share.png" /** * This returns a Uri of the form content://fileprovider.accessible.path * It points to the same file as the localUri passed but can be used for sharing outside the app * local FileOutputStreams are not able to write using content:// uri, so localImageUri should be used instead */ internal fun sharableUri(context: Context, localUri: Uri) = FileProvider.getUriForFile(context, "${context.packageName}.ch.liip.picshare.provider", localUri.toFile()) /** * This returns a Uri of the form file://path.to.localfile * It points to the same file as the sharableImageUri function but can be used inside this app to write to the file * Others app won't be able to read file:// uri, so for sharing, sharableImageUri should be used instead */ internal fun localImageUri(context: Context): Uri = Uri.fromFile(sharedImageFile(context)) private fun sharedImageFile(context: Context): File = File("${context.cacheDir}/$SHARED_FOLDER", SHARED_IMAGE_NAME) internal fun createEmptyCacheFile(context: Context) { val file = sharedImageFile(context) if(!file.exists()) { file.parentFile.mkdirs() file.createNewFile() } } internal fun destroyCacheFile(context: Context) { val file = sharedImageFile(context) if(file.exists()) { file.delete() } }
1
Kotlin
1
2
a3927fe3043c886249a8190ce29792dab53d5910
1,577
PicShare
MIT License
list2/hangman/app/src/main/java/com/example/hangman/MainActivity.kt
luk9400
172,599,840
false
{"Text": 1, "Ignore List": 24, "Markdown": 1, "Gradle": 39, "Java Properties": 27, "Shell": 15, "Batchfile": 15, "Proguard": 13, "Kotlin": 71, "XML": 150, "JSON": 7, "JavaScript": 5, "Git Attributes": 1, "INI": 2, "Starlark": 3, "Java": 2, "OpenStep Property List": 4, "Objective-C": 4}
package com.example.hangman import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast import kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { var game: Game? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) game = Game(resources.getStringArray(R.array.words)) // game needs !! or 'as Game' :( textView.text = game!!.censorWord((game as Game).word) } fun click(view: View) { if (inputText.text.toString() != "") { val char = inputText.text.first() val game = game!! if (game.word.contains(char, true)) { game.checker(game.word, char, 0) textView.text = game.censorWord(game.word) if (textView.text.toString() == game.word && game.lives > 0) { Toast.makeText(this, "You won!", Toast.LENGTH_LONG).show() } } else { if (game.lives > 0) { game.lives-- val stage = 13 - game.lives val id = resources.getIdentifier("hangman$stage", "drawable", applicationContext.packageName) imageView.setImageResource(id) if (game.lives == 0) { Toast.makeText(this, "You lost!", Toast.LENGTH_LONG).show() } } } inputText.setText("") } } }
10
null
1
1
bda76056a94bbfe1e5dc9512a115cb00fbebfea2
1,624
mobilki
MIT License
library/src/main/java/com/adevinta/android/barista/assertion/BaristaAssistiveTextAssertions.kt
IanArb
189,291,312
false
{"Gradle": 5, "Markdown": 6, "Java Properties": 1, "Shell": 2, "Ignore List": 4, "Batchfile": 1, "Gradle Kotlin DSL": 3, "XML": 62, "Kotlin": 92, "Java": 107, "INI": 2, "CODEOWNERS": 1, "YAML": 3, "SVG": 1}
package com.adevinta.android.barista.assertion import android.view.View import androidx.annotation.IdRes import androidx.annotation.StringRes import androidx.test.espresso.matcher.ViewMatchers import androidx.test.platform.app.InstrumentationRegistry import com.adevinta.android.barista.internal.assertAny import com.google.android.material.textfield.TextInputLayout import org.hamcrest.Description import org.hamcrest.Matcher import org.hamcrest.TypeSafeMatcher object BaristaAssistiveTextAssertions { @JvmStatic fun assertAssistiveText(@IdRes viewId: Int, @StringRes text: Int) { val resourceString = InstrumentationRegistry.getInstrumentation().targetContext.resources.getString(text) assertAssistiveText(viewId, resourceString) } @JvmStatic fun assertAssistiveText(@IdRes viewId: Int, text: String) { ViewMatchers.withId(viewId).assertAny(matchAssistiveText(text)) } private fun matchAssistiveText(expectedAssistiveText: String): Matcher<View> { return object : TypeSafeMatcher<View>() { override fun describeTo(description: Description) { description.appendText("with helper text: ").appendText(expectedAssistiveText) } override fun matchesSafely(item: View): Boolean { return when (item) { is TextInputLayout -> expectedAssistiveText == item.helperText.toString() else -> { throw UnsupportedOperationException("View of class ${item.javaClass.simpleName} not supported") } } } } } }
1
null
1
1
1c660cd7b37f605fbe865080d3739d72cc794677
1,520
Barista
Apache License 2.0
app/src/main/java/com/obaied/mailme/util/DummyDataFactory.kt
afjoseph
108,640,784
false
{"Gradle": 4, "YAML": 1, "Java Properties": 3, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "JSON": 1, "Proguard": 2, "Kotlin": 58, "XML": 27, "Java": 2}
package com.joseph.mailme.util import java.util.* /** * Created by ab on 08/04/2017. */ object DummyDataFactory { fun randomUuid(): String { return UUID.randomUUID().toString() } }
1
null
1
1
08af470a09ba2f9912adc2f0e4d69a375452fe8b
202
recorded
MIT License
app/src/main/java/com/yinhao/wanandroid/network/BaseRepository.kt
sdwfhjq123
276,372,979
false
{"Kotlin": 226215, "Java": 54873}
package com.yinhao.wanandroid.network import com.yinhao.wanandroid.model.WanResponse import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.coroutineScope import java.io.IOException import com.yinhao.wanandroid.model.Result /** * Created by luyao * on 2019/4/10 9:41 */ open class BaseRepository { suspend fun <T : Any> apiCall(call: suspend () -> WanResponse<T>): WanResponse<T> { return call.invoke() } suspend fun <T : Any> safeApiCall( call: suspend () -> Result<T> ): Result<T> { return try { call() } catch (e: Exception) { // An exception was thrown when calling the API so we're converting this to an IOException Result.Error(IOException(e.message, e)) } } suspend fun <T : Any> executeResponse( response: WanResponse<T>, successBlock: (suspend CoroutineScope.() -> Unit)? = null, errorBlock: (suspend CoroutineScope.() -> Unit)? = null ): Result<T> { return coroutineScope { if (response.errorCode == -1) { errorBlock?.let { it() } Result.Error(IOException(response.errorMsg)) } else { successBlock?.let { it() } Result.Success(response.data) } } } }
0
Kotlin
0
0
a16806ea0fef94416bd899f776f04596bf317148
1,321
wanandroid
Apache License 2.0
app/src/main/java/com/yinhao/wanandroid/network/BaseRepository.kt
sdwfhjq123
276,372,979
false
{"Kotlin": 226215, "Java": 54873}
package com.yinhao.wanandroid.network import com.yinhao.wanandroid.model.WanResponse import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.coroutineScope import java.io.IOException import com.yinhao.wanandroid.model.Result /** * Created by luyao * on 2019/4/10 9:41 */ open class BaseRepository { suspend fun <T : Any> apiCall(call: suspend () -> WanResponse<T>): WanResponse<T> { return call.invoke() } suspend fun <T : Any> safeApiCall( call: suspend () -> Result<T> ): Result<T> { return try { call() } catch (e: Exception) { // An exception was thrown when calling the API so we're converting this to an IOException Result.Error(IOException(e.message, e)) } } suspend fun <T : Any> executeResponse( response: WanResponse<T>, successBlock: (suspend CoroutineScope.() -> Unit)? = null, errorBlock: (suspend CoroutineScope.() -> Unit)? = null ): Result<T> { return coroutineScope { if (response.errorCode == -1) { errorBlock?.let { it() } Result.Error(IOException(response.errorMsg)) } else { successBlock?.let { it() } Result.Success(response.data) } } } }
0
Kotlin
0
0
a16806ea0fef94416bd899f776f04596bf317148
1,321
wanandroid
Apache License 2.0
jps-plugin/testData/incremental/pureKotlin/delegatedPropertyInlineExtensionAccessor/inlineGet.kt
kenny9221
43,519,360
true
{"Java": 15647080, "Kotlin": 10589205, "JavaScript": 176060, "Protocol Buffer": 41947, "HTML": 25327, "Lex": 17278, "ANTLR": 9689, "CSS": 9358, "Groovy": 5199, "Shell": 4638, "Batchfile": 3703, "IDL": 3251}
package inline inline fun Inline.get(receiver: Any?, prop: PropertyMetadata): Int { return 0 }
0
Java
0
0
4ee1b4da84ae0ac62322442cd0954171582802e8
99
kotlin
Apache License 2.0
src/test/kotlin/org/mechdancer/algebra/vector/TestOrthogonalize.kt
MechDancer
128,765,281
false
null
package org.mechdancer.algebra.vector import org.junit.Test import org.mechdancer.algebra.doubleEquals import org.mechdancer.algebra.function.vector.dot import org.mechdancer.algebra.function.vector.isNormalized import org.mechdancer.algebra.function.vector.orthogonalize import org.mechdancer.algebra.implement.vector.vector3D class TestOrthogonalize { @Test fun testOrthogonalize() { val orthogonalized = listOf(vector3D(1, 0, 0), vector3D(1, 2, 3), vector3D(5, 6, 7) ).orthogonalize() orthogonalized.forEachIndexed { i, v -> assert(v.isNormalized()) for (j in 0 until i) assert(doubleEquals(.0, v dot orthogonalized[j])) } } }
1
Kotlin
1
6
2cbc7e60b3cd32f46a599878387857f738abda46
754
linearalgebra
Do What The F*ck You Want To Public License
plugins/gradle/src/org/jetbrains/plugins/gradle/issue/DeprecatedGradleVersionIssue.kt
ingokegel
72,937,917
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.issue import com.intellij.build.issue.BuildIssue import com.intellij.build.issue.BuildIssueQuickFix import com.intellij.openapi.application.impl.ApplicationInfoImpl import com.intellij.openapi.externalSystem.issue.quickfix.ReimportQuickFix import com.intellij.openapi.project.Project import com.intellij.pom.Navigatable import org.gradle.util.GradleVersion import org.jetbrains.annotations.ApiStatus import org.jetbrains.plugins.gradle.issue.quickfix.GradleVersionQuickFix import org.jetbrains.plugins.gradle.issue.quickfix.GradleWrapperSettingsOpenQuickFix import org.jetbrains.plugins.gradle.jvmcompat.GradleJvmSupportMatrix import org.jetbrains.plugins.gradle.util.GradleConstants import org.jetbrains.plugins.gradle.util.GradleUtil @ApiStatus.Internal class DeprecatedGradleVersionIssue(gradleVersion: GradleVersion, projectPath: String) : BuildIssue { override val title: String = "Gradle ${gradleVersion.version} support can be dropped in the next release" override val description: String override val quickFixes = mutableListOf<BuildIssueQuickFix>() override fun getNavigatable(project: Project): Navigatable? = null init { val oldestRecommendedGradleVersion = GradleJvmSupportMatrix.getOldestRecommendedGradleVersionByIdea() require(gradleVersion < oldestRecommendedGradleVersion) val issueDescription = StringBuilder() val ideVersionName = ApplicationInfoImpl.getShadowInstance().versionName issueDescription.append(""" The project uses Gradle ${gradleVersion.version}. The support for Gradle older that ${oldestRecommendedGradleVersion.version} will likely be dropped by $ideVersionName in the next release. Gradle ${oldestRecommendedGradleVersion.version} release notes can be found at https://docs.gradle.org/${oldestRecommendedGradleVersion.version}/release-notes.html """.trimIndent()) issueDescription.append("\n\nPossible solution:\n") val wrapperPropertiesFile = GradleUtil.findDefaultWrapperPropertiesFile(projectPath) if (wrapperPropertiesFile == null) { val gradleVersionFix = GradleVersionQuickFix(projectPath, oldestRecommendedGradleVersion, true) issueDescription.append( " - <a href=\"${gradleVersionFix.id}\">Upgrade Gradle wrapper to ${oldestRecommendedGradleVersion.version} version " + "and re-import the project</a>\n") quickFixes.add(gradleVersionFix) } else { val wrapperSettingsOpenQuickFix = GradleWrapperSettingsOpenQuickFix(projectPath, "distributionUrl") val reimportQuickFix = ReimportQuickFix(projectPath, GradleConstants.SYSTEM_ID) issueDescription.append(" - <a href=\"${wrapperSettingsOpenQuickFix.id}\">Open Gradle wrapper settings</a>, " + "change `distributionUrl` property to use Gradle ${oldestRecommendedGradleVersion.version} or newer and <a href=\"${reimportQuickFix.id}\">reload the project</a>\n") quickFixes.add(wrapperSettingsOpenQuickFix) quickFixes.add(reimportQuickFix) } description = issueDescription.toString() } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
3,243
intellij-community
Apache License 2.0
mobile_app1/module831/src/main/java/module831packageKt0/Foo172.kt
uber-common
294,831,672
false
null
package module831packageKt0; annotation class Foo172Fancy @Foo172Fancy class Foo172 { fun foo0(){ module831packageKt0.Foo171().foo3() } fun foo1(){ foo0() } fun foo2(){ foo1() } fun foo3(){ foo2() } }
6
Java
6
72
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
237
android-build-eval
Apache License 2.0
app/src/main/kotlin/io/github/nuhkoca/vivy/ui/di/MainModule.kt
nuhkoca
258,777,733
false
null
/* * Copyright (C) 2020. <NAME>. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.nuhkoca.vivy.ui.di import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModel import dagger.Binds import dagger.Module import dagger.Provides import dagger.multibindings.IntoMap import io.github.nuhkoca.vivy.data.model.view.DoctorViewItem import io.github.nuhkoca.vivy.di.factory.FragmentKey import io.github.nuhkoca.vivy.di.factory.ViewModelKey import io.github.nuhkoca.vivy.ui.detail.DoctorDetailFragment import io.github.nuhkoca.vivy.ui.doctors.DoctorsFragment import io.github.nuhkoca.vivy.ui.doctors.DoctorsViewModel import io.github.nuhkoca.vivy.ui.doctors.adapter.DoctorsAdapter import io.github.nuhkoca.vivy.ui.doctors.adapter.DoctorsLoadStateAdapter import io.github.nuhkoca.vivy.util.recyclerview.MenuItem import io.github.nuhkoca.vivy.ui.doctors.adapter.RecentDoctorsAdapter import io.github.nuhkoca.vivy.util.event.SingleLiveEvent import javax.inject.Scope @Module internal abstract class MainModule { @Binds @IntoMap @MainScope @FragmentKey(DoctorsFragment::class) internal abstract fun bindDoctorsFragment(doctorsFragment: DoctorsFragment): Fragment @Binds @IntoMap @MainScope @FragmentKey(DoctorDetailFragment::class) internal abstract fun bindDoctorDetailFragment(doctorDetailFragment: DoctorDetailFragment): Fragment @Binds @IntoMap @MainScope @ViewModelKey(DoctorsViewModel::class) internal abstract fun bindDoctorsViewModel(viewModel: DoctorsViewModel): ViewModel @Module internal companion object { @Provides @MainScope internal fun provideDoctorsAdapter( itemClickLiveData: SingleLiveEvent<DoctorViewItem>, menuClickLiveData: SingleLiveEvent<MenuItem> ) = DoctorsAdapter(itemClickLiveData, menuClickLiveData) @Provides @MainScope internal fun provideRecentDoctorsAdapter( itemClickLiveData: SingleLiveEvent<DoctorViewItem>, menuClickLiveData: SingleLiveEvent<MenuItem> ) = RecentDoctorsAdapter(itemClickLiveData, menuClickLiveData) @Provides @MainScope internal fun provideDoctorsLoadStateAdapter( retryClickListener: SingleLiveEvent<Unit> ) = DoctorsLoadStateAdapter(retryClickListener) @Provides @MainScope internal fun provideItemClickLiveData() = SingleLiveEvent<DoctorViewItem>() @Provides @MainScope internal fun provideRetryClickListener() = SingleLiveEvent<Unit>() @Provides @MainScope internal fun provideMenuClickListener() = SingleLiveEvent<MenuItem>() } } @Scope @MustBeDocumented internal annotation class MainScope
1
null
3
18
512412bef33ffdd0ab0ac2bb358a88ebb0a09c44
3,313
vivy-challenge
Apache License 2.0
src/main/kotlin/no/fdk/dataset/preview/controller/CsrfController.kt
Informasjonsforvaltning
426,257,371
false
null
package no.fdk.dataset.preview.controller import org.springframework.security.web.csrf.CsrfToken import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RestController @RestController class CsrfController { @GetMapping("/preview/csrf") fun csrf(csrfToken: CsrfToken): CsrfToken { return csrfToken } }
6
Kotlin
0
0
95f1c4409698e4e93e5f6f975900a2e869382774
374
fdk-dataset-preview-service
Apache License 2.0
Client(Android)/app/src/main/java/com/example/integratedqueuesystem/data/reservation/ReservationRecordRepository.kt
mr6915tri8513
505,257,512
false
{"Kotlin": 112869, "C#": 86410}
package com.example.integratedqueuesystem.data.reservation import androidx.lifecycle.LiveData class ReservationRecordRepository(private val reservationRecordDao: ReservationRecordDao) { val allRecords: LiveData<List<ReservationRecord>> = reservationRecordDao.readAllRecord() suspend fun addRecord(record: ReservationRecord): Long { return reservationRecordDao.addRecord(record) } suspend fun updateState(id: Long, state: Int) { reservationRecordDao.updateState(id, state) } suspend fun updateState(id: Long, state: Int, pushKey: String, num: String) { reservationRecordDao.updateState(id, state, pushKey, num) } }
0
Kotlin
0
1
e8350808ce123c785d337f4b969ee2fba1e87efb
671
Integrated-Queue-System
MIT License
src/main/java/dev/andante/companion/command/SettingsCommand.kt
andantet
544,100,698
false
null
package dev.andante.companion.command import com.mojang.brigadier.CommandDispatcher import com.mojang.brigadier.context.CommandContext import com.mojang.brigadier.exceptions.CommandSyntaxException import com.mojang.brigadier.exceptions.DynamicCommandExceptionType import dev.andante.companion.Companion import dev.andante.companion.api.setting.SettingsContainer import net.fabricmc.fabric.api.client.command.v2.ClientCommandManager.literal import net.fabricmc.fabric.api.client.command.v2.FabricClientCommandSource import net.minecraft.text.Text import net.minecraft.util.Formatting object SettingsCommand { private val RELOADED_SETTINGS_TEXT = Text.translatable("command.${Companion.MOD_ID}.settings.reloaded_all_settings") private val SETTINGS_RELOAD_FAILURE_EXCEPTION = DynamicCommandExceptionType { id -> Text.translatable("command.${Companion.MOD_ID}.settings.settings_reload_failure", id) } fun register(dispatcher: CommandDispatcher<FabricClientCommandSource>) { dispatcher.register( literal("${Companion.MOD_ID}:settings") .then( literal("reload") .executes(::executeReload) ) ) } @Throws(CommandSyntaxException::class) private fun executeReload(context: CommandContext<FabricClientCommandSource>): Int { SettingsContainer.ALL_CONTAINERS.forEach { container -> try { container.load() } catch (throwable: Throwable) { throwable.printStackTrace() throw SETTINGS_RELOAD_FAILURE_EXCEPTION.create(container.id) } } context.source.sendFeedback(RELOADED_SETTINGS_TEXT.formatted(Formatting.LIGHT_PURPLE)) return 1 } }
4
Kotlin
3
14
683110a531ab3126b585af94fc377dbe3526c587
1,771
companion
MIT License
wrapper/godot-library/src/main/kotlin/godot/generated/ImageTexture.kt
payload
189,718,948
true
{"Kotlin": 3888394, "C": 6051, "Batchfile": 714, "Shell": 574}
@file:Suppress("unused", "ClassName", "EnumEntryName", "FunctionName", "SpellCheckingInspection", "PARAMETER_NAME_CHANGED_ON_OVERRIDE", "UnusedImport", "PackageDirectoryMismatch") package godot import godot.gdnative.* import godot.core.* import godot.utils.* import godot.icalls.* import kotlinx.cinterop.* // NOTE: THIS FILE IS AUTO GENERATED FROM JSON API CONFIG open class ImageTexture : Texture { constructor() : super("ImageTexture") constructor(variant: Variant) : super(variant) internal constructor(mem: COpaquePointer) : super(mem) internal constructor(name: String) : super(name) // Enums enum class Storage(val id: Long) { STORAGE_RAW(0), STORAGE_COMPRESS_LOSSY(1), STORAGE_COMPRESS_LOSSLESS(2), ; companion object { fun fromInt(value: Long) = values().single { it.id == value } } } // Signals class Signal { companion object { } } companion object { infix fun from(other: Texture): ImageTexture = ImageTexture("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Resource): ImageTexture = ImageTexture("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Reference): ImageTexture = ImageTexture("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Object): ImageTexture = ImageTexture("").apply { setRawMemory(other.rawMemory) } infix fun from(other: Variant): ImageTexture = fromVariant(ImageTexture(""), other) // Constants const val STORAGE_RAW: Long = 0 const val STORAGE_COMPRESS_LOSSY: Long = 1 const val STORAGE_COMPRESS_LOSSLESS: Long = 2 } // Properties open var storage: Long get() = _icall_Long(getStorageMethodBind, this.rawMemory) set(value) = _icall_Unit_Long(setStorageMethodBind, this.rawMemory, value) open var lossyQuality: Double get() = _icall_Double(getLossyStorageQualityMethodBind, this.rawMemory) set(value) = _icall_Unit_Double(setLossyStorageQualityMethodBind, this.rawMemory, value) // Methods private val createMethodBind: CPointer<godot_method_bind> by lazy { getMB("ImageTexture", "create") } open fun create(width: Long, height: Long, format: Long, flags: Long = 7) { _icall_Unit_Long_Long_Long_Long(createMethodBind, this.rawMemory, width, height, format, flags) } private val createFromImageMethodBind: CPointer<godot_method_bind> by lazy { getMB("ImageTexture", "create_from_image") } open fun createFromImage(image: Image, flags: Long = 7) { _icall_Unit_Object_Long(createFromImageMethodBind, this.rawMemory, image, flags) } private val getFormatMethodBind: CPointer<godot_method_bind> by lazy { getMB("ImageTexture", "get_format") } open fun getFormat(): Image.Format { return Image.Format.fromInt(_icall_Long(getFormatMethodBind, this.rawMemory)) } private val loadMethodBind: CPointer<godot_method_bind> by lazy { getMB("ImageTexture", "load") } open fun load(path: String): GodotError { return GodotError.fromInt(_icall_Long_String(loadMethodBind, this.rawMemory, path)) } private val setDataMethodBind: CPointer<godot_method_bind> by lazy { getMB("ImageTexture", "set_data") } open fun setData(image: Image) { _icall_Unit_Object(setDataMethodBind, this.rawMemory, image) } private val setStorageMethodBind: CPointer<godot_method_bind> by lazy { getMB("ImageTexture", "set_storage") } open fun setStorage(mode: Long) { _icall_Unit_Long(setStorageMethodBind, this.rawMemory, mode) } private val getStorageMethodBind: CPointer<godot_method_bind> by lazy { getMB("ImageTexture", "get_storage") } open fun getStorage(): ImageTexture.Storage { return ImageTexture.Storage.fromInt(_icall_Long(getStorageMethodBind, this.rawMemory)) } private val setLossyStorageQualityMethodBind: CPointer<godot_method_bind> by lazy { getMB("ImageTexture", "set_lossy_storage_quality") } open fun setLossyStorageQuality(quality: Double) { _icall_Unit_Double(setLossyStorageQualityMethodBind, this.rawMemory, quality) } private val getLossyStorageQualityMethodBind: CPointer<godot_method_bind> by lazy { getMB("ImageTexture", "get_lossy_storage_quality") } open fun getLossyStorageQuality(): Double { return _icall_Double(getLossyStorageQualityMethodBind, this.rawMemory) } private val setSizeOverrideMethodBind: CPointer<godot_method_bind> by lazy { getMB("ImageTexture", "set_size_override") } open fun setSizeOverride(size: Vector2) { _icall_Unit_Vector2(setSizeOverrideMethodBind, this.rawMemory, size) } open fun _reload_hook(rid: RID) { } }
0
Kotlin
1
2
70473f9b9a0de08d82222b735e7f9b07bbe91700
4,813
kotlin-godot-wrapper
Apache License 2.0
app/src/main/java/hiendao/moviefinder/di/AppModule.kt
HienDao14
826,173,311
false
{"Kotlin": 438834}
package hiendao.moviefinder.di import android.app.Application import android.content.Context import android.content.SharedPreferences import androidx.room.Room import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import hiendao.moviefinder.data.local.dao.CreditDAO import hiendao.moviefinder.data.local.database.CreditDatabase import hiendao.moviefinder.data.local.dao.MovieDAO import hiendao.moviefinder.data.local.database.MovieDatabase import hiendao.moviefinder.data.local.dao.TvSeriesDAO import hiendao.moviefinder.data.local.database.TvSeriesDatabase import hiendao.moviefinder.data.network.movie.MovieApi import hiendao.moviefinder.data.network.search.SearchApi import hiendao.moviefinder.data.network.tvseries.TvSeriesApi import hiendao.moviefinder.data.network.util.base_url.BaseUrl.BASE_API_URL import hiendao.moviefinder.data.network.util.interceptor.MyInterceptor import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class AppModule { @Provides fun provideMyInterceptor(): MyInterceptor{ return MyInterceptor() } @Provides fun provideOkHttpClient(myInterceptor: MyInterceptor): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(myInterceptor) .followRedirects(true) .followSslRedirects(true) .retryOnConnectionFailure(true) .build() } @Provides fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit { return Retrofit.Builder() .baseUrl(BASE_API_URL) .client(okHttpClient) .addConverterFactory(MoshiConverterFactory.create()) .build() } @Provides fun provideMovieApi(retrofit: Retrofit): MovieApi { return retrofit.create(MovieApi::class.java) } @Provides fun provideTvSeriesApi(retrofit: Retrofit): TvSeriesApi{ return retrofit.create(TvSeriesApi::class.java) } @Provides fun provideSearchApi(retrofit: Retrofit): SearchApi{ return retrofit.create(SearchApi::class.java) } @Provides @Singleton fun provideMovieDatabase(app: Application): MovieDatabase { return Room.databaseBuilder( app, MovieDatabase::class.java, "moviedb.db" ) .fallbackToDestructiveMigration() .build() } @Provides @Singleton fun provideCreditDatabase(app: Application): CreditDatabase { return Room.databaseBuilder( app, CreditDatabase::class.java, "creditdb.db" ) .fallbackToDestructiveMigration() .build() } @Provides @Singleton fun provideTvSeriesDatabase(app: Application): TvSeriesDatabase { return Room.databaseBuilder( app, TvSeriesDatabase::class.java, "tvseriesdb.db" ) .fallbackToDestructiveMigration() .build() } @Provides @Singleton fun provideMovieDAO( movieDatabase: MovieDatabase ): MovieDAO { return movieDatabase.dao } @Provides @Singleton fun provideCreditDAO( creditDatabase: CreditDatabase ): CreditDAO { return creditDatabase.creditDao } @Provides @Singleton fun provideTvSeriesDAO( tvSeriesDatabase: TvSeriesDatabase ): TvSeriesDAO { return tvSeriesDatabase.dao } @Provides @Singleton fun provideSharedPref(app: Application): SharedPreferences{ return app.getSharedPreferences("prefs", Context.MODE_PRIVATE) } }
0
Kotlin
0
0
7f3f66b7a169ece9b34c7488455654c08353ee2d
3,784
Movie-Discover
MIT License
core/src/commonMain/kotlin/com/ramitsuri/notificationjournal/core/network/DataSendHelperImpl.kt
ramitsuri
667,037,607
false
{"Kotlin": 341758, "Shell": 8383, "Python": 3405, "HTML": 1499, "JavaScript": 1016}
package com.ramitsuri.notificationjournal.core.network import com.rabbitmq.client.Channel import com.rabbitmq.client.Connection import com.rabbitmq.client.ConnectionFactory import com.rabbitmq.client.MessageProperties import com.ramitsuri.notificationjournal.core.model.Tag import com.ramitsuri.notificationjournal.core.model.entry.JournalEntry import com.ramitsuri.notificationjournal.core.model.sync.Payload import com.ramitsuri.notificationjournal.core.model.sync.Sender import com.ramitsuri.notificationjournal.core.model.template.JournalEntryTemplate import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.coroutines.withContext import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import kotlin.time.Duration.Companion.seconds internal class DataSendHelperImpl( private val ioDispatcher: CoroutineDispatcher, private val hostName: String, private val exchangeName: String, private val deviceName: String, private val deviceId: String, private val username: String, private val password: String, private val json: Json, ) : DataSendHelper { private var connection: Connection? = null private var channel: Channel? = null private val mutex: Mutex = Mutex() override suspend fun sendEntry(entries: List<JournalEntry>): Boolean { return Payload.Entries( data = entries, sender = getSender() ).send() } override suspend fun sendTags(tags: List<Tag>): Boolean { return Payload.Tags( data = tags, sender = getSender() ).send() } override suspend fun sendTemplates(templates: List<JournalEntryTemplate>): Boolean { return Payload.Templates( data = templates, sender = getSender() ).send() } private suspend fun Payload.send(): Boolean { return withContext(ioDispatcher) { mutex.withLock { createChannelIfNecessary() try { val message = json.encodeToString(this@send).toByteArray() channel?.let { it.basicPublish( exchangeName, "", MessageProperties.PERSISTENT_TEXT_PLAIN, message ) it.waitForConfirmsOrDie(5.seconds.inWholeMilliseconds) true } ?: run { false } } catch (e: Exception) { log("failed to send message: $e") false } } } } override suspend fun closeConnection() { mutex.withLock { closeConnectionInternal() } } private fun closeConnectionInternal() { runCatching { connection?.close() connection = null channel?.close() channel = null } } private fun getSender() = Sender(name = deviceName, id = deviceId) private fun createChannelIfNecessary() { try { if (connection == null) { connection = ConnectionFactory().apply { host = hostName username = [email protected] password = [email protected] isAutomaticRecoveryEnabled = true isTopologyRecoveryEnabled = true }.newConnection() channel = connection?.createChannel() channel?.confirmSelect() } } catch (e: Exception) { log("Failed to connect to RabbitMQ: $e") closeConnectionInternal() } } private fun log(message: String) { println("$TAG: $message") } companion object { private const val TAG = "DataSendHelper" } }
0
Kotlin
0
0
e3a37568eba34fad4a8001925faa638b45216532
4,072
notification-journal
MIT License
app/src/main/java/com/example/gengo/ui/LessonScreen.kt
murban11
729,578,478
false
{"Kotlin": 70414}
package com.example.gengo.ui import android.util.Log import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview const val TAG = "LessonScreen" data class QuizItem( val question: String, val answers: Array<String>, val indexOfCorrect: Int, ) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as QuizItem if (question != other.question) return false return true } override fun hashCode(): Int { return question.hashCode() } } @Composable fun LessonScreen( fetchFields: (callback: (List<Pair<String, String>>) -> Unit) -> Unit, modifier: Modifier = Modifier, onReturnClick: () -> Unit = {}, ) { val quizItems = remember { mutableStateListOf<QuizItem>() } var current by remember { mutableIntStateOf(0) } var pointsEarned by remember { mutableIntStateOf(0) } if (quizItems.isEmpty()) { fetchFields { fields -> Log.i(TAG, "Received ${fields.size} lesson fields") assert(fields.size >= 4) val indexes = IntArray(fields.size) { it } val items: MutableList<QuizItem> = mutableListOf() fields.forEachIndexed { index, field -> indexes.shuffle() val selected = IntArray(4) { indexes[it] } if (!selected.contains(index)) { selected[(0..3).random()] = index } val correct = selected.indexOfFirst { it == index } val item = QuizItem(field.first, Array(4) { fields[selected[it]].second }, correct) if (!items.contains(item)) { items.add(item) } } items.forEach { Log.i( TAG, """ Question: ${it.question} Answers: ${it.answers.joinToString(", ")} Correct: ${it.answers[it.indexOfCorrect]} """.trimIndent(), ) if (!quizItems.contains(it)) { quizItems.add(it) } } Log.i(TAG, "Created ${quizItems.size} quiz cards") } } if (quizItems.isNotEmpty() && current < quizItems.size) { LinearProgressIndicator( progress = current.toFloat() / quizItems.size, modifier = modifier.fillMaxWidth(), color = MaterialTheme.colorScheme.secondary, trackColor = MaterialTheme.colorScheme.onBackground, ) CardView( quizItem = quizItems[current], modifier = modifier, ) { wasAnsweredCorrectly -> current += 1 pointsEarned += if (wasAnsweredCorrectly) 1 else 0 } } else if (quizItems.isNotEmpty()) { SummaryView( pointsEarned = pointsEarned, pointsTotal = quizItems.size, onReturnClick = onReturnClick, ) } } @Preview(showBackground = true) @Composable fun LessonScreenPreview() { LessonScreen( fetchFields = { callback -> callback( listOf( Pair("a", "あ"), Pair("i", "い"), Pair("u", "う"), Pair("e", "え"), Pair("o", "お"), ) ) } ) }
0
Kotlin
1
0
28658edefe434ce5dbd972a6329e034b4dae16cc
3,965
gengo
MIT License
baseKit/src/main/java/me/shetj/base/tools/app/SoftInputUtil.kt
SheTieJun
137,007,462
false
{"Kotlin": 841510, "Java": 165162}
package me.shetj.base.tools.app import android.graphics.Rect import android.view.Window class SoftInputUtil { private var softInputHeightChanged = false private var listener: ISoftInputChanged? = null private var isSoftInputShowing = false private var rootViewVisibleHeight = 0 private val rect = Rect() interface ISoftInputChanged { fun onChanged(isSoftInputShow: Boolean) } fun attachSoftInput(rootView: Window?, listener: ISoftInputChanged?) { if (listener == null || rootView == null) return this.listener = listener rootView.decorView.viewTreeObserver.addOnGlobalLayoutListener { var inputShow = false rootView.decorView.getWindowVisibleDisplayFrame(rect) val visibleHeight: Int = rect.height() if (rootViewVisibleHeight == 0) { rootViewVisibleHeight = visibleHeight return@addOnGlobalLayoutListener } // 根视图显示高度没有变化,可以看做软键盘显示/隐藏状态没有变化 if (rootViewVisibleHeight == visibleHeight) { return@addOnGlobalLayoutListener } if (rootViewVisibleHeight - visibleHeight > 200) { inputShow = true } // 根视图显示高度变大超过了200,可以看做软键盘隐藏了 if (visibleHeight - rootViewVisibleHeight > 200) { inputShow = false } rootViewVisibleHeight = visibleHeight if (isSoftInputShowing != inputShow || inputShow && softInputHeightChanged) { listener.onChanged(inputShow) isSoftInputShowing = inputShow } } } fun dismiss() { isSoftInputShowing = false } }
1
Kotlin
1
7
b6935cc5983d32b51dc7c4850dd1e8f63a38a75b
1,726
BaseKit
MIT License
composeApp/src/commonMain/kotlin/screens/disclosure/DisclosureScreen.kt
thaapasa
702,418,399
false
{"Kotlin": 476702, "Swift": 661, "Shell": 262}
package fi.tuska.beerclock.screens.disclosure import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Button import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import cafe.adriel.voyager.core.screen.Screen import cafe.adriel.voyager.navigator.LocalNavigator import cafe.adriel.voyager.navigator.Navigator import cafe.adriel.voyager.navigator.currentOrThrow import fi.tuska.beerclock.images.AppImage import fi.tuska.beerclock.localization.Strings import fi.tuska.beerclock.screens.today.HomeScreen import fi.tuska.beerclock.settings.GlobalUserPreferences import fi.tuska.beerclock.settings.UserStore import fi.tuska.beerclock.ui.composables.ViewModel import fi.tuska.beerclock.ui.composables.rememberWithDispose import fi.tuska.beerclock.ui.layout.SubLayout import kotlinx.coroutines.launch import org.koin.core.component.KoinComponent import org.koin.core.component.get object DisclosureScreen : Screen { @Composable override fun Content() { SubLayout( content = { innerPadding -> DisclosurePage(innerPadding) }, title = "", showTopBar = false, ) } } @Composable fun DisclosurePage(innerPadding: PaddingValues) { val strings = Strings.get() val scrollState = rememberScrollState() val navigator = LocalNavigator.currentOrThrow val vm = rememberWithDispose { DisclosureViewModel(navigator) } Column( Modifier.padding(innerPadding).fillMaxWidth() .verticalScroll(scrollState) ) { Image( painter = AppImage.BEERCLOCK_FEATURE.painter(), modifier = Modifier.fillMaxWidth(), contentScale = ContentScale.FillWidth, contentDescription = "Feature" ) Column(modifier = Modifier.fillMaxWidth().padding(16.dp)) { Text( text = strings.appName, style = MaterialTheme.typography.headlineLarge, modifier = Modifier.align(Alignment.CenterHorizontally).padding(bottom = 8.dp) ) HorizontalDivider( modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp), color = MaterialTheme.colorScheme.primary ) strings.disclosureTexts.map { Text( text = it, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(vertical = 4.dp) ) } } Row( modifier = Modifier.fillMaxWidth().padding(bottom = 32.dp), horizontalArrangement = Arrangement.Center, ) { Button(onClick = vm::agreeToDisclosure) { Text( strings.dismissDisclosure, style = MaterialTheme.typography.titleSmall, ) } } } } class DisclosureViewModel(private val navigator: Navigator) : ViewModel(), KoinComponent { val prefs: GlobalUserPreferences = get() private val store = UserStore() fun agreeToDisclosure() { launch { store.setHasAgreedDisclosure(true) navigator.replaceAll(HomeScreen()) } } }
1
Kotlin
0
2
2fd90678ed1f66ba8f23adec85cb74f90fa2165e
3,906
beerclock
Apache License 2.0
kotlin-quarkus/src/main/kotlin/br/com/cvc/evaluation/broker/BrokerService.kt
zekiefa
363,503,512
false
null
package br.com.cvc.evaluation.broker import br.com.cvc.evaluation.broker.dto.BrokerHotel import org.eclipse.microprofile.rest.client.inject.RegisterRestClient import javax.enterprise.context.ApplicationScoped import javax.ws.rs.GET import javax.ws.rs.Path import javax.ws.rs.PathParam @Path("/hotels") @ApplicationScoped @RegisterRestClient interface BrokerService { @GET @Path("/avail/{codeCity}") fun findHotelsByCity(@PathParam("codeCity") codeCity: Int): Set<BrokerHotel> @GET @Path("/{codeHotel}") fun getHotelDetails(@PathParam("codeHotel") codeHotel: Int): BrokerHotel }
0
Kotlin
0
0
04d51cc1c45df79a0927451395dc30eccc6fda00
604
kotlin
Apache License 2.0
app/src/main/java/com/jkhetle/themovies/ui/viewmodel/MovieDetailsViewModel.kt
jitendraAndroid
715,130,297
false
{"Kotlin": 52815, "C": 49706, "C++": 49656, "CMake": 26926}
package com.jkhetle.themovies.ui.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.jkhetle.themovies.data.entity.MovieDetailsResponse import com.jkhetle.themovies.ui.repository.MovieDetailsRepository import com.jkhetle.utilities.ResourceState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MovieDetailsViewModel @Inject constructor( private val movieDetailsRepository: MovieDetailsRepository, ) : ViewModel() { private val _movieDetails: MutableStateFlow<ResourceState<MovieDetailsResponse>> = MutableStateFlow(ResourceState.Loading()) val movieDetails: StateFlow<ResourceState<MovieDetailsResponse>> = _movieDetails fun getMovieDetails(movieId: String, language: String) { viewModelScope.launch(Dispatchers.IO) { movieDetailsRepository.getMovieDetails(movieId, language) .collectLatest { movieDetailsResponse -> _movieDetails.value = movieDetailsResponse } } } companion object { const val TAG = "MovieDetailsViewModel" } }
0
Kotlin
0
0
252d686c3d202bd82a30302b22fad704adf5b1a3
1,362
TheMovies
Creative Commons Zero v1.0 Universal
library/radix-kotlin/src/jsMain/kotlin/radix_ui/components/Dialog.kt
dead8309
657,395,822
false
null
// Automatically generated - do not modify! @file:JsModule("@radix-ui/react-dialog") @file:JsNonModule @file:Suppress( "VIRTUAL_MEMBER_HIDDEN", ) package radix_ui.components import react.StateSetter import web.dom.Element import web.events.Event external interface DialogProps: react.PropsWithChildren, react.PropsWithClassName { override var children: react.ReactNode? var open: Boolean? var defaultOpen: Boolean? var onOpenChange: StateSetter<Boolean> var modal: Boolean? } external interface DialogTriggerProps: react.dom.html.ButtonHTMLAttributes<web.html.HTMLButtonElement>, react.PropsWithClassName { var asChild: Boolean } external interface DialogPortalProps: PortalProps, react.PropsWithChildren, react.PropsWithClassName { override var children: react.ReactNode? /** * Used to force mounting when more control is needed. Useful when * controlling animation with React animation libraries. */ var forceMount: Boolean? /* true */ } external interface DialogOverlayProps: DialogOverlayImplProps, react.PropsWithClassName { /** * Used to force mounting when more control is needed. Useful when * controlling animation with React animation libraries. */ var forceMount: Boolean? /* true */ } external interface DialogOverlayImplProps: react.dom.html.HTMLAttributes<web.html.HTMLDivElement>, react.PropsWithClassName { } external interface DialogContentProps: DialogContentTypeProps, react.PropsWithClassName { /** * Used to force mounting when more control is needed. Useful when * controlling animation with React animation libraries. */ var forceMount: Boolean? /* true */ } external interface DialogContentTypeProps: DialogContentImplProps, react.PropsWithClassName { } external interface DialogContentImplProps: DismissableLayerProps, react.PropsWithClassName { /** * When `true`, focus cannot escape the `Content` via keyboard, * pointer, or a programmatic focus. * @defaultValue false */ var trapFocus: dynamic /* FocusScopeProps['trapped'] */ /** * Event handler called when auto-focusing on open. * Can be prevented. */ var onOpenAutoFocus: dynamic /* FocusScopeProps['onMountAutoFocus'] */ /** * Event handler called when auto-focusing on close. * Can be prevented. */ var onCloseAutoFocus: dynamic /* FocusScopeProps['onUnmountAutoFocus'] */ } external interface DialogTitleProps: react.dom.html.HTMLAttributes<web.html.HTMLHeadingElement>, react.PropsWithClassName { } external interface DialogDescriptionProps: react.dom.html.HTMLAttributes<web.html.HTMLParagraphElement>, react.PropsWithClassName { } external interface DialogCloseProps: react.dom.html.ButtonHTMLAttributes<web.html.HTMLButtonElement>, react.PropsWithClassName { var asChild: Boolean } @JsName("Dialog") internal external val Dialog: react.FC<DialogProps> @JsName("DialogTrigger") internal external val DialogTrigger: react.FC<DialogTriggerProps> @JsName("DialogPortal") internal external val DialogPortal: react.FC<DialogPortalProps> @JsName("DialogOverlay") internal external val DialogOverlay: react.FC<DialogOverlayProps> @JsName("DialogContent") internal external val DialogContent: react.FC<DialogContentProps> @JsName("DialogTitle") internal external val DialogTitle: react.FC<DialogTitleProps> @JsName("DialogDescription") internal external val DialogDescription: react.FC<DialogDescriptionProps> @JsName("DialogClose") internal external val DialogClose: react.FC<DialogCloseProps>
0
Kotlin
0
4
8413055f558c4fccaee9f39fe372d21ff6d466c8
3,447
shadcn-kotlin
MIT License
cfg4k-core/src/main/kotlin/com/jdiazcano/cfg4k/parsers/CommonParsers.kt
jdiazcano
75,337,058
false
null
package com.jdiazcano.cfg4k.parsers import com.jdiazcano.cfg4k.binders.convert import com.jdiazcano.cfg4k.binders.createCollection import com.jdiazcano.cfg4k.core.ConfigContext import com.jdiazcano.cfg4k.core.ConfigObject import com.jdiazcano.cfg4k.core.toConfig import com.jdiazcano.cfg4k.utils.TypeStructure import java.net.InetAddress import java.sql.Connection import java.sql.Driver import java.sql.DriverManager import java.util.UUID import java.util.regex.Pattern object PatternParser : Parser<Pattern> { override fun parse(context: ConfigContext, value: ConfigObject, typeStructure: TypeStructure) = Pattern.compile(value.asString()) } object RegexParser : Parser<Regex> { override fun parse(context: ConfigContext, value: ConfigObject, typeStructure: TypeStructure) = value.asString().toRegex() } object UUIDParser : Parser<UUID> { override fun parse(context: ConfigContext, value: ConfigObject, typeStructure: TypeStructure) = UUID.fromString(value.asString()) } object SQLDriverParser : Parser<Driver> { override fun parse(context: ConfigContext, value: ConfigObject, typeStructure: TypeStructure) = DriverManager.getDriver(value.asString()) } object SQLConnectionParser : Parser<Connection> { override fun parse(context: ConfigContext, value: ConfigObject, typeStructure: TypeStructure) = DriverManager.getConnection(value.asString()) } object InetAddressParser : Parser<InetAddress> { override fun parse(context: ConfigContext, value: ConfigObject, typeStructure: TypeStructure) = InetAddress.getByName(value.asString()) } object ListParser : Parser<MutableCollection<*>> { override fun parse(context: ConfigContext, value: ConfigObject, typeStructure: TypeStructure): MutableCollection<*> { val collection = createCollection(typeStructure.raw) value.asList().forEachIndexed { index, innerObject -> collection.add(convert(context.copy(propertyName = "${context.propertyName}[$index]"), innerObject, typeStructure.generics[0])) } return collection } } object MapParser { fun parse(configContext: ConfigContext, value: ConfigObject, typeStructure: TypeStructure): Map<*, *> { return value.asObject().map { convert(configContext, it.key.toConfig(), typeStructure.generics[0]) to convert(configContext.copy(propertyName = "${configContext.propertyName}.${it.key}"), it.value, typeStructure.generics[1]) }.toMap() } }
10
Kotlin
7
80
d2fa6a616a4860445d7268a7f932e41ad0c45993
2,467
cfg4k
Apache License 2.0
mw-kreator-regul-biznesowych/app-modul-silnik-regul/src/test/kotlin/reguly/TesterNormalizatoraSekwencji.kt
mwwojcik
176,818,289
false
{"Java": 10915639, "HTML": 8198722, "Kotlin": 167279, "TSQL": 126258, "TeX": 55580, "SQLPL": 51424, "Shell": 40173, "XSLT": 22453, "CSS": 16916, "C": 12865, "Lex": 12595, "ANTLR": 7931, "Groovy": 6748, "PLpgSQL": 6727, "Python": 6682, "Perl": 3473, "PHP": 2581, "Batchfile": 2578, "JavaScript": 827}
package reguly import org.junit.Assert.assertTrue import org.junit.Test import org.junit.runner.RunWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.context.junit4.SpringRunner import reguly.nlp.NormalizatorSekwencjiNLP import javax.annotation.PostConstruct @SpringBootTest(classes = arrayOf(NormalizatorSekwencjiNLP::class)) @RunWith(SpringRunner::class) open class TesterNormalizatoraSekwencjiTest { @PostConstruct fun init() { println("") } @Autowired lateinit var normalizator: NormalizatorSekwencjiNLP @Test fun uruchomTest() { val postac = normalizator.zwrocPostacZnormalizowana("Jeśli data jest większa od '01-01-2019' to wyświetl komunikat \"data jest większa\" w przeciwnym wypadku wyświetl komunikat \"data wcale nie jest większa tylko mniejsza\"") assertTrue ( postac.komunikaty != null && postac.komunikaty!!.keys.size == 2 ) println(postac.postacKanoniczna) val regulaBezDopasowan = "Jeśli rok jest większy niż 2000 to sprawdź regułę RS-200" val postacBezDopasowan = normalizator.zwrocPostacZnormalizowana(regulaBezDopasowan) assertTrue ( postacBezDopasowan.komunikaty != null && postacBezDopasowan.komunikaty!!.keys.size == 0 ) } }
1
null
1
1
c2b0e8bceb12fbe04bf4db6ca662b90431e9096a
1,354
ml_workspace_kotlin
MIT License
composeApp/src/commonMain/kotlin/presentation/settings/locale/LocaleStrings.kt
vrcm-team
746,586,818
false
{"Kotlin": 556756, "Swift": 567}
package io.github.vrcmteam.vrcm.presentation.settings.locale import androidx.compose.runtime.Composable import androidx.compose.runtime.Stable import io.github.vrcmteam.vrcm.presentation.settings.LocalSettingsState @Stable data class LocaleStrings( val startupDialogTitle: String = "New version available", val startupDialogUpdate: String = "Update", val startupDialogIgnore: String = "Ignore", val startupDialogRememberVersion: String = "Ignore This Version Update", val authLoginTitle: String = "Login", val authLoginButton: String = "LOGIN", val authLoginUsername: String = "Username", val authLoginPassword: String = "Password", val authVerifyTitle: String = "Verify", val authVerifyButton: String = "VERIFY", val fiendLocationPagerWebsite: String = "Active on the Website", val fiendLocationPagerPrivate: String = "Friends in Private Worlds", val fiendLocationPagerTraveling: String = "Friends is Traveling", val fiendLocationPagerLocation: String = "by Location", val fiendListPagerSearch: String = "Search", val notificationFriendRequest: String = "wants to be your friend", val homeNotificationEmpty: String = "No Notification Yet", val stettingLanguage: String = "Language", val stettingThemeMode: String = "ThemeMode", val stettingSystemThemeMode: String = "System", val stettingLightThemeMode: String = "Light", val stettingDarkThemeMode: String = "Dark", val stettingThemeColor: String = "ThemeColor", val stettingLogout: String = "Logout", val stettingAbout: String = "About Application", val stettingVersion: String = "Version", val stettingAlreadyLatest: String = "Already Latest", val profileFriendRequestSent: String = "Friend Request Sent", val profileSendFriendRequest: String = "Send Friend Request", val profileFriendRequestDeleted: String = "Friend Request Deleted", val profileDeleteFriendRequest: String = "Delete Friend Request", val profileAcceptFriendRequest: String = "Accept Friend Request", val profileFriendRequestAccepted: String = "Friend Request Accepted", val profileUnfriended: String = "Friend is Unfriended", val profileUnfriend: String = "Unfriend", val profileViewJsonData: String = "Viewing JSON data", ) val strings: LocaleStrings @Composable get() { return when (LocalSettingsState.current.value.languageTag) { LanguageTag.EN -> LocaleStringsEn LanguageTag.JA -> LocaleStringsJa LanguageTag.ZH_HANS -> LocaleStringsZhHans LanguageTag.ZH_HANT -> LocaleStringsZhHant else -> LocaleStringsEn } }
0
Kotlin
3
23
cf723aee7c5653df01f8c1aa3e45f88cff3a45b6
2,672
VRCM
MIT License
src/main/kotlin/no/nav/hjelpemidler/joark/service/AsyncPacketListener.kt
navikt
334,088,348
false
{"Kotlin": 145416, "Dockerfile": 144}
package no.nav.hjelpemidler.joark.service import com.github.navikt.tbd_libs.rapids_and_rivers.JsonMessage import com.github.navikt.tbd_libs.rapids_and_rivers.River import com.github.navikt.tbd_libs.rapids_and_rivers_api.MessageContext import com.github.navikt.tbd_libs.rapids_and_rivers_api.MessageProblems import io.github.oshai.kotlinlogging.KotlinLogging import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.runBlocking private val log = KotlinLogging.logger {} private val secureLog = KotlinLogging.logger("tjenestekall") interface AsyncPacketListener : River.PacketListener { suspend fun onPacketAsync(packet: JsonMessage, context: MessageContext) override fun onPacket(packet: JsonMessage, context: MessageContext) = runBlocking(Dispatchers.IO) { onPacketAsync(packet, context) } override fun onError(problems: MessageProblems, context: MessageContext) = secureLog.info { problems.toExtendedReport() } }
0
Kotlin
0
1
0af2d3ea8f72c476eca868b221f3b6d70a7fede3
994
hm-joark-sink
MIT License
api/src/main/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/api/RedisPoller.kt
navikt
495,713,363
false
{"Kotlin": 1169408, "PLpgSQL": 153, "Dockerfile": 68}
package no.nav.helsearbeidsgiver.inntektsmelding.api import kotlinx.coroutines.delay import kotlinx.serialization.json.JsonElement import no.nav.helsearbeidsgiver.felles.rapidsrivers.redis.RedisKey import no.nav.helsearbeidsgiver.felles.rapidsrivers.redis.RedisStore import no.nav.helsearbeidsgiver.utils.log.sikkerLogger import java.util.UUID private const val MAX_RETRIES = 10 private const val WAIT_MILLIS = 500L // TODO Bruke kotlin.Result istedenfor exceptions? class RedisPoller( private val redisStore: RedisStore, ) { private val sikkerLogger = sikkerLogger() suspend fun hent(key: UUID): JsonElement { repeat(MAX_RETRIES) { sikkerLogger.debug("Polling redis: $it time(s) for key $key") val result = redisStore.get(RedisKey.of(key)) if (result != null) { sikkerLogger.info("Hentet verdi for: '$key' = $result") return result } else { delay(WAIT_MILLIS) } } throw RedisPollerTimeoutException(key) } } class RedisPollerTimeoutException( uuid: UUID, ) : Exception("Brukte for lang tid på å svare ($uuid).")
11
Kotlin
0
2
cb84d8faa54406c614b2248ab8d852b16515de4c
1,172
helsearbeidsgiver-inntektsmelding
MIT License
src/test/kotlin/com/teambition/kafka/connect/mongo/utils/Mongod.kt
reactioncommerce
155,609,228
true
{"Kotlin": 104127, "Shell": 5102, "Dockerfile": 693, "JavaScript": 519, "Makefile": 71}
package com.teambition.kafka.connect.mongo.utils import com.mongodb.BasicDBList import com.mongodb.BasicDBObject import com.mongodb.MongoClient import com.mongodb.ServerAddress import com.mongodb.client.MongoDatabase import de.flapdoodle.embed.mongo.MongodExecutable import de.flapdoodle.embed.mongo.MongodProcess import de.flapdoodle.embed.mongo.MongodStarter import de.flapdoodle.embed.mongo.config.IMongodConfig import de.flapdoodle.embed.mongo.config.MongodConfigBuilder import de.flapdoodle.embed.mongo.config.Net import de.flapdoodle.embed.mongo.config.Storage import de.flapdoodle.embed.mongo.distribution.Version import de.flapdoodle.embed.process.runtime.Network import org.apache.commons.io.FileUtils import java.io.File /** * @author <NAME> */ class Mongod { companion object { val collections = arrayOf("test1", "test2", "test3") } private val replicaPath = "tmp" private var mongodExecutable: MongodExecutable? = null private var mongodProcess: MongodProcess? = null private var mongodStarter: MongodStarter? = null private var mongodConfig: IMongodConfig? = null private var mongoClient: MongoClient? = null fun start(): Mongod { mongodStarter = MongodStarter.getDefaultInstance() mongodConfig = MongodConfigBuilder() .version(Version.Main.V3_3) .replication(Storage(replicaPath, "rs0", 1024)) .net(Net(12345, Network.localhostIsIPv6())) .build() mongodExecutable = mongodStarter!!.prepare(mongodConfig) mongodProcess = mongodExecutable!!.start() mongoClient = MongoClient(ServerAddress("localhost", 12345)) // Initialize rs0 val adminDatabase = mongoClient!!.getDatabase("admin") val replicaSetSetting = BasicDBObject() val members = BasicDBList() val host = BasicDBObject() replicaSetSetting["_id"] = "rs0" host["_id"] = 0 host["host"] = "127.0.0.1:12345" members.add(host) replicaSetSetting["members"] = members adminDatabase.runCommand(BasicDBObject("isMaster", 1)) adminDatabase.runCommand(BasicDBObject("replSetInitiate", replicaSetSetting)) return this } fun stop(): Mongod { mongodProcess!!.stop() mongodExecutable!!.stop() FileUtils.deleteDirectory(File(replicaPath)) return this } fun getDatabase(db: String): MongoDatabase { return mongoClient!!.getDatabase(db) } }
0
Kotlin
1
3
082d879d27b3dad40c2462547c6f5a13c1ddb303
2,500
kafka-connect-mongo-fork
Apache License 2.0
goblin-transport-client/src/main/java/org/goblinframework/transport/client/channel/TransportClientImpl.kt
xiaohaiz
206,246,434
false
{"Java": 807217, "Kotlin": 650572, "FreeMarker": 27779, "JavaScript": 968}
package org.goblinframework.transport.client.channel import io.netty.bootstrap.Bootstrap import io.netty.channel.* import io.netty.channel.nio.NioEventLoopGroup import io.netty.channel.socket.SocketChannel import io.netty.channel.socket.nio.NioSocketChannel import io.netty.handler.logging.LogLevel import io.netty.handler.logging.LoggingHandler import org.apache.commons.collections4.map.LRUMap import org.goblinframework.core.system.GoblinSystem import org.goblinframework.core.util.RandomUtils import org.goblinframework.core.util.StringUtils import org.goblinframework.transport.client.handler.TransportResponseContext import org.goblinframework.transport.client.module.TransportClientModule import org.goblinframework.transport.codec.TransportMessage import org.goblinframework.transport.codec.TransportMessageDecoder import org.goblinframework.transport.codec.TransportMessageEncoder import org.goblinframework.transport.protocol.* import org.slf4j.LoggerFactory import java.net.InetSocketAddress import java.util.* import java.util.concurrent.atomic.AtomicReference class TransportClientImpl internal constructor(private val client: TransportClient) { companion object { private val logger = LoggerFactory.getLogger(TransportClientImpl::class.java) } internal val handshakeResponseReference = AtomicReference<HandshakeResponse?>() private val heartbeatInProgress = Collections.synchronizedMap(LRUMap<String, HeartbeatRequest>(32)) private val stateChannelReference = AtomicReference<TransportClientChannel>(TransportClientChannel.CONNECTING) private val channelReference = AtomicReference<Channel?>() private val worker: NioEventLoopGroup internal val connectFuture = TransportClientConnectFuture() internal val disconnectFuture = TransportClientDisconnectFuture(client.clientManager) init { val setting = client.setting val threads = client.setting.workerThreads() worker = NioEventLoopGroup(threads) val bootstrap = Bootstrap() bootstrap.group(worker) bootstrap.channel(NioSocketChannel::class.java) bootstrap.option(ChannelOption.SO_KEEPALIVE, setting.keepAlive()) bootstrap.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, setting.connectTimeoutInMillis()) val initializer = object : ChannelInitializer<SocketChannel>() { override fun initChannel(ch: SocketChannel) { val pipeline = ch.pipeline() if (setting.debugMode()) { pipeline.addLast(LoggingHandler(LogLevel.DEBUG)) } pipeline.addLast("encoder", TransportMessageEncoder.getInstance()) pipeline.addLast("decoder", TransportMessageDecoder.newInstance()) pipeline.addLast(TransportClientChannelHandler(this@TransportClientImpl)) } } bootstrap.handler(initializer) val remoteAddress = InetSocketAddress(setting.serverHost(), setting.serverPort()) bootstrap.connect(remoteAddress).addListener(object : ChannelFutureListener { override fun operationComplete(future: ChannelFuture) { if (!future.isSuccess) { updateStateChannel(TransportClientChannel.CONNECT_FAILED) val cause = TransportClientException("Exception opening connection", future.cause()) connectFuture.complete(client, cause) return } val channel = future.channel() channelReference.set(channel) updateStateChannel(TransportClientChannel(TransportClientState.CONNECTED, this@TransportClientImpl)) val request = HandshakeRequest() request.serverId = setting.serverId() request.clientId = GoblinSystem.applicationId() request.extensions = linkedMapOf() request.extensions["clientName"] = GoblinSystem.applicationName() request.extensions["clientLanguage"] = "java/kotlin" request.extensions["receiveShutdown"] = setting.receiveShutdown() val serializer = TransportProtocol.getSerializerId(request.javaClass) writeTransportMessage(TransportMessage(request, serializer)) } }) } @Synchronized fun updateStateChannel(sc: TransportClientChannel) { val previous = stateChannelReference.get().state if (previous === TransportClientState.SHUTDOWN) { return } stateChannelReference.set(sc) if (logger.isDebugEnabled) { logger.debug("{} state changed: {} -> {}", this, previous, sc.state) } client.onStateChange(sc.state) } fun available(): Boolean { return stateChannelReference.get().available() } fun stateChannel(): TransportClientChannel { return stateChannelReference.get() } fun sendHeartbeat() { if (!client.setting.sendHeartbeat()) { return } if (!available()) { return } val request = HeartbeatRequest() request.token = RandomUtils.nextObjectId() val serializer = TransportProtocol.getSerializerId(request::class.java) writeTransportMessage(TransportMessage(request, serializer)) heartbeatInProgress[request.token] = request if (heartbeatInProgress.size >= TransportClientModule.maxSufferanceHeartLost) { updateStateChannel(TransportClientChannel.HEARTBEAT_LOST) } } fun onTransportMessage(msg: TransportMessage) { if (msg.message == null) { // unrecognized message received, ignore and return directly return } when (val message = msg.message) { is HandshakeResponse -> { if (message.success) { handshakeResponseReference.set(message) updateStateChannel(TransportClientChannel(TransportClientState.HANDSHAKED, this)) } else { updateStateChannel(TransportClientChannel.HANDSHAKE_FAILED) } connectFuture.complete(client) return } is HeartbeatResponse -> { message.token?.run { heartbeatInProgress.remove(this) } return } is ShutdownRequest -> { val handler = client.setting.shutdownRequestHandler() val success = handler.handleShutdownRequest(message) if (success) { val name = client.setting.name() client.clientManager.closeConnection(name) } return } is TransportResponse -> { val handler = client.setting.handlerSetting().transportResponseHandler() val ctx = TransportResponseContext() ctx.response = message if (ctx.response.extensions == null) { ctx.response.extensions = linkedMapOf() } ctx.response.extensions["SERVER_ID"] = StringUtils.defaultString(client.setting.serverId()) ctx.response.extensions["SERVER_HOST"] = client.setting.serverHost() ctx.response.extensions["SERVER_PORT"] = client.setting.serverPort().toString() handler.handleTransportResponse(ctx) return } else -> logger.error("Unrecognized message received: $message") } } fun writeTransportMessage(msg: TransportMessage) { channelReference.get()?.writeAndFlush(msg) } internal fun close() { updateStateChannel(TransportClientChannel.SHUTDOWN) heartbeatInProgress.clear() worker.shutdownGracefully().addListener { if (!it.isSuccess) { val cause = TransportClientException("Exception closing connection", it.cause()) disconnectFuture.complete(client, cause) } else { disconnectFuture.complete(client) } } } }
0
Java
6
9
b1db234912ceb23bdd81ac66a3bf61933b717d0b
7,371
goblinframework
Apache License 2.0
app/src/main/java/ru/igla/duocamera/utils/CameraUtils.kt
iglaweb
414,899,591
false
{"Kotlin": 85927, "Java": 2752}
package ru.igla.duocamera.utils import android.annotation.SuppressLint import android.hardware.camera2.CameraCharacteristics import android.hardware.camera2.CameraManager import android.media.MediaRecorder import ru.igla.duocamera.dto.CameraInfo import ru.igla.duocamera.dto.CameraReqType object CameraUtils { /** Converts a lens orientation enum into a human-readable string */ private fun lensOrientationString(value: Int) = when (value) { CameraCharacteristics.LENS_FACING_BACK -> "Back" CameraCharacteristics.LENS_FACING_FRONT -> "Front" CameraCharacteristics.LENS_FACING_EXTERNAL -> "External" else -> "Unknown" } /** Lists all video-capable cameras and supported resolution and FPS combinations */ @SuppressLint("InlinedApi") fun enumerateVideoCameras(cameraManager: CameraManager): List<CameraInfo> { val availableCameras: MutableList<CameraInfo> = mutableListOf() // Iterate over the list of cameras and add those with high speed video recording // capability to our output. This function only returns those cameras that declare // constrained high speed video recording, but some cameras may be capable of doing // unconstrained video recording with high enough FPS for some use cases and they will // not necessarily declare constrained high speed video capability. cameraManager.cameraIdList.forEach { id -> val characteristics = cameraManager.getCameraCharacteristics(id) val orientation = lensOrientationString( characteristics.get(CameraCharacteristics.LENS_FACING)!! ) // Query the available capabilities and output formats val capabilities = characteristics.get( CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES )!! val cameraConfig = characteristics.get( CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP )!! // Return cameras that declare to be backward compatible if (capabilities.contains( CameraCharacteristics .REQUEST_AVAILABLE_CAPABILITIES_BACKWARD_COMPATIBLE ) ) { // Recording should always be done in the most efficient format, which is // the format native to the camera framework val targetClass = MediaRecorder::class.java // For each size, list the expected FPS cameraConfig.getOutputSizes(targetClass).forEach { size -> // Get the number of seconds that each frame will take to process val secondsPerFrame = cameraConfig.getOutputMinFrameDuration(targetClass, size) / 1_000_000_000.0 // Compute the frames per second to let user select a configuration val fps = if (secondsPerFrame > 0) (1.0 / secondsPerFrame).toInt() else 0 val fpsLabel = if (fps > 0) "$fps" else "N/A" availableCameras.add( CameraInfo( CameraReqType.GENERAL_CAMERA_SIZE, "$orientation ($id) $size $fpsLabel FPS", id, size, fps ) ) } } } return availableCameras } }
1
Kotlin
0
6
5743d5c22fdc96d2d2f0f0e2b00e17ee4c75147e
3,467
DuoCamera
Apache License 2.0
src/main/kotlin/ch/hellorin/challengames/service/provider/CannotChooseGameException.kt
Hellorin
187,896,910
false
null
package ch.hellorin.challengames.service.provider import java.lang.Exception class CannotChooseGameException(val gameData: List<Triple<Long, String, String>>) : Exception("Games found: ${gameData.joinToString { it.second }}")
2
Kotlin
0
0
3b8b7ea9e33c239ea7f089ef12d8e8d27f55ac0b
235
challengames
Apache License 2.0
j2k/old/tests/testData/fileOrElement/class/kt-639.kt
JetBrains
278,369,660
false
null
// ERROR: Not enough information to infer type variable K // ERROR: Not enough information to infer type variable K package demo import java.util.HashMap internal class Test { constructor() {} constructor(s: String) {} } internal class User { fun main() { val m = HashMap(1) val m2 = HashMap(10) val t1 = Test() val t2 = Test("") } }
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
386
intellij-kotlin
Apache License 2.0
lib/sisyphus-protobuf/src/main/kotlin/com/bybutter/sisyphus/protobuf/ProtoEnum.kt
sustly
290,148,776
true
{"Kotlin": 1090965, "ANTLR": 8164}
package com.bybutter.sisyphus.protobuf interface ProtoEnum { val proto: String val number: Int } interface ProtoEnumDsl<T : ProtoEnum> { operator fun invoke(value: String): T fun fromProto(value: String): T? operator fun invoke(value: Int): T fun fromNumber(value: Int): T? operator fun invoke(): T }
5
Kotlin
0
0
4d34d230a794a1edee9e53996f756a70a722bec5
335
sisyphus
MIT License
libraries/cache/src/test/java/com/aliumujib/artic/cache/impl/CacheTimeManagerTest.kt
aliumujib
210,103,091
false
{"Kotlin": 448725}
/* * Copyright 2020 <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.aliumujib.artic.cache.impl import android.app.Application import android.content.Context import androidx.test.core.app.ApplicationProvider.getApplicationContext import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.runBlocking import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class CacheTimeManagerTest { private lateinit var cacheTimeManager: CacheTimeManager private lateinit var context: Context @Before fun setup() { context = getApplicationContext<Application>() cacheTimeManager = CacheTimeManager(context) } @Test fun `saveLastCacheTime saves correctly`() = runBlocking { val lastCacheTime = System.currentTimeMillis() cacheTimeManager.saveLastCacheTime(lastCacheTime) assertThat(cacheTimeManager.getLastCacheTime()).isEqualTo(lastCacheTime) } }
0
Kotlin
6
47
ad986536632f532d0d24aa3847bdef33ab7a5d16
1,565
Artic
Apache License 2.0
app/src/main/kotlin/com/absinthe/libchecker/recyclerview/diff/LibStringDiffUtil.kt
zhaobozhen
248,400,799
false
null
package com.absinthe.libchecker.recyclerview.diff import androidx.recyclerview.widget.DiffUtil import com.absinthe.libchecker.bean.LibStringItemChip class LibStringDiffUtil : DiffUtil.ItemCallback<LibStringItemChip>() { override fun areItemsTheSame(oldItem: LibStringItemChip, newItem: LibStringItemChip): Boolean { return oldItem.item.name == newItem.item.name } override fun areContentsTheSame( oldItem: LibStringItemChip, newItem: LibStringItemChip ): Boolean { return oldItem.item == newItem.item && oldItem.chip == newItem.chip } }
38
null
83
987
bbfdf8353172281af5ae08694305c32e837cb497
567
LibChecker
Apache License 2.0
src/main/kotlin/com/forgerock/sapi/gateway/ob/uk/tests/functional/payment/file/payments/consents/api/v3_1_8/GetFilePaymentsConsents.kt
SecureApiGateway
330,627,234
false
{"Kotlin": 1238224, "Java": 2078, "Makefile": 940, "Dockerfile": 464}
package com.forgerock.sapi.gateway.ob.uk.tests.functional.payment.file.payments.api.v3_1_8 import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isNotEmpty import assertk.assertions.isNotNull import assertk.assertions.isNull import com.forgerock.sapi.gateway.framework.conditions.Status import com.forgerock.sapi.gateway.framework.extensions.junit.CreateTppCallback import com.forgerock.sapi.gateway.ob.uk.support.payment.PaymentFactory import com.forgerock.sapi.gateway.ob.uk.support.payment.PaymentFileType import com.forgerock.sapi.gateway.ob.uk.tests.functional.payment.file.payments.consents.api.v3_1_8.CreateFilePaymentsConsents import com.forgerock.sapi.gateway.uk.common.shared.api.meta.obie.OBVersion import org.assertj.core.api.Assertions class GetFilePaymentsConsents(val version: OBVersion, val tppResource: CreateTppCallback.TppResource) { private val createFilePaymentsConsentsApi = CreateFilePaymentsConsents(version, tppResource) fun shouldGetFilePaymentsConsents() { // Given val fileContent = PaymentFactory.getFileAsString(PaymentFactory.FilePaths.XML_FILE_PATH) val consentRequest = PaymentFactory.createOBWriteFileConsent3WithFileInfo( fileContent, PaymentFileType.UK_OBIE_PAIN_001_001_008.type ) // When val consentResponse = createFilePaymentsConsentsApi.createFilePaymentConsent(consentRequest) // Then assertThat(consentResponse).isNotNull() assertThat(consentResponse.data).isNotNull() assertThat(consentResponse.data.consentId).isNotEmpty() Assertions.assertThat(consentResponse.data.status.toString()).`is`(Status.consentCondition) } fun shouldGetFilePaymentsConsents_withoutOptionalDebtorAccountTest() { // Given val fileContent = PaymentFactory.getFileAsString(PaymentFactory.FilePaths.XML_FILE_PATH) val consentRequest = PaymentFactory.createOBWriteFileConsent3WithFileInfo( fileContent, PaymentFileType.UK_OBIE_PAIN_001_001_008.type ) consentRequest.data.initiation.debtorAccount(null) // when val consentResponse = createFilePaymentsConsentsApi.createFilePaymentConsent(consentRequest) // Then assertThat(consentResponse).isNotNull() assertThat(consentResponse.data).isNotNull() assertThat(consentResponse.data.consentId).isNotEmpty() Assertions.assertThat(consentResponse.data.status.toString()).`is`(Status.consentCondition) assertThat(consentResponse.data.initiation.debtorAccount).isNull() } }
8
Kotlin
0
5
a48d451a4cef8929c1b81e0b34c140e65d2d8c7e
2,630
secure-api-gateway-ob-uk-functional-tests
Apache License 2.0
src/main/kotlin/com/forgerock/sapi/gateway/ob/uk/tests/functional/payment/file/payments/consents/api/v3_1_8/GetFilePaymentsConsents.kt
SecureApiGateway
330,627,234
false
{"Kotlin": 1238224, "Java": 2078, "Makefile": 940, "Dockerfile": 464}
package com.forgerock.sapi.gateway.ob.uk.tests.functional.payment.file.payments.api.v3_1_8 import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isNotEmpty import assertk.assertions.isNotNull import assertk.assertions.isNull import com.forgerock.sapi.gateway.framework.conditions.Status import com.forgerock.sapi.gateway.framework.extensions.junit.CreateTppCallback import com.forgerock.sapi.gateway.ob.uk.support.payment.PaymentFactory import com.forgerock.sapi.gateway.ob.uk.support.payment.PaymentFileType import com.forgerock.sapi.gateway.ob.uk.tests.functional.payment.file.payments.consents.api.v3_1_8.CreateFilePaymentsConsents import com.forgerock.sapi.gateway.uk.common.shared.api.meta.obie.OBVersion import org.assertj.core.api.Assertions class GetFilePaymentsConsents(val version: OBVersion, val tppResource: CreateTppCallback.TppResource) { private val createFilePaymentsConsentsApi = CreateFilePaymentsConsents(version, tppResource) fun shouldGetFilePaymentsConsents() { // Given val fileContent = PaymentFactory.getFileAsString(PaymentFactory.FilePaths.XML_FILE_PATH) val consentRequest = PaymentFactory.createOBWriteFileConsent3WithFileInfo( fileContent, PaymentFileType.UK_OBIE_PAIN_001_001_008.type ) // When val consentResponse = createFilePaymentsConsentsApi.createFilePaymentConsent(consentRequest) // Then assertThat(consentResponse).isNotNull() assertThat(consentResponse.data).isNotNull() assertThat(consentResponse.data.consentId).isNotEmpty() Assertions.assertThat(consentResponse.data.status.toString()).`is`(Status.consentCondition) } fun shouldGetFilePaymentsConsents_withoutOptionalDebtorAccountTest() { // Given val fileContent = PaymentFactory.getFileAsString(PaymentFactory.FilePaths.XML_FILE_PATH) val consentRequest = PaymentFactory.createOBWriteFileConsent3WithFileInfo( fileContent, PaymentFileType.UK_OBIE_PAIN_001_001_008.type ) consentRequest.data.initiation.debtorAccount(null) // when val consentResponse = createFilePaymentsConsentsApi.createFilePaymentConsent(consentRequest) // Then assertThat(consentResponse).isNotNull() assertThat(consentResponse.data).isNotNull() assertThat(consentResponse.data.consentId).isNotEmpty() Assertions.assertThat(consentResponse.data.status.toString()).`is`(Status.consentCondition) assertThat(consentResponse.data.initiation.debtorAccount).isNull() } }
8
Kotlin
0
5
a48d451a4cef8929c1b81e0b34c140e65d2d8c7e
2,630
secure-api-gateway-ob-uk-functional-tests
Apache License 2.0
src/test/kotlin/io/github/nstdio/http/ext/MockWebServerTest.kt
nstdio
403,128,821
false
null
/* * Copyright (C) 2022 <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 io.github.nstdio.http.ext import mockwebserver3.junit5.internal.MockWebServerExtension import org.junit.jupiter.api.extension.ExtendWith @Target(AnnotationTarget.ANNOTATION_CLASS, AnnotationTarget.CLASS) @ExtendWith(MockWebServerExtension::class) annotation class MockWebServerTest
1
Kotlin
1
2
71eb5b76ffecad250cb23531f1393fe34232aa34
886
http-client-ext
Apache License 2.0
core/navigation/src/main/kotlin/nl/q42/template/navigation/viewmodel/RouteNavigator.kt
Q42
593,537,486
false
{"Kotlin": 55441, "Python": 2058}
package nl.q42.template.navigation.viewmodel import androidx.annotation.VisibleForTesting import com.ramcosta.composedestinations.spec.Direction import io.github.aakira.napier.Napier import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow /** * Navigator to use when initiating navigation from a ViewModel. */ interface RouteNavigator { fun onNavigated(state: NavigationState) fun navigateUp() fun popToRoute(staticRoute: String) fun navigateTo(routeDestination: Direction) fun navigateTo(route: String) val navigationState: StateFlow<NavigationState> } class MyRouteNavigator : RouteNavigator { /** * Note that I'm using a single state here, not a list of states. As a result, if you quickly * update the state multiple times, the view will only receive and handle the latest state, * which is fine for my use case. */ override val navigationState: MutableStateFlow<NavigationState> = MutableStateFlow(NavigationState.Idle) override fun onNavigated(state: NavigationState) { // clear navigation state, if state is the current state: navigationState.compareAndSet(state, NavigationState.Idle) } override fun popToRoute(staticRoute: String) = navigate(NavigationState.PopToRoute(staticRoute)) override fun navigateUp() = navigate(NavigationState.NavigateUp()) override fun navigateTo(routeDestination: Direction) = navigate(NavigationState.NavigateToRoute(routeDestination.route)) override fun navigateTo(route: String) = navigate(NavigationState.NavigateToRoute(route)) @VisibleForTesting fun navigate(state: NavigationState) { Napier.i { state.toString() } navigationState.value = state } }
7
Kotlin
0
7
b53f705012c8bc1bc957ccdd55f834657f1ef227
1,766
Template.Android
MIT License
app/src/main/java/com/maary/liveinpeace/service/ForegroundService.kt
Steve-Mr
639,919,933
false
{"Kotlin": 74136, "Python": 1571}
package com.maary.liveinpeace.service import android.annotation.SuppressLint import android.app.Notification import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.content.IntentFilter import android.media.AudioDeviceCallback import android.media.AudioDeviceInfo import android.media.AudioManager import android.os.Build import android.os.IBinder import android.util.Log import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.graphics.drawable.IconCompat import com.maary.liveinpeace.Constants.Companion.ACTION_NAME_SETTINGS import com.maary.liveinpeace.Constants.Companion.ACTION_TOGGLE_AUTO_CONNECTION_ADJUSTMENT import com.maary.liveinpeace.Constants.Companion.ALERT_TIME import com.maary.liveinpeace.Constants.Companion.BROADCAST_ACTION_FOREGROUND import com.maary.liveinpeace.Constants.Companion.BROADCAST_ACTION_MUTE import com.maary.liveinpeace.Constants.Companion.BROADCAST_ACTION_SLEEPTIMER_TOGGLE import com.maary.liveinpeace.Constants.Companion.BROADCAST_ACTION_SLEEPTIMER_UPDATE import com.maary.liveinpeace.Constants.Companion.BROADCAST_FOREGROUND_INTENT_EXTRA import com.maary.liveinpeace.Constants.Companion.CHANNEL_ID_DEFAULT import com.maary.liveinpeace.Constants.Companion.CHANNEL_ID_PROTECT import com.maary.liveinpeace.Constants.Companion.ID_NOTIFICATION_ALERT import com.maary.liveinpeace.Constants.Companion.ID_NOTIFICATION_FOREGROUND import com.maary.liveinpeace.Constants.Companion.ID_NOTIFICATION_GROUP_FORE import com.maary.liveinpeace.Constants.Companion.ID_NOTIFICATION_GROUP_PROTECT import com.maary.liveinpeace.Constants.Companion.ID_NOTIFICATION_PROTECT import com.maary.liveinpeace.Constants.Companion.MODE_IMG import com.maary.liveinpeace.Constants.Companion.MODE_NUM import com.maary.liveinpeace.Constants.Companion.PREF_ENABLE_EAR_PROTECTION import com.maary.liveinpeace.Constants.Companion.PREF_ICON import com.maary.liveinpeace.Constants.Companion.PREF_WATCHING_CONNECTING_TIME import com.maary.liveinpeace.Constants.Companion.SHARED_PREF import com.maary.liveinpeace.DeviceMapChangeListener import com.maary.liveinpeace.DeviceTimer import com.maary.liveinpeace.R import com.maary.liveinpeace.SleepNotification.find import com.maary.liveinpeace.database.Connection import com.maary.liveinpeace.database.ConnectionDao import com.maary.liveinpeace.database.ConnectionRoomDatabase import com.maary.liveinpeace.receiver.MuteMediaReceiver import com.maary.liveinpeace.receiver.SettingsReceiver import com.maary.liveinpeace.receiver.SleepReceiver import com.maary.liveinpeace.receiver.VolumeReceiver import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.text.DateFormat import java.time.LocalDate import java.util.Date class ForegroundService: Service() { private lateinit var database: ConnectionRoomDatabase private lateinit var connectionDao: ConnectionDao private val deviceTimerMap: MutableMap<String, DeviceTimer> = mutableMapOf() private val volumeDrawableIds = intArrayOf( R.drawable.ic_volume_silent, R.drawable.ic_volume_low, R.drawable.ic_volume_middle, R.drawable.ic_volume_high, R.drawable.ic_volume_mega ) private lateinit var volumeComment: Array<String> private lateinit var audioManager: AudioManager companion object { private var isForegroundServiceRunning = false @JvmStatic fun isForegroundServiceRunning(): Boolean { return isForegroundServiceRunning } private val deviceMap: MutableMap<String, Connection> = mutableMapOf() // 在伴生对象中定义一个静态方法,用于其他类访问deviceMap fun getConnections(): MutableList<Connection> { return deviceMap.values.toMutableList() } private val deviceMapChangeListeners: MutableList<DeviceMapChangeListener> = mutableListOf() fun addDeviceMapChangeListener(listener: DeviceMapChangeListener) { deviceMapChangeListeners.add(listener) } fun removeDeviceMapChangeListener(listener: DeviceMapChangeListener) { deviceMapChangeListeners.remove(listener) } } private fun notifyDeviceMapChange() { deviceMapChangeListeners.forEach { listener -> listener.onDeviceMapChanged(deviceMap) } } private fun getVolumePercentage(context: Context): Int { val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager val currentVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) val maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) return 100 * currentVolume / maxVolume } private fun getVolumeLevel(percent: Int): Int { return when(percent) { in 0..0 -> 0 in 1..25 -> 1 in 26..50 -> 2 in 50..80 -> 3 else -> 4 } } private val volumeChangeReceiver = object : VolumeReceiver() { @SuppressLint("MissingPermission") override fun updateNotification(context: Context) { Log.v("MUTE_TEST", "VOLUME_CHANGE_RECEIVER") with(NotificationManagerCompat.from(applicationContext)){ notify(ID_NOTIFICATION_FOREGROUND, createForegroundNotification(applicationContext)) } } } private val sleepReceiver = object : SleepReceiver() { @SuppressLint("MissingPermission") override fun updateNotification(context: Context) { with(NotificationManagerCompat.from(applicationContext)){ notify(ID_NOTIFICATION_FOREGROUND, createForegroundNotification(applicationContext)) } } } private fun saveDataWhenStop(){ val disconnectedTime = System.currentTimeMillis() for ( (deviceName, connection) in deviceMap){ val connectedTime = connection.connectedTime val connectionTime = disconnectedTime - connectedTime!! CoroutineScope(Dispatchers.IO).launch { connectionDao.insert( Connection( name = connection.name, type = connection.type, connectedTime = connection.connectedTime, disconnectedTime = disconnectedTime, duration = connectionTime, date = connection.date ) ) } deviceMap.remove(deviceName) } return } private val audioDeviceCallback = object : AudioDeviceCallback() { @SuppressLint("MissingPermission") override fun onAudioDevicesAdded(addedDevices: Array<out AudioDeviceInfo>?) { val connectedTime = System.currentTimeMillis() val sharedPreferences = getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) // 在设备连接时记录设备信息和接入时间 addedDevices?.forEach { deviceInfo -> if (deviceInfo.type in listOf( AudioDeviceInfo.TYPE_BUILTIN_EARPIECE, AudioDeviceInfo.TYPE_BUILTIN_MIC, AudioDeviceInfo.TYPE_BUILTIN_SPEAKER, AudioDeviceInfo.TYPE_BUILTIN_SPEAKER_SAFE, AudioDeviceInfo.TYPE_FM_TUNER, AudioDeviceInfo.TYPE_REMOTE_SUBMIX, AudioDeviceInfo.TYPE_TELEPHONY, 28, ) ) { return@forEach } val deviceName = deviceInfo.productName.toString().trim() if (deviceName == Build.MODEL) return@forEach Log.v("MUTE_DEVICE", deviceName) Log.v("MUTE_TYPE", deviceInfo.type.toString()) deviceMap[deviceName] = Connection( id=1, name = deviceInfo.productName.toString(), type = deviceInfo.type, connectedTime = connectedTime, disconnectedTime = null, duration = null, date = LocalDate.now().toString() ) notifyDeviceMapChange() if (sharedPreferences.getBoolean(PREF_ENABLE_EAR_PROTECTION, false)){ val audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager var boolProtected = false while (getVolumePercentage(applicationContext)>25) { boolProtected = true audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_LOWER, 0) } while (getVolumePercentage(applicationContext)<10) { boolProtected = true audioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0) } if (boolProtected){ with(NotificationManagerCompat.from(applicationContext)){ notify(ID_NOTIFICATION_PROTECT, createProtectionNotification()) } } } // 执行其他逻辑,比如将设备信息保存到数据库或日志中 } if (sharedPreferences.getBoolean(PREF_WATCHING_CONNECTING_TIME, false)){ for ((productName, _) in deviceMap){ if (deviceTimerMap.containsKey(productName)) continue val deviceTimer = DeviceTimer(context = applicationContext, deviceName = productName) Log.v("MUTE_DEVICEMAP", productName) deviceTimer.start() deviceTimerMap[productName] = deviceTimer } } Log.v("MUTE_MAP", deviceMap.toString()) // Handle newly added audio devices with(NotificationManagerCompat.from(applicationContext)){ notify(ID_NOTIFICATION_FOREGROUND, createForegroundNotification(applicationContext)) } } @SuppressLint("MissingPermission") override fun onAudioDevicesRemoved(removedDevices: Array<out AudioDeviceInfo>?) { // 在设备连接时记录设备信息和接入时间 removedDevices?.forEach { deviceInfo -> val deviceName = deviceInfo.productName.toString() val disconnectedTime = System.currentTimeMillis() if (deviceMap.containsKey(deviceName)){ val connectedTime = deviceMap[deviceName]?.connectedTime val connectionTime = disconnectedTime - connectedTime!! if (connectionTime > ALERT_TIME){ val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(ID_NOTIFICATION_ALERT) } val baseConnection = deviceMap[deviceName] CoroutineScope(Dispatchers.IO).launch { if (baseConnection != null) { connectionDao.insert( Connection( name = baseConnection.name, type = baseConnection.type, connectedTime = baseConnection.connectedTime, disconnectedTime = disconnectedTime, duration = connectionTime, date = baseConnection.date ) ) } } deviceMap.remove(deviceName) notifyDeviceMapChange() } val sharedPreferences = getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE) if (sharedPreferences.getBoolean(PREF_WATCHING_CONNECTING_TIME, false)){ if (deviceTimerMap.containsKey(deviceName)){ deviceTimerMap[deviceName]?.stop() deviceTimerMap.remove(deviceName) } } // 执行其他逻辑,比如将设备信息保存到数据库或日志中 } // Handle removed audio devices with(NotificationManagerCompat.from(applicationContext)){ notify(ID_NOTIFICATION_FOREGROUND, createForegroundNotification(applicationContext)) } } } @RequiresApi(Build.VERSION_CODES.TIRAMISU) override fun onCreate() { super.onCreate() Log.v("MUTE_TEST", "ON_CREATE") audioManager = getSystemService(Context.AUDIO_SERVICE) as AudioManager audioManager.registerAudioDeviceCallback(audioDeviceCallback, null) // 注册音量变化广播接收器 val filter = IntentFilter().apply { addAction("android.media.VOLUME_CHANGED_ACTION") } registerReceiver(volumeChangeReceiver, filter) val sleepFilter = IntentFilter().apply { addAction(BROADCAST_ACTION_SLEEPTIMER_UPDATE) } registerReceiver(sleepReceiver, sleepFilter, RECEIVER_NOT_EXPORTED) database = ConnectionRoomDatabase.getDatabase(applicationContext) connectionDao = database.connectionDao() startForeground(ID_NOTIFICATION_FOREGROUND, createForegroundNotification(context = applicationContext)) notifyForegroundServiceState(true) Log.v("MUTE_TEST", "ON_CREATE_FINISH") } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { super.onStartCommand(intent, flags, startId) Log.v("MUTE_TEST", "ON_START_COMMAND") // 返回 START_STICKY,以确保 Service 在被终止后能够自动重启 return START_STICKY } override fun onDestroy() { notifyForegroundServiceState(false) Log.v("MUTE_TEST", "ON_DESTROY") saveDataWhenStop() // 取消注册音量变化广播接收器 unregisterReceiver(volumeChangeReceiver) unregisterReceiver(sleepReceiver) audioManager.unregisterAudioDeviceCallback(audioDeviceCallback) val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.cancel(ID_NOTIFICATION_FOREGROUND) Log.v("MUTE_TEST", "ON_DESTROY_FINISH") super.onDestroy() } override fun onBind(p0: Intent?): IBinder? { TODO("Not yet implemented") } private fun notifyForegroundServiceState(isRunning: Boolean) { isForegroundServiceRunning = isRunning val intent = Intent(BROADCAST_ACTION_FOREGROUND) intent.putExtra(BROADCAST_FOREGROUND_INTENT_EXTRA, isRunning) sendBroadcast(intent) } @SuppressLint("LaunchActivityFromNotification") fun createForegroundNotification(context: Context): Notification { val currentVolume = getVolumePercentage(context) val currentVolumeLevel = getVolumeLevel(currentVolume) volumeComment = resources.getStringArray(R.array.array_volume_comment) val nIcon = generateNotificationIcon(context, getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE).getInt(PREF_ICON, MODE_IMG)) val settingsIntent = Intent(this, SettingsReceiver::class.java).apply { action = ACTION_NAME_SETTINGS } val snoozePendingIntent: PendingIntent = PendingIntent.getBroadcast(this, 0, settingsIntent, PendingIntent.FLAG_IMMUTABLE) val actionSettings : NotificationCompat.Action = NotificationCompat.Action.Builder( R.drawable.ic_baseline_settings_24, resources.getString(R.string.settings), snoozePendingIntent ).build() val sharedPreferences = getSharedPreferences( SHARED_PREF, Context.MODE_PRIVATE ) var protectionActionTitle = R.string.protection if (sharedPreferences != null){ if (sharedPreferences.getBoolean(PREF_ENABLE_EAR_PROTECTION, false)){ protectionActionTitle = R.string.dont_protect } } val protectionIntent = Intent(this, SettingsReceiver::class.java).apply { action = ACTION_TOGGLE_AUTO_CONNECTION_ADJUSTMENT } val protectionPendingIntent: PendingIntent = PendingIntent.getBroadcast(this, 0, protectionIntent, PendingIntent.FLAG_IMMUTABLE) val actionProtection : NotificationCompat.Action = NotificationCompat.Action.Builder( R.drawable.ic_headphones_protection, resources.getString(protectionActionTitle), protectionPendingIntent ).build() val sleepIntent = Intent(context, MuteMediaReceiver::class.java) sleepIntent.action = BROADCAST_ACTION_SLEEPTIMER_TOGGLE val pendingSleepIntent = PendingIntent.getBroadcast(context, 0, sleepIntent, PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) val sleepNotification = find() var sleepTitle = resources.getString(R.string.sleep) if (sleepNotification != null ){ sleepTitle = DateFormat.getTimeInstance(DateFormat.SHORT).format(Date(sleepNotification.`when`)) } val actionSleepTimer: NotificationCompat.Action = NotificationCompat.Action.Builder ( R.drawable.ic_tile, sleepTitle, pendingSleepIntent ).build() val muteMediaIntent = Intent(context, MuteMediaReceiver::class.java) muteMediaIntent.action = BROADCAST_ACTION_MUTE val pendingMuteIntent = PendingIntent.getBroadcast(context, 0, muteMediaIntent, PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_UPDATE_CURRENT) // 将 Service 设置为前台服务,并创建一个通知 return NotificationCompat.Builder(this, CHANNEL_ID_DEFAULT) .setContentTitle(getString(R.string.to_be_or_not)) .setOnlyAlertOnce(true) .setContentText(String.format( resources.getString(R.string.current_volume_percent), volumeComment[currentVolumeLevel], currentVolume)) .setSmallIcon(nIcon) .setOngoing(true) .setContentIntent(pendingMuteIntent) .setPriority(NotificationCompat.PRIORITY_LOW) .addAction(actionSettings) .addAction(actionSleepTimer) .addAction(actionProtection) .setGroup(ID_NOTIFICATION_GROUP_FORE) .setGroupSummary(false) .build() } fun createProtectionNotification(): Notification { return NotificationCompat.Builder(this, CHANNEL_ID_PROTECT) .setContentTitle(getString(R.string.ears_protected)) .setSmallIcon(R.drawable.ic_headphones_protection) .setPriority(NotificationCompat.PRIORITY_LOW) .setGroup(ID_NOTIFICATION_GROUP_PROTECT) .setTimeoutAfter(3000) .build() } @SuppressLint("DiscouragedApi") private fun generateNotificationIcon(context: Context, iconMode: Int): IconCompat { val currentVolume = getVolumePercentage(context) val currentVolumeLevel = getVolumeLevel(currentVolume) if (iconMode == MODE_NUM) { val resourceId = resources.getIdentifier("num_$currentVolume", "drawable", context.packageName) return IconCompat.createWithResource(this, resourceId) } else { return IconCompat.createWithResource(context, volumeDrawableIds[currentVolumeLevel]) } } }
0
Kotlin
2
14
92ed6d4781c64a808e9975178f0bfb0ccd82bb55
19,878
LiveInPeace
Apache License 2.0
idbdata/src/main/java/com/gmail/eamosse/idbdata/data/MovieTopRated.kt
corentin-ach
429,756,030
true
{"Kotlin": 58287}
package com.gmail.eamosse.idbdata.data data class MovieTopRated( val id: Int, val name: String, val date: String, val poster: String? )
0
Kotlin
0
0
05675c909adac274600a978b76f5503be79ccc89
154
the-movie-app
Apache License 2.0
src/main/kotlin/dev/zwei/mailchimp/domain/mailChimp/apiObjects/lists/Lists.kt
0OZ
453,667,678
false
null
package dev.zwei.mailchimp.domain.mailChimp.apiObjects.lists import dev.zwei.mailchimp.domain.mailChimp.apiObjects.Link data class Lists( val _links: List<Link>?, val constraints: Constraints?, val lists: List<MailChimpList>?, val total_items: Int? )
0
Kotlin
0
0
87f7e8b1918654d8ca70f472a4290ca224a68460
268
mailchimpkt
MIT License
app/src/main/java/com/weatherapp/data/viewmodel/SearchViewModel.kt
AhmedZaki918
529,578,472
false
{"Kotlin": 142653}
package com.weatherapp.data.viewmodel import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.weatherapp.data.local.Constants.IMPERIAL import com.weatherapp.data.local.Constants.METRIC import com.weatherapp.data.local.Constants.TEMP_UNIT import com.weatherapp.data.model.forecast.FiveDaysForecastResponse import com.weatherapp.data.model.geocoding.GeocodingResponse import com.weatherapp.data.model.weather.CurrentWeatherResponse import com.weatherapp.data.network.Resource import com.weatherapp.data.repository.SearchRepo import com.weatherapp.util.DataStoreRepo import com.weatherapp.util.RequestState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.async import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SearchViewModel @Inject constructor( private val repo: SearchRepo, private val dataStoreRepo: DataStoreRepo ) : ViewModel() { private var tempUnit = "" val searchTextState: MutableState<String> = mutableStateOf("") val requestState: MutableState<RequestState> = mutableStateOf(RequestState.IDLE) private val _geocoding = MutableStateFlow<Resource<List<GeocodingResponse>>>(Resource.Idle) val geocoding: StateFlow<Resource<List<GeocodingResponse>>> = _geocoding private val _currentWeather = MutableStateFlow<Resource<CurrentWeatherResponse>>(Resource.Idle) val currentWeather: StateFlow<Resource<CurrentWeatherResponse>> = _currentWeather private val _weatherForecast = MutableStateFlow<Resource<FiveDaysForecastResponse>>(Resource.Idle) val weatherForecast: StateFlow<Resource<FiveDaysForecastResponse>> = _weatherForecast init { viewModelScope.launch { dataStoreRepo.readInt(TEMP_UNIT).collectLatest { unit -> tempUnit = when (unit) { 0 -> METRIC 1 -> IMPERIAL else -> METRIC } } } } fun initGeocoding(city: String) { viewModelScope.launch { _geocoding.value = repo.getGeocoding(city) requestState.value = RequestState.SUCCESS } } fun initCurrentWeather(latitude: Double, longitude: Double) { viewModelScope.launch { val weather = async { repo.getCurrentWeather(latitude, longitude, tempUnit) } val forecast = async { repo.getFiveDaysForecast(latitude, longitude, tempUnit) } updateUi(weather.await(), forecast.await()) } } private fun updateUi( weatherResponse: Resource<CurrentWeatherResponse>, forecastResponse: Resource<FiveDaysForecastResponse> ) { _currentWeather.value = weatherResponse _weatherForecast.value = forecastResponse } }
0
Kotlin
1
10
fdaf1ab7f8d5676517b584754c8306c75b41f90e
3,079
Weather-App
The Unlicense
ktmidi-ci/src/commonMain/kotlin/dev/atsushieno/ktmidi/ci/ClientConnection.kt
atsushieno
340,913,447
false
null
package dev.atsushieno.ktmidi.ci import dev.atsushieno.ktmidi.ci.json.Json import dev.atsushieno.ktmidi.ci.propertycommonrules.* enum class SubscriptionActionState { Subscribing, Subscribed, Unsubscribing, Unsubscribed } data class ClientSubscription(var pendingRequestId: Byte?, var subscriptionId: String?, val propertyId: String, var state: SubscriptionActionState) class ClientConnection( private val parent: MidiCIDevice, val targetMUID: Int, deviceDetails: DeviceDetails, var maxSimultaneousPropertyRequests: Byte = 0, var productInstanceId: String = "", ) { var deviceInfo = MidiCIDeviceInfo( deviceDetails.manufacturer, deviceDetails.family, deviceDetails.modelNumber, deviceDetails.softwareRevisionLevel, "", "", "", "", "" ) var jsonSchema: Json.JsonValue? = null val profileClient = ProfileClientFacade(parent, this) val propertyClient = PropertyClientFacade(parent, this) }
9
null
6
69
48792a4826cea47edbec7eabcd62d5a489dd374e
1,020
ktmidi
MIT License
media/sample-benchmark/src/main/java/com/google/android/horologist/mediasample/benchmark/StartupBenchmark.kt
google
451,563,714
false
null
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.mediasample.benchmark import androidx.benchmark.macro.CompilationMode import androidx.test.filters.LargeTest import com.google.android.horologist.media.benchmark.BaseStartupBenchmark import com.google.android.horologist.media.benchmark.MediaApp import org.junit.runner.RunWith import org.junit.runners.Parameterized @LargeTest @RunWith(Parameterized::class) class StartupBenchmark( override val compilationMode: CompilationMode ) : BaseStartupBenchmark() { override val mediaApp: MediaApp = TestMedia.MediaSampleApp companion object { @Parameterized.Parameters(name = "compilation={0}") @JvmStatic fun parameters() = listOf(CompilationMode.None(), CompilationMode.Partial()) } }
71
Kotlin
69
430
bcfd31399a85d9eef772947fec6765a905d3529c
1,378
horologist
Apache License 2.0
app/src/main/java/com/androidyuan/kotlin_android_learn/model/UserData.kt
weizongwei5
91,679,734
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 7, "Kotlin": 14}
package com.androidyuan.kotlin_android_learn.model /** * Created by wei on 17-5-19. */ data class UserData(val name:String,val age:Int){ }
1
null
1
1
07da9b7f9a08df282d33caca26b03364a6546f7a
142
Kotlin_Android_Learn
Apache License 2.0
app/src/main/java/com/example/avjindersinghsekhon/minimaltodo/addToDo/AddToDoActivity.kt
mvp-sales
778,225,582
false
{"Kotlin": 83065, "Java": 9990}
package com.example.avjindersinghsekhon.minimaltodo.addToDo import android.os.Bundle import android.view.View import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import com.example.avjindersinghsekhon.minimaltodo.R import com.example.avjindersinghsekhon.minimaltodo.appDefault.AppDefaultActivity import com.example.avjindersinghsekhon.minimaltodo.main.MainViewModel import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class AddToDoActivity : AppDefaultActivity() { private val viewModel: AddTodoViewModel by viewModels() override fun contentViewLayoutRes(): Int { return R.layout.activity_add_to_do } override fun createInitialFragment(): Fragment { return AddToDoFragment.newInstance() } companion object { const val TODO_ID = "TODO_ID" } }
0
Kotlin
0
0
445e421b2b20038f41da3085c2677e9a3c283dfb
923
MinimalTodo
MIT License
knee-runtime/src/backendMain/kotlin/buffer/IntBuffer.kt
deepmedia
552,404,398
false
{"Kotlin": 544280}
package io.deepmedia.tools.knee.runtime.buffer import io.deepmedia.tools.knee.runtime.* import kotlinx.cinterop.* import platform.android.jobject class FloatBuffer private constructor(private val bytes: ByteBuffer) { @PublishedApi internal constructor(environment: JniEnvironment, jobject: jobject) : this(ByteBuffer( environment = environment, jobject = jobject, storage = null, freeStorage = { }, size = environment.getDirectBufferCapacity(jobject).toInt() * 4 )) constructor(environment: JniEnvironment, size: Int) : this(ByteBuffer( environment = environment, size = size * 4 )) @PublishedApi internal val obj get() = bytes.obj val size: Int get() = bytes.size / 4 val ptr: CArrayPointer<FloatVar> = bytes.ptr.reinterpret() fun free() = bytes.free() }
5
Kotlin
2
76
033fe352320a38b882381929fecb7b1811e00ebb
848
Knee
Apache License 2.0
src/main/kotlin/mathlingua/cli/CliUtil.kt
DominicKramer
203,428,613
false
null
/* * Copyright 2021 The MathLingua Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package mathlingua.cli import mathlingua.backend.SourceCollection import mathlingua.backend.SourceFile import mathlingua.backend.ValueAndSource import mathlingua.frontend.chalktalk.phase2.ast.common.Phase2Node import mathlingua.frontend.support.ParseError import mathlingua.frontend.support.ValidationFailure internal fun bold(text: String) = "\u001B[1m$text\u001B[0m".onWindowsReturn(text) @Suppress("SAME_PARAMETER_VALUE") internal fun green(text: String) = "\u001B[32m$text\u001B[0m".onWindowsReturn(text) internal fun red(text: String) = "\u001B[31m$text\u001B[0m".onWindowsReturn(text) @Suppress("UNUSED") internal fun yellow(text: String) = "\u001B[33m$text\u001B[0m".onWindowsReturn(text) internal val COMPLETIONS = Completions( items = listOf( CompletionItem(name = "and", parts = listOf("and:")), CompletionItem(name = "exists", parts = listOf("exists:", "where?:", "suchThat?:")), CompletionItem( name = "existsUnique", parts = listOf("existsUnique:", "where?:", "suchThat?:")), CompletionItem( name = "forAll", parts = listOf("forAll:", "where?:", "suchThat?:", "then:")), CompletionItem(name = "if", parts = listOf("if:", "then:")), CompletionItem(name = "iff", parts = listOf("iff:", "then:")), CompletionItem(name = "not", parts = listOf("not:")), CompletionItem(name = "or", parts = listOf("or:")), CompletionItem( name = "piecewise", parts = listOf("piecewise:\nwhen:\nthen:\nelse?:")), CompletionItem(name = "generated", parts = listOf("generated:", "from:", "when?:")), CompletionItem( name = "Defines:", parts = listOf( "Defines:", "with?:", "given?:", "when?:", "means?:", "satisfying:", "expressing:", "using?:", "writing?:", "written:", "called?:", "Providing?:", "Metadata?:"), ), CompletionItem( name = "States", parts = listOf( "States:", "given?:", "when?:", "that:", "using?:", "written:", "called?:", "Metadata?:"), ), CompletionItem( name = "equality", parts = listOf("equality:", "between:", "provided:")), CompletionItem(name = "membership", parts = listOf("membership:", "through:")), CompletionItem(name = "view", parts = listOf("view:", "as:", "via:", "by?:")), CompletionItem(name = "symbols", parts = listOf("symbols:", "where?:")), CompletionItem(name = "memberSymbols", parts = listOf("memberSymbols:", "where?:")), CompletionItem( name = "Resource", parts = listOf( "Resource:\n. type? = \"\"\n. name? = \"\"\n. author? = \"\"\n. homepage? = \"\"\n. url? = \"\"\n. offset? = \"\"\nMetadata?:"), ), CompletionItem( name = "Axiom", parts = listOf( "Axiom:", "given?:", "where?:", "suchThat?:", "then:", "iff?:", "using?:", "Metadata?:"), ), CompletionItem( name = "Conjecture", parts = listOf( "Conjecture:", "given?:", "where?:", "suchThat?:", "then:", "iff?:", "using?:", "Metadata?:")), CompletionItem( name = "Theorem", parts = listOf( "Theorem:", "given?:", "where?:", "suchThat?:", "then:", "iff?:", "using?:", "Proof?:", "Metadata?:"), ), CompletionItem(name = "matching", parts = listOf("matching:")), CompletionItem(name = "Topic", parts = listOf("Topic:", "content:", "Metadata?:")), CompletionItem(name = "Note", parts = listOf("Note:", "content:", "Metadata?:")), CompletionItem(name = "Specify", parts = listOf("Specify:")), CompletionItem(name = "zero", parts = listOf("zero:", "is:")), CompletionItem(name = "positiveInt", parts = listOf("positiveInt:", "is:")), CompletionItem(name = "negativeInt", parts = listOf("negativeInt:", "is:")), CompletionItem(name = "positiveFloat", parts = listOf("positiveFloat:", "is:")), CompletionItem(name = "negativeFloat", parts = listOf("negativeFloat:", "is:")))) internal fun getGitHubUrl(): String? { val pro = try { ProcessBuilder("git", "ls-remote", "--get-url").start() } catch (e: Exception) { return null } val exit = pro.waitFor() return if (exit != 0) { null } else { String(pro.inputStream.readAllBytes()).replace("<EMAIL>:", "https://github.com/") } } internal fun buildSignatureIndex(sourceCollection: SourceCollection): SignatureIndex { val entries = mutableListOf<SignatureIndexEntry>() for (path in sourceCollection.getAllPaths()) { val page = sourceCollection.getPage(path) ?: continue for (entity in page.fileResult.entities) { val signature = entity.signature ?: continue entries.add( SignatureIndexEntry( id = entity.id, relativePath = entity.relativePath, signature = signature, called = entity.called)) } } return SignatureIndex(entries = entries) } internal data class RenderedTopLevelElement( val renderedFormHtml: String, val rawFormHtml: String, val node: Phase2Node?) internal fun getCompleteRenderedTopLevelElements( f: VirtualFile, sourceCollection: SourceCollection, noexpand: Boolean, errors: MutableList<ValueAndSource<ParseError>> ): List<RenderedTopLevelElement> { val result = mutableListOf<RenderedTopLevelElement>() val expandedPair = sourceCollection.prettyPrint(file = f, html = true, literal = false, doExpand = !noexpand) val literalPair = sourceCollection.prettyPrint(file = f, html = true, literal = true, doExpand = false) errors.addAll( expandedPair.second.map { ValueAndSource( value = it, source = SourceFile(file = f, content = "", validation = ValidationFailure(emptyList()))) }) for (i in 0 until expandedPair.first.size) { result.add( RenderedTopLevelElement( renderedFormHtml = fixClassNameBug(expandedPair.first[i].first), rawFormHtml = fixClassNameBug(literalPair.first[i].first), node = expandedPair.first[i].second)) } return result } /* * Class names generation has a bug where the class description looks like * class=mathlingua - top - level * instead of the correct * class="mathlingua-top-level" * The following function finds the incorrect class names and converts them * to their correct form. */ internal fun fixClassNameBug(html: String) = html .replace(Regex("class[ ]*=[ ]*([ \\-_a-zA-Z0-9]+)")) { // for each `class=..`. found replace ` - ` with `-` val next = it.groups[0]?.value?.replace(" - ", "-") ?: it.value // then replace `class=...` with `class="..."` "class=\"${next.replaceFirst(Regex("class[ ]*=[ ]*"), "")}\"" } .replace("<body>", " ") .replace("</body>", " ") // ----------------------------------------------------------------------------- private fun String.onWindowsReturn(text: String): String = if (System.getProperty("os.name").lowercase().contains("win")) { text } else { this }
4
Kotlin
0
67
c264bc61ac7d9e520018f2652b110c4829876c82
9,844
mathlingua
Apache License 2.0
src/main/kotlin/com/cjcrafter/openai/assistants/Assistant.kt
CJCrafter
609,739,470
false
{"Kotlin": 249530}
package com.cjcrafter.openai.assistants import com.cjcrafter.openai.chat.tool.Tool import com.fasterxml.jackson.annotation.JsonProperty /** * Represents the assistant metadata returned by the OpenAI API. * * @property id The unique id of the assistant, always starts with asst_ * @property createdAt The unix timestamp of when the assistant was created * @property name The name of the assistant, if present * @property description The description of the assistant, if present * @property model The model used by the assistant * @property instructions The instructions for the assistant, if present * @property tools The tools used by the assistant * @property fileIds The list of file ids used in tools * @property metadata Data stored by YOU, the developer, to store additional information */ data class Assistant( @JsonProperty(required = true) val id: String, @JsonProperty("created_at", required = true) val createdAt: Int, @JsonProperty(required = true) val name: String?, @JsonProperty(required = true) val description: String?, @JsonProperty(required = true) val model: String, @JsonProperty(required = true) val instructions: String?, @JsonProperty(required = true) val tools: List<Tool>, @JsonProperty("file_ids", required = true) val fileIds: List<String>, @JsonProperty(required = true) val metadata: Map<String, String>, )
6
Kotlin
10
68
6f42852e460e2b935a5dbd3c53df112ba958aea2
1,386
ChatGPT-Java-API
MIT License
app/src/main/java/ru/tech/imageresizershrinker/presentation/erase_background_screen/components/PathPaint.kt
T8RIN
478,710,402
false
null
package ru.tech.imageresizershrinker.presentation.erase_background_screen.components import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path data class PathPaint( val path: Path, val strokeWidth: Float, val blurRadius: Float, val drawColor: Color = Color.Transparent, val isErasing: Boolean, val drawMode: DrawMode = DrawMode.Pen ) sealed class DrawMode(val ordinal: Int) { data object Neon : DrawMode(1) data object Highlighter : DrawMode(2) data object Pen : DrawMode(0) companion object { val entries by lazy { listOf( Pen, Neon, Highlighter ) } operator fun invoke(ordinal: Int) = when (ordinal) { 1 -> Neon 2 -> Highlighter else -> Pen } } }
14
Kotlin
47
568
bf80cfe6bc19e7d2cd163b060b5231fafa1bdd74
830
ImageToolbox
Apache License 2.0
core/src/main/java/io/github/crow_misia/libyuv/AbstractBuffer.kt
introtuce-nex2me
394,541,163
true
{"C++": 4444711, "Kotlin": 151196, "Python": 113902, "C": 42229, "Makefile": 7628, "CMake": 5674, "Shell": 1551}
package io.github.crow_misia.libyuv abstract class AbstractBuffer( releaseCallback: Runnable?, ) : Buffer { companion object { private val noneCallback = Runnable { } } private val refCountDelegate = RefCountDelegate(releaseCallback ?: noneCallback) override fun retain() = refCountDelegate.retain() override fun close() = refCountDelegate.release() }
0
null
0
0
34d64485ea93bbb0e21de0f650691fbbde8d45df
385
libyuv-android
Apache License 2.0
core/ui/src/main/java/com/msg/ui/makeToast.kt
School-of-Company
700,744,250
false
{"Kotlin": 724178}
package com.msg.ui import android.content.Context import android.widget.Toast fun makeToast(context: Context, message: String, duration: Int = Toast.LENGTH_SHORT) { Toast.makeText(context, message, duration).show() }
6
Kotlin
1
22
358bf40188fa2fc2baf23aa6b308b039cb3fbc8c
222
Bitgoeul-Android
MIT License
core/data/src/main/kotlin/cn/wj/android/cashbook/core/data/repository/impl/TagRepositoryImpl.kt
WangJie0822
365,932,300
false
{"Kotlin": 1323186, "Java": 1271087}
package cn.wj.android.cashbook.core.data.repository.impl import cn.wj.android.cashbook.core.common.annotation.CashbookDispatchers import cn.wj.android.cashbook.core.common.annotation.Dispatcher import cn.wj.android.cashbook.core.common.model.recordDataVersion import cn.wj.android.cashbook.core.common.model.tagDataVersion import cn.wj.android.cashbook.core.common.model.updateVersion import cn.wj.android.cashbook.core.data.repository.TagRepository import cn.wj.android.cashbook.core.data.repository.asModel import cn.wj.android.cashbook.core.data.repository.asTable import cn.wj.android.cashbook.core.database.dao.TagDao import cn.wj.android.cashbook.core.database.dao.TransactionDao import cn.wj.android.cashbook.core.model.model.TagModel import javax.inject.Inject import kotlin.coroutines.CoroutineContext import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.withContext class TagRepositoryImpl @Inject constructor( private val tagDao: TagDao, private val transactionDao: TransactionDao, @Dispatcher(CashbookDispatchers.IO) private val coroutineContext: CoroutineContext, ) : TagRepository { override val tagListData: Flow<List<TagModel>> = tagDataVersion.map { getAllTagList() } private suspend fun getAllTagList(): List<TagModel> = withContext(coroutineContext) { tagDao.queryAll() .map { it.asModel() } } override suspend fun updateTag(tag: TagModel) = withContext(coroutineContext) { val tagTable = tag.asTable() if (null == tagTable.id) { tagDao.insert(tagTable) } else { tagDao.update(tagTable) } tagDataVersion.updateVersion() recordDataVersion.updateVersion() } override suspend fun deleteTag(tag: TagModel) = withContext(coroutineContext) { transactionDao.deleteTag(tag.id) tagDataVersion.updateVersion() recordDataVersion.updateVersion() } override suspend fun getRelatedTag(recordId: Long): List<TagModel> = withContext(coroutineContext) { tagDao.queryByRecordId(recordId) .map { it.asModel() } } override suspend fun getTagById(tagId: Long): TagModel? = withContext(coroutineContext) { tagListData.first().firstOrNull { it.id == tagId } } override suspend fun deleteRelatedWithAsset(assetId: Long): Unit = withContext(coroutineContext) { tagDao.deleteRelatedWithAsset(assetId) } override suspend fun countTagByName(name: String): Int = withContext(coroutineContext) { tagDao.countByName(name) } }
0
Kotlin
7
23
004fb1d6e81ff60fd9e8cb46dc131107a720bbe5
2,840
Cashbook
Apache License 2.0
compiler/fir/checkers/src/org/jetbrains/kotlin/fir/analysis/checkers/type/FirUnsupportedModifiersInFunctionTypeParameterChecker.kt
JetBrains
3,432,266
false
{"Kotlin": 73228872, "Java": 6651359, "Swift": 4257359, "C": 2624202, "C++": 1891343, "Objective-C": 639940, "Objective-C++": 165521, "JavaScript": 135764, "Python": 43529, "Shell": 31554, "TypeScript": 22854, "Lex": 18369, "Groovy": 17190, "Batchfile": 11693, "CSS": 11368, "Ruby": 6922, "EJS": 5241, "HTML": 5073, "Dockerfile": 4705, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "LLVM": 395, "Scala": 80}
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.analysis.checkers.type import org.jetbrains.kotlin.* import org.jetbrains.kotlin.diagnostics.DiagnosticReporter import org.jetbrains.kotlin.diagnostics.reportOn import org.jetbrains.kotlin.diagnostics.valOrVarKeyword import org.jetbrains.kotlin.fir.FirFunctionTypeParameter import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext import org.jetbrains.kotlin.fir.analysis.checkers.getModifierList import org.jetbrains.kotlin.fir.analysis.checkers.syntax.FirSyntaxChecker import org.jetbrains.kotlin.fir.analysis.diagnostics.FirErrors import org.jetbrains.kotlin.fir.types.FirFunctionTypeRef import org.jetbrains.kotlin.fir.types.FirTypeRef import org.jetbrains.kotlin.psi.KtParameter import org.jetbrains.kotlin.psi.KtValVarKeywordOwner object FirUnsupportedModifiersInFunctionTypeParameterChecker : FirFunctionalTypeParameterSyntaxChecker() { override fun checkPsiOrLightTree( element: FirFunctionTypeParameter, source: KtSourceElement, context: CheckerContext, reporter: DiagnosticReporter ) { checkModifiers(source, reporter, context) checkValOrVarKeyword(source, reporter, context) } private fun checkValOrVarKeyword(source: KtSourceElement, reporter: DiagnosticReporter, context: CheckerContext) { val keyword = when (source) { is KtPsiSourceElement -> (source.psi as? KtValVarKeywordOwner)?.valOrVarKeyword?.toKtPsiSourceElement() is KtLightSourceElement -> source.treeStructure.valOrVarKeyword(source.lighterASTNode)?.toKtLightSourceElement(source.treeStructure) } ?: return reporter.reportOn( keyword, FirErrors.UNSUPPORTED, "val or var on parameter in function type", context ) } private fun checkModifiers(source: KtSourceElement, reporter: DiagnosticReporter, context: CheckerContext): Boolean { val modifiersList = source.getModifierList() ?: return true for (modifier in modifiersList.modifiers) { reporter.reportOn( modifier.source, FirErrors.UNSUPPORTED, "modifier on parameter in function type", context ) } return false } }
163
Kotlin
5686
46,039
f98451e38169a833f60b87618db4602133e02cf2
2,539
kotlin
Apache License 2.0
Quiz/app/src/main/java/com/example/quiz/view/ResultFragment.kt
KamilDonda
321,666,752
false
null
package com.example.quiz.view import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.OnBackPressedCallback import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.navigation.findNavController import com.example.quiz.R import com.example.quiz.view_model.vm.ResultViewModel import kotlinx.android.synthetic.main.fragment_result.* class ResultFragment : Fragment() { private lateinit var viewModelResult: ResultViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) activity?.onBackPressedDispatcher?.addCallback(this, object : OnBackPressedCallback(true) { override fun handleOnBackPressed() {} }) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { viewModelResult = ViewModelProvider(requireActivity()).get(ResultViewModel::class.java) return inflater.inflate(R.layout.fragment_result, container, false) } @SuppressLint("SetTextI18n") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val result = viewModelResult.result if (result < 4) textViewResultInfo.text = "Maybe next time.." if (result in 4..6) textViewResultInfo.text = "Not bad but could be better" if (result >= 7) textViewResultInfo.text = "Congratulations!" textViewResult.text = "$result/10" imageViewArrow.setOnClickListener { imageViewArrow.animate().rotationBy(imageViewArrow.rotation + 370).withEndAction { it.findNavController().navigate(R.id.action_resultFragment_to_categoryFragment) }.start() } } }
0
Kotlin
0
1
755580ba0eefe3e44ed12096a60b15bcd0a3b826
1,958
QuizzzyMobile
MIT License
app/src/main/java/com/qing/rainfall_tool/ui/Home.kt
qs2042
714,541,475
false
{"Kotlin": 151363, "Java": 13946}
package com.qing.rainfall_tool.ui import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.fragment.app.Fragment import androidx.recyclerview.widget.RecyclerView import androidx.viewpager.widget.PagerAdapter import androidx.viewpager.widget.ViewPager import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.CircleCrop import com.bumptech.glide.request.RequestOptions import com.qing.rainfall_tool.R import com.qing.rainfall_tool.component.PageRecyclerView /* package com.qing.rainfall_tool.ui import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.viewpager.widget.PagerAdapter import androidx.viewpager.widget.ViewPager import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.CircleCrop import com.bumptech.glide.request.RequestOptions import com.qing.rainfall_tool.R class Home : Fragment() { companion object { val imageList = listOf( R.drawable.profile, R.drawable.love, R.drawable.title ) } lateinit var viewPager: ViewPager lateinit var recyclerView: RecyclerView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_home, container, false) return view } private fun init(view: View) { viewPager = view.findViewById(R.id.viewPager) recyclerView = view.findViewById(R.id.recycler_view) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) init(view) // 轮播图 val viewPagerAdapter = ViewPagerAdapter(requireActivity(), imageList) viewPager.adapter = viewPagerAdapter // val layoutManager = GridLayoutManager(requireActivity(), 2) layoutManager.orientation = GridLayoutManager.HORIZONTAL recyclerView.layoutManager = layoutManager recyclerView.adapter = RecycleAdapter( this.requireContext(), arrayListOf("景点", "美食", "娱乐", "酒店", "电影票", "周末游", "自驾游", "论坛", "机票", "火车票") ) } // 轮播图 class ViewPagerAdapter(private val context: Context, private val images: List<Int>) : PagerAdapter() { override fun instantiateItem(container: ViewGroup, position: Int): Any { val inflater = LayoutInflater.from(context) // 简单的做法, 如果需要对图片增加一些功能, 还是使用布局比较好 */ /*val img = ImageView(context) img.setImageResource(images[position]) img.scaleType = ImageView.ScaleType.CENTER_CROP // 设置图片的缩放类型为覆盖模式 container.addView(img) return img*//* val view = inflater.inflate(R.layout.item_image, container, false) val imageView = view.findViewById<ImageView>(R.id.imageView) imageView.setImageResource(images[position]) imageView.scaleType = ImageView.ScaleType.CENTER_CROP // 设置图片的缩放类型为覆盖模式 container.addView(view) return view } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as View) } override fun getCount(): Int { return images.size } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view == `object` } } class RecycleAdapter(var context: Context, var list: java.util.ArrayList<String>) : RecyclerView.Adapter<RecycleAdapter.ViewHolder>() { // class: viewHolder class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var textView: TextView? = null var imageView: ImageView? = null init { textView = itemView.findViewById<View>(R.id.textView) as TextView imageView = itemView.findViewById<View>(R.id.imageView) as ImageView } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // 创建ViewHolder,返回每一项的布局 val inflater = LayoutInflater.from(context).inflate(R.layout.item_image_text, parent, false) return ViewHolder(inflater!!) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = list[position] // 将数据和控件绑定 holder.textView?.text = item Glide.with(context) .load(R.drawable.title) // fit: center .fitCenter() // 通过CircleCrop, 将图片变为圆形 .apply(RequestOptions.bitmapTransform(CircleCrop())) .into(holder.imageView!!) } override fun getItemCount(): Int { return list.size } } class GridItemDecoration(spacing: Int, color: Int) : RecyclerView.ItemDecoration() { private var paint: Paint = Paint() init { paint.color = color paint.strokeWidth = spacing.toFloat() } override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { // super.onDraw(canvas, parent, state) val childCount: Int = parent.childCount val spanCount = 2 // 每行格子数量 for (i in 0 until childCount) { val child = parent.getChildAt(i) val position = parent.getChildAdapterPosition(child) val left = child.left val right = child.right val top = child.top val bottom = child.bottom // 绘制垂直方向的线条 if ((position + 1) % spanCount != 0) { val startX = right.toFloat() val startY = top.toFloat() val stopX = right.toFloat() val stopY = bottom.toFloat() canvas.drawLine(startX, startY, stopX, stopY, paint) } // 绘制水平方向的线条 if (position >= spanCount) { val startX = left.toFloat() val startY = top.toFloat() val stopX = left.toFloat() val stopY = bottom.toFloat() canvas.drawLine(startX, startY, stopX, stopY, paint) } } } } }*/ class Home : Fragment() { companion object { val imageList = listOf( R.mipmap.bg_106364616, R.mipmap.bg_107651594, R.mipmap.bg_87013637 ) } lateinit var viewPager: ViewPager lateinit var recyclerView: RecyclerView lateinit var mRecyclerView: PageRecyclerView lateinit var dataList: ArrayList<String> lateinit var myAdapter: PageRecyclerView.PageAdapter override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_home, container, false) return view } private fun init(view: View) { viewPager = view.findViewById(R.id.viewPager) // recyclerView = view.findViewById(R.id.recycler_view) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) init(view) dataList = ArrayList() for (i in 0..49) { dataList.add(i.toString()) } // 轮播图 val viewPagerAdapter = ViewPagerAdapter(requireActivity(), imageList) viewPager.adapter = viewPagerAdapter mRecyclerView = view.findViewById(R.id.cusom_swipe_view); // 设置指示器 mRecyclerView.setIndicator(view.findViewById(R.id.indicator)); // 设置行数和列数 mRecyclerView.setPageSize(2, 5); // 设置页间距 mRecyclerView.setPageMargin(5) // 动画 /*val myAnim = AnimationUtils.loadAnimation(this as Context, R.anim.in_from_right) myAnim.fillAfter = true;//android动画结束后停在结束位置 val set = AnimationSet(false) set.addAnimation(myAnim); //加入动画集合 val controller = LayoutAnimationController(set, 1.0f) mRecyclerView.setLayoutAnimation(controller)*/ // // mRecyclerView.setLayoutManager(new AutoGridLayoutManager(RecycleViewActivity.this,dataList.size())); // 设置数据 val callback = object : PageRecyclerView.CallBack { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { // 在这里创建和返回你的ViewHolder val view = LayoutInflater.from([email protected]).inflate(R.layout.item_image_text, parent, false); return MyHolder(view); } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { // 在这里绑定数据到你的ViewHolder val holder = holder as MyHolder holder.tv.text = dataList[position] holder.tv.visibility = View.GONE /*Glide.with(this@Home) .load(R.drawable.title) // fit: center .fitCenter() // 通过CircleCrop, 将图片变为圆形 .apply(RequestOptions.bitmapTransform(CircleCrop())) .into(holder.iv)*/ } } mRecyclerView.adapter = mRecyclerView.PageAdapter(dataList, callback) } class MyHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var tv: TextView var iv: ImageView init { this.tv = itemView.findViewById(R.id.textView) this.iv = itemView.findViewById(R.id.imageView) /*tv.setOnClickListener { Toast.makeText(this@Home as Context, adapterPosition, Toast.LENGTH_SHORT).show(); } tv.setOnLongClickListener { myAdapter.remove(adapterPosition) return true; }*/ } } // 轮播图 class ViewPagerAdapter(private val context: Context, private val images: List<Int>) : PagerAdapter() { override fun instantiateItem(container: ViewGroup, position: Int): Any { val inflater = LayoutInflater.from(context) // 简单的做法, 如果需要对图片增加一些功能, 还是使用布局比较好 /*val img = ImageView(context) img.setImageResource(images[position]) img.scaleType = ImageView.ScaleType.CENTER_CROP // 设置图片的缩放类型为覆盖模式 container.addView(img) return img*/ val view = inflater.inflate(R.layout.item_image, container, false) val imageView = view.findViewById<ImageView>(R.id.imageView) imageView.setImageResource(images[position]) imageView.scaleType = ImageView.ScaleType.CENTER_CROP // 设置图片的缩放类型为覆盖模式 container.addView(view) return view } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as View) } override fun getCount(): Int { return images.size } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view == `object` } } class RecycleAdapter(var context: Context, var list: java.util.ArrayList<String>) : RecyclerView.Adapter<RecycleAdapter.ViewHolder>() { // class: viewHolder class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { var textView: TextView? = null var imageView: ImageView? = null init { textView = itemView.findViewById<View>(R.id.textView) as TextView imageView = itemView.findViewById<View>(R.id.imageView) as ImageView } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { // 创建ViewHolder,返回每一项的布局 val inflater = LayoutInflater.from(context).inflate(R.layout.item_image_text, parent, false) return ViewHolder(inflater!!) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = list[position] // 将数据和控件绑定 holder.textView?.text = item Glide.with(context) .load(R.drawable.title) // fit: center .fitCenter() // 通过CircleCrop, 将图片变为圆形 .apply(RequestOptions.bitmapTransform(CircleCrop())) .into(holder.imageView!!) } override fun getItemCount(): Int { return list.size } } class GridItemDecoration(spacing: Int, color: Int) : RecyclerView.ItemDecoration() { private var paint: Paint = Paint() init { paint.color = color paint.strokeWidth = spacing.toFloat() } override fun onDraw(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { // super.onDraw(canvas, parent, state) val childCount: Int = parent.childCount val spanCount = 2 // 每行格子数量 for (i in 0 until childCount) { val child = parent.getChildAt(i) val position = parent.getChildAdapterPosition(child) val left = child.left val right = child.right val top = child.top val bottom = child.bottom // 绘制垂直方向的线条 if ((position + 1) % spanCount != 0) { val startX = right.toFloat() val startY = top.toFloat() val stopX = right.toFloat() val stopY = bottom.toFloat() canvas.drawLine(startX, startY, stopX, stopY, paint) } // 绘制水平方向的线条 if (position >= spanCount) { val startX = left.toFloat() val startY = top.toFloat() val stopX = left.toFloat() val stopY = bottom.toFloat() canvas.drawLine(startX, startY, stopX, stopY, paint) } } } } }
0
Kotlin
0
0
d0e5ae1931b12531ec1f55a29a7b9b52ae9f8419
14,922
Rainfall-android-tool
Apache License 2.0
yutilskt/src/main/java/com/yechaoa/yutilskt/TimeUtil.kt
yechaoa
86,978,971
false
null
package com.yechaoa.yutilskt import java.text.ParseException import java.text.SimpleDateFormat import java.util.* /** * Created by yechao on 2020/1/7. * Describe : 日期 * * GitHub : https://github.com/yechaoa * CSDN : http://blog.csdn.net/yechaoa */ object TimeUtilKt { /** * 获取当前年月日 */ val date: String get() { val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) val date = Date() return sdf.format(date) } /** * 获取当前时分秒 */ val time: String get() { val sdf = SimpleDateFormat("HH:mm:ss", Locale.getDefault()) val date = Date() return sdf.format(date) } /** * 获取当前年月日时分秒 */ val dateAndTime: String get() { val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()) val date = Date(System.currentTimeMillis()) return sdf.format(date) } /** * 获取当前时间,返回Long类型 */ val timeForLong: Long get() = System.currentTimeMillis() /** * 转换为年月日 */ fun formatDate(mDate: String?): String { val sdf = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()) var date: Date? = null try { date = sdf.parse(mDate) } catch (e: ParseException) { e.printStackTrace() } return sdf.format(date) } }
1
null
8
76
4f6d6ce486680db91656018769b1c73c9d5ca8fa
1,430
YUtils
Apache License 2.0
app/src/main/java/si/betoo/hodler/UserSettings.kt
aweCodeMan
116,491,961
false
null
package si.betoo.hodler import android.content.Context import android.preference.PreferenceManager import io.reactivex.Observable import io.reactivex.subjects.BehaviorSubject import java.util.concurrent.TimeUnit class UserSettings(private val context: Context) { private val observableUserCurrencies = BehaviorSubject.create<Map<String, String>>() private val observableMainCurrency = BehaviorSubject.create<Map<String, String>>() init { observableUserCurrencies.doOnSubscribe { observableUserCurrencies.onNext(loadCurrencyCodesFromPreferences(context)) } observableMainCurrency.doOnSubscribe { observableMainCurrency.onNext(loadMainCurrency(context)) } } fun getUserCurrencies(): Observable<Map<String, String>> { observableUserCurrencies.onNext(loadCurrencyCodesFromPreferences(context)) return observableUserCurrencies } fun getMainCurrency(): Observable<Map<String, String>> { observableMainCurrency.onNext(loadMainCurrency(context)) return observableMainCurrency } fun refresh() { Observable.just("") .debounce(500, TimeUnit.MILLISECONDS) .delay(1, TimeUnit.SECONDS) .subscribe({ observableUserCurrencies.onNext(loadCurrencyCodesFromPreferences(context)) observableMainCurrency.onNext(loadMainCurrency(context)) }) } private fun loadMainCurrency(context: Context): Map<String, String> { val codes = context.resources.getStringArray(R.array.available_total_currencies_code) val symbols = context.resources.getStringArray(R.array.available_total_currencies_symbol) val mainCurrencyCode = PreferenceManager.getDefaultSharedPreferences(context) .getString("main_currency_code", "EUR") val map: MutableMap<String, String> = HashMap() map.put(mainCurrencyCode, symbols[codes.indexOf(mainCurrencyCode)]) return map } private fun loadCurrencyCodesFromPreferences(context: Context): MutableMap<String, String> { val codes = context.resources.getStringArray(R.array.available_total_currencies_code) val symbols = context.resources.getStringArray(R.array.available_total_currencies_symbol) val mainCurrencyCode = PreferenceManager.getDefaultSharedPreferences(context) .getString("main_currency_code", "EUR") val additionalCurrencyCodes = PreferenceManager.getDefaultSharedPreferences(context) .getStringSet("selected_currency_codes", HashSet()) val map: MutableMap<String, String> = HashMap() map.put(mainCurrencyCode, symbols[codes.indexOf(mainCurrencyCode)]) additionalCurrencyCodes.forEach { code -> map.put(code, symbols[codes.indexOf(code)]) } return map } }
1
null
1
1
9224429b2f28aa37e3add34eda11da0d9916b09e
2,890
hodler
MIT License
src/main/kotlin/io/docrozza/normalization/function/GraphDigestPlan.kt
docrozza
427,397,971
false
{"Kotlin": 45520}
package io.docrozza.normalization.function import com.complexible.stardog.index.statistics.Cardinality import com.complexible.stardog.plan.* import com.google.common.collect.ImmutableSet import com.complexible.stardog.plan.QueryDataset.Scope import com.google.common.collect.ImmutableList class GraphDigestPlan( parent: PlanNode, subjects: List<QueryTerm>, objects: List<QueryTerm>, context: QueryTerm?, scope: Scope, cost: Double, cardinality: Cardinality, subjVars: ImmutableSet<Int>, predVars: ImmutableSet<Int>, objVars: ImmutableSet<Int>, contextVars: ImmutableSet<Int>, assuredVars: ImmutableSet<Int>, allVars: ImmutableSet<Int>): AbstractPropertyFunctionPlanNode(parent, subjects, objects, context, scope, cost, cardinality, subjVars, predVars, objVars, contextVars, assuredVars, allVars) { private val inputs = subjects.asSequence() .filter { it.isVariable } .fold(ImmutableList.builder<QueryTerm>()) { list, v -> list.add(v) } .build() override fun getURI() = GraphDigest.iri override fun getInputs() : ImmutableList<QueryTerm> = inputs override fun canEquals(other: Any) = other is GraphDigestPlan override fun createBuilder() = GraphDigestPlanBuilder() override fun copy() = GraphDigestPlan(arg.copy(), subjects, objects, context, scope, cost, cardinality, subjectVars, predicateVars, objectVars, contextVars, assuredVars, allVars) }
1
Kotlin
0
0
a5443f6d55cb4e67cdf1a49d181734ec05c4c238
1,468
normalization
MIT License
src/main/kotlin/com/github/sieves/api/ApiBlock.kt
synth-dev
484,500,855
false
{"Kotlin": 693390, "Java": 1384}
package com.github.sieves.api import com.github.sieves.api.ApiTile.* import com.github.sieves.registry.Registry import com.github.sieves.registry.Registry.Items import com.github.sieves.registry.internal.net.ConfigurePacket import com.github.sieves.registry.internal.net.TakeUpgradePacket import com.github.sieves.dsl.Log import com.github.sieves.dsl.getLevel import net.minecraft.core.BlockPos import net.minecraft.server.level.ServerPlayer import net.minecraft.world.InteractionHand import net.minecraft.world.InteractionResult import net.minecraft.world.entity.player.Player import net.minecraft.world.level.Level import net.minecraft.world.level.block.Block import net.minecraft.world.level.block.EntityBlock import net.minecraft.world.level.block.entity.BlockEntity import net.minecraft.world.level.block.entity.BlockEntityTicker import net.minecraft.world.level.block.entity.BlockEntityType import net.minecraft.world.level.block.state.BlockState import net.minecraft.world.phys.BlockHitResult import net.minecraftforge.items.ItemHandlerHelper import net.minecraftforge.items.wrapper.InvWrapper import net.minecraftforge.network.NetworkEvent abstract class ApiBlock<R : com.github.sieves.api.ApiTile<R>>( properties: Properties, private val type: () -> BlockEntityType<R> ) : Block(properties), EntityBlock { private val ticker: BlockEntityTicker<R> = Ticker() init { Registry.Net.TakeUpgrade.serverListener(::onTakeUpgrade) Registry.Net.Configure.serverListener(::onConfiguration) } private fun onConfiguration(configurePacket: ConfigurePacket, context: NetworkEvent.Context): Boolean { val level = configurePacket.getLevel(configurePacket.world) val blockEntity = level.getBlockEntity(configurePacket.blockPos) if (blockEntity !is ApiTile<*>) return false blockEntity.getConfig().deserializeNBT(configurePacket.config.serializeNBT()) blockEntity.update() Log.info { "Updated configuration: $configurePacket" } return true } /** * Delegates our menu opening to our tile entity */ override fun use( pState: BlockState, pLevel: Level, pPos: BlockPos, pPlayer: Player, pHand: InteractionHand, pHit: BlockHitResult ): InteractionResult { val hand = pPlayer.getItemInHand(InteractionHand.MAIN_HAND).item if (hand == Items.Linker || hand == Items.SpeedUpgrade || hand == Items.EfficiencyUpgrade) return InteractionResult.PASS if (!pLevel.isClientSide) { val tile = pLevel.getBlockEntity(pPos) if (tile is ApiTile<*>) tile.onMenu(pPlayer as ServerPlayer) } return InteractionResult.SUCCESS } protected fun onTakeUpgrade(configurePacket: TakeUpgradePacket, context: NetworkEvent.Context): Boolean { val inv = context.sender?.inventory ?: return false val level = context.sender!!.level val blockEntity = level.getBlockEntity(configurePacket.blockPos) if (blockEntity !is ApiTile<*>) return false val extracted = blockEntity.getConfig().upgrades.extractItem(configurePacket.slot, configurePacket.count, false) ItemHandlerHelper.insertItem(InvWrapper(inv), extracted, false) blockEntity.update() Log.info { "Updated configuration: $configurePacket" } return true } /** * This down casts our ticker to the correct type */ @Suppress("UNCHECKED_CAST") override fun <T : BlockEntity?> getTicker( pLevel: Level, pState: BlockState, pBlockEntityType: BlockEntityType<T> ): BlockEntityTicker<T> { return ticker as BlockEntityTicker<T> } /** * Automatically creates our block entity for us */ override fun newBlockEntity(pPos: BlockPos, pState: BlockState): BlockEntity? = type().create(pPos, pState) }
7
Kotlin
1
1
0a3a6ce6e25762c42dd88e1cbd113a32108633ff
3,864
synth
MIT License
core/runtime/src/main/kotlin/edu/byu/uapi/server/util/DefaultTypeIntrospector.kt
byu-oit
130,911,554
false
null
package edu.byu.uapi.server.util import edu.byu.uapi.server.inputs.create import edu.byu.uapi.spi.UAPITypeError import edu.byu.uapi.spi.dictionary.TypeDictionary import kotlin.reflect.KClass import kotlin.reflect.KParameter import kotlin.reflect.full.primaryConstructor import kotlin.reflect.full.starProjectedType import kotlin.reflect.full.valueParameters class DefaultTypeIntrospector: TypeIntrospector { @Throws(UAPITypeError::class) override fun <Type : Any> introspectForCreate( type: KClass<Type>, typeDictionary: TypeDictionary ): IntrospectedCreateInfo<Type> { val ctor = type.primaryConstructor ?: throw UAPITypeError.create(type, "Missing primary constructor") val analyzedParams = ctor.valueParameters .map { introspectCreateParam(it, typeDictionary) } TODO("not implemented") } private val collectionStar = Collection::class.starProjectedType private fun introspectCreateParam(param: KParameter, typeDictionary: TypeDictionary): CreateParameter { val type = param.type if (DarkMagic.isCollectionType(type) || DarkMagic.isArrayType(type)) { return introspectCollection(param, typeDictionary) } val klass = DarkMagic.typeToClass(type) if (typeDictionary.isScalarType(klass)) { return introspectScalarParam(param, klass, typeDictionary) } return introspectComplexCreateParam(param, typeDictionary) } private fun introspectComplexCreateParam( param: KParameter, typeDictionary: TypeDictionary ): ComplexCreateParameter { TODO("not implemented") } private fun introspectScalarParam( param: KParameter, klass: KClass<*>, typeDictionary: TypeDictionary ): ScalarCreateParameter { TODO("not implemented") } private fun introspectCollection( param: KParameter, typeDictionary: TypeDictionary ): CreateParameter { TODO() } }
16
Kotlin
0
0
1ca0e357a1b00cf11c1e1c9a1b00af4455d6d30c
2,016
kotlin-uapi
Apache License 2.0
reports/src/main/kotlin/com/jakewharton/diffuse/diff/ManifestDiff.kt
usefulness
456,081,262
true
{"Kotlin": 143412}
package com.jakewharton.diffuse.diff import com.github.difflib.DiffUtils import com.github.difflib.UnifiedDiffUtils import com.jakewharton.diffuse.diffuseTable import com.jakewharton.diffuse.format.AndroidManifest internal class ManifestDiff( val oldManifest: AndroidManifest, val newManifest: AndroidManifest, ) { internal val parsedPropertiesChanged = oldManifest.packageName != newManifest.packageName || oldManifest.versionName != newManifest.versionName || oldManifest.versionCode != newManifest.versionCode val diff: List<String> = run { val oldLines = oldManifest.xml.lines() val newLines = newManifest.xml.lines() val diff = DiffUtils.diff(oldLines, newLines) UnifiedDiffUtils.generateUnifiedDiff(AndroidManifest.NAME, AndroidManifest.NAME, oldLines, diff, 1) } val changed = parsedPropertiesChanged || diff.isNotEmpty() } internal fun ManifestDiff.toDetailReport() = buildString { if (parsedPropertiesChanged) { appendLine() appendLine( diffuseTable { header { row("", "old", "new") } row("package", oldManifest.packageName, newManifest.packageName) row("version code", oldManifest.versionCode, newManifest.versionCode) row("version name", oldManifest.versionName, newManifest.versionName) }, ) } if (diff.isNotEmpty()) { appendLine() diff.drop(2) // Skip file name headers .forEach { appendLine(it) } appendLine() } }
19
Kotlin
100
5
6ddb448e783a5868a217ce1b4f4bd2fa5958a9ac
1,469
diffuse
Apache License 2.0
app/src/main/java/com/sample/easyworkmanager/custom/CustomWorkManagerActivity.kt
santosh-kumar-kaushal
292,203,021
false
null
package com.sample.easyworkmanager.custom import android.os.Build import android.os.Bundle import android.util.Log import androidx.annotation.RequiresApi import androidx.lifecycle.Observer import com.library.workmanager.ITaskExecutionCallback import com.library.workmanager.WorkType import com.sample.easyworkmanager.BaseActivity import com.sample.easyworkmanager.R class CustomWorkManagerActivity : BaseActivity(), ITaskExecutionCallback { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Initialize your scheduler. val ownTaskScheduler = OwnTaskScheduler( this, this, this, WorkType.CUSTOM ) // call your request. ownTaskScheduler.scheduleCustomRequest() viewModel.getData.observe(this, Observer { Log.e("MainActivity", it) }) } override fun onTaskExecutionInProgress() { Log.e("CustMainActivity", "onTaskExecutionInProgress...") } override fun onTaskExecutionCompleted() { Log.e("CustMainActivity", "onTaskExecutionCompleted.") } override fun onTaskExecutionFailed() { Log.e("CustMainActivity", "onTaskExecutionFailed.") } @RequiresApi(Build.VERSION_CODES.N) override fun startBackgroundTask() { Log.e("CustMainActivity", "startBackgroundTask.") viewModel.fetchDataFromApi() } }
0
Kotlin
1
1
ff744363d620870aa09ea6e39f388fb7e722fa93
1,485
EasyWorkManager
Apache License 2.0
src/main/kotlin/web/template/metaTemplate.kt
CubeSugarCheese
545,268,622
false
null
package web.template import kotlinx.html.* inline fun HTML.commonPage( title: String, crossinline page: BODY.() -> Unit ) { head { lang = "zh" title(title) meta { name = "referrer" content = "no-referrer" } } body { header() page() footer() } }
0
Kotlin
0
0
6dbaab8771efcfa7692a83606c2087e85a95f82d
350
LK-wap
MIT License
braintrust-java-core/src/test/kotlin/com/braintrustdata/api/models/TopLevelHelloWorldParamsTest.kt
braintrustdata
752,086,100
false
{"Kotlin": 5588048, "Shell": 3637, "Dockerfile": 366}
// File generated from our OpenAPI spec by Stainless. package com.braintrustdata.api.models import java.time.LocalDate import java.time.OffsetDateTime import java.time.format.DateTimeFormatter import java.util.UUID import org.junit.jupiter.api.Test import org.assertj.core.api.Assertions.assertThat import org.apache.hc.core5.http.ContentType import com.braintrustdata.api.core.ContentTypes import com.braintrustdata.api.core.JsonNull import com.braintrustdata.api.core.JsonString import com.braintrustdata.api.core.JsonValue import com.braintrustdata.api.core.MultipartFormValue import com.braintrustdata.api.models.* import com.braintrustdata.api.models.TopLevelHelloWorldParams class TopLevelHelloWorldParamsTest { @Test fun createTopLevelHelloWorldParams() { TopLevelHelloWorldParams.builder().build() } }
1
Kotlin
0
2
515b9f0161f26c9de6880936bf5410e23fc2c40a
832
braintrust-java
Apache License 2.0
idea/testData/inspectionsLocal/liftOut/ifToAssignment/multipleAssignments.kt
JakeWharton
99,388,807
true
null
// PROBLEM: none fun foo(x: Boolean): String { var s = "" <caret>if (x) { s += "a" s += "b" } else { s += "c" } return s }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
167
kotlin
Apache License 2.0
app/src/main/java/com/whywhom/soft/whyradiobox/adapter/ItunesPodcastListAdapter.kt
whywhom
232,916,639
false
null
package com.whywhom.soft.whyradiobox.adapter import android.app.Activity import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import com.squareup.picasso.Picasso import com.squareup.picasso.RequestCreator import com.whywhom.soft.whyradiobox.R import com.whywhom.soft.whyradiobox.model.Entry import com.whywhom.soft.whyradiobox.model.PodcastSearchResult import java.lang.ref.WeakReference import java.util.* /** * Created by wuhaoyong on 2020-02-10. */ class ItunesPodcastListAdapter(mainActivity: Activity): BaseAdapter() { private var mainActivityRef: WeakReference<Activity>? = WeakReference<Activity>(mainActivity) private val data: MutableList<PodcastSearchResult> = ArrayList<PodcastSearchResult>() fun updateData(newData: List<PodcastSearchResult>) { data.clear() data.addAll(newData!!) notifyDataSetChanged() } override fun getCount(): Int { return data.size } override fun getItem(position: Int): PodcastSearchResult { return data[position] } override fun getItemId(position: Int): Long { return 0 } override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? { var convertView = convertView val holder: Holder if (convertView == null) { convertView = View.inflate(mainActivityRef!!.get(), R.layout.podcast_grid_item, null) holder = Holder() holder.imageView = convertView.findViewById(R.id.itemImage) convertView.tag = holder } else { holder = convertView.tag as Holder } val item: PodcastSearchResult = getItem(position) holder.imageView!!.contentDescription = item.title.toString() val request: RequestCreator = Picasso.get().load(item.imageUrl).placeholder(R.drawable.rss_96) request.fit() .centerCrop() .into(holder.imageView) return convertView } internal class Holder { var imageView: ImageView? = null } }
0
Kotlin
0
2
8956e4e2e7770d31f247527d57cfa23d368965ff
2,129
whyradiobox
MIT License
router-protobuf/src/test/kotlin/io/moia/router/proto/ProtoDeserializationHandlerTest.kt
moia-oss
178,225,288
false
null
package io.moia.router.proto import com.amazonaws.services.lambda.runtime.events.APIGatewayProxyRequestEvent import io.moia.router.withHeader import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test internal class ProtoDeserializationHandlerTest { @Test fun `Deserializer should not support if the content type of the input is null`() { assertFalse(ProtoDeserializationHandler().supports(APIGatewayProxyRequestEvent())) } @Test fun `Deserializer should not support if the content type of the input is json`() { assertFalse(ProtoDeserializationHandler().supports(APIGatewayProxyRequestEvent().withHeader("content-type", "application/json"))) } @Test fun `Deserializer should support if the content type of the input is protobuf`() { assertTrue(ProtoDeserializationHandler().supports(APIGatewayProxyRequestEvent().withHeader("content-type", "application/x-protobuf"))) assertTrue(ProtoDeserializationHandler().supports(APIGatewayProxyRequestEvent().withHeader("content-type", "application/vnd.moia.v1+x-protobuf"))) } }
6
null
5
20
c600e15889c01fd0ee962ff855910af094e657ea
1,171
lambda-kotlin-request-router
Apache License 2.0
tauri-plugin-vpnservice/android/src/main/java/TauriVpnService.kt
EasyTier
698,328,708
false
{"Rust": 845851, "Vue": 31423, "TypeScript": 22214, "Kotlin": 12430, "Shell": 9077, "Swift": 1603, "JavaScript": 1142, "CSS": 847, "HTML": 364}
package com.plugin.vpnservice import android.content.Intent import android.net.VpnService import android.os.Build import android.os.ParcelFileDescriptor import android.os.Bundle import java.net.InetAddress import java.util.Arrays import app.tauri.plugin.JSObject class TauriVpnService : VpnService() { companion object { @JvmField var triggerCallback: (String, JSObject) -> Unit = { _, _ -> } @JvmField var self: TauriVpnService? = null const val IPV4_ADDR = "IPV4_ADDR" const val ROUTES = "ROUTES" const val DNS = "DNS" const val DISALLOWED_APPLICATIONS = "DISALLOWED_APPLICATIONS" const val MTU = "MTU" } private lateinit var vpnInterface: ParcelFileDescriptor override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { println("vpn on start command ${intent?.getExtras()} $intent") var args = intent?.getExtras() vpnInterface = createVpnInterface(args) println("vpn created ${vpnInterface.fd}") var event_data = JSObject() event_data.put("fd", vpnInterface.fd) triggerCallback("vpn_service_start", event_data) return START_STICKY } override fun onCreate() { super.onCreate() self = this println("vpn on create") } override fun onDestroy() { println("vpn on destroy") super.onDestroy() disconnect() self = null } override fun onRevoke() { println("vpn on revoke") super.onRevoke() disconnect() self = null } private fun disconnect() { if (self == this && this::vpnInterface.isInitialized) { triggerCallback("vpn_service_stop", JSObject()) vpnInterface.close() } } private fun createVpnInterface(args: Bundle?): ParcelFileDescriptor { var builder = Builder() .setSession("TauriVpnService") .setBlocking(false) var mtu = args?.getInt(MTU) ?: 1500 var ipv4Addr = args?.getString(IPV4_ADDR) ?: "10.126.126.1/24" var dns = args?.getString(DNS) ?: "192.168.3.11" var routes = args?.getStringArray(ROUTES) ?: emptyArray() var disallowedApplications = args?.getStringArray(DISALLOWED_APPLICATIONS) ?: emptyArray() println("vpn create vpn interface. mtu: $mtu, ipv4Addr: $ipv4Addr, dns:" + "$dns, routes: ${java.util.Arrays.toString(routes)}," + "disallowedApplications: ${java.util.Arrays.toString(disallowedApplications)}") val ipParts = ipv4Addr.split("/") if (ipParts.size != 2) throw IllegalArgumentException("Invalid IP addr string") builder.addAddress(ipParts[0], ipParts[1].toInt()) builder.setMtu(mtu) builder.addDnsServer(dns) for (route in routes) { val ipParts = route.split("/") if (ipParts.size != 2) throw IllegalArgumentException("Invalid IP addr string") builder.addRoute(ipParts[0], ipParts[1].toInt()) } for (app in disallowedApplications) { builder.addDisallowedApplication(app) } return builder.also { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { it.setMetered(false) } } .establish() ?: throw IllegalStateException("Failed to init VpnService") } }
30
Rust
82
968
b6fb7ac9627e20d2b0a105be98d72147f3d2367e
3,441
EasyTier
Apache License 2.0
kore/src/main/kotlin/strings/impls/ComparableForStringCompare2.kt
ksharp-lang
573,931,056
false
{"Kotlin": 1496266, "Java": 53036, "TypeScript": 3203}
package strings.impls import org.ksharp.common.cast import org.ksharp.ir.Call import org.ksharp.ir.Equal import org.ksharp.ir.Greater import org.ksharp.ir.Less class ComparableForStringCompare2 : Call { override fun execute(vararg arguments: Any): Any { val (left, right) = arguments val compareTo = left.cast<String>().compareTo(right.cast()) return when { compareTo < 0 -> Less compareTo > 0 -> Greater else -> Equal } } }
3
Kotlin
0
0
da3228ddcb9c0491db2caac4a07c16ca914f2903
503
ksharp-kt
Apache License 2.0
src/main/kotlin/no/nav/sosialhjelp/innsyn/digisosapi/test/DigisosApiTestClientImpl.kt
navikt
184,267,271
false
{"Kotlin": 775621, "Dockerfile": 427}
package no.nav.sosialhjelp.innsyn.digisosapi.test import no.nav.sosialhjelp.api.fiks.DigisosSak import no.nav.sosialhjelp.api.fiks.exceptions.FiksClientException import no.nav.sosialhjelp.api.fiks.exceptions.FiksServerException import no.nav.sosialhjelp.innsyn.app.exceptions.BadStateException import no.nav.sosialhjelp.innsyn.app.maskinporten.MaskinportenClient import no.nav.sosialhjelp.innsyn.digisosapi.FiksClientImpl import no.nav.sosialhjelp.innsyn.digisosapi.VedleggMetadata import no.nav.sosialhjelp.innsyn.digisosapi.test.dto.DigisosApiWrapper import no.nav.sosialhjelp.innsyn.digisosapi.test.dto.FilOpplastingResponse import no.nav.sosialhjelp.innsyn.utils.IntegrationUtils.BEARER import no.nav.sosialhjelp.innsyn.utils.logger import no.nav.sosialhjelp.innsyn.utils.objectMapper import no.nav.sosialhjelp.innsyn.vedlegg.FilForOpplasting import org.springframework.context.annotation.Profile import org.springframework.http.HttpHeaders.AUTHORIZATION import org.springframework.http.MediaType import org.springframework.stereotype.Component import org.springframework.util.LinkedMultiValueMap import org.springframework.web.reactive.function.BodyInserters import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClientResponseException import org.springframework.web.reactive.function.client.bodyToMono /** * Brukes kun i dev eller ved lokal testing mot fiks-test */ @Profile("!prod-fss") @Component class DigisosApiTestClientImpl( private val fiksWebClient: WebClient, private val digisosApiTestWebClient: WebClient, private val maskinportenClient: MaskinportenClient, private val fiksClientImpl: FiksClientImpl, ) : DigisosApiTestClient { private val testbrukerNatalie = System.getenv("TESTBRUKER_NATALIE") ?: "11111111111" override fun oppdaterDigisosSak( fiksDigisosId: String?, digisosApiWrapper: DigisosApiWrapper, ): String? { var id = fiksDigisosId if (fiksDigisosId == null || fiksDigisosId == "001" || fiksDigisosId == "002" || fiksDigisosId == "003") { id = opprettDigisosSak() log.info("Laget ny digisossak: $id") } return digisosApiTestWebClient.post() .uri("/digisos/api/v1/11415cd1-e26d-499a-8421-751457dfcbd5/$id") .header(AUTHORIZATION, BEARER + maskinportenClient.getToken()) .body(BodyInserters.fromValue(objectMapper.writeValueAsString(digisosApiWrapper))) .retrieve() .bodyToMono<String>() .onErrorMap(WebClientResponseException::class.java) { e -> log.warn("Fiks - oppdaterDigisosSak feilet - ${e.statusCode} ${e.statusText}", e) when { e.statusCode.is4xxClientError -> FiksClientException(e.statusCode.value(), e.message, e) else -> FiksServerException(e.statusCode.value(), e.message, e) } } .block() .also { log.info("Postet DigisosSak til Fiks og fikk response: $it") } ?: id } // Brukes for å laste opp Pdf-er fra test-fagsystem i q-miljø override fun lastOppNyeFilerTilFiks( files: List<FilForOpplasting>, soknadId: String, ): List<String> { val body = LinkedMultiValueMap<String, Any>() files.forEachIndexed { fileId, file -> val vedleggMetadata = VedleggMetadata(file.filnavn, file.mimetype, file.storrelse) body.add( "vedleggSpesifikasjon:$fileId", fiksClientImpl.createHttpEntityOfString(fiksClientImpl.serialiser(vedleggMetadata), "vedleggSpesifikasjon:$fileId"), ) body.add("dokument:$fileId", fiksClientImpl.createHttpEntityOfFile(file, "dokument:$fileId")) } val opplastingResponseList = digisosApiTestWebClient.post() .uri("/digisos/api/v1/11415cd1-e26d-499a-8421-751457dfcbd5/$soknadId/filer") .header(AUTHORIZATION, BEARER + maskinportenClient.getToken()) .contentType(MediaType.MULTIPART_FORM_DATA) .body(BodyInserters.fromMultipartData(body)) .retrieve() .bodyToMono<List<FilOpplastingResponse>>() .onErrorMap(WebClientResponseException::class.java) { e -> log.warn("Fiks - Opplasting av filer feilet - ${e.statusCode} ${e.statusText}", e) when { e.statusCode.is4xxClientError -> FiksClientException(e.statusCode.value(), e.message, e) else -> FiksServerException(e.statusCode.value(), e.message, e) } } .block() ?: throw BadStateException("Ingen feil, men heller ingen opplastingResponseList") log.info("Filer sendt til Fiks") return opplastingResponseList.map { it.dokumentlagerDokumentId } } override fun hentInnsynsfil( fiksDigisosId: String, token: String, ): String? { try { val soknad = fiksWebClient.get() .uri("/digisos/api/v1/soknader/$fiksDigisosId") .accept(MediaType.APPLICATION_JSON) .header(AUTHORIZATION, token) .retrieve() .bodyToMono(DigisosSak::class.java) .onErrorMap(WebClientResponseException::class.java) { e -> log.warn("Fiks - Nedlasting av søknad feilet - ${e.statusCode} ${e.statusText}", e) when { e.statusCode.is4xxClientError -> FiksClientException(e.statusCode.value(), e.message, e) else -> FiksServerException(e.statusCode.value(), e.message, e) } } .block() ?: throw BadStateException("Ingen feil, men heller ingen soknad") val digisosSoker = soknad.digisosSoker ?: throw BadStateException("Soknad mangler digisosSoker") return fiksWebClient.get() .uri("/digisos/api/v1/soknader/$fiksDigisosId/dokumenter/${digisosSoker.metadata}") .accept(MediaType.APPLICATION_JSON) .header(AUTHORIZATION, token) .retrieve() .bodyToMono(String::class.java) .onErrorMap(WebClientResponseException::class.java) { e -> log.warn("Fiks - Nedlasting av innsynsfil feilet - ${e.statusCode} ${e.statusText}", e) when { e.statusCode.is4xxClientError -> FiksClientException(e.statusCode.value(), e.message, e) else -> FiksServerException(e.statusCode.value(), e.message, e) } } .block() } catch (e: RuntimeException) { return null } } fun opprettDigisosSak(): String? { val response = digisosApiTestWebClient.post() .uri("/digisos/api/v1/11415cd1-e26d-499a-8421-751457dfcbd5/ny?sokerFnr=$testbrukerNatalie") .header(AUTHORIZATION, BEARER + maskinportenClient.getToken()) .body(BodyInserters.fromValue("")) .retrieve() .bodyToMono<String>() .onErrorMap(WebClientResponseException::class.java) { e -> log.warn("Fiks - opprettDigisosSak feilet - ${e.statusCode} ${e.statusText}", e) when { e.statusCode.is4xxClientError -> FiksClientException(e.statusCode.value(), e.message, e) else -> FiksServerException(e.statusCode.value(), e.message, e) } } .block() log.info("Opprettet sak hos Fiks. Digisosid: $response") return response?.replace("\"", "") } companion object { private val log by logger() } }
5
Kotlin
0
0
c1fb303b4fb1e06b062b92be0696ad7531dc1df5
8,044
sosialhjelp-innsyn-api
MIT License
lang/test/org/partiql/lang/util/AnnoationInterpolationConstants.kt
partiql
186,474,394
false
null
package org.partiql.lang.util /** * Simplifies the syntax of adding the `$partiql_bag::` annotation inside of a raw string literal. * * Instead of `"""${'$'}partiql_bag::[1, 2, 3] """` we can simply type `"""$partiql_bag::[1, 2, 3]"""`. */ internal const val partiql_bag = "\$partiql_bag" /** * Simplifies the syntax of adding the `partiql_missing::` annotation inside of a raw string literal. * * Instead of `"""${'$'}partiql_missing::null """` we can simply type `"""$partiql_missing::null"""`. */ internal const val partiql_missing = "\$partiql_missing"
188
null
55
519
ff041b28c6db53853c3b370690246bc01913a400
567
partiql-lang-kotlin
Apache License 2.0
data/src/main/java/com/msg/sms/data/remote/datasource/authentication/RemoteAuthenticationDataSource.kt
GSM-MSG
625,706,722
false
{"Kotlin": 733672}
package com.msg.sms.data.remote.datasource.authentication import com.msg.sms.data.remote.dto.athentication.request.SubmitAuthenticationFormRequest import com.msg.sms.data.remote.dto.athentication.response.AuthenticationFormResponse import com.msg.sms.data.remote.dto.athentication.response.VerifyAuthenticationResponse import kotlinx.coroutines.flow.Flow interface RemoteAuthenticationDataSource { suspend fun fetchAuthenticationForm(): Flow<AuthenticationFormResponse> suspend fun submitAuthenticationForm(formData: SubmitAuthenticationFormRequest): Flow<Unit> suspend fun verifyAuthentication(): Flow<VerifyAuthenticationResponse> }
11
Kotlin
1
16
d279f3f1266caac16ce2e5c2230e13d7e078a37f
650
SMS-Android
MIT License
src/main/java/com/nativedevps/drive/DriveQueryBuilder.kt
merlinJeyakumar
660,900,490
false
null
package com.nativedevps.drive /* * mimeType = 'application/vnd.google-apps.spreadsheet' and name contains '${applicationName}' and trashed = false * docs: https://developers.google.com/drive/api/guides/search-files * */ class DriveQueryBuilder { private var query: StringBuilder = StringBuilder() fun setMime(mime: String): DriveQueryBuilder { query.append("mimeType = '$mime'") return this } fun and(): DriveQueryBuilder { query.append(" and ") return this } fun contains(field: String = "name", text: String): DriveQueryBuilder { query.append("$field contains '$text'") return this } fun trashed(boolean: Boolean): DriveQueryBuilder { query.append("trashed = $boolean") return this } fun clear(): DriveQueryBuilder { query.clear() return this } fun build(): String { return query.toString() } override fun toString(): String { return query.toString() } } object DriveMimeTypes { val mimeSpreadsheet = "application/vnd.google-apps.spreadsheet" }
0
Kotlin
0
0
44f0d53f5f8e5e38e85dad80f5351dbc6f72b132
1,115
JGoogleAuth
MIT License
android/app/src/main/kotlin/com/example/health_heaven/MainActivity.kt
jad-debugs
306,993,052
false
{"Dart": 11292, "HTML": 1127, "Swift": 404, "Kotlin": 130, "Objective-C": 38}
package com.example.health_heaven import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
Dart
0
0
3418f2ed4e9cf2d6dcc572c5f4263c4a140c83f0
130
health_haven
MIT License
ontrack-extension-github/src/main/java/net/nemerosa/ontrack/extension/github/ingestion/support/IngestionImageServiceExceptions.kt
nemerosa
19,351,480
false
null
package net.nemerosa.ontrack.extension.github.ingestion.support import net.nemerosa.ontrack.model.exceptions.InputException class IngestionImageProtocolUnsupportedException(protocol: String, ref: String) : InputException( """Image protocol not supported: $protocol in image ref $ref""" ) class IngestionImageRefFormatException(ref: String, message: String) : InputException( """Image ref format is incorrect. $message: $ref""" ) class IngestionImagePNGException(ref: String) : InputException( """Only PNG images are supported: $ref""" ) class IngestionImageMissingGitException(ref: String, message: String) : InputException( """Project is not configured. $message: $ref""" ) class IngestionImageNotFoundException(ref: String) : InputException( """Image not found: $ref""" )
57
Kotlin
27
97
7c71a3047401e088ba0c6d43aa3a96422024857f
800
ontrack
MIT License
app/src/main/java/ru/luckycactus/steamroulette/presentation/ui/widget/card_stack/CardStackLayoutManager.kt
luckycactus
196,364,852
false
null
package ru.luckycactus.steamroulette.presentation.ui.widget.card_stack import android.view.View import android.view.ViewGroup import android.view.animation.DecelerateInterpolator import androidx.recyclerview.widget.RecyclerView import kotlin.math.absoluteValue class CardStackLayoutManager : RecyclerView.LayoutManager() { var maxChildrenCount: Int = 3 set(value) { field = maxOf(1, value) } var scaleGap: Float = 0.2f set(value) { field = value.coerceIn(0f, 1f) } private val interpolator = DecelerateInterpolator() override fun generateDefaultLayoutParams(): RecyclerView.LayoutParams = RecyclerView.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT ) override fun onLayoutChildren(recycler: RecyclerView.Recycler, state: RecyclerView.State) { detachAndScrapAttachedViews(recycler) val childCount = minOf(maxChildrenCount, state.itemCount) for (i in childCount - 1 downTo 0) { val v = recycler.getViewForPosition(i) addView(v) measureChildWithMargins(v, 0, 0) layoutDecorated( v, paddingLeft, paddingTop, width - paddingRight, height - paddingBottom ) setChildGaps(v, i, 0f) } } fun setChildGaps(view: View, layer: Int, swipeProgress: Float) { var scale = 1f if (layer > 0) scale -= (layer - interpolator.getInterpolation(swipeProgress.absoluteValue)) * scaleGap view.scaleX = scale view.scaleY = scale } }
0
Kotlin
0
5
285530179743f1274595eebb07211cd470ef7928
1,709
steam-roulette
Apache License 2.0
app/src/main/java/com/bwidlarz/speechcalculator/data/SharedPrefSettings.kt
Okelm
100,065,700
false
null
package com.bwidlarz.speechcalculator.data import android.content.Context import android.content.SharedPreferences class SharedPrefSettings(context: Context) : Settings { private val sharedPreferences: SharedPreferences = context.getSharedPreferences("app", Context.MODE_PRIVATE) override var tutorialShownId: Int get() = sharedPreferences.getInt(TUTORIAL_SHOWN, 0) set(value) { sharedPreferences.edit().putInt(TUTORIAL_SHOWN, value).apply() } override var lastExpression: String get() = sharedPreferences.getString(LAST_KNOWN_EXPRESSION, "5 + 5") set(value) { sharedPreferences.edit().putString(LAST_KNOWN_EXPRESSION, value).apply() } override var lastEvaluation: String get() = sharedPreferences.getString(LAST_KNOWN_EVALUATION, "10") set(value) { sharedPreferences.edit().putString(LAST_KNOWN_EVALUATION, value).apply() } companion object { const val TUTORIAL_SHOWN = "tutorial_shown" const val LAST_KNOWN_EXPRESSION = "last_known_expression" const val LAST_KNOWN_EVALUATION = "last_known_evaluation" } }
0
Kotlin
0
0
a75e438610e7c7c10442ca93838cd83d06139ee8
1,171
SpeechCalculator
MIT License
app/src/main/java/com/jrk/mood4food/recipes/add_mod/IngredientAdapter.kt
Honrix
369,880,093
false
null
package com.jrk.mood4food.recipes.add_mod import android.app.Activity import android.app.LauncherActivity.ListItem import android.text.Editable import android.text.TextWatcher import android.util.Log import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.EditText import android.widget.ImageView import com.jrk.mood4food.R class IngredientAdapter(private var ingredients: Array<Ingredient>, private val context: Activity) : ArrayAdapter<Ingredient>(context, R.layout.activity_edit_recipe, ingredients) { override fun getView(position: Int, view: View?, parent: ViewGroup): View { val inflater = context.layoutInflater val rowView = inflater.inflate(R.layout.adapter_edit_ingredient, null, true) val ingredient_name = rowView.findViewById(R.id.input_ingredient) as EditText val ingredient_amount = rowView.findViewById(R.id.input_amount) as EditText val remove_ingredient = rowView.findViewById(R.id.remove_ingredient) as ImageView val listItem = getItem(position) ingredient_name.setText(ingredients[position].name) ingredient_amount.setText(ingredients[position].amount) //Update Name on Change ingredient_name.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) { } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { listItem!!.name = s.toString() } }) //Update Amount on change ingredient_amount.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(p0: Editable?) { } override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { listItem!!.amount = s.toString() } }) remove_ingredient.setOnClickListener{ listItem!!.amount = "" listItem.name = "" ingredient_amount.setText(listItem.amount) ingredient_name.setText(listItem.name) } return rowView } }
0
null
0
0
fc086543ef8993e5e43d070d8754f60c94bda003
2,395
Mood4Food
MIT License
core/src/main/java/com/mohfahmi/storyapp/core/utils/Helper.kt
MohFahmi27
535,535,970
false
{"Kotlin": 147264}
package com.mohfahmi.storyapp.core.utils import android.content.ContentResolver import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.Matrix import android.net.Uri import android.os.Environment import android.view.View import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.MultipartBody import okhttp3.RequestBody.Companion.asRequestBody import org.json.JSONObject import retrofit2.Response import java.io.* import java.text.SimpleDateFormat import java.util.* fun Response<out Any>.getErrorMessage(): String { val errorBody = JSONObject(this.errorBody()?.charStream()?.readText() ?: "") return errorBody.get("message") as String } fun View.visible() { this.visibility = View.VISIBLE } fun View.invisible() { this.visibility = View.INVISIBLE } fun String.capitalize(): String = this.replaceFirstChar { it.uppercase() } val timeStamp: String = SimpleDateFormat( "dd-MM-yyyy", Locale.US ).format(System.currentTimeMillis()) fun createCustomTempFile(context: Context): File { val storageDir: File? = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) return File.createTempFile(timeStamp, ".jpg", storageDir) } fun rotateBitmap(bitmap: Bitmap, isBackCamera: Boolean = false): Bitmap { val matrix = Matrix() return if (isBackCamera) { matrix.postRotate(90f) Bitmap.createBitmap( bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true ) } else { matrix.postRotate(-90f) matrix.postScale(-1f, 1f, bitmap.width / 2f, bitmap.height / 2f) Bitmap.createBitmap( bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true ) } } fun File.toMultipartBody(key: String): MultipartBody.Part = MultipartBody.Part.createFormData( key, this.name, this.asRequestBody("image/*".toMediaTypeOrNull()) ) fun uriToFile(selectedImg: Uri, context: Context): File { val contentResolver: ContentResolver = context.contentResolver val myFile = createCustomTempFile(context) val inputStream = contentResolver.openInputStream(selectedImg) as InputStream val outputStream: OutputStream = FileOutputStream(myFile) val buf = ByteArray(1024) var len: Int while (inputStream.read(buf).also { len = it } > 0) outputStream.write(buf, 0, len) outputStream.close() inputStream.close() return myFile } fun reduceFileImage(file: File): File { val bitmap = BitmapFactory.decodeFile(file.path) var compressQuality = 100 var streamLength: Int do { val bmpStream = ByteArrayOutputStream() bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, bmpStream) val bmpPicByteArray = bmpStream.toByteArray() streamLength = bmpPicByteArray.size compressQuality -= 5 } while (streamLength > 1000000) bitmap.compress(Bitmap.CompressFormat.JPEG, compressQuality, FileOutputStream(file)) return file }
0
Kotlin
0
3
33e94844c52da1ad24f68e204dc0e220d564c4c4
3,164
MyIntermediateAndroidSubmission
Apache License 2.0
attribution/src/test/java/com/affise/attribution/parameters/CountryProviderTest.kt
affise
496,592,599
false
null
package com.affise.attribution.parameters import com.google.common.truth.Truth import org.junit.Test import java.util.Locale /** * Test for [CountryProvider] */ class CountryProviderTest { @Test fun provide() { Locale.setDefault(Locale("lang", "COUNTRY")) val countryProvider = CountryProvider() val actual = countryProvider.provide() Truth.assertThat(actual).isEqualTo("COUNTRY") } }
0
null
0
5
ab7d393c6583208e33cef9e10e01ba9dd752bbcb
432
sdk-android
MIT License
app/src/main/java/com/example/cuisine/ShowLinkActivity.kt
P4NK4J
197,951,254
false
null
package com.example.cuisine import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_show_link.* class ShowLinkActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_show_link) var extras = intent.extras if(extras != null) { var link = extras.get("link") // the link which we passes in intent inside adapter webViewId.loadUrl(link.toString()) // accessing web using web view } } }
1
null
1
3
f354eb5b37eb1c49210c8535740cd83ec4972a68
631
android_kotlin_Cuisine_app
MIT License
app/src/main/java/com/example/android/droidcafeinput/OrderActivity.kt
saharEnhance
258,701,018
false
null
/* * Copyright (C) 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.droidcafeinput import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.View import android.widget.* import android.widget.AdapterView.OnItemSelectedListener /** * This activity handles radio buttons for choosing a delivery method for an * order, a spinner for setting the label for a phone number, and EditText input * controls. */ class OrderActivity : AppCompatActivity(), OnItemSelectedListener { /** * Sets the content view to activity_order, and gets the intent and its * data. Also creates an array adapter and layout for a spinner. * * @param savedInstanceState Saved instance state bundle. */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_order) // Get the intent and its data. val intent = intent val message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE) val textView = findViewById<TextView>(R.id.order_textview) textView.text = message // Create the spinner. val spinner = findViewById<Spinner>(R.id.label_spinner) if (spinner != null) { spinner.onItemSelectedListener = this } // Create an ArrayAdapter using the string array and default spinner // layout. val adapter = ArrayAdapter.createFromResource( this, R.array.labels_array, android.R.layout.simple_spinner_item) // Specify the layout to use when the list of choices appears. adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) // Apply the adapter to the spinner. if (spinner != null) { spinner.adapter = adapter } } /** * Checks which radio button was clicked and displays a toast message to * show the choice. * * @param view The radio button view. */ fun onRadioButtonClicked(view: View) { // Is the button now checked? val checked = (view as RadioButton).isChecked when (view.getId()) { R.id.sameday -> if (checked) // Same day service displayToast(getString( R.string.same_day_messenger_service)) R.id.nextday -> if (checked) // Next day delivery displayToast(getString( R.string.next_day_ground_delivery)) R.id.pickup -> if (checked) // Pick up displayToast(getString( R.string.pick_up)) else -> { } } } /** * Displays the actual message in a toast message. * * @param message Message to display. */ fun displayToast(message: String?) { Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show() } // Interface callback for when any spinner item is selected. override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) { val spinnerLabel = adapterView.getItemAtPosition(i).toString() displayToast(spinnerLabel) } // Interface callback for when no spinner item is selected. override fun onNothingSelected(adapterView: AdapterView<*>?) { // Do nothing. } }
0
Kotlin
0
0
8d35e258b61fdcbabaab615ea18648bb287fef07
4,001
MenusAndDialogsLabcode
Apache License 2.0
BaseExtend/src/main/java/com/chen/baseextend/widget/LikeImageView.kt
chen397254698
268,411,455
false
null
package com.chen.baseextend.widget import android.content.Context import android.util.AttributeSet import android.view.animation.AnimationUtils import androidx.appcompat.widget.AppCompatImageView import com.chen.baseextend.R /** * @author alan * @date 2019/3/28 * 点赞小图标 */ class LikeImageView(context: Context, attrs: AttributeSet?) : AppCompatImageView(context, attrs) { private val mAnimation by lazy { AnimationUtils.loadAnimation(context, R.anim.like_click) } private var mCurrentLikeStatus = LikeStatus.UN_LIKE public fun startAnimation() { clearAnimation() startAnimation(mAnimation) } public fun setLikeStatus(status: LikeStatus) { this.mCurrentLikeStatus = status } enum class LikeStatus(var status: String) { // 已点赞 LIKING("LIKING"), // 未点赞 UN_LIKE("UN_LIKE") } }
1
Kotlin
14
47
85ffc5e307c6171767e14bbfaf992b8d62ec1cc6
887
EasyAndroid
Apache License 2.0
BaseExtend/src/main/java/com/chen/baseextend/widget/LikeImageView.kt
chen397254698
268,411,455
false
null
package com.chen.baseextend.widget import android.content.Context import android.util.AttributeSet import android.view.animation.AnimationUtils import androidx.appcompat.widget.AppCompatImageView import com.chen.baseextend.R /** * @author alan * @date 2019/3/28 * 点赞小图标 */ class LikeImageView(context: Context, attrs: AttributeSet?) : AppCompatImageView(context, attrs) { private val mAnimation by lazy { AnimationUtils.loadAnimation(context, R.anim.like_click) } private var mCurrentLikeStatus = LikeStatus.UN_LIKE public fun startAnimation() { clearAnimation() startAnimation(mAnimation) } public fun setLikeStatus(status: LikeStatus) { this.mCurrentLikeStatus = status } enum class LikeStatus(var status: String) { // 已点赞 LIKING("LIKING"), // 未点赞 UN_LIKE("UN_LIKE") } }
1
Kotlin
14
47
85ffc5e307c6171767e14bbfaf992b8d62ec1cc6
887
EasyAndroid
Apache License 2.0
feature/movie-details/impl/src/test/java/br/com/moov/moviedetails/data/DefaultMovieDetailRepositoryTest.kt
alex-tavella
79,517,727
false
null
/* * Copyright 2021 <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 br.com.moov.moviedetails.data import br.com.moov.core.result.Result import br.com.moov.moviedetails.domain.GetMovieDetailError import br.com.moov.moviedetails.domain.MovieDetail import br.com.moov.moviedetails.testdoubles.TestMovieDetailDataSource import kotlinx.coroutines.runBlocking import org.junit.Assert.assertEquals import org.junit.Test class DefaultMovieDetailRepositoryTest { private val movies: List<MovieDetail> = listOf( MovieDetail( id = 123, title = "Lord of the Rings" ) ) private val repository = DefaultMovieDetailRepository(TestMovieDetailDataSource(movies)) @Test fun getMovieDetail_exists_returnsMovieDetail() = runBlocking { val actual = repository.getMovieDetail(123) assertEquals(Result.Ok(MovieDetail(123, "Lord of the Rings")), actual) } @Test fun getMovieDetail_notFound_returnsNull() = runBlocking { val actual = repository.getMovieDetail(456) assertEquals(Result.Err(GetMovieDetailError), actual) } }
3
Kotlin
1
0
5f14670bddfbbdc0da1a3d394193dc87f9ea1996
1,642
MooV
Apache License 2.0
POEHelper/app/src/test/java/com/resdev/poehelper/UtilTest.kt
AlexejSrc
254,309,271
false
null
package com.resdev.poehelper import android.content.Context import com.resdev.poehelper.di.DaggerTestComponent import com.resdev.poehelper.model.retrofit.PoeLeagueLoading import com.resdev.poehelper.utils.* import kotlinx.coroutines.runBlocking import org.junit.Test import org.mockito.Mockito.mock import javax.inject.Inject class UtilTest { lateinit var leagues: Array<String> @Inject lateinit var poeLeagueLoading: PoeLeagueLoading val languages = arrayListOf("en", "ru", "ko", "ge", "br") init { runBlocking { DaggerTestComponent.create().inject(this@UtilTest) leagues = poeLeagueLoading.loadLeagues().getEditedLeagues() ?: throw Exception() } } @Test fun arrayWithFirstNullTest(){ val array = listOf(null, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0) val dataSet = getGraphDataset(array, 106.0, true, mock(Context::class.java)) assert(dataSet != null) } @Test fun isBlackDark(){ assert(!isColorLight("00000000")) } @Test fun isWhiteDark(){ assert(isColorLight("FFFFFFFF")) } @Test fun getCalendar(){ println("Last 7 days: ${getDaysSet()}") } @Test fun testUrlGenerators(){ println("Urls generating test") for (i in languages){ for (j in leagues){ println(generatePoeMarketExchangeUrl(j, i)) println(generatePoeMarketTradeUrl(j, i)) } } } }
0
Kotlin
0
0
36f552425743db80cb005b0cc0e46380955b3ac2
1,480
POEHelper
MIT License
PruebaFirebase/app/src/main/java/com/example/pruebatema5/PantallaCRUD.kt
MiguelParamos
450,413,851
false
{"Kotlin": 41422}
package com.example.pruebatema5 import adapters_holders.TelefonoAdapter import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.CheckBox import android.widget.EditText import androidx.recyclerview.widget.RecyclerView import clases.Telefono import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore open abstract class PantallaCRUD : AppCompatActivity() { protected val botonInsertar: Button by lazy { findViewById(R.id.botonInsertar) } protected val campoModelo: EditText by lazy { findViewById(R.id.campoModelo) } protected val campoNuevo: CheckBox by lazy { findViewById(R.id.campoNuevo) } protected val campoCuandoComprado: EditText by lazy { findViewById(R.id.campoCuandoComprado) } protected val campoPrecio: EditText by lazy { findViewById(R.id.campoPrecio) } protected val lista: RecyclerView by lazy { findViewById(R.id.lista) }; protected lateinit var adapter: TelefonoAdapter protected var listaTelefonos: ArrayList<Telefono> =ArrayList<Telefono>() //PropietarioActual almacena el propietario para el telefono // que se va a insertar/Modificar protected var propietarioActual:String?=null; protected var modeloAnterior:String?=null; fun rellenarCampos( mod:String, prec:Float ,cc:String, nuevo:Boolean,prop:String){ modeloAnterior=mod campoModelo.setText(mod) campoCuandoComprado.setText(cc) campoNuevo.isChecked=nuevo campoPrecio.setText(""+prec) botonInsertar.text=resources.getString(R.string.editar) this.propietarioActual=prop; } fun actualizarAdapter(){ this.consultarBD() adapter.notifyDataSetChanged() } abstract fun consultarBD(); abstract fun borrarElementoBD(pk:String); override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } }
0
Kotlin
0
0
80b4363abc698b2a0716e7f43ccf0f67c896540e
1,977
pruebasTema5PMDM2122
Apache License 2.0
2024/Azure/cosmosdbJava/src/main/kotlin/Main.kt
kyoya-p
253,926,918
false
{"Kotlin": 905678, "JavaScript": 83182, "HTML": 55744, "TypeScript": 53381, "Java": 30096, "C++": 28982, "CMake": 20831, "Dart": 14886, "Shell": 7841, "Batchfile": 6182, "CSS": 5729, "Dockerfile": 3601, "C": 2974, "Swift": 1622, "PowerShell": 234, "Objective-C": 78}
fun main(args: Array<String>) { val connStr = System.getenv("CONNSTR") when (args[0]) { "countTenantDevice" -> countDocuments(connStr) else -> findDocuments(connStr, db = args[0], collName = args[1], filters = args.drop(2)) } }
16
Kotlin
1
1
ac04f4229b4b473e7e18d42aaab417b838430fa6
257
samples
Apache License 2.0
data/src/main/java/com/techsensei/data/network/ProfileClient.kt
zeeshanali-k
410,526,232
false
null
package com.techsensei.data.network import com.techsensei.data.network.dto.ProfileImageResponse import com.techsensei.data.utils.QueryConstants import okhttp3.MultipartBody import retrofit2.http.Multipart import retrofit2.http.POST import retrofit2.http.Part import retrofit2.http.Query interface ProfileClient { @Multipart @POST("update-profile-image") suspend fun updateProfileImage( @Part requestBody: MultipartBody.Part, @Query(QueryConstants.ID_QUERY_ARG) userId: Int ): ProfileImageResponse }
0
Kotlin
0
4
470b95803cdda7b8b3161ea7ba3f661adae86485
533
Gup
Apache License 2.0
app/src/main/java/in/dimigo/dimigoin/ui/attendance/AttendanceViewModel.kt
dimigo-din
276,088,881
false
null
package `in`.dimigo.dimigoin.ui.attendance import `in`.dimigo.dimigoin.data.model.* import `in`.dimigo.dimigoin.data.usecase.attendance.AttendanceUseCase import `in`.dimigo.dimigoin.data.usecase.config.ConfigUseCase import `in`.dimigo.dimigoin.data.util.DateUtil import `in`.dimigo.dimigoin.data.util.UserDataStore import `in`.dimigo.dimigoin.ui.custom.PlaceProvider import `in`.dimigo.dimigoin.ui.item.AttendanceDetailItem import `in`.dimigo.dimigoin.ui.item.AttendanceItem import `in`.dimigo.dimigoin.ui.main.fragment.main.AttendanceLocation import `in`.dimigo.dimigoin.ui.util.EventWrapper import android.annotation.SuppressLint import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.launch class AttendanceViewModel( private val attendanceUseCase: AttendanceUseCase, private val configUseCase: ConfigUseCase, userDataStore: UserDataStore ) : ViewModel(), PlaceProvider { private val userData = userDataStore.requireUserData() val isTeacher = userData.isTeacher() val hasAttendancePermission = userData.hasPermission(Permission.ATTENDANCE) private val _attendanceTableData = MutableLiveData<List<Int>>() val attendanceTableData: LiveData<List<Int>> = _attendanceTableData private val _attendanceData = MutableLiveData<List<AttendanceItem>>() val attendanceData: LiveData<List<AttendanceItem>> = _attendanceData private val _attendanceLogs = MutableLiveData<List<AttendanceLogModel>?>() val attendanceLogs: LiveData<List<AttendanceLogModel>?> = _attendanceLogs private val _isRefreshing = MutableLiveData(false) val isRefreshing: LiveData<Boolean> = _isRefreshing private val _event = MutableLiveData<EventWrapper<AttendanceFragment.Event>>() val event: LiveData<EventWrapper<AttendanceFragment.Event>> = _event private val _currentTimeCode = MutableLiveData("") val currentTimeCode: LiveData<String> = _currentTimeCode val grade = MutableLiveData(1) val klass = MutableLiveData(1) val query = MutableLiveData<String>() override var places: List<PlaceModel>? = null init { refresh() } fun refresh() = viewModelScope.launch { _isRefreshing.value = true if (!isTeacher) { grade.value = userData.grade klass.value = userData.klass } if (isTeacher || hasAttendancePermission) awaitAll( async { fetchAttendanceStatus() }, async { updateCurrentTimeCode() }, async { fetchAttendanceTimeline() }, async { fetchPlaces() } ) else awaitAll( async { fetchAttendanceStatus() }, async { updateCurrentTimeCode() } ) _isRefreshing.value = false } fun onHistoryButtonClick() { if (!isTeacher && !hasAttendancePermission) return _event.value = EventWrapper(AttendanceFragment.Event.ShowHistoryDialog) } fun onPlaceButtonClick(item: AttendanceItem) { if (!isTeacher && !hasAttendancePermission) return _event.value = EventWrapper(AttendanceFragment.Event.ShowSelectPlaceDialog(item)) } fun onAttendanceDetailButtonClick(item: AttendanceItem) { if (!isTeacher && !hasAttendancePermission) return _event.value = EventWrapper(AttendanceFragment.Event.ShowAttendanceDetailDialog(item)) } suspend fun fetchAttendanceDetail(userModel: UserModel): AttendanceDetailItem? { var result: AttendanceDetailItem? = null attendanceUseCase.getAttendanceDetail(userModel).onSuccess { result = it } return result } private suspend fun fetchAttendanceStatus() { var data: List<AttendanceStatusModel> = listOf() attendanceUseCase.getAttendanceStatus(grade.value ?: 1, klass.value ?: 1).onSuccess { data = it }.onFailure { _event.value = EventWrapper(AttendanceFragment.Event.AttendanceFetchFailed) } applyAttendanceStatus(data) applyAttendanceTableData(data) } @SuppressLint("NullSafeMutableLiveData") private suspend fun fetchAttendanceTimeline() { attendanceUseCase.getAttendanceTimeline(grade.value ?: 1, klass.value ?: 1).onSuccess { _attendanceLogs.value = it }.onFailure { _attendanceLogs.value = null } } private fun applyAttendanceStatus(dataList: List<AttendanceStatusModel>) { _attendanceData.value = dataList.map { val place = it.log?.place val location: AttendanceLocation = place?.let { log -> AttendanceLocation.fromPlace(log) } ?: AttendanceLocation.Class AttendanceItem( it.student, location, place?.name, it.log?.time?.let { time -> DateUtil.toLocalDateTimeWithDefaultZone(time) } ) } } private fun applyAttendanceTableData(dataList: List<AttendanceStatusModel>) { val result = mutableListOf(0, 0, 0, 0, 0) for (data in dataList) { if (data.log != null) { val cursor = when (data.log.place.type) { PlaceType.CLASSROOM -> 0 PlaceType.INGANG -> 1 PlaceType.CIRCLE -> 2 PlaceType.ETC -> 3 PlaceType.ABSENT -> break } result[cursor]++ } else { result[0]++ } } result[4] = dataList.size _attendanceTableData.value = result } private suspend fun updateCurrentTimeCode() { configUseCase.getCurrentTimeCode().onSuccess { _currentTimeCode.value = it }.onFailure { _currentTimeCode.value = "" } } override suspend fun fetchPlaces() { attendanceUseCase.getAllPlaces().onSuccess { places = it } } fun changeCurrentAttendancePlace(place: PlaceModel, remark: String, student: UserModel) { viewModelScope.launch { _isRefreshing.value = true attendanceUseCase.changeCurrentAttendancePlace(place, remark, student).onSuccess { refresh() }.onFailure { _event.value = EventWrapper(AttendanceFragment.Event.ChangeLocationFailed(student)) } _isRefreshing.value = false } } }
10
null
1
21
b89dbdb7f5a540d59a0b70bc91fb29eb7d6a9846
6,626
dimigoin-android
Apache License 2.0
lookandfeel/src/androidMain/kotlin/com/github/alexzhirkevich/lookandfeel/app/AdaptiveApplication.android.kt
alexzhirkevich
636,411,288
false
null
package com.github.alexzhirkevich.lookandfeel.app import com.github.alexzhirkevich.lookandfeel.theme.LookAndFeel internal actual val platformLookAndFeel : LookAndFeel = LookAndFeel.Material3
1
Kotlin
7
211
5a5a23cd002875e05e16eca414ec0ae2587e35f8
193
compose-look-and-feel
Apache License 2.0