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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/example/android/happyplaces/activities/HappyPlaceDetailActivity.kt | Horizon-369 | 665,927,562 | false | null | package com.example.android.happyplaces.activities
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.android.happyplaces.R
import com.example.android.happyplaces.databinding.ActivityHappyPlaceDetailBinding
import com.example.android.happyplaces.models.HappyPlaceModel
class HappyPlaceDetailActivity : AppCompatActivity() {
private lateinit var binding: ActivityHappyPlaceDetailBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityHappyPlaceDetailBinding.inflate(LayoutInflater.from(this))
setContentView(binding.root)
var happyPlaceDetailModel: HappyPlaceModel? = null
if (intent.hasExtra(MainActivity.EXTRA_PLACE_DETAILS)){
happyPlaceDetailModel =
intent.getParcelableExtra(MainActivity.EXTRA_PLACE_DETAILS) as HappyPlaceModel?
}
if (happyPlaceDetailModel != null){
setSupportActionBar(binding.toolbarHappyPlaceDetail)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.title = happyPlaceDetailModel.title
binding.toolbarHappyPlaceDetail.setNavigationOnClickListener{
onBackPressed()
}
binding.ivPlaceImage.setImageURI(Uri.parse(happyPlaceDetailModel.image))
binding.tvDescription.text = happyPlaceDetailModel.description
binding.tvLocation.text = happyPlaceDetailModel.location
binding.btnViewOnMap.setOnClickListener{
val intent = Intent(this, MapActivity::class.java)
intent.putExtra(MainActivity.EXTRA_PLACE_DETAILS, happyPlaceDetailModel)
startActivity(intent)
}
}
}
} | 0 | Kotlin | 0 | 0 | 836bea45b55c1e3c437a65c381f5e10efdfb125c | 1,912 | HappyPlaces | MIT License |
next/kmp/dwebview/src/iosMain/kotlin/org/dweb_browser/dwebview/engine/DWebUIDelegate.kt | BioforestChain | 594,577,896 | false | {"Kotlin": 3446191, "TypeScript": 818538, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16184, "Shell": 13534, "JavaScript": 3982, "Svelte": 3504, "CSS": 818} | package org.dweb_browser.dwebview.engine
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.launch
import org.dweb_browser.core.module.getUIApplication
import org.dweb_browser.dwebview.DwebViewI18nResource
import org.dweb_browser.dwebview.debugDWebView
import org.dweb_browser.helper.Signal
import org.dweb_browser.helper.platform.addMmid
import platform.AVFoundation.AVAuthorizationStatusAuthorized
import platform.AVFoundation.AVAuthorizationStatusDenied
import platform.AVFoundation.AVAuthorizationStatusNotDetermined
import platform.AVFoundation.AVAuthorizationStatusRestricted
import platform.AVFoundation.AVCaptureDevice
import platform.AVFoundation.AVMediaType
import platform.AVFoundation.AVMediaTypeAudio
import platform.AVFoundation.AVMediaTypeVideo
import platform.AVFoundation.authorizationStatusForMediaType
import platform.AVFoundation.requestAccessForMediaType
import platform.UIKit.UIAlertAction
import platform.UIKit.UIAlertActionStyleCancel
import platform.UIKit.UIAlertActionStyleDefault
import platform.UIKit.UIAlertController
import platform.UIKit.UIAlertControllerStyleAlert
import platform.UIKit.UIViewController
import platform.WebKit.WKFrameInfo
import platform.WebKit.WKMediaCaptureType
import platform.WebKit.WKNavigationAction
import platform.WebKit.WKPermissionDecision
import platform.WebKit.WKSecurityOrigin
import platform.WebKit.WKUIDelegateProtocol
import platform.WebKit.WKWebView
import platform.WebKit.WKWebViewConfiguration
import platform.WebKit.WKWindowFeatures
import platform.darwin.NSObject
class DWebUIDelegate(internal val engine: DWebViewEngine) : NSObject(), WKUIDelegateProtocol {
//#region Alert Confirm Prompt
private val jsAlertSignal = Signal<Pair<JsParams, SignalResult<Unit>>>()
private val jsConfirmSignal = Signal<Pair<JsParams, SignalResult<Boolean>>>()
private val jsPromptSignal = Signal<Pair<JsPromptParams, SignalResult<String?>>>()
private val closeSignal = engine.closeSignal
internal val createWindowSignal = engine.createWindowSignal
internal data class JsParams(
val webView: WKWebView,
val message: String,
val wkFrameInfo: WKFrameInfo,
)
internal data class JsPromptParams(
val webView: WKWebView,
val prompt: String,
val defaultText: String?,
val wkFrameInfo: WKFrameInfo,
)
class CreateWebViewParams(
val webView: WKWebView,
val createWebViewWithConfiguration: WKWebViewConfiguration,
val forNavigationAction: WKNavigationAction,
val windowFeatures: WKWindowFeatures,
){
val navigationUrl by lazy { forNavigationAction.request.URL?.absoluteString }
}
sealed interface CreateWebViewHookPolicy;
class CreateWebViewHookPolicyAllow(val webView: WKWebView) : CreateWebViewHookPolicy
object CreateWebViewHookPolicyDeny : CreateWebViewHookPolicy
object CreateWebViewHookPolicyContinue : CreateWebViewHookPolicy
val createWebViewHooks = mutableListOf<CreateWebViewParams.() -> CreateWebViewHookPolicy>()
override fun webView(
webView: WKWebView,
createWebViewWithConfiguration: WKWebViewConfiguration,
forNavigationAction: WKNavigationAction,
windowFeatures: WKWindowFeatures,
): WKWebView? {
if (createWebViewHooks.isEmpty()) {
return null
}
val params = CreateWebViewParams(
webView,
createWebViewWithConfiguration,
forNavigationAction,
windowFeatures
)
for (hook in createWebViewHooks) {
return when (val policy = params.hook()) {
is CreateWebViewHookPolicyAllow -> policy.webView
is CreateWebViewHookPolicyDeny -> null
is CreateWebViewHookPolicyContinue -> continue
}
}
return null
}
override fun webViewDidClose(webView: WKWebView) {
engine.mainScope.launch {
closeSignal.emit()
}
}
private fun UIAlertController.addMmid() {
addMmid(engine.remoteMM.mmid)
}
override fun webView(
webView: WKWebView,
runJavaScriptAlertPanelWithMessage: String,
initiatedByFrame: WKFrameInfo,
completionHandler: () -> Unit,
) {
val finalNext = Signal<Pair<JsParams, SignalResult<Unit>>>()
finalNext.listen {
val (params, ctx) = it
val vc = webView.getUIViewController()
if (vc != null) {
val alertController = UIAlertController.alertControllerWithTitle(
params.webView.title,
params.message,
UIAlertControllerStyleAlert
)
alertController.addMmid()
alertController.addAction(
UIAlertAction.actionWithTitle(
DwebViewI18nResource.alert_action_ok.text,
UIAlertActionStyleDefault
) {
ctx.complete(Unit)
})
vc.presentViewController(alertController, true, null)
} else {
ctx.complete(Unit)
}
}
engine.mainScope.launch {
jsAlertSignal.emitForResult(
JsParams(
webView,
runJavaScriptAlertPanelWithMessage,
initiatedByFrame
), finalNext
)
completionHandler()
}
}
override fun webView(
webView: WKWebView,
runJavaScriptConfirmPanelWithMessage: String,
initiatedByFrame: WKFrameInfo,
completionHandler: (Boolean) -> Unit,
) {
val finalNext = Signal<Pair<JsParams, SignalResult<Boolean>>>()
finalNext.listen {
val (params, ctx) = it
val vc = webView.getUIViewController()
if (vc != null) {
val confirmController = UIAlertController.alertControllerWithTitle(
params.webView.title,
params.message,
UIAlertControllerStyleAlert
)
confirmController.addMmid()
confirmController.addAction(
UIAlertAction.actionWithTitle(
DwebViewI18nResource.confirm_action_cancel.text,
UIAlertActionStyleCancel
) {
ctx.complete(false)
})
confirmController.addAction(
UIAlertAction.actionWithTitle(
DwebViewI18nResource.confirm_action_confirm.text,
UIAlertActionStyleDefault
) {
ctx.complete(true)
})
vc.presentViewController(confirmController, true, null)
} else {
ctx.complete(false)
}
}
engine.mainScope.launch {
val (confirm, _) = jsConfirmSignal.emitForResult(
JsParams(
webView,
runJavaScriptConfirmPanelWithMessage,
initiatedByFrame
), finalNext
)
completionHandler(confirm!!)
}
}
override fun webView(
webView: WKWebView,
runJavaScriptTextInputPanelWithPrompt: String,
defaultText: String?,
initiatedByFrame: WKFrameInfo,
completionHandler: (String?) -> Unit,
) {
val finalNext = Signal<Pair<JsPromptParams, SignalResult<String?>>>()
finalNext.listen {
val (params, ctx) = it
val vc = webView.getUIViewController()
if (vc != null) {
val promptController = UIAlertController.alertControllerWithTitle(
params.webView.title,
params.prompt,
UIAlertControllerStyleAlert
)
promptController.addMmid()
promptController.addTextFieldWithConfigurationHandler { textField ->
textField?.text = params.defaultText
textField?.selectAll(null)
promptController.addAction(
UIAlertAction.actionWithTitle(
DwebViewI18nResource.prompt_action_cancel.text,
UIAlertActionStyleCancel
) {
ctx.complete(null)
})
promptController.addAction(
UIAlertAction.actionWithTitle(
DwebViewI18nResource.prompt_action_confirm.text,
UIAlertActionStyleDefault
) {
ctx.complete(textField?.text)
})
}
vc.presentViewController(promptController, true, null)
} else {
ctx.complete(null)
}
}
engine.mainScope.launch {
val (promptText, _) = jsPromptSignal.emitForResult(
JsPromptParams(
webView,
runJavaScriptTextInputPanelWithPrompt,
defaultText,
initiatedByFrame
), finalNext
)
completionHandler(promptText ?: "")
}
}
override fun webView(
webView: WKWebView,
requestMediaCapturePermissionForOrigin: WKSecurityOrigin,
initiatedByFrame: WKFrameInfo,
type: WKMediaCaptureType,
decisionHandler: (WKPermissionDecision) -> Unit,
) {
val mediaTypes = when (type) {
WKMediaCaptureType.WKMediaCaptureTypeCamera -> listOf(AVMediaTypeVideo)
WKMediaCaptureType.WKMediaCaptureTypeMicrophone -> listOf(AVMediaTypeAudio)
WKMediaCaptureType.WKMediaCaptureTypeCameraAndMicrophone -> listOf(
AVMediaTypeVideo,
AVMediaTypeAudio
)
else -> emptyList()
}
if (mediaTypes.isEmpty()) {
decisionHandler(WKPermissionDecision.WKPermissionDecisionPrompt)
return
}
engine.mainScope.launch {
mediaTypes.forEach {
val isAuthorized = when (AVCaptureDevice.authorizationStatusForMediaType(it)) {
AVAuthorizationStatusNotDetermined -> AVCaptureDevice.requestAccessForMediaType(
it
)
.await()
AVAuthorizationStatusAuthorized -> true
AVAuthorizationStatusDenied -> false
/*
* 1. 家长控制功能启用,限制了应用访问摄像头或麦克风
* 2. 机构部署的设备,限制了应用访问硬件功能
* 3. 用户在 iCloud 中的"隐私"设置中针对应用禁用了访问权限
*/
AVAuthorizationStatusRestricted -> null
else -> null
}
/// 认证失败
if (isAuthorized == false) {
decisionHandler(WKPermissionDecision.WKPermissionDecisionDeny)
return@launch
}
/// 受限 或者 未知?
/// TODO 用额外的提示框提示用户
if (isAuthorized == null) {
decisionHandler(WKPermissionDecision.WKPermissionDecisionPrompt)
return@launch
}
}
/// 所有的权限都验证通过
decisionHandler(WKPermissionDecision.WKPermissionDecisionGrant)
}
}
fun AVCaptureDevice.Companion.requestAccessForMediaType(mediaType: AVMediaType?): Deferred<Boolean> {
val deferred = CompletableDeferred<Boolean>()
AVCaptureDevice.requestAccessForMediaType(mediaType) {
deferred.complete(it)
}
return deferred
}
internal class SignalResult<R> {
var result: R? = null
var hasResult: Boolean = false
/**
* 写入结果
*/
fun complete(result: R) {
if (hasResult) return
this.result = result
hasResult = true
next()
}
/**
* 跳过处置,由下一个处理者接管
*/
fun next() {
waiter.complete(Unit)
}
val waiter = CompletableDeferred<Unit>()
}
private suspend fun <T, R> Signal<Pair<T, SignalResult<R>>>.emitForResult(
args: T,
finallyNext: Signal<Pair<T, SignalResult<R>>>,
): Pair<R?, Boolean> {
try {
val ctx = SignalResult<R>()
[email protected](Pair(args, ctx))
finallyNext.emit(Pair(args, ctx))
ctx.waiter.await()
if (ctx.hasResult) {
return Pair(ctx.result, true)
}
} catch (e: Throwable) {
debugDWebView("DUIDelegateProtocol", e.message ?: e.stackTraceToString())
}
return Pair(null, false)
}
private fun WKWebView.getUIViewController(): UIViewController? {
return engine.remoteMM.getUIApplication().keyWindow?.rootViewController
}
//#endregion
} | 66 | Kotlin | 5 | 20 | 6db1137257e38400c87279f4ccf46511752cd45a | 11,442 | dweb_browser | MIT License |
src/commonMain/kotlin/org/guiVista/io/application/action/Action.kt | gui-vista | 331,127,596 | false | null | package org.guiVista.io.application.action
/** Represents a single named action that may have state. */
public expect interface Action
| 0 | Kotlin | 0 | 0 | 72e2c1b7ae9f5489eff83ad915ef9ddedc87726e | 136 | guivista-io | Apache License 2.0 |
services/core-gateway/src/main/kotlin/org/example/api/ClientApiController.kt | Arslanka-Educational | 784,642,540 | false | {"Kotlin": 121240} | package org.example.api
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.example.api.dto.UserRegisterRequest
import org.example.domain.AuthorizationUserDetails
import org.example.domain.User
import org.example.service.AuthorizationUserDetailsService
import org.example.service.JwtService
import org.springframework.http.ResponseEntity
import org.springframework.security.core.Authentication
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("\${api.base-path:}")
class ClientApiController(
private val userService: AuthorizationUserDetailsService,
private val jwtService: JwtService,
) {
@RequestMapping(
method = [RequestMethod.POST],
value = ["/v1/client/login"],
produces = ["application/json"],
consumes = ["application/json"]
)
suspend fun v1ClientLoginPost(authentication: Authentication): ResponseEntity<String> {
val userDetails = authentication.principal as AuthorizationUserDetails
return ResponseEntity.ok().body(jwtService.generateToken(userDetails))
}
@RequestMapping(
method = [RequestMethod.POST],
value = ["/v1/client/register"],
produces = ["application/json"],
consumes = ["application/json"]
)
suspend fun v1ClientRegisterPost(@RequestBody userRegisterRequest: UserRegisterRequest): ResponseEntity<User> = runBlocking {
ResponseEntity.ok().body(userService.registerUser(userRegisterRequest))
}
} | 1 | Kotlin | 0 | 4 | fba88651674e394bf2b302095fa3ff5fdc3cfc13 | 1,747 | OpenBook | Apache License 2.0 |
2021/src/main/kotlin/day6_imp.kt | madisp | 434,510,913 | false | {"Kotlin": 388138} | import utils.Parser
import utils.Solution
import utils.withLCounts
fun main() {
Day6Imp.run()
}
object Day6Imp : Solution<Map<Int, Long>>() {
override val name = "day6"
override val parser = Parser.ints.map { it.withLCounts() }
override fun part1(input: Map<Int, Long>): Long {
return simulate(input, forDays = 80).sum()
}
override fun part2(input: Map<Int, Long>): Long {
return simulate(input, forDays = 256).sum()
}
private fun simulate(input: Map<Int, Long>, forDays: Int): LongArray {
val state = LongArray(10) { index -> input[index] ?: 0L }
for (i in 0 until forDays) {
val count = state[0]
state[9] = (state[9]) + count
state[7] = (state[7]) + count
state[0] = 0
for (j in 1 .. 9) {
state[j - 1] = state[j]
}
state[9] = 0
}
return state
}
} | 0 | Kotlin | 0 | 1 | 3f106415eeded3abd0fb60bed64fb77b4ab87d76 | 847 | aoc_kotlin | MIT License |
server/src/main/kotlin/org/kryptonmc/krypton/coordinate/GlobalPos.kt | KryptonMC | 255,582,002 | false | null | /*
* This file is part of the Krypton project, licensed under the Apache License v2.0
*
* Copyright (C) 2021-2023 KryptonMC and the contributors of the Krypton project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kryptonmc.krypton.coordinate
import org.kryptonmc.api.resource.ResourceKey
import org.kryptonmc.api.resource.ResourceKeys
import org.kryptonmc.api.util.Vec3i
import org.kryptonmc.api.world.World
import org.kryptonmc.krypton.network.Writable
import org.kryptonmc.krypton.network.buffer.BinaryReader
import org.kryptonmc.krypton.network.buffer.BinaryWriter
import org.kryptonmc.krypton.util.serialization.Codecs
import org.kryptonmc.serialization.Codec
import org.kryptonmc.serialization.codecs.RecordCodecBuilder
@JvmRecord
data class GlobalPos(val dimension: ResourceKey<World>, val position: Vec3i) : Writable {
constructor(reader: BinaryReader) : this(ResourceKey.of(ResourceKeys.DIMENSION, reader.readKey()), reader.readBlockPos())
override fun write(writer: BinaryWriter) {
writer.writeResourceKey(dimension)
writer.writeBlockPos(position)
}
companion object {
@JvmField
val CODEC: Codec<GlobalPos> = RecordCodecBuilder.create { instance ->
instance.group(
Codecs.DIMENSION.fieldOf("dimension").getting { it.dimension },
BlockPos.CODEC.fieldOf("pos").getting { it.position }
).apply(instance) { dimension, pos -> GlobalPos(dimension, pos) }
}
}
}
| 27 | Kotlin | 11 | 233 | a9eff5463328f34072cdaf37aae3e77b14fcac93 | 2,018 | Krypton | Apache License 2.0 |
src/main/java/no/nav/familie/integrasjoner/journalpost/internal/SafJournalpostRequest.kt | navikt | 224,182,192 | false | null | package no.nav.familie.integrasjoner.journalpost.internal
data class SafRequestVariabler(val journalpostId: String)
data class SafJournalpostRequest(
val variables: Any,
val query: String
)
| 9 | Kotlin | 0 | 3 | a48d4af90badad67cb4d7e1273216f10f3e02fde | 200 | familie-integrasjoner | MIT License |
archivarius/src/test/java/com/sherepenko/android/archivarius/entries/JsonLogEntryTest.kt | asherepenko | 237,088,692 | false | null | package com.sherepenko.android.archivarius.entries
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import com.sherepenko.android.archivarius.utils.ArchivariusTestUtils
import java.io.ByteArrayOutputStream
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class JsonLogEntryTest {
private lateinit var outputStream: ByteArrayOutputStream
@Before
fun setUp() {
outputStream = ByteArrayOutputStream()
}
@Test
@Throws(Exception::class)
fun testFormat() {
val json = mutableMapOf(
"message" to "test message",
"timestamp" to "2014-05-01T14:15:16.000+00:00"
)
val entry = JsonLogEntry(json)
ArchivariusTestUtils.writeTo(outputStream, entry)
assertThat(String(outputStream.toByteArray())).isEqualTo(
"{\"message\":\"test message\",\"timestamp\":\"2014-05-01T14:15:16.000+00:00\"}\n"
)
}
}
| 0 | Kotlin | 0 | 2 | 2829053317fbf042ac0f67d39a412487d2ebaec5 | 1,026 | android-archivarius | MIT License |
libs/tracing/src/main/kotlin/net/corda/tracing/BatchRecordTracer.kt | corda | 346,070,752 | false | {"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.tracing
import net.corda.messaging.api.records.Record
interface BatchRecordTracer {
fun startSpanFor(event: Record<*, *>, correlationId: String)
fun errorSpanFor(correlationId: String, error: Exception, outputRecord: Record<*, *>): Record<*, *>
fun completeSpanFor(correlationId: String, outputRecord: Record<*, *>): Record<*, *>
} | 14 | Kotlin | 27 | 69 | 0766222eb6284c01ba321633e12b70f1a93ca04e | 366 | corda-runtime-os | Apache License 2.0 |
app/src/main/java/com/dk/newssync/di/module/EntriesModule.kt | dimkonomis | 173,963,908 | false | null | package com.dk.newssync.di.module
import androidx.lifecycle.ViewModel
import com.dk.newssync.di.ViewModelKey
import com.dk.newssync.presentation.ui.entries.EntriesViewModel
import dagger.Binds
import dagger.Module
import dagger.multibindings.IntoMap
/**
* Created by <NAME> (<EMAIL>) on 08/12/2018.
**/
@Module
interface EntriesModule {
@Binds
@IntoMap
@ViewModelKey(EntriesViewModel::class)
fun bindEntriesViewModel(entriesViewModel: EntriesViewModel): ViewModel
} | 2 | Kotlin | 7 | 50 | b299ca3b040c93cfa79d47fd7b7e3335c9ccc5a4 | 487 | NewsSync | Apache License 2.0 |
app/src/main/java/com/seyone22/anime/data/api/response/NextAiringEpisode.kt | seyone22 | 862,263,189 | false | {"Kotlin": 35282} | package com.seyone22.anime.data.api.response
import kotlinx.serialization.Serializable
@Serializable
data class NextAiringEpisode (
val episode: Int,
val timeUntilAiring: Int
) | 0 | Kotlin | 0 | 0 | 8fa4cebec729e94afecb1806f2614061e01404f6 | 186 | Anime | MIT License |
corekt/src/main/java/com/lodz/android/corekt/anko/AnkoCoroutines.kt | LZ9 | 137,967,291 | false | {"Kotlin": 2174239} | package com.lodz.android.corekt.anko
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.*
/**
* 协程扩展类
* @author zhouL
* @date 2019/5/15
*/
@Suppress("FunctionName")
fun IoScope(): CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
/** 主线程执行 */
@JvmOverloads
fun runOnMain(scope: CoroutineScope = MainScope(), action: suspend () -> Unit): Job = scope.launch(Dispatchers.Main) { action() }
/** 主线程执行(ViewModel) */
fun ViewModel.runOnMain(action: suspend () -> Unit): Job = viewModelScope.launch(Dispatchers.Main) { action() }
/** 主线程执行(AppCompatActivity) */
fun AppCompatActivity.runOnMain(action: suspend () -> Unit): Job = lifecycleScope.launch(Dispatchers.Main) { action() }
/** 主线程执行(Fragment) */
fun Fragment.runOnMain(action: suspend () -> Unit): Job = lifecycleScope.launch(Dispatchers.Main) { action() }
/** 主线程执行捕获异常 */
@JvmOverloads
fun runOnMainCatch(
action: suspend () -> Unit,
error: (e: Exception) -> Unit = {},
scope: CoroutineScope = MainScope()
): Job = scope.launch(Dispatchers.Main) {
try {
action()
} catch (e: Exception) {
e.printStackTrace()
error(e)
}
}
/** 主线程执行捕获异常(ViewModel) */
@JvmOverloads
fun ViewModel.runOnMainCatch(
action: suspend () -> Unit,
error: (e: Exception) -> Unit = {}
): Job = viewModelScope.launch(Dispatchers.Main) {
try {
action()
} catch (e: Exception) {
e.printStackTrace()
error(e)
}
}
/** 主线程执行捕获异常(AppCompatActivity) */
@JvmOverloads
fun AppCompatActivity.runOnMainCatch(
action: suspend () -> Unit,
error: (e: Exception) -> Unit = {}
): Job = lifecycleScope.launch(Dispatchers.Main) {
try {
action()
} catch (e: Exception) {
e.printStackTrace()
error(e)
}
}
/** 主线程执行捕获异常(Fragment) */
@JvmOverloads
fun Fragment.runOnMainCatch(
action: suspend () -> Unit,
error: (e: Exception) -> Unit = {}
): Job = lifecycleScope.launch(Dispatchers.Main) {
try {
action()
} catch (e: Exception) {
e.printStackTrace()
error(e)
}
}
/** 主线程延迟[timeMillis]毫秒执行 */
@JvmOverloads
fun runOnMainDelay(
timeMillis: Long,
scope: CoroutineScope = IoScope(),
action: suspend () -> Unit
): Job = scope.launch(Dispatchers.Main) {
delay(timeMillis)
launch(Dispatchers.Main) { action() }
}
/** 主线程延迟[timeMillis]毫秒执行(ViewModel) */
fun ViewModel.runOnMainDelay(
timeMillis: Long,
action: suspend () -> Unit
): Job = viewModelScope.launch(Dispatchers.IO) {
delay(timeMillis)
launch(Dispatchers.Main) { action() }
}
/** 主线程延迟[timeMillis]毫秒执行(AppCompatActivity) */
fun AppCompatActivity.runOnMainDelay(
timeMillis: Long,
action: suspend () -> Unit
): Job = lifecycleScope.launch(Dispatchers.IO) {
delay(timeMillis)
launch(Dispatchers.Main) { action() }
}
/** 主线程延迟[timeMillis]毫秒执行(Fragment) */
fun Fragment.runOnMainDelay(
timeMillis: Long,
action: suspend () -> Unit
): Job = lifecycleScope.launch(Dispatchers.IO) {
delay(timeMillis)
launch(Dispatchers.Main) { action() }
}
/** 异步线程执行 */
@JvmOverloads
fun runOnIO(scope: CoroutineScope = IoScope(), actionIO: suspend () -> Unit): Job = scope.launch(Dispatchers.IO) { actionIO() }
/** 异步线程执行(ViewModel) */
fun ViewModel.runOnIO(actionIO: suspend () -> Unit): Job = viewModelScope.launch(Dispatchers.IO) { actionIO() }
/** 异步线程执行(AppCompatActivity) */
fun AppCompatActivity.runOnIO(actionIO: suspend () -> Unit): Job = lifecycleScope.launch(Dispatchers.IO) { actionIO() }
/** 异步线程执行(Fragment) */
fun Fragment.runOnIO(actionIO: suspend () -> Unit): Job = lifecycleScope.launch(Dispatchers.IO) { actionIO() }
/** 异步线程执行捕获异常 */
@JvmOverloads
fun runOnIOCatch(
actionIO: suspend () -> Unit,
error: (e: Exception) -> Unit = {},
scope: CoroutineScope = IoScope()
): Job = scope.launch(Dispatchers.IO) {
try {
actionIO()
} catch (e: Exception) {
e.printStackTrace()
launch(Dispatchers.Main) { error(e) }
}
}
/** 异步线程执行捕获异常(ViewModel) */
@JvmOverloads
fun ViewModel.runOnIOCatch(
actionIO: suspend () -> Unit,
error: (e: Exception) -> Unit = {}
): Job = viewModelScope.launch(Dispatchers.IO) {
try {
actionIO()
} catch (e: Exception) {
e.printStackTrace()
launch(Dispatchers.Main) { error(e) }
}
}
/** 异步线程执行捕获异常(AppCompatActivity) */
@JvmOverloads
fun AppCompatActivity.runOnIOCatch(
actionIO: suspend () -> Unit,
error: (e: Exception) -> Unit = {}
): Job = lifecycleScope.launch(Dispatchers.IO) {
try {
actionIO()
} catch (e: Exception) {
e.printStackTrace()
launch(Dispatchers.Main) { error(e) }
}
}
/** 异步线程执行捕获异常(Fragment) */
@JvmOverloads
fun Fragment.runOnIOCatch(
actionIO: suspend () -> Unit,
error: (e: Exception) -> Unit = {}
): Job = lifecycleScope.launch(Dispatchers.IO) {
try {
actionIO()
} catch (e: Exception) {
e.printStackTrace()
launch(Dispatchers.Main) { error(e) }
}
}
/** 在主线程执行挂起函数[action](如果挂起函数耗时则会阻断主线程) */
fun <T> awaitOrNull(action: suspend () -> T?): T? = runBlocking { action() }
/** 在主线程执行挂起函数[action](如果挂起函数耗时则会阻断主线程) */
fun <T> await(action: suspend () -> T): T = runBlocking { action() } | 0 | Kotlin | 3 | 11 | 3441dd22a2b6b24bc988b5355932b35eb5d15884 | 5,429 | AgileDevKt | Apache License 2.0 |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/PreserveColor.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: PreserveColor
*
* Full name: System`PreserveColor
*
* Usage: PreserveColor is an option for ImageRestyle and related functions that specifies whether to preserve colors in the original image.
*
* Options: None
*
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/PreserveColor
* Documentation: web: http://reference.wolfram.com/language/ref/PreserveColor.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun preserveColor(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("PreserveColor", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,066 | mathemagika | Apache License 2.0 |
ok-common-backend/src/main/kotlin/ru/otus/kotlin/messaging/pagination.kt | otuskotlin | 331,712,866 | false | null | package ru.otus.kotlin.messaging
data class Page(
val pageSize: Int = 10,
val pageNumber: Int = 0
)
| 0 | Kotlin | 1 | 0 | e275c21b8b4415b91e0e367bff81751cc7655ee9 | 109 | otuskotlin-202012-messages-ir | MIT License |
src/main/kotlin/com/financesbox/shared/application/cqs/command/Command.kt | FinancesBox | 839,818,989 | false | {"Kotlin": 76010, "Dockerfile": 247} | package com.financesbox.shared.application.cqs.command
import com.financesbox.shared.domain.event.Event
open class Command<E : Event>
| 0 | Kotlin | 0 | 0 | 9496b4dabb13b163a161d7e0843649f592f7a4ad | 136 | core-api | MIT License |
app/src/main/java/aguilarkevin/dev/nftmarketplace/ui/profile/components/ProfileBanner.kt | ivansanguezax | 653,423,961 | false | null | package aguilarkevin.dev.nftmarketplace.ui.profile.components
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.skydoves.landscapist.glide.GlideImage
@Composable
fun ProfileBanner(imageUrl: String, height: Dp) {
GlideImage(
imageModel = imageUrl,
// Crop, Fit, Inside, FillHeight, FillWidth, None
contentScale = ContentScale.Crop,
modifier = Modifier
.height(height)
.fillMaxWidth()
.clip(RoundedCornerShape(16.dp))
)
} | 0 | Kotlin | 0 | 0 | c093ed1e8ecb9dcc9bfe101bcc30aa84db2c8fcb | 855 | NFTPluriapp | MIT License |
simplified-tests/src/test/java/org/nypl/simplified/tests/pdf/PdfViewerProviderTest.kt | ThePalaceProject | 367,082,997 | false | {"Kotlin": 3281089, "JavaScript": 853788, "Java": 374503, "CSS": 65407, "HTML": 49220, "Shell": 5017, "Ruby": 178} | package org.nypl.simplified.tests.pdf
import one.irradia.mime.vanilla.MIMEParser
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.librarysimplified.viewer.pdf.pdfjs.PdfViewerProvider
import org.mockito.Mockito
import org.nypl.simplified.books.api.Book
import org.nypl.simplified.books.api.BookFormat
import org.nypl.simplified.viewer.spi.ViewerPreferences
class PdfViewerProviderTest {
@Test
fun supportsPdfBooks() {
val preferences = ViewerPreferences(
flags = mapOf()
)
val book = Mockito.mock(Book::class.java)
val format = Mockito.mock(BookFormat.BookFormatPDF::class.java)
val provider = PdfViewerProvider()
Assertions.assertTrue(provider.canSupport(preferences, book, format))
}
@Test
fun potentiallySupportsPdfFiles() {
val provider = PdfViewerProvider()
Assertions.assertTrue(
provider.canPotentiallySupportType(
MIMEParser.parseRaisingException("application/pdf")
)
)
}
}
| 0 | Kotlin | 4 | 8 | 82dee2e0f39a74afc5a429d0124e20f77b1eac13 | 998 | android-core | Apache License 2.0 |
android/src/main/java/com/reactnativeselectpanel/SelectPanelPackage.kt | RockyF | 279,457,927 | false | {"Objective-C": 2863, "Kotlin": 1356, "TypeScript": 876, "Ruby": 585, "JavaScript": 77} | package com.reactnativeselectpanel
import java.util.Arrays
import java.util.Collections
import com.facebook.react.ReactPackage
import com.facebook.react.bridge.NativeModule
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.uimanager.ViewManager
import com.facebook.react.bridge.JavaScriptModule
class SelectPanelPackage : ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> {
return Arrays.asList<NativeModule>(SelectPanelModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> {
return emptyList<ViewManager<*, *>>()
}
}
| 17 | Objective-C | 0 | 0 | 3e0a096782df4110bbe4d61382d725751ebf8efd | 710 | react-native-select-panel | MIT License |
app/src/main/java/in/evilcorp/bricksopenlauncher/injection/AppComponent.kt | dimskiy | 211,170,325 | false | null | package `in`.evilcorp.bricksopenlauncher.injection
import `in`.evilcorp.bricksopenlauncher.LauncherApp
import `in`.evilcorp.bricksopenlauncher.injection.modules.*
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjector
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
@Component(modules = [
AndroidSupportInjectionModule::class,
InjectorBindMainModule::class,
InjectorBindOverlayModule::class,
AppModule::class,
OverlayControlsModule::class,
StorageModule::class
])
@Singleton
interface AppComponent: AndroidInjector<LauncherApp> {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: LauncherApp): Builder
fun appModule(appModule: AppModule): Builder
fun build(): AppComponent
}
} | 9 | Kotlin | 9 | 17 | f66e039bae8b85c2534f83b593490c1633234f86 | 858 | BricksOpenLauncher | MIT License |
app/src/main/java/com/stanroy/weebpeep/data/repository/dataSourceImpl/AnimeLocalDataSourceImpl.kt | stanroy | 399,533,551 | false | null | package com.stanroy.weebpeep.data.repository.dataSourceImpl
import com.stanroy.weebpeep.data.db.AnimeDAO
import com.stanroy.weebpeep.data.model.Anime
import com.stanroy.weebpeep.data.repository.dataSource.AnimeLocalDataSource
class AnimeLocalDataSourceImpl(private val animeDAO: AnimeDAO) : AnimeLocalDataSource {
override suspend fun insertIntoDatabase(animeList: List<Anime>) {
animeDAO.insertIntoDatabase(animeList)
}
override suspend fun insertWithoutReplacing(animeList: List<Anime>) {
animeDAO.insertWithoutReplacing(animeList)
}
override fun getAllAnime(): List<Anime> {
return animeDAO.getAllAnime()
}
override fun clearAll() {
animeDAO.clearAll()
}
override suspend fun addAnimeToFavourites(malId: Int) {
animeDAO.addAnimeToFavourites(malId)
}
override suspend fun deleteAnimeFromFavourite(malId: Int) {
animeDAO.deleteAnimeFromFavourites(malId)
}
override suspend fun getFavouriteAnime(): List<Anime> {
return animeDAO.getFavouriteAnime()
}
}
| 0 | Kotlin | 0 | 0 | 7171faf85c8d2d38e27f5785bdc89296c033b219 | 1,073 | weeb-peep | MIT License |
Praticas/Navegacao-Firestore-2_firestore_atividades/app/src/main/java/com/example/navegacao1/ui/telas/TelaPrincipal.kt | AllanSmithll | 763,734,397 | false | {"Kotlin": 62582, "Assembly": 32} | package com.example.navegacao1.ui.telas
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.example.navegacao1.model.dados.Usuario
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
@Composable
fun TelaPrincipal(modifier: Modifier = Modifier, onLogoffClick: () -> Unit) {
val scope = rememberCoroutineScope()
val usuarios = remember { mutableStateListOf<Usuario>() }
Column(modifier = modifier.padding(16.dp)) {
Text(
text = "Tela Principal",
style = MaterialTheme.typography.headlineMedium,
modifier = Modifier.padding(bottom = 16.dp)
)
Button(onClick = {
scope.launch(Dispatchers.IO) {
usuarioDAO.buscar(callback = { usuariosRetornados ->
usuarios.clear()
usuarios.addAll(usuariosRetornados)
})
}
}) {
Text("Carregar")
}
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = { onLogoffClick() }) {
Text("Sair")
}
Spacer(modifier = Modifier.height(16.dp))
LazyColumn(
contentPadding = PaddingValues(vertical = 8.dp),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
items(usuarios) { usuario ->
Card(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp),
elevation = CardDefaults.cardElevation(4.dp)
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(
text = "Nome: ${usuario.nome}",
style = MaterialTheme.typography.bodyLarge.copy(fontWeight = FontWeight.Bold)
)
}
}
}
}
}
} | 0 | Kotlin | 0 | 1 | 143cf39ec22d33b02c5596760091ca69fd7502f4 | 2,862 | ProgramacaoparaDispositivosMoveis | MIT License |
src/main/kotlin/ampersand/userservice/infrastructure/security/jwt/JwtProperties.kt | Team-Ampersand | 745,334,935 | false | {"Kotlin": 37212, "Dockerfile": 91} | package ampersand.userservice.infrastructure.security.jwt
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.NestedConfigurationProperty
@ConfigurationProperties(prefix = "jwt")
data class JwtProperties(
val secretKey: String,
@NestedConfigurationProperty
val accessTokenProperties: AccessTokenProperties,
@NestedConfigurationProperty
val refreshTokenProperties: RefreshTokenProperties
) {
fun getAccessTokenExpirationAsHour() =
this.accessTokenProperties.expirationAsHour.toLong()
fun getRefreshTokenExpirationAsHour() =
this.refreshTokenProperties.expirationAsHour.toLong()
}
interface BaseTokenProperties {
val expirationAsHour: Int
}
data class AccessTokenProperties(
override val expirationAsHour: Int
) : BaseTokenProperties
data class RefreshTokenProperties(
override val expirationAsHour: Int
) : BaseTokenProperties | 4 | Kotlin | 0 | 2 | 1a21bd0b3f66e56503e448eb923e376599af036c | 961 | Dotori-V3-Member | Apache License 2.0 |
app/src/main/java/com/codepath/apps/restclienttemplate/models/User.kt | LizaFeng | 464,006,060 | false | {"Kotlin": 31887} | package com.codepath.apps.restclienttemplate.models
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import org.json.JSONObject
//Making this Parcelable since we need this in Tweet and Tweet is Parcelable
//Do the same as Tweet with the variables
@Parcelize
//We will work on the User model before we work on the Tweet model because User is intertwined with Tweet
class User (var name: String = "", var screenName: String = "",
var publicImageUrl: String = ""): Parcelable {
//Variable explanations
//These are var instead of val because we dont know the value yet and it would be changed later
//Something that we can reference without creating new instances of the user object
companion object{
//What we need is a method that takes in a Json object and convert it into a user object
fun fromJson(jsonObject: JSONObject): User{
val user= User()
//"name" is the string in the json file that contains the username
//setting the name of the object of User to be "name" from json file
user.name = jsonObject.getString("name")
user.screenName=jsonObject.getString("screen_name")
user.publicImageUrl = jsonObject.getString("profile_image_url_https")
return user
}
}
} | 3 | Kotlin | 1 | 0 | 61e4cf5e609aeac371ef60a858470c60631c01e2 | 1,328 | SimpleTweet | Apache License 2.0 |
src/main/kotlin/org/cngr/webapp/controllers/VersionController.kt | psenger | 426,014,560 | false | {"Kotlin": 3272, "Shell": 127} | package org.cngr.webapp.controllers
import com.fasterxml.jackson.databind.ObjectMapper
import io.swagger.annotations.Api
import org.cngr.webapp.configurations.GitConfig
import org.cngr.webapp.model.VersionModel
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import springfox.documentation.annotations.ApiIgnore
@RestController
@Api(value="Version api")
class VersionController( @Autowired val gitConfig: GitConfig ) {
@GetMapping(value = ["/version"], produces = [MediaType.APPLICATION_JSON_VALUE])
fun helloWorld(): ResponseEntity<Any?> {
return ResponseEntity.ok(ObjectMapper().writeValueAsString(VersionModel(
commitId = gitConfig.commitId,
now = System.currentTimeMillis().toString(),
)))
}
}
| 0 | Kotlin | 0 | 0 | 3993f3babddd536bd6f0b0d5da787753e985cc40 | 976 | kotlin-spring-boot-starter | MIT License |
common/src/commonMain/kotlin/io/config4k/async/AsyncStringSource.kt | Matt1Krause | 323,059,657 | false | null | package io.config4k.async
interface AsyncStringSource {
suspend fun get(): String
} | 0 | Kotlin | 0 | 0 | da4bbb1a0248fb134e6be3942ff0527cb99bb016 | 88 | Config4k | Apache License 2.0 |
app/src/main/java/com/example/movplayv3/ui/screens/details/components/MovplayMovieDetailsInfoSection.kt | Aldikitta | 514,876,509 | false | {"Kotlin": 850016} | package com.example.movplayv3.ui.screens.details.components
import android.annotation.SuppressLint
import androidx.compose.animation.*
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
import com.example.movplayv3.R
import com.example.movplayv3.data.model.ExternalId
import com.example.movplayv3.data.model.ShareDetails
import com.example.movplayv3.data.model.movie.MovieDetails
import com.example.movplayv3.ui.components.sections.MovplayGenresSection
import com.example.movplayv3.ui.components.texts.MovplayAdditionalInfoText
import com.example.movplayv3.ui.components.texts.MovplayExpandableText
import com.example.movplayv3.ui.theme.spacing
import com.example.movplayv3.utils.formattedRuntime
import com.example.movplayv3.utils.timeString
import com.example.movplayv3.utils.yearString
import java.util.*
@OptIn(ExperimentalAnimationApi::class)
@SuppressLint("UnrememberedMutableState")
@Composable
fun MovplayMovieDetailsInfoSection(
movieDetails: MovieDetails?,
watchAtTime: Date?,
modifier: Modifier = Modifier,
imdbExternalId: ExternalId.Imdb? = null,
onShareClicked: (ShareDetails) -> Unit = {}
) {
val otherOriginalTitle: Boolean by derivedStateOf {
movieDetails?.run { originalTitle.isNotEmpty() && title != originalTitle } ?: false
}
val watchAtTimeString = watchAtTime?.let { time ->
stringResource(R.string.movie_details_watch_at, time.timeString())
}
Crossfade(modifier = modifier, targetState = movieDetails) { details ->
if (details != null) {
Column(
modifier = Modifier.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.small)
) {
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = details.title,
style = MaterialTheme.typography.headlineSmall,
fontWeight = FontWeight.ExtraBold
)
if (otherOriginalTitle) {
Text(text = details.originalTitle)
}
MovplayAdditionalInfoText(
modifier = Modifier.fillMaxWidth(),
infoTexts = details.run {
listOfNotNull(
releaseDate?.yearString(),
runtime?.formattedRuntime(),
watchAtTimeString
)
}
)
}
AnimatedVisibility(
visible = imdbExternalId != null,
enter = fadeIn() + scaleIn(initialScale = 0.7f),
exit = fadeOut() + scaleOut()
) {
IconButton(
modifier = Modifier.background(
color = MaterialTheme.colorScheme.surface,
shape = CircleShape
),
onClick = {
imdbExternalId?.let { id ->
val shareDetails = ShareDetails(
title = details.title,
imdbId = id
)
onShareClicked(shareDetails)
}
}
) {
Icon(
imageVector = Icons.Filled.Share,
contentDescription = "share",
tint = MaterialTheme.colorScheme.primary
)
}
}
}
if (details.genres.isNotEmpty()) {
MovplayGenresSection(genres = details.genres)
}
Column(
modifier = Modifier.padding(top = MaterialTheme.spacing.small),
verticalArrangement = Arrangement.spacedBy(MaterialTheme.spacing.extraSmall)
) {
details.tagline?.let { tagline ->
if (tagline.isNotEmpty()) {
Text(
text = "\"$tagline\"",
fontStyle = FontStyle.Italic,
fontSize = 12.sp
)
}
}
details.overview.let { overview ->
if (overview.isNotBlank()) {
MovplayExpandableText(
modifier = Modifier.fillMaxWidth(),
text = overview
)
}
}
}
}
}
}
} | 1 | Kotlin | 12 | 77 | 8344e2a5cf62289c2b56494bf4ecd5227e26de31 | 6,062 | MovplayV3 | Apache License 2.0 |
data/weather/src/commonTest/kotlin/tech/antibytes/keather/data/weather/model/api/RequestPositionSpec.kt | bitPogo | 762,226,385 | false | {"Kotlin": 372822, "MDX": 11276, "TypeScript": 8443, "JavaScript": 8164, "Swift": 6863, "CSS": 2415, "XS": 819, "C": 194, "HTML": 184, "SCSS": 91} | /*
* Copyright (c) 2024 <NAME> (bitPogo) / All rights reserved.
*
* Use of this source code is governed by Apache v2.0
*/
package io.bitpogo.keather.data.weather.model.api
import io.bitpogo.keather.entity.Latitude
import io.bitpogo.keather.entity.Longitude
import kotlin.js.JsName
import kotlin.test.Test
import tech.antibytes.kfixture.fixture
import tech.antibytes.kfixture.kotlinFixture
import tech.antibytes.util.test.mustBe
class RequestPositionSpec {
private val fixture = kotlinFixture()
@Test
@JsName("fn0")
fun `Given a RequestPosition it serializes always to latitude longitude`() {
// Given
val location = RequestPosition(Longitude(fixture.fixture()), Latitude(fixture.fixture()))
// When
val actual = location.toString()
// Then
actual mustBe "${location.latitude.lat},${location.longitude.long}"
}
}
| 0 | Kotlin | 0 | 0 | 7e0b2d1d800f835b0afc2bbeedb708f393668c64 | 890 | keather | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/etterlevelse/EtterlevelseService.kt | navikt | 453,046,573 | false | null | package no.nav.syfo.etterlevelse
import java.time.Duration
import java.time.Instant
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import no.nav.syfo.application.ApplicationState
import no.nav.syfo.application.metrics.PRODUCED_MESSAGE_COUNTER
import no.nav.syfo.etterlevelse.model.JuridiskVurderingKafkaMessage
import no.nav.syfo.etterlevelse.model.JuridiskVurderingResult
import no.nav.syfo.log
import no.nav.syfo.util.Unbounded
import org.apache.kafka.clients.consumer.KafkaConsumer
import org.apache.kafka.clients.producer.KafkaProducer
import org.apache.kafka.clients.producer.ProducerRecord
class EtterlevelseService(
private val applicationState: ApplicationState,
private val kafkaConsumer: KafkaConsumer<String, JuridiskVurderingResult>,
private val internPikTopic: String,
private val kafkaProducer: KafkaProducer<String, JuridiskVurderingKafkaMessage>,
private val etterlevelseTopic: String
) {
private var lastLogTime = Instant.now().toEpochMilli()
private val logTimer = 60_000L
@DelicateCoroutinesApi
fun startConsumer() {
GlobalScope.launch(Dispatchers.Unbounded) {
while (applicationState.ready) {
try {
log.info("Starting consuming topic")
kafkaConsumer.subscribe(listOf(internPikTopic))
start()
} catch (ex: Exception) {
log.error(
"Error running kafka consumer, unsubscribing and waiting 10 seconds for retry",
ex
)
kafkaConsumer.unsubscribe()
delay(10_000)
}
}
}
}
private fun start() {
var processedMessages = 0
while (applicationState.ready) {
val records = kafkaConsumer.poll(Duration.ofSeconds(10))
records.forEach {
it.value().juridiskeVurderinger.forEach { juridiskVurdering ->
sendToKafka(juridiskVurdering.tilJuridiskVurderingKafkaMessage())
}
}
processedMessages += records.count()
processedMessages = logProcessedMessages(processedMessages)
}
}
private fun sendToKafka(juridiskVurderingKafkaMessage: JuridiskVurderingKafkaMessage) {
try {
kafkaProducer
.send(
ProducerRecord(
etterlevelseTopic,
juridiskVurderingKafkaMessage.fodselsnummer,
juridiskVurderingKafkaMessage
)
)
.get()
PRODUCED_MESSAGE_COUNTER.inc()
} catch (ex: Exception) {
log.error("Failed to send message to kafka for id ${juridiskVurderingKafkaMessage.id}")
throw ex
}
}
private fun logProcessedMessages(processedMessages: Int): Int {
val currentLogTime = Instant.now().toEpochMilli()
if (processedMessages > 0 && currentLogTime - lastLogTime > logTimer) {
log.info("Processed $processedMessages messages")
lastLogTime = currentLogTime
return 0
}
return processedMessages
}
}
| 0 | Kotlin | 0 | 0 | d58a1c6645de63d22eae08ee19d40251b791c15e | 3,397 | teamsykmelding-pik | MIT License |
app/src/main/java/com/vr/app/sh/ui/base/TestsOneClassViewModelFactory.kt | Vadim-Rudak | 510,027,925 | false | {"Kotlin": 257696} | package com.vr.app.sh.ui.base
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.vr.app.sh.domain.UseCase.GetListQuestions
import com.vr.app.sh.domain.UseCase.GetListTestsInClass
import com.vr.app.sh.domain.UseCase.SaveQuestionsInBD
import com.vr.app.sh.ui.other.InternetConnection
import com.vr.app.sh.ui.tests.viewmodel.TestsOneClassViewModel
class TestsOneClassViewModelFactory(
val context: Context,
val getListTestsInClass: GetListTestsInClass,
val getListQuestions: GetListQuestions,
val saveQuestionsInBD: SaveQuestionsInBD
): ViewModelProvider.Factory {
var num_class:Int = 0
fun setClass(num_class: Int){
this.num_class = num_class
}
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return if (modelClass.isAssignableFrom(TestsOneClassViewModel::class.java)) {
TestsOneClassViewModel(
resources = context.resources,
getListTestsInClass = getListTestsInClass,
getListQuestions = getListQuestions,
saveQuestionsInBD = saveQuestionsInBD,
numClass = num_class,
internetConnect = InternetConnection.useInternet(context)
) as T
} else {
throw IllegalArgumentException("ViewModel Not Found")
}
}
} | 0 | Kotlin | 0 | 0 | 8a3e4f80636a19187cf053f4a9e58301f1b135ef | 1,393 | SH | Apache License 2.0 |
app/src/main/java/ru/nikstep/alarm/ui/alarmlog/AlarmLogViewModel.kt | nikita715 | 224,504,692 | false | null | package ru.nikstep.alarm.ui.alarmlog
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import ru.nikstep.alarm.model.AlarmLog
import ru.nikstep.alarm.service.data.AlarmLogDataService
import ru.nikstep.alarm.util.data.Result
import ru.nikstep.alarm.util.data.emitLiveData
import javax.inject.Inject
class AlarmLogViewModel @Inject constructor(
private val alarmLogDataService: AlarmLogDataService
) : ViewModel() {
fun getAlarmLogs(): LiveData<Result<List<AlarmLog>>> = emitLiveData {
alarmLogDataService.findAll()
}
} | 0 | Kotlin | 0 | 1 | 5eae531ba4a8184f4f8abfefcbab2c4486efc003 | 562 | spotify-alarm-clock | Apache License 2.0 |
utbot-js/src/main/kotlin/utils/JsOsUtils.kt | UnitTestBot | 480,810,501 | false | null | package utils
import java.util.Locale
abstract class OsProvider {
abstract fun getCmdPrefix(): Array<String>
abstract fun getAbstractivePathTool(): String
abstract val npmPackagePostfix: String
companion object {
fun getProviderByOs(): OsProvider {
val osData = System.getProperty("os.name").lowercase(Locale.getDefault())
return when {
osData.contains("windows") -> WindowsProvider()
else -> LinuxProvider()
}
}
}
}
class WindowsProvider : OsProvider() {
override fun getCmdPrefix() = emptyArray<String>()
override fun getAbstractivePathTool() = "where"
override val npmPackagePostfix = ".cmd"
}
class LinuxProvider : OsProvider() {
override fun getCmdPrefix() = emptyArray<String>()
override fun getAbstractivePathTool() = "which"
override val npmPackagePostfix = ""
}
| 398 | Kotlin | 32 | 91 | abb62682c70d7d2ecc4ad610851d304f7ad716e4 | 909 | UTBotJava | Apache License 2.0 |
app/src/main/java/com/pukkol/launcher/viewutil/TextView.kt | niektuytel | 340,502,518 | false | {"Gradle": 4, "Markdown": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 2, "Java": 2, "XML": 254, "Kotlin": 91} | package com.pukkol.launcher.viewutil
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.pukkol.launcher.data.model.Item
class TextView : AppCompatTextView {
constructor(context: Context?) : super(context!!) {
init(null)
}
constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {
init(attrs)
}
constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context!!, attrs, defStyleAttr) {
init(attrs)
}
private fun init(attrs: AttributeSet?) {}
fun setText(item: Item) {
if (item.labelVisible) {
visibility = VISIBLE
text = item.label
setTextColor(item.labelColor)
// setTag(item);
} else {
visibility = GONE
}
}
} | 1 | null | 1 | 1 | 21f2facb6ac80cecbc02207425669f3394107508 | 880 | launcher | Apache License 2.0 |
src/main/java/app/base/IBaseView.kt | inpot | 125,452,656 | false | null | package app.base
import android.support.v7.app.AppCompatDialog
/**
* Created by daniel on 18-1-31.
*/
interface IBaseView{
fun showLoading()
fun onCreateLoadingDialog():AppCompatDialog?
fun dismissLoading()
fun showError(e: Throwable)
} | 1 | null | 1 | 1 | ed60228d999244154d15a814993bd653d97387d5 | 256 | AppBaseLib | Apache License 2.0 |
src/test/kotlin/com/pestphp/pest/tests/PestIconProviderTest.kt | jeffersonsimaogoncalves | 314,714,294 | true | {"Gradle Kotlin DSL": 2, "Gradle": 1, "Markdown": 4, "Java Properties": 1, "YAML": 5, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "INI": 2, "PHP": 34, "Kotlin": 58, "Java": 1, "SVG": 14, "XML": 2, "HTML": 1} | package com.pestphp.pest.tests
import com.intellij.openapi.util.Iconable.ICON_FLAG_VISIBILITY
import com.pestphp.pest.PestIconProvider
import com.pestphp.pest.PestIcons
import junit.framework.TestCase
import kotlin.test.assertNotEquals
class PestIconProviderTest : PestLightCodeFixture() {
override fun setUp() {
super.setUp()
myFixture.copyFileToProject("SimpleTest.php")
}
override fun getTestDataPath(): String? {
return basePath + "fixtures"
}
fun testCanGetPestIconForPestFile() {
val file = myFixture.configureByFile("SimpleTest.php")
TestCase.assertEquals(
PestIconProvider().getIcon(file, ICON_FLAG_VISIBILITY),
PestIcons.FILE
)
}
fun testCanGetOtherIconForNonPestFile() {
val file = myFixture.configureByFile("SimpleScript.php")
assertNotEquals(
PestIcons.FILE,
PestIconProvider().getIcon(file, ICON_FLAG_VISIBILITY)
)
}
}
| 0 | null | 0 | 1 | f38f951fbbeefe0221a995b71229a24b672b4531 | 992 | pest-intellij | MIT License |
library/src/main/java/com/github/sumimakito/awesomeqr/option/background/StillBackground.kt | sumimakito | 89,555,035 | false | null | package com.github.sumimakito.awesomeqr.option.background
import android.graphics.Bitmap
import android.graphics.Rect
class StillBackground @JvmOverloads constructor(alpha: Float = 0.6f,
clippingRect: Rect? = null,
bitmap: Bitmap? = null) : Background(alpha, clippingRect, bitmap) {
override fun duplicate(): StillBackground {
return StillBackground(
alpha,
clippingRect,
if (bitmap != null) bitmap!!.copy(Bitmap.Config.ARGB_8888, true) else null
)
}
} | 20 | Kotlin | 261 | 1,815 | ac94ebc44f0fcbe43f1950702675af2b8f85bdb1 | 622 | AwesomeQRCode | Apache License 2.0 |
tradeit-android-sdk/src/androidTest/kotlin/it/trade/android/sdk/model/TradeItSecurityQuestionParcelableTest.kt | tradingticket | 74,619,601 | false | null | package it.trade.android.sdk.model
import android.os.Parcel
import android.support.test.filters.SmallTest
import android.support.test.runner.AndroidJUnit4
import org.hamcrest.Matchers.`is`
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*
@RunWith(AndroidJUnit4::class)
@SmallTest
class TradeItSecurityQuestionParcelableTest {
private var tradeItSecurityQuestion: TradeItSecurityQuestionParcelable? = null
@Before
fun createTradeItSecurityQuestion() {
tradeItSecurityQuestion = TradeItSecurityQuestionParcelable("My security question", Arrays.asList("option1", "option2", "option3"))
}
@Test
fun securityQuestion_ParcelableWriteRead() {
val parcel = Parcel.obtain()
tradeItSecurityQuestion!!.writeToParcel(parcel, tradeItSecurityQuestion!!.describeContents())
// After you're done with writing, you need to reset the parcel for reading.
parcel.setDataPosition(0)
// Read the data.
val createdFromParcel = TradeItSecurityQuestionParcelable.CREATOR.createFromParcel(parcel)
val securityQuestion = createdFromParcel.securityQuestion
val securityQuestionOptions = createdFromParcel.securityQuestionOptions
assertThat(securityQuestion, `is`(tradeItSecurityQuestion!!.securityQuestion))
assertThat(securityQuestionOptions, `is`(tradeItSecurityQuestion!!.securityQuestionOptions))
}
}
| 2 | Kotlin | 10 | 13 | 1d784e9eba023479652ccc5963ea7a77624bde01 | 1,484 | AndroidSDK | Apache License 2.0 |
platform/feedback/src/com/intellij/feedback/new_ui/state/NewUIInfoService.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.feedback.new_ui.state
import com.intellij.openapi.components.*
import com.intellij.openapi.util.registry.Registry
import kotlinx.datetime.Clock
import kotlinx.datetime.LocalDateTime
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
import kotlinx.serialization.Serializable
@Service(Service.Level.APP)
@State(name = "NewUIInfoState",
storages = [Storage(StoragePathMacros.NON_ROAMABLE_FILE, deprecated = true), Storage("NewUIInfoService.xml")])
class NewUIInfoService : PersistentStateComponent<NewUIInfoState> {
companion object {
@JvmStatic
fun getInstance(): NewUIInfoService = service()
}
private var state = NewUIInfoState()
override fun getState(): NewUIInfoState = state
override fun loadState(state: NewUIInfoState) {
this.state = state
}
fun updateEnableNewUIDate() {
if (state.enableNewUIDate == null) {
state.enableNewUIDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
}
}
fun updateDisableNewUIDate() {
if (state.disableNewUIDate == null) {
state.disableNewUIDate = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
}
}
}
@Serializable
data class NewUIInfoState(
var numberNotificationShowed: Int = 0,
var feedbackSent: Boolean = false,
var enableNewUIDate: LocalDateTime? = if (Registry.get("ide.experimental.ui").asBoolean())
Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
else null,
var disableNewUIDate: LocalDateTime? = null
) | 214 | null | 4829 | 15,129 | 5578c1c17d75ca03071cc95049ce260b3a43d50d | 1,662 | intellij-community | Apache License 2.0 |
basic_apps/motivation_generator/app/src/main/java/com/example/motivationgenerator/mock/Mock.kt | LucasGeek | 235,174,423 | false | null | package com.example.motivationgenerator.mock
import com.example.motivationgenerator.util.MotivationConstants
import kotlin.random.Random
class Phrase(val description: String, val category: Int)
fun Int.random(): Int = Random.nextInt(this)
class Mock {
private val ALL = MotivationConstants.PHRASE_FILTER.ALL
private val MORNING = MotivationConstants.PHRASE_FILTER.MORNING
private val HAPPY = MotivationConstants.PHRASE_FILTER.HAPPY
private val mListPhrases: List<Phrase> = listOf(
Phrase("Não sabendo que era impossível, foi lá e fez.", HAPPY),
Phrase("Você não é derrotado quando perde, você é derrotado quando desiste!", HAPPY),
Phrase("Quando está mais escuro, vemos mais estrelas!", HAPPY),
Phrase("Insanidade é fazer sempre a mesma coisa e esperar um resultado diferente.", HAPPY),
Phrase("Não pare quando estiver cansado, pare quando tiver terminado.", HAPPY),
Phrase("O que você pode fazer agora que tem o maior impacto sobre o seu sucesso?", HAPPY),
Phrase("Felicidade tem nome: Deus, família e amigos.", HAPPY),
Phrase("Não importa o que você decidiu. O que importa é que isso te faça feliz.", HAPPY),
Phrase("Ser feliz não é viver apenas momentos de alegria. É ter coragem de enfrentar os momentos de tristeza e sabedoria para transformar os problemas em aprendizado.", HAPPY),
Phrase("Nem todos os anjos tem asas, às vezes eles têm apenas o dom de te fazer sorrir.", HAPPY),
Phrase("A vida me ensinou que chorar alivia, mas sorrir torna tudo mais bonito.", HAPPY),
Phrase("Chique é ser feliz. Elegante é ser honesto. Bonito é ser caridoso. Sábio é saber ser grato. O resto é inversão de valores.", HAPPY),
Phrase("Corra o risco. Se der certo, felicidade. Se não, sabedoria.", HAPPY),
Phrase("Prefira o sorriso, faz bem a você e aos que estão ao seu redor. Dê risada de tudo, de si mesmo. Não adie alegrias. Seja feliz hoje!", HAPPY),
Phrase("Tomara que a felicidade te pegue de jeito, e não te solte nunca mais... Vou achar bem feito porque você vai ganhar o que você merece: ser feliz!", HAPPY),
Phrase("Que o vento leve, que a chuva lave, que a alma brilhe, que o coração acalme, que a harmonia se instale e a felicidade permaneça.", HAPPY),
Phrase("A amizade não se compra, se encontra. A felicidade não se encontra, se sente. O amor não se sente, se vive.", HAPPY),
Phrase("Que a vontade de ser feliz seja sempre maior que o medo de se machucar.", HAPPY),
Phrase("Aí vem a vida e te vira do avesso só para provar que a felicidade vem de dentro pra fora.", HAPPY),
Phrase("Faça mais do que te faz feliz.", HAPPY),
Phrase("Sorrir não mata. Viver não dói. Abraçar não arde. Beijar não fere. Rir não machuca. Ou seja, você não tem motivos para não tentar ser feliz.", HAPPY),
Phrase("Eu nasci para ser feliz, não para ser normal.", HAPPY),
Phrase("Seja feliz. Não aceite menos que isso.", HAPPY),
Phrase("Já que a felicidade incomoda tanto, vamos cuidar de ser ainda mais felizes e incomodar muito mais!", HAPPY),
Phrase("Viva do seu jeito. Seja feliz como você é.", HAPPY),
Phrase("Não existe um caminho para a felicidade. A felicidade é o caminho.", HAPPY),
Phrase("Se te faz bem, não importa a idade, não importa o lugar, não importa o momento: vai e agarra sua felicidade.", HAPPY),
Phrase("O melhor lugar do mundo é sempre ao lado de quem te faz feliz.", HAPPY),
Phrase("Deixe um sinal de alegria por onde você passar.", HAPPY),
Phrase("A felicidade é como uma borboleta: quanto mais você corre atrás dela, mais ela foge. Um dia você se distrai e ela pousa em seu ombro.", HAPPY),
Phrase("Não deixe o medo te impedir de ser feliz.", HAPPY),
Phrase("O sorriso é o arco-íris do rosto.", HAPPY),
Phrase("Ser feliz sem motivo é a mais autêntica forma de felicidade.", HAPPY),
Phrase("Talvez o final feliz seja só seguir em frente!", HAPPY),
Phrase("Bonito é ser o motivo do sorriso de alguém.", HAPPY),
Phrase("A felicidade te procura quando você menos espera ser encontrado.", HAPPY),
Phrase("Se a felicidade bater, apanhe!", HAPPY),
Phrase("Aproveite as pequenas coisas.", HAPPY),
Phrase("Espalhe o bem que a felicidade vem!", HAPPY),
Phrase("Nunca desperdice a chance de fazer alguém feliz.", HAPPY),
Phrase("Que os dias felizes sejam os mais longos!", HAPPY),
Phrase("Viva pelo prazer! Nada envelhece tão bem quanto a felicidade!", HAPPY),
Phrase("Seja feliz todo dia!", HAPPY),
Phrase("Que a felicidade faça a gente de gato e sapato.", HAPPY),
Phrase("Felicidade é quando a boca é pequena demais para o sorriso que a alma quer dar.", HAPPY),
Phrase("O segredo da felicidade é não dar importância ao que não tem importância.", HAPPY),
Phrase("Hoje eu só quero ser feliz e mais nada.", HAPPY),
Phrase("Felicidade não se expõe, nem se impõe. Felicidade se vive.", HAPPY),
Phrase("Que o vento sopre sempre a favor da felicidade! ", HAPPY),
Phrase("Quem semeia amor, colhe felicidade.", HAPPY),
Phrase("Um dia sem rir é um dia desperdiçado.", HAPPY),
Phrase("Que a felicidade seja sonho, meta e realidade.", HAPPY),
Phrase("Coloque 'ser feliz no topo da sua lista de prioridades.", HAPPY),
Phrase("Sonhe muito, ria alto... A ordem dos fatores não altera a felicidade.", HAPPY),
Phrase("Insista na felicidade.", HAPPY),
Phrase("Felicidade não é ausência de conflito, mas habilidade em lidar com ele. Alguém feliz não tem o melhor de tudo, mas torna tudo melhor.", HAPPY),
Phrase("Entenda que a felicidade não é ter. É ser!", HAPPY),
Phrase("Felicidade é ter alguém para amar, algo para fazer e alguma coisa pela qual esperar.", HAPPY),
Phrase("Aqui até a tristeza pula de alegria.", HAPPY),
Phrase("Se a felicidade está nas pequenas coisas te desejo uma vida cheia de coisinhas.", HAPPY),
Phrase("A felicidade é uma jornada e não um destino.", HAPPY),
Phrase("O final feliz é a gente que faz.", HAPPY),
Phrase("A felicidade tem amnésia. É preciso lembrá-la todo dia que você existe.", HAPPY),
Phrase("A fórmula da felicidade é só sua.", HAPPY),
Phrase("Feliz é quem pode ostentar boas amizades e um grande amor!", HAPPY),
Phrase("Que você encontre felicidade nas coisas simples!", HAPPY),
Phrase("Fazer o outro feliz é ser feliz sem saber.", HAPPY),
Phrase("A felicidade não depende do que nos falta, mas do bom uso do que temos!", HAPPY),
Phrase("Na plenitude da felicidade, cada dia é uma vida inteira.", HAPPY),
Phrase("Felicidade é encontrar a saída e querer ficar.", HAPPY),
Phrase("Felicidade é quando a sua liberdade te preenche!", HAPPY),
Phrase("Nada é errado se te faz feliz.", HAPPY),
Phrase("Felicidade é agradecer o dia e a vida.", HAPPY),
Phrase("Felicidade é saber viver o hoje.", HAPPY),
Phrase("A melhor maneira de ser feliz é contribuindo para a felicidade dos outros.", HAPPY),
Phrase("Ser sincero com o seu coração é a melhor forma de ser feliz.", HAPPY),
Phrase("Seja como o sol: levante, brilhe e ilumine o mundo!", HAPPY),
Phrase("Felicidade é a combinação de sorte com escolhas bem feitas.", HAPPY),
Phrase("Não existe felicidade onde não há perdão.", HAPPY),
Phrase("A vida é open bar, você só decide de que se embriagar. Que tal um porre de felicidade?", HAPPY),
Phrase("A felicidade é aquele momento em que não desejamos nada diferente daquilo que é.", HAPPY),
Phrase("Aqui a felicidade tem prioridade!", HAPPY),
Phrase("Que a nossa vontade de ser feliz, seja maior que o nosso medo.", HAPPY),
Phrase("Eu tenho mil motivos para ser feliz!", HAPPY),
Phrase("O que estraga a felicidade é o medo.", HAPPY),
Phrase("Que a nossa meta seja sempre ser feliz pra caramba e que a nossa mania seja sempre multiplicar a meta.", HAPPY),
Phrase("Felicidade é ficar juntinho de pernas pro ar.", HAPPY),
Phrase("Corra atrás da tua própria felicidade.", HAPPY),
Phrase("Que nenhum sentimento ruim consiga alcançar a nossa felicidade.", HAPPY),
Phrase("Alimente, todos os dias, a sua vontade de ser feliz.", HAPPY),
Phrase("Felicidade é uma escolha diária.", HAPPY),
Phrase("A felicidade está exatamente onde não costumamos procurar.", HAPPY),
Phrase("É preciso muito pouco para fazer uma vida feliz.", HAPPY),
Phrase("Que a felicidade entre, puxe uma cadeira e fique ao seu lado para sempre!", HAPPY),
Phrase("A felicidade não é algo pronto. Ela é feita das suas próprias ações.", HAPPY),
Phrase("Ao seu lado descobri que entre o sonho e a realidade, existe um espaço chamado felicidade, e para que a minha felicidade se torne realidade, preciso estar ao seu lado.", HAPPY),
Phrase("Acho que a felicidade é uma espécie de susto; quando você vê, já aconteceu. Ela é justamente uma construção pequena de todos os dias...", HAPPY),
Phrase("A felicidade repartida com o próximo dura para sempre.", HAPPY),
Phrase("A preguiça me impede de ser triste! ", HAPPY),
Phrase("Felicidade não é lógica. Por vezes ela quebra todas as regras que dela conhecemos.", HAPPY),
Phrase("Eu desafio você a ter uma overdose de felicidade.", HAPPY),
Phrase("A ousadia é uma condição especial da nossa felicidade.", HAPPY),
Phrase("O propósito da vida é seguir a felicidade de propósito.", HAPPY),
Phrase("Que a gente tenha tudo o que precisa pra ser feliz, mas que saiba ser feliz com bem pouco.", HAPPY),
Phrase("A nossa felicidade se esconde em simples momentos da nossa rotina!", HAPPY),
Phrase("Felicidade é poder estar com quem você gosta em algum lugar.", HAPPY),
Phrase("A felicidade só é real quando compartilhada.", HAPPY),
Phrase("Ser feliz é viver morto de paixão.", HAPPY),
Phrase("Não importa a cor do céu. Quem faz o dia bonito é você.", MORNING),
Phrase("Bom dia! Que seu dia seja igual a vontade de Deus: bom, perfeito e agradável.", MORNING),
Phrase("Sorria! Deus acaba de te dar um novo dia e coisas extraordinárias podem acontecer se você crer!", MORNING),
Phrase("Um pequeno pensamento positivo pela manhã pode mudar todo o seu dia.", MORNING),
Phrase("Que o dia seja leve, que a tristeza seja breve e que o dia seja feliz. Bom dia!", MORNING),
Phrase("Pra hoje: sorrisos bobos, uma mente tranquila e um coração cheio de paz.", MORNING),
Phrase("Que o dia comece bem e termine ainda melhor.", MORNING),
Phrase("Independente do que estiver sentindo, levante-se, vista-se e saia para brilhar.", MORNING),
Phrase("A cada nova manhã, nasce junto uma nova chance. Bom dia!", MORNING),
Phrase("Bom dia! Comece o dia sorrindo. Afinal, coisa boa atrai coisa boa.", MORNING),
Phrase("Sempre que o sol nasce, você tem uma nova oportunidade de ser feliz. Bom dia!", MORNING),
Phrase("Que o amor seja a melhor forma de começar e terminar o dia.", MORNING),
Phrase("Que esse dia seja cheio de energia positiva, amém.", MORNING),
Phrase("Hoje eu acordei tão linda que quando fui bocejar, miei.", MORNING),
Phrase("Tenha um bom dia, uma semana fantástica e uma vida maravilhosa.", MORNING),
Phrase("A melhor maneira de prever o futuro é inventá-lo.", MORNING),
Phrase("Você perde todas as chances que você não aproveita.", MORNING),
Phrase("Fracasso é o condimento que dá sabor ao sucesso.", MORNING),
Phrase("Enquanto não estivermos comprometidos, haverá hesitação!", MORNING),
Phrase("Se você não sabe onde quer ir, qualquer caminho serve.", MORNING),
Phrase("Se você acredita, faz toda a diferença.", MORNING),
Phrase("Riscos devem ser corridos, porque o maior perigo é não arriscar nada!", MORNING),
Phrase("Não importa a cor do céu. Quem faz o dia bonito é você.", MORNING),
Phrase("Bom dia! Que seu dia seja igual a vontade de Deus: bom, perfeito e agradável.", MORNING),
Phrase("Sorria! Deus acaba de te dar um novo dia e coisas extraordinárias podem acontecer se você crer!", MORNING),
Phrase("Um pequeno pensamento positivo pela manhã pode mudar todo o seu dia.", MORNING),
Phrase("Que o dia seja leve, que a tristeza seja breve e que o dia seja feliz. Bom dia!", MORNING),
Phrase("Pra hoje: sorrisos bobos, uma mente tranquila e um coração cheio de paz.", MORNING),
Phrase("Que o dia comece bem e termine ainda melhor.", MORNING),
Phrase("Independente do que estiver sentindo, levante-se, vista-se e saia para brilhar.", MORNING),
Phrase("A cada nova manhã, nasce junto uma nova chance. Bom dia!", MORNING),
Phrase("Bom dia! Comece o dia sorrindo. Afinal, coisa boa atrai coisa boa.", MORNING),
Phrase("Sempre que o sol nasce, você tem uma nova oportunidade de ser feliz. Bom dia!", MORNING),
Phrase("Que o amor seja a melhor forma de começar e terminar o dia.", MORNING),
Phrase("Que esse dia seja cheio de energia positiva, amém.", MORNING),
Phrase("Hoje eu acordei tão linda que quando fui bocejar, miei.", MORNING),
Phrase("Tenha um bom dia, uma semana fantástica e uma vida maravilhosa.", MORNING),
Phrase("Viva cada momento, ria todos os dias, ame além das palavras... Tenha um bom dia!", MORNING),
Phrase("O seu sorriso pode mudar o dia de alguém.", MORNING),
Phrase("Comece o dia com foco em coisas boas. Você é quem faz do seu dia um dia feliz. Seja como um fotógrafo, capture as melhores imagens e delete o que não preste.", MORNING),
Phrase("Bom dia é a forma mais disfarçada de falar 'acordei e pensei em você'.", MORNING),
Phrase("Bom dia! A vida sempre nos oferece uma segunda chance e ela se chama amanhecer!", MORNING),
Phrase("Bom dia pra você que, assim como eu, transforma o bem em um bem ainda maior e, como se não bastasse, sorri quando o mundo quer te fazer chorar!", MORNING),
Phrase("Hoje você tem duas opções: ser feliz ou ser mais feliz ainda. Bom dia!", MORNING),
Phrase("Um dia feliz começa com um sorriso no rosto. Bom dia!", MORNING),
Phrase("A vida é o nosso maior presente, tenha consciência disso. Bom Dia!", MORNING),
Phrase("Hoje é um dia que nunca mais irá se repetir. Aproveite. Tenha um bom dia!", MORNING),
Phrase("Acorda! O melhor ainda está por vir. Bom dia!", MORNING),
Phrase("Que hoje nada e nem ninguém estrague seu dia. Bom dia!", MORNING),
Phrase("Seja o bom dia que você deseja!", MORNING),
Phrase("Bom dia! Amenidades, leveza e calma na alma... É o que quero para hoje.", MORNING),
Phrase("Três passos para ter um bom dia: sorria, agradeça e ame-se.", MORNING),
Phrase("Hoje vai ser um bom dia!", MORNING),
Phrase("Tenha um dia feliz, repleto de alegria e felicidade!", MORNING),
Phrase("Que o dia nos apronte boas surpresas e nos faça sorrir.", MORNING),
Phrase("Desejo a você um bom dia, com um bom sorriso, bom humor, um bom café e boa fé!", MORNING),
Phrase("Hoje é dia de semear coisas boas.", MORNING),
Phrase("Comece cada dia sendo grato por ele. Bom dia!", MORNING),
Phrase("O bom dia que você deseja só depende de você!", MORNING),
Phrase("Bom dia! Acorde todos os dias com um motivo para fazer o seu dia incrível.", MORNING),
Phrase("Bom dia para você que acordou acreditando que tudo vai dar certo!", MORNING),
Phrase("Para começar bem o dia, uma pitadinha de amor e outra bem generosa de gratidão.", MORNING),
Phrase("Que o dia nos abrace com sorrisos, esperança e pitadas de aconchego.", MORNING),
Phrase("Cada novo amanhecer é uma nova chance que a vida te dá!", MORNING),
Phrase("Todo dia é sempre um recomeço!", MORNING),
Phrase("O primeiro sorriso do meu dia aparece quando abro os olhos e me lembro de você. Bom dia, meu amor!", MORNING),
Phrase("Comece o dia longe de toda negatividade. Bom dia!", MORNING),
Phrase("Comece o dia com um sorriso e termine com um champagne.", MORNING),
Phrase("Novo dia, nova emoção!", MORNING),
Phrase("Viva um dia de cada vez para ser feliz todos os dias. Bom dia!", MORNING),
Phrase("Hoje o dia vai ser lindão! ", MORNING),
Phrase("O mundo é de quem acorda feliz!", MORNING),
Phrase("Bom dia, amigo, que a paz seja contigo. Eu vim somente dizer que eu te amo tanto.", MORNING),
Phrase("Um novo dia vem nascendo, um novo sol já vai raiar. Parece a vida, rompendo em luz e que nos convida a amar.", MORNING),
Phrase("Minha idade não define minha maturidade, minhas notas não definem minha inteligência e as fofocas que fazem de mim não definem quem eu sou.", MORNING),
Phrase("Não deixe que as pessoas te façam desistir daquilo que você mais quer na vida. Acredite. Lute. Conquiste. E acima de tudo, seja feliz.", MORNING),
Phrase("Não coloque limites em seus sonhos, coloque fé.", MORNING),
Phrase("Não importa o que você decidiu. O que importa é que isso te faça feliz.", MORNING),
Phrase("Um pequeno pensamento positivo pela manhã pode mudar todo o seu dia.", MORNING),
Phrase("O que você tem de diferente é o que você tem de mais bonito.", MORNING),
Phrase("Algumas pessoas sempre vão jogar pedras no seu caminho, depende de você o que você faz com elas. Uma parede ou uma ponte?", MORNING),
Phrase("Viva simples, sonhe grande, seja grato, dê amor, ria muito!", MORNING)
)
fun getPhrase(value: Int): String {
val filtered = mListPhrases.filter { it -> (it.category == value || value == ALL) }
val rand = (filtered.size).random()
return filtered[rand].description
}
} | 0 | Kotlin | 0 | 0 | c4885d49adbd0cd6af461ca5a954bf9f28ce002e | 18,167 | Android-Native-APPS | MIT License |
basic_apps/motivation_generator/app/src/main/java/com/example/motivationgenerator/mock/Mock.kt | LucasGeek | 235,174,423 | false | null | package com.example.motivationgenerator.mock
import com.example.motivationgenerator.util.MotivationConstants
import kotlin.random.Random
class Phrase(val description: String, val category: Int)
fun Int.random(): Int = Random.nextInt(this)
class Mock {
private val ALL = MotivationConstants.PHRASE_FILTER.ALL
private val MORNING = MotivationConstants.PHRASE_FILTER.MORNING
private val HAPPY = MotivationConstants.PHRASE_FILTER.HAPPY
private val mListPhrases: List<Phrase> = listOf(
Phrase("Não sabendo que era impossível, foi lá e fez.", HAPPY),
Phrase("Você não é derrotado quando perde, você é derrotado quando desiste!", HAPPY),
Phrase("Quando está mais escuro, vemos mais estrelas!", HAPPY),
Phrase("Insanidade é fazer sempre a mesma coisa e esperar um resultado diferente.", HAPPY),
Phrase("Não pare quando estiver cansado, pare quando tiver terminado.", HAPPY),
Phrase("O que você pode fazer agora que tem o maior impacto sobre o seu sucesso?", HAPPY),
Phrase("Felicidade tem nome: Deus, família e amigos.", HAPPY),
Phrase("Não importa o que você decidiu. O que importa é que isso te faça feliz.", HAPPY),
Phrase("Ser feliz não é viver apenas momentos de alegria. É ter coragem de enfrentar os momentos de tristeza e sabedoria para transformar os problemas em aprendizado.", HAPPY),
Phrase("Nem todos os anjos tem asas, às vezes eles têm apenas o dom de te fazer sorrir.", HAPPY),
Phrase("A vida me ensinou que chorar alivia, mas sorrir torna tudo mais bonito.", HAPPY),
Phrase("Chique é ser feliz. Elegante é ser honesto. Bonito é ser caridoso. Sábio é saber ser grato. O resto é inversão de valores.", HAPPY),
Phrase("Corra o risco. Se der certo, felicidade. Se não, sabedoria.", HAPPY),
Phrase("Prefira o sorriso, faz bem a você e aos que estão ao seu redor. Dê risada de tudo, de si mesmo. Não adie alegrias. Seja feliz hoje!", HAPPY),
Phrase("Tomara que a felicidade te pegue de jeito, e não te solte nunca mais... Vou achar bem feito porque você vai ganhar o que você merece: ser feliz!", HAPPY),
Phrase("Que o vento leve, que a chuva lave, que a alma brilhe, que o coração acalme, que a harmonia se instale e a felicidade permaneça.", HAPPY),
Phrase("A amizade não se compra, se encontra. A felicidade não se encontra, se sente. O amor não se sente, se vive.", HAPPY),
Phrase("Que a vontade de ser feliz seja sempre maior que o medo de se machucar.", HAPPY),
Phrase("Aí vem a vida e te vira do avesso só para provar que a felicidade vem de dentro pra fora.", HAPPY),
Phrase("Faça mais do que te faz feliz.", HAPPY),
Phrase("Sorrir não mata. Viver não dói. Abraçar não arde. Beijar não fere. Rir não machuca. Ou seja, você não tem motivos para não tentar ser feliz.", HAPPY),
Phrase("Eu nasci para ser feliz, não para ser normal.", HAPPY),
Phrase("Seja feliz. Não aceite menos que isso.", HAPPY),
Phrase("Já que a felicidade incomoda tanto, vamos cuidar de ser ainda mais felizes e incomodar muito mais!", HAPPY),
Phrase("Viva do seu jeito. Seja feliz como você é.", HAPPY),
Phrase("Não existe um caminho para a felicidade. A felicidade é o caminho.", HAPPY),
Phrase("Se te faz bem, não importa a idade, não importa o lugar, não importa o momento: vai e agarra sua felicidade.", HAPPY),
Phrase("O melhor lugar do mundo é sempre ao lado de quem te faz feliz.", HAPPY),
Phrase("Deixe um sinal de alegria por onde você passar.", HAPPY),
Phrase("A felicidade é como uma borboleta: quanto mais você corre atrás dela, mais ela foge. Um dia você se distrai e ela pousa em seu ombro.", HAPPY),
Phrase("Não deixe o medo te impedir de ser feliz.", HAPPY),
Phrase("O sorriso é o arco-íris do rosto.", HAPPY),
Phrase("Ser feliz sem motivo é a mais autêntica forma de felicidade.", HAPPY),
Phrase("Talvez o final feliz seja só seguir em frente!", HAPPY),
Phrase("Bonito é ser o motivo do sorriso de alguém.", HAPPY),
Phrase("A felicidade te procura quando você menos espera ser encontrado.", HAPPY),
Phrase("Se a felicidade bater, apanhe!", HAPPY),
Phrase("Aproveite as pequenas coisas.", HAPPY),
Phrase("Espalhe o bem que a felicidade vem!", HAPPY),
Phrase("Nunca desperdice a chance de fazer alguém feliz.", HAPPY),
Phrase("Que os dias felizes sejam os mais longos!", HAPPY),
Phrase("Viva pelo prazer! Nada envelhece tão bem quanto a felicidade!", HAPPY),
Phrase("Seja feliz todo dia!", HAPPY),
Phrase("Que a felicidade faça a gente de gato e sapato.", HAPPY),
Phrase("Felicidade é quando a boca é pequena demais para o sorriso que a alma quer dar.", HAPPY),
Phrase("O segredo da felicidade é não dar importância ao que não tem importância.", HAPPY),
Phrase("Hoje eu só quero ser feliz e mais nada.", HAPPY),
Phrase("Felicidade não se expõe, nem se impõe. Felicidade se vive.", HAPPY),
Phrase("Que o vento sopre sempre a favor da felicidade! ", HAPPY),
Phrase("Quem semeia amor, colhe felicidade.", HAPPY),
Phrase("Um dia sem rir é um dia desperdiçado.", HAPPY),
Phrase("Que a felicidade seja sonho, meta e realidade.", HAPPY),
Phrase("Coloque 'ser feliz no topo da sua lista de prioridades.", HAPPY),
Phrase("Sonhe muito, ria alto... A ordem dos fatores não altera a felicidade.", HAPPY),
Phrase("Insista na felicidade.", HAPPY),
Phrase("Felicidade não é ausência de conflito, mas habilidade em lidar com ele. Alguém feliz não tem o melhor de tudo, mas torna tudo melhor.", HAPPY),
Phrase("Entenda que a felicidade não é ter. É ser!", HAPPY),
Phrase("Felicidade é ter alguém para amar, algo para fazer e alguma coisa pela qual esperar.", HAPPY),
Phrase("Aqui até a tristeza pula de alegria.", HAPPY),
Phrase("Se a felicidade está nas pequenas coisas te desejo uma vida cheia de coisinhas.", HAPPY),
Phrase("A felicidade é uma jornada e não um destino.", HAPPY),
Phrase("O final feliz é a gente que faz.", HAPPY),
Phrase("A felicidade tem amnésia. É preciso lembrá-la todo dia que você existe.", HAPPY),
Phrase("A fórmula da felicidade é só sua.", HAPPY),
Phrase("Feliz é quem pode ostentar boas amizades e um grande amor!", HAPPY),
Phrase("Que você encontre felicidade nas coisas simples!", HAPPY),
Phrase("Fazer o outro feliz é ser feliz sem saber.", HAPPY),
Phrase("A felicidade não depende do que nos falta, mas do bom uso do que temos!", HAPPY),
Phrase("Na plenitude da felicidade, cada dia é uma vida inteira.", HAPPY),
Phrase("Felicidade é encontrar a saída e querer ficar.", HAPPY),
Phrase("Felicidade é quando a sua liberdade te preenche!", HAPPY),
Phrase("Nada é errado se te faz feliz.", HAPPY),
Phrase("Felicidade é agradecer o dia e a vida.", HAPPY),
Phrase("Felicidade é saber viver o hoje.", HAPPY),
Phrase("A melhor maneira de ser feliz é contribuindo para a felicidade dos outros.", HAPPY),
Phrase("Ser sincero com o seu coração é a melhor forma de ser feliz.", HAPPY),
Phrase("Seja como o sol: levante, brilhe e ilumine o mundo!", HAPPY),
Phrase("Felicidade é a combinação de sorte com escolhas bem feitas.", HAPPY),
Phrase("Não existe felicidade onde não há perdão.", HAPPY),
Phrase("A vida é open bar, você só decide de que se embriagar. Que tal um porre de felicidade?", HAPPY),
Phrase("A felicidade é aquele momento em que não desejamos nada diferente daquilo que é.", HAPPY),
Phrase("Aqui a felicidade tem prioridade!", HAPPY),
Phrase("Que a nossa vontade de ser feliz, seja maior que o nosso medo.", HAPPY),
Phrase("Eu tenho mil motivos para ser feliz!", HAPPY),
Phrase("O que estraga a felicidade é o medo.", HAPPY),
Phrase("Que a nossa meta seja sempre ser feliz pra caramba e que a nossa mania seja sempre multiplicar a meta.", HAPPY),
Phrase("Felicidade é ficar juntinho de pernas pro ar.", HAPPY),
Phrase("Corra atrás da tua própria felicidade.", HAPPY),
Phrase("Que nenhum sentimento ruim consiga alcançar a nossa felicidade.", HAPPY),
Phrase("Alimente, todos os dias, a sua vontade de ser feliz.", HAPPY),
Phrase("Felicidade é uma escolha diária.", HAPPY),
Phrase("A felicidade está exatamente onde não costumamos procurar.", HAPPY),
Phrase("É preciso muito pouco para fazer uma vida feliz.", HAPPY),
Phrase("Que a felicidade entre, puxe uma cadeira e fique ao seu lado para sempre!", HAPPY),
Phrase("A felicidade não é algo pronto. Ela é feita das suas próprias ações.", HAPPY),
Phrase("Ao seu lado descobri que entre o sonho e a realidade, existe um espaço chamado felicidade, e para que a minha felicidade se torne realidade, preciso estar ao seu lado.", HAPPY),
Phrase("Acho que a felicidade é uma espécie de susto; quando você vê, já aconteceu. Ela é justamente uma construção pequena de todos os dias...", HAPPY),
Phrase("A felicidade repartida com o próximo dura para sempre.", HAPPY),
Phrase("A preguiça me impede de ser triste! ", HAPPY),
Phrase("Felicidade não é lógica. Por vezes ela quebra todas as regras que dela conhecemos.", HAPPY),
Phrase("Eu desafio você a ter uma overdose de felicidade.", HAPPY),
Phrase("A ousadia é uma condição especial da nossa felicidade.", HAPPY),
Phrase("O propósito da vida é seguir a felicidade de propósito.", HAPPY),
Phrase("Que a gente tenha tudo o que precisa pra ser feliz, mas que saiba ser feliz com bem pouco.", HAPPY),
Phrase("A nossa felicidade se esconde em simples momentos da nossa rotina!", HAPPY),
Phrase("Felicidade é poder estar com quem você gosta em algum lugar.", HAPPY),
Phrase("A felicidade só é real quando compartilhada.", HAPPY),
Phrase("Ser feliz é viver morto de paixão.", HAPPY),
Phrase("Não importa a cor do céu. Quem faz o dia bonito é você.", MORNING),
Phrase("Bom dia! Que seu dia seja igual a vontade de Deus: bom, perfeito e agradável.", MORNING),
Phrase("Sorria! Deus acaba de te dar um novo dia e coisas extraordinárias podem acontecer se você crer!", MORNING),
Phrase("Um pequeno pensamento positivo pela manhã pode mudar todo o seu dia.", MORNING),
Phrase("Que o dia seja leve, que a tristeza seja breve e que o dia seja feliz. Bom dia!", MORNING),
Phrase("Pra hoje: sorrisos bobos, uma mente tranquila e um coração cheio de paz.", MORNING),
Phrase("Que o dia comece bem e termine ainda melhor.", MORNING),
Phrase("Independente do que estiver sentindo, levante-se, vista-se e saia para brilhar.", MORNING),
Phrase("A cada nova manhã, nasce junto uma nova chance. Bom dia!", MORNING),
Phrase("Bom dia! Comece o dia sorrindo. Afinal, coisa boa atrai coisa boa.", MORNING),
Phrase("Sempre que o sol nasce, você tem uma nova oportunidade de ser feliz. Bom dia!", MORNING),
Phrase("Que o amor seja a melhor forma de começar e terminar o dia.", MORNING),
Phrase("Que esse dia seja cheio de energia positiva, amém.", MORNING),
Phrase("Hoje eu acordei tão linda que quando fui bocejar, miei.", MORNING),
Phrase("Tenha um bom dia, uma semana fantástica e uma vida maravilhosa.", MORNING),
Phrase("A melhor maneira de prever o futuro é inventá-lo.", MORNING),
Phrase("Você perde todas as chances que você não aproveita.", MORNING),
Phrase("Fracasso é o condimento que dá sabor ao sucesso.", MORNING),
Phrase("Enquanto não estivermos comprometidos, haverá hesitação!", MORNING),
Phrase("Se você não sabe onde quer ir, qualquer caminho serve.", MORNING),
Phrase("Se você acredita, faz toda a diferença.", MORNING),
Phrase("Riscos devem ser corridos, porque o maior perigo é não arriscar nada!", MORNING),
Phrase("Não importa a cor do céu. Quem faz o dia bonito é você.", MORNING),
Phrase("Bom dia! Que seu dia seja igual a vontade de Deus: bom, perfeito e agradável.", MORNING),
Phrase("Sorria! Deus acaba de te dar um novo dia e coisas extraordinárias podem acontecer se você crer!", MORNING),
Phrase("Um pequeno pensamento positivo pela manhã pode mudar todo o seu dia.", MORNING),
Phrase("Que o dia seja leve, que a tristeza seja breve e que o dia seja feliz. Bom dia!", MORNING),
Phrase("Pra hoje: sorrisos bobos, uma mente tranquila e um coração cheio de paz.", MORNING),
Phrase("Que o dia comece bem e termine ainda melhor.", MORNING),
Phrase("Independente do que estiver sentindo, levante-se, vista-se e saia para brilhar.", MORNING),
Phrase("A cada nova manhã, nasce junto uma nova chance. Bom dia!", MORNING),
Phrase("Bom dia! Comece o dia sorrindo. Afinal, coisa boa atrai coisa boa.", MORNING),
Phrase("Sempre que o sol nasce, você tem uma nova oportunidade de ser feliz. Bom dia!", MORNING),
Phrase("Que o amor seja a melhor forma de começar e terminar o dia.", MORNING),
Phrase("Que esse dia seja cheio de energia positiva, amém.", MORNING),
Phrase("Hoje eu acordei tão linda que quando fui bocejar, miei.", MORNING),
Phrase("Tenha um bom dia, uma semana fantástica e uma vida maravilhosa.", MORNING),
Phrase("Viva cada momento, ria todos os dias, ame além das palavras... Tenha um bom dia!", MORNING),
Phrase("O seu sorriso pode mudar o dia de alguém.", MORNING),
Phrase("Comece o dia com foco em coisas boas. Você é quem faz do seu dia um dia feliz. Seja como um fotógrafo, capture as melhores imagens e delete o que não preste.", MORNING),
Phrase("Bom dia é a forma mais disfarçada de falar 'acordei e pensei em você'.", MORNING),
Phrase("Bom dia! A vida sempre nos oferece uma segunda chance e ela se chama amanhecer!", MORNING),
Phrase("Bom dia pra você que, assim como eu, transforma o bem em um bem ainda maior e, como se não bastasse, sorri quando o mundo quer te fazer chorar!", MORNING),
Phrase("Hoje você tem duas opções: ser feliz ou ser mais feliz ainda. Bom dia!", MORNING),
Phrase("Um dia feliz começa com um sorriso no rosto. Bom dia!", MORNING),
Phrase("A vida é o nosso maior presente, tenha consciência disso. Bom Dia!", MORNING),
Phrase("Hoje é um dia que nunca mais irá se repetir. Aproveite. Tenha um bom dia!", MORNING),
Phrase("Acorda! O melhor ainda está por vir. Bom dia!", MORNING),
Phrase("Que hoje nada e nem ninguém estrague seu dia. Bom dia!", MORNING),
Phrase("Seja o bom dia que você deseja!", MORNING),
Phrase("Bom dia! Amenidades, leveza e calma na alma... É o que quero para hoje.", MORNING),
Phrase("Três passos para ter um bom dia: sorria, agradeça e ame-se.", MORNING),
Phrase("Hoje vai ser um bom dia!", MORNING),
Phrase("Tenha um dia feliz, repleto de alegria e felicidade!", MORNING),
Phrase("Que o dia nos apronte boas surpresas e nos faça sorrir.", MORNING),
Phrase("Desejo a você um bom dia, com um bom sorriso, bom humor, um bom café e boa fé!", MORNING),
Phrase("Hoje é dia de semear coisas boas.", MORNING),
Phrase("Comece cada dia sendo grato por ele. Bom dia!", MORNING),
Phrase("O bom dia que você deseja só depende de você!", MORNING),
Phrase("Bom dia! Acorde todos os dias com um motivo para fazer o seu dia incrível.", MORNING),
Phrase("Bom dia para você que acordou acreditando que tudo vai dar certo!", MORNING),
Phrase("Para começar bem o dia, uma pitadinha de amor e outra bem generosa de gratidão.", MORNING),
Phrase("Que o dia nos abrace com sorrisos, esperança e pitadas de aconchego.", MORNING),
Phrase("Cada novo amanhecer é uma nova chance que a vida te dá!", MORNING),
Phrase("Todo dia é sempre um recomeço!", MORNING),
Phrase("O primeiro sorriso do meu dia aparece quando abro os olhos e me lembro de você. Bom dia, meu amor!", MORNING),
Phrase("Comece o dia longe de toda negatividade. Bom dia!", MORNING),
Phrase("Comece o dia com um sorriso e termine com um champagne.", MORNING),
Phrase("Novo dia, nova emoção!", MORNING),
Phrase("Viva um dia de cada vez para ser feliz todos os dias. Bom dia!", MORNING),
Phrase("Hoje o dia vai ser lindão! ", MORNING),
Phrase("O mundo é de quem acorda feliz!", MORNING),
Phrase("Bom dia, amigo, que a paz seja contigo. Eu vim somente dizer que eu te amo tanto.", MORNING),
Phrase("Um novo dia vem nascendo, um novo sol já vai raiar. Parece a vida, rompendo em luz e que nos convida a amar.", MORNING),
Phrase("Minha idade não define minha maturidade, minhas notas não definem minha inteligência e as fofocas que fazem de mim não definem quem eu sou.", MORNING),
Phrase("Não deixe que as pessoas te façam desistir daquilo que você mais quer na vida. Acredite. Lute. Conquiste. E acima de tudo, seja feliz.", MORNING),
Phrase("Não coloque limites em seus sonhos, coloque fé.", MORNING),
Phrase("Não importa o que você decidiu. O que importa é que isso te faça feliz.", MORNING),
Phrase("Um pequeno pensamento positivo pela manhã pode mudar todo o seu dia.", MORNING),
Phrase("O que você tem de diferente é o que você tem de mais bonito.", MORNING),
Phrase("Algumas pessoas sempre vão jogar pedras no seu caminho, depende de você o que você faz com elas. Uma parede ou uma ponte?", MORNING),
Phrase("Viva simples, sonhe grande, seja grato, dê amor, ria muito!", MORNING)
)
fun getPhrase(value: Int): String {
val filtered = mListPhrases.filter { it -> (it.category == value || value == ALL) }
val rand = (filtered.size).random()
return filtered[rand].description
}
} | 0 | Kotlin | 0 | 0 | c4885d49adbd0cd6af461ca5a954bf9f28ce002e | 18,167 | Android-Native-APPS | MIT License |
android/src/main/java/com/magicleap/magicscript/ar/renderable/ModelRenderableLoaderImpl.kt | magic-script | 187,085,008 | false | null | /*
* Copyright (c) 2019-2020 Magic Leap, Inc. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.magicleap.magicscript.ar.renderable
import android.content.Context
import android.net.Uri
import com.google.ar.sceneform.assets.RenderableSource
import com.google.ar.sceneform.rendering.ModelRenderable
import com.magicleap.magicscript.ar.ArResourcesProvider
import com.magicleap.magicscript.ar.ModelType
import com.magicleap.magicscript.utils.DataResult
import com.magicleap.magicscript.utils.Utils
import com.magicleap.magicscript.utils.logMessage
class ModelRenderableLoaderImpl(
private val context: Context,
private val arResourcesProvider: ArResourcesProvider
) : ModelRenderableLoader,
ArResourcesProvider.ArLoadedListener {
init {
arResourcesProvider.addArLoadedListener(this)
}
private val pendingRequests = mutableListOf<ModelRenderableLoader.LoadRequest>()
override fun loadRenderable(request: ModelRenderableLoader.LoadRequest) {
if (arResourcesProvider.isArLoaded()) {
load(request)
} else {
pendingRequests.add(request)
}
}
override fun cancel(request: ModelRenderableLoader.LoadRequest) {
request.cancel()
pendingRequests.remove(request)
}
override fun onArLoaded(firstTime: Boolean) {
val requestIterator = pendingRequests.iterator()
while (requestIterator.hasNext()) {
load(requestIterator.next())
requestIterator.remove()
}
}
private fun load(request: ModelRenderableLoader.LoadRequest) {
val modelUri = request.modelUri
val builder = ModelRenderable.builder()
val modelType = Utils.detectModelType(modelUri, context)
when (modelType) {
ModelType.GLB -> setGLBSource(builder, modelUri, request.glbRecenterMode)
ModelType.SFB -> setSFBSource(builder, modelUri)
ModelType.UNKNOWN -> {
val errorMessage = "Unresolved model type"
logMessage(errorMessage, true)
request.listener.invoke(DataResult.Error(Exception(errorMessage)))
return
}
}
builder
.setRegistryId(modelUri)
.build()
.thenAccept { renderable ->
if (!request.isCancelled) {
renderable.isShadowReceiver = false
renderable.isShadowCaster = false
request.listener.invoke(DataResult.Success(renderable))
}
}
.exceptionally { throwable ->
logMessage("error loading ModelRenderable: $throwable")
request.listener.invoke(DataResult.Error(throwable))
null
}
}
private fun setGLBSource(
builder: ModelRenderable.Builder,
uri: Uri,
recenterMode: RenderableSource.RecenterMode
) {
val source = RenderableSource.builder()
.setSource(context, uri, RenderableSource.SourceType.GLB)
.setRecenterMode(recenterMode)
.build()
builder.setSource(context, source)
}
private fun setSFBSource(builder: ModelRenderable.Builder, uri: Uri) {
builder.setSource(context, uri)
}
} | 41 | Swift | 2 | 16 | b1a543f22af76447e9e58788fc494324dc40be14 | 3,833 | magic-script-components-react-native | Apache License 2.0 |
src/main/kotlin/me/glaremasters/deluxequeues/commands/CommandDeluxeQueues.kt | deluxequeues | 196,781,604 | false | null | package me.glaremasters.deluxequeues.commands
import ch.jalu.configme.SettingsManager
import co.aikar.commands.BaseCommand
import co.aikar.commands.CommandHelp
import co.aikar.commands.CommandIssuer
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.CommandPermission
import co.aikar.commands.annotation.Dependency
import co.aikar.commands.annotation.Description
import co.aikar.commands.annotation.HelpCommand
import co.aikar.commands.annotation.Subcommand
import co.aikar.commands.annotation.Syntax
import co.aikar.commands.bungee.contexts.OnlinePlayer
import me.glaremasters.deluxequeues.DeluxeQueues
import me.glaremasters.deluxequeues.configuration.sections.ConfigOptions
import me.glaremasters.deluxequeues.messages.Messages
import me.glaremasters.deluxequeues.queues.QueueHandler
import me.glaremasters.deluxequeues.utils.ADMIN_PERM
import me.glaremasters.deluxequeues.utils.BASE_PERM
import net.md_5.bungee.api.connection.ProxiedPlayer
@CommandAlias("%dq")
class CommandDeluxeQueues : BaseCommand() {
@Dependency private lateinit var queueHandler: QueueHandler
@Dependency private lateinit var settingsManager: SettingsManager
@Dependency private lateinit var deluxeQueues: DeluxeQueues
@Subcommand("reload")
@Description("{@@descriptions.reload}")
@CommandPermission(ADMIN_PERM)
fun reload(issuer: CommandIssuer) {
settingsManager.reload()
// Update the notify methods for each queue
queueHandler.getQueues().forEach { queue ->
queue.notifyMethod = settingsManager.getProperty(ConfigOptions.INFORM_METHOD)
}
issuer.sendInfo(Messages.RELOAD__SUCCESS)
}
@Subcommand("remove")
@Description("{@@descriptions.remove}")
@CommandPermission(ADMIN_PERM)
@Syntax("<player>")
fun remove(issuer: CommandIssuer, player: OnlinePlayer) {
queueHandler.clearPlayer(player.player)
currentCommandIssuer.sendInfo(Messages.ADMIN__REMOVED, "{player}", player.player.name)
}
@Subcommand("leave")
@Description("{@@descriptions.command-leave}")
@CommandPermission(BASE_PERM + "leave")
fun leave(player: ProxiedPlayer) {
queueHandler.clearPlayer(player)
currentCommandIssuer.sendInfo(Messages.QUEUES__LEFT)
}
@HelpCommand
@CommandPermission(BASE_PERM + "help")
@Description("{@@descriptions.help}")
fun help(help: CommandHelp) {
help.showHelp()
}
} | 0 | Kotlin | 2 | 2 | 5b54f8f59c07382df856d1a2b48f43464969430b | 2,461 | DeluxeQueues | MIT License |
airbyte-data/src/test/kotlin/io/airbyte/data/services/impls/data/ConnectionTimelineEventServiceDataImplTest.kt | airbytehq | 592,970,656 | false | null | /*
* Copyright (c) 2020-2024 Airbyte, Inc., all rights reserved.
*/
package io.airbyte.data.services.impls.data
import io.airbyte.commons.jackson.MoreMappers
import io.airbyte.config.FailureReason
import io.airbyte.data.repositories.ConnectionTimelineEventRepository
import io.airbyte.data.repositories.entities.ConnectionTimelineEvent
import io.airbyte.data.services.ConnectionTimelineEventService
import io.airbyte.data.services.shared.SyncFailedEvent
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.util.Optional
import java.util.UUID
internal class ConnectionTimelineEventServiceDataImplTest {
private lateinit var repository: ConnectionTimelineEventRepository
private lateinit var service: ConnectionTimelineEventService
@BeforeEach
internal fun setUp() {
repository = mockk()
service =
ConnectionTimelineEventServiceDataImpl(
repository = repository,
mapper = MoreMappers.initMapper(),
)
}
@Test
internal fun `write sync failed event`() {
val connectionId = UUID.randomUUID()
every {
repository.save(any())
} returns ConnectionTimelineEvent(connectionId = connectionId, eventType = "")
val syncFailedEvent =
SyncFailedEvent(
jobId = 100L,
startTimeEpochSeconds = 10L,
endTimeEpochSeconds = 11L,
bytesLoaded = 0L,
recordsLoaded = 2L,
attemptsCount = 5,
failureReason = Optional.of(FailureReason()),
)
service.writeEvent(connectionId = connectionId, event = syncFailedEvent)
verify {
repository.save(any())
}
}
}
| 49 | null | 209 | 176 | dfbe1d243e506d202ad166398b17eff20b834b78 | 1,689 | airbyte-platform | MIT License |
src/main/kotlin/org/athenian/17-typealiases.kt | athenian-programming | 196,145,981 | false | null | package org.athenian
typealias FIntToString = (Int) -> String
typealias FIntToInt = (Int) -> Int
typealias StringMap = Map<String, String>
fun main() {
val unaliased: (Int) -> String = { "The int = $it" }
println(unaliased(4))
val aliased: FIntToString = { "The value is $it" }
println(aliased(5))
val squared: FIntToInt = { it * it }
println(squared(6))
fun dumpMap(map: StringMap) = map.forEach { (k, v) -> println("Key: $k Val: $v") }
dumpMap(mapOf("a" to "a val"))
} | 1 | null | 1 | 1 | df0f94b4df896f0496210968438423b25f1365b8 | 492 | kotlin-highlights | Apache License 2.0 |
app/src/main/java/com/suihan74/satena/scenes/preferences/favoriteSites/FavoriteSitesActionsImplForPreferences.kt | suihan74 | 207,459,108 | false | {"Kotlin": 1734003, "Java": 10330} | package com.suihan74.satena.scenes.preferences.favoriteSites
import android.app.Activity
import android.content.Intent
import com.suihan74.satena.models.favoriteSite.FavoriteSiteAndFavicon
import com.suihan74.satena.scenes.browser.BrowserActivity
import com.suihan74.satena.scenes.preferences.pages.FavoriteSitesFragment
class FavoriteSitesActionsImplForPreferences : FavoriteSitesViewModelInterface {
private fun openMenuDialog(
site: FavoriteSiteAndFavicon,
activity: Activity,
fragment: FavoriteSitesFragment
) {
fragment.viewModel.openMenuDialog(
activity,
site,
fragment.childFragmentManager
)
}
override fun onClickItem(
site: FavoriteSiteAndFavicon,
activity: Activity,
fragment: FavoriteSitesFragment
) {
openMenuDialog(site, activity, fragment)
}
override fun onLongClickItem(
site: FavoriteSiteAndFavicon,
activity: Activity,
fragment: FavoriteSitesFragment
) {
openMenuDialog(site, activity, fragment)
}
override fun onClickAddButton(
activity: Activity,
fragment: FavoriteSitesFragment
) {
fragment.viewModel.openItemRegistrationDialog(
null,
fragment.childFragmentManager
)
}
override fun openInBrowser(site: FavoriteSiteAndFavicon, activity: Activity) {
val intent = Intent(activity, BrowserActivity::class.java).also {
it.putExtra(BrowserActivity.EXTRA_URL, site.site.url)
}
activity.startActivity(intent)
}
}
| 34 | Kotlin | 1 | 7 | d18b936e17647745920115041fe15d761a209d8a | 1,619 | Satena | MIT License |
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/project/importer/control/dto/ImportColumn.kt | boschglobal | 805,348,245 | false | {"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344} | /*
* ************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2018 - 2022
*
* ************************************************************************
*/
package com.bosch.pt.iot.smartsite.project.importer.control.dto
import net.sf.mpxj.FieldType
open class ImportColumn(
val name: String,
val columnType: ImportColumnType,
val fieldType: FieldType? = null,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ImportColumn) return false
if (name != other.name) return false
if (fieldType != other.fieldType) return false
if (columnType != other.columnType) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + fieldType.hashCode()
result = 31 * result + columnType.hashCode()
return result
}
}
| 0 | Kotlin | 3 | 9 | 9f3e7c4b53821bdfc876531727e21961d2a4513d | 929 | bosch-pt-refinemysite-backend | Apache License 2.0 |
app/src/main/java/com/github/cheapmon/balalaika/ui/dictionary/DictionaryFragment.kt | cheapmon | 233,464,548 | false | null | /*
* Copyright 2020 Simon Kaleschke
*
* 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.github.cheapmon.balalaika.ui.dictionary
import android.content.Intent
import android.media.MediaPlayer
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.ui.platform.ComposeView
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.github.cheapmon.balalaika.MainViewModel
import com.github.cheapmon.balalaika.R
import com.github.cheapmon.balalaika.model.DataCategory
import com.github.cheapmon.balalaika.model.DictionaryEntry
import com.github.cheapmon.balalaika.model.Property
import com.github.cheapmon.balalaika.model.SearchRestriction
import com.github.cheapmon.balalaika.util.exhaustive
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.ExperimentalCoroutinesApi
/**
* Fragment for dictionary usage
*
* The user may:
* - See lexemes and their properties
* - Reorder dictionary entries
* - Choose a dictionary view
* - Go to the base of a lexeme
* - Bookmark an entry
* - Collapse an entry
* - See advanced actions on an entry
*/
@ExperimentalCoroutinesApi
@AndroidEntryPoint
class DictionaryFragment : Fragment() {
private val viewModel: DictionaryViewModel by viewModels()
private val activityViewModel: MainViewModel by activityViewModels()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return ComposeView(requireContext()).apply {
setContent {
DictionaryEntryScreen(
activityViewModel = activityViewModel,
navController = findNavController(),
onNavigateToSearch = ::onOpenSearch,
onClickBase = ::onClickBaseButton,
onBookmark = ::onClickBookmarkButton,
onClickProperty = ::onClickProperty,
onOpenDictionaries = ::onOpenDictionaries
)
}
}
}
private fun onOpenSearch() {
val directions = DictionaryFragmentDirections.actionNavHomeToNavSearch()
findNavController().navigate(directions)
}
/** Open dictionary screen */
private fun onOpenDictionaries() {
val directions = DictionaryFragmentDirections.selectDictionary()
findNavController().navigate(directions)
}
/** Add or remove an entry to bookmarks */
private fun onClickBookmarkButton(entry: DictionaryEntry) {
viewModel.toggleBookmark(entry)
viewModel.refresh()
val message = if (entry.bookmark != null) {
getString(R.string.dictionary_bookmark_remove, entry.representation)
} else {
getString(R.string.dictionary_bookmark_add, entry.representation)
}
Snackbar.make(requireView(), message, Snackbar.LENGTH_SHORT).show()
}
/** Go to base of a lexeme */
private fun onClickBaseButton(entry: DictionaryEntry) {
viewModel.setInitialEntry(entry.base)
}
/** Actions when a property is clicked */
private fun onClickProperty(category: DataCategory, property: Property, text: String) {
when (property) {
is Property.Audio -> audioActionListener.onAction(property)
is Property.Example -> {
}
is Property.Morphology -> searchWithRestriction(text, category)
is Property.Plain -> searchWithRestriction(text, category)
is Property.Reference -> referenceActionListener.onAction(property)
is Property.Simple -> searchWithRestriction(text, category)
is Property.Url -> urlActionListener.onAction(property)
is Property.Wordnet -> wordnetActionListener.onAction(property)
}.exhaustive
}
private interface WidgetActionListener<T : Property> {
fun onAction(property: T)
}
private val audioActionListener = object : WidgetActionListener<Property.Audio> {
/** Play audio file */
override fun onAction(property: Property.Audio) {
try {
MediaPlayer.create(context, property.fileName.toUri()).apply {
start()
setOnCompletionListener { release() }
}
} catch (ex: Exception) {
Snackbar.make(
requireView(),
R.string.dictionary_playback_failed,
Snackbar.LENGTH_SHORT
).show()
}
}
}
private val referenceActionListener = object : WidgetActionListener<Property.Reference> {
override fun onAction(property: Property.Reference) {
viewModel.setInitialEntry(property.entry)
}
}
private val urlActionListener = object : WidgetActionListener<Property.Url> {
override fun onAction(property: Property.Url) {
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(property.url)))
}
}
private val wordnetActionListener = object : WidgetActionListener<Property.Wordnet> {
override fun onAction(property: Property.Wordnet) {
viewModel.setWordnetParam(property)
}
}
private fun searchWithRestriction(item: String, category: DataCategory) {
val restriction = SearchRestriction(category, item)
val directions = DictionaryFragmentDirections.actionNavHomeToNavSearch(restriction)
findNavController().navigate(directions)
}
}
| 1 | Kotlin | 1 | 2 | ced6f772ab5df750ce0005f58a276361554fde63 | 6,327 | balalaika | Apache License 2.0 |
app/src/androidTest/java/io/mochadwi/AppRepositoryTest.kt | mochadwi | 189,831,173 | false | null | package io.mochadwi
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.test.ext.junit.runners.AndroidJUnit4
import io.mochadwi.data.repository.AppRepository
import io.mochadwi.util.ext.default
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.koin.test.KoinTest
import org.koin.test.inject
/**
*
* In syaa Allah created or modified by @mochadwi
* On 2019-05-20 for social-app
*/
@RunWith(AndroidJUnit4::class)
class AppRepositoryTest : KoinTest {
private val repository by inject<AppRepository>()
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
@Test
fun test_getPostsApi() {
runBlocking {
val result = repository.getPostsAsync().await()
result?.forEach(::println)
}
}
@Test
fun test_searchPostsApi() {
runBlocking {
val result = repository.searchPostsAsync("foo").await()
result?.forEach(::println)
}
}
@Test
fun test_isNotEmptyPostsApi() {
runBlocking {
val result = repository.getPostsAsync().await()
assertEquals(true, result != null)
assertEquals(true, result?.isNotEmpty().default)
}
}
} | 0 | Kotlin | 1 | 29 | 65afc6ec314c39d09211cdac52d6be34a52c1c0e | 1,347 | android-social-app | Apache License 2.0 |
app/src/main/java/co/icanteach/projectx/domain/FetchPopularTvShowUseCase.kt | mertceyhan | 218,565,173 | true | {"Kotlin": 38070} | package co.icanteach.projectx.domain
import co.icanteach.projectx.common.Resource
import co.icanteach.projectx.data.feed.MoviesRepository
import co.icanteach.projectx.ui.populartvshows.model.PopularTvShowItem
import io.reactivex.Observable
import javax.inject.Inject
class FetchPopularTvShowUseCase @Inject constructor(
private val repository: MoviesRepository,
private val mapper: PopularTvShowMapper
) {
fun fetchMovies(page: Int): Observable<Resource<List<PopularTvShowItem>>> {
return repository
.fetchMovies(page)
.map { resource ->
Resource(
status = resource.status,
data = resource.data?.let { mapper.mapFrom(it) },
error = resource.error
)
}
}
} | 0 | Kotlin | 0 | 1 | ee2669f2aa9b1ebc672fcd7627e6a369eb8681bd | 809 | ProjectX | MIT License |
src/test/kotlin/kLoops/music/SequencerKtTest.kt | Onuchin-Artem | 231,309,462 | false | null | package kLoops.music
import org.junit.Test
import org.junit.Assert.*
class SequencerKtTest {
@Test
fun euclideanRythm() {
assertEquals("k . k . .", euclideanRythm(2, 5, "k"))
assertEquals("x . x . x . x . .", euclideanRythm(4, 9, "x"))
}
} | 0 | Kotlin | 0 | 8 | f81e5127ed3dfc1c4b86e22d91727ea95178a1ec | 271 | k-Loops | MIT License |
feature/menu/main/src/main/kotlin/com/ngapp/metanmobile/feature/menu/ui/ThemeModeRowItem.kt | ngapp-dev | 878,233,406 | false | {"Kotlin": 1167674} | /*
* Copyright 2024 NGApps Dev (https://github.com/ngapp-dev). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.ngapp.metanmobile.feature.menu.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import com.ngapp.metanmobile.core.designsystem.theme.Gray400
import com.ngapp.metanmobile.core.designsystem.theme.MMColors
import com.ngapp.metanmobile.core.designsystem.theme.MMTypography
import com.ngapp.metanmobile.core.designsystem.theme.cardBackgroundColor
import com.ngapp.metanmobile.core.model.userdata.LanguageConfig
import com.ngapp.metanmobile.feature.menu.R
@Composable
internal fun LanguageConfigRowItem(
modifier: Modifier = Modifier,
titleResId: Int,
languageConfig: LanguageConfig,
onShowAlertDialog: () -> Unit,
) {
val languageName = when (languageConfig) {
LanguageConfig.RU -> R.string.feature_menu_main_pref_language_russian
LanguageConfig.BE -> R.string.feature_menu_main_pref_language_belarusian
LanguageConfig.EN -> R.string.feature_menu_main_pref_language_english
}
Row(
modifier = modifier
.fillMaxWidth()
.background(MMColors.cardBackgroundColor)
.height(64.dp)
.clickable(onClick = onShowAlertDialog)
.padding(all = 16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
text = stringResource(id = titleResId),
overflow = TextOverflow.Ellipsis,
modifier = Modifier
.fillMaxWidth()
.weight(1f)
.padding(vertical = 4.dp),
style = MMTypography.titleLarge
)
Text(
text = stringResource(id = languageName),
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(vertical = 4.dp),
style = MMTypography.headlineMedium,
color = Gray400
)
}
} | 0 | Kotlin | 0 | 0 | f44bd23069c40a0342ed1310505f5bcc0547868c | 2,977 | metanmobile | Apache License 2.0 |
app/src/main/java/util/prefs/UsernamePref.kt | jguerinet | 45,987,287 | false | null | /*
* Copyright 2014-2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.guerinet.mymartlet.util.prefs
import android.content.Context
import android.content.SharedPreferences
import com.guerinet.mymartlet.R
import com.guerinet.suitcase.prefs.NullStringPref
/**
* Stores and loads the user's username (McGill email)
* @author <NAME>
* @since 1.0.0
*/
class UsernamePref(context: Context, prefs: SharedPreferences) :
NullStringPref(prefs, "username", null) {
private val emailSuffix: String = context.getString(R.string.login_email)
/** User's full email, null if none */
val full: String?
get() = super.value?.run { super.value + emailSuffix }
}
| 27 | Kotlin | 3 | 9 | c1bdb3095663958882e1fb30b7175f21083dd6e2 | 1,212 | MyMartlet | Apache License 2.0 |
library/src/commonMain/kotlin/dev/afalabarce/kmm/jetpackcompose/RadioButtonGroup.kt | afalabarce | 813,304,744 | false | {"Kotlin": 117698, "Ruby": 2250} | package dev.afalabarce.kmm.jetpackcompose
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import org.jetbrains.compose.ui.tooling.preview.Preview
@Composable
inline fun <reified T> RadioButtonGroup(
modifier: Modifier = Modifier,
crossinline radioButtonLabel: @Composable (T) -> Unit = { },
crossinline radioButtonBody: @Composable (T) -> Unit = { },
radioButtonValues: Array<T>,
selectedValue: T?,
borderStroke: BorderStroke? = null,
dividerHeight: Dp = 4.dp,
excludedValues: Array<T> = emptyArray(),
radioButtonItemShape: Shape = MaterialTheme.shapes.medium,
crossinline onCheckedChanged: (T) -> Unit
) {
Column(
modifier = modifier
) {
radioButtonValues
.filter { notExcluded -> !excludedValues.any { excluded -> excluded == notExcluded } }
.forEachIndexed { index, item ->
if (index > 0)
Spacer(modifier = Modifier.size(dividerHeight))
Column(
modifier = Modifier
.clip(radioButtonItemShape)
.border(borderStroke ?: BorderStroke(0.dp, Color.Unspecified), radioButtonItemShape)
.fillMaxWidth()
.clickable { onCheckedChanged(item) },
) {
var radioButtonWidth: Dp by remember { mutableStateOf(48.dp) }
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
RadioButton(
selected = item == selectedValue,
onClick = { onCheckedChanged(item) }
)
Spacer(modifier = Modifier.width(2.dp))
radioButtonLabel(item)
}
Row(
modifier = Modifier.padding(start = radioButtonWidth.plus(2.dp)).fillMaxWidth(),
verticalAlignment = Alignment.Top
) {
radioButtonBody(item)
}
}
}
}
}
@Preview
@Composable
fun RadioGroupPreview() {
val data = arrayOf("Hello", "World")
RadioButtonGroup(
modifier = Modifier.padding(end = 8.dp).fillMaxWidth(),
radioButtonValues = data,
selectedValue = null,
radioButtonItemShape = RoundedCornerShape(4.dp),
radioButtonLabel = {
Text(text = it)
},
radioButtonBody = {
Button(
modifier = Modifier.fillMaxWidth(),
onClick = {}
) {
Text(text = "Click me, $it")
}
}
) {
}
}
| 0 | Kotlin | 0 | 0 | 8839e9134b03c924259dd06fa94fbc8671d76889 | 3,710 | kmm-jetpackcompose | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/kendraranking/_BuildableLastArgumentExtensions.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.kendraranking
import kotlin.Unit
import software.amazon.awscdk.services.kendraranking.CfnExecutionPlan
/**
* You can set additional capacity units to meet the needs of your rescore execution plan.
*/
public inline
fun CfnExecutionPlan.setCapacityUnits(block: CfnExecutionPlanCapacityUnitsConfigurationPropertyDsl.() -> Unit
= {}) {
val builder = CfnExecutionPlanCapacityUnitsConfigurationPropertyDsl()
builder.apply(block)
return setCapacityUnits(builder.build())
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 700 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/com/shepeliev/livemvi/feature/CounterFeatureImpl.kt | shepeliev | 229,240,925 | false | null | package com.shepeliev.livemvi.feature
import com.badoo.mvicore.element.Actor
import com.badoo.mvicore.element.Reducer
import com.badoo.mvicore.feature.ActorReducerFeature
import com.shepeliev.livemvi.data.CalculatorApi
import com.shepeliev.livemvi.feature.CounterFeature.*
import com.shepeliev.livemvi.mvicore.rxFlow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
private const val SLOW_LOADING_THRESHOLD_MS = 1_000L
class CounterFeatureImpl(calculatorApi: CalculatorApi, coroutineScope: CoroutineScope) :
ActorReducerFeature<Wish, Effect, State, Nothing>(
initialState = State(),
actor = ActorImpl(calculatorApi, coroutineScope),
reducer = ReducerImpl()
), CounterFeature {
private class ActorImpl(
private val calculatorApi: CalculatorApi,
coroutineScope: CoroutineScope
) : Actor<State, Wish, Effect>,
CoroutineScope by coroutineScope {
override fun invoke(state: State, action: Wish) = rxFlow<Effect> {
when (action) {
is Wish.Add -> {
onNext(Effect.Loading)
launch {
delay(SLOW_LOADING_THRESHOLD_MS)
onNext(Effect.StillLoading)
}
val result = calculatorApi.add(state.counter, action.n)
onNext(Effect.Success(result))
onComplete()
}
}
}
}
private class ReducerImpl : Reducer<State, Effect> {
override fun invoke(state: State, effect: Effect): State {
return when (effect) {
is Effect.Loading -> state.copy(isLoading = true)
is Effect.StillLoading -> state.copy(isSlowLoading = true)
is Effect.Success -> state.copy(
counter = effect.payload,
isLoading = false,
isSlowLoading = false
)
}
}
}
}
| 0 | Kotlin | 1 | 1 | ac6495931d2f89f3165b9fb68b7bf58ea52ad40f | 2,044 | mvicore_courutines_example | Apache License 2.0 |
src/dev/silash/kotlinHtmx/attributes/htmx/HxVals.kt | silas00301 | 825,155,225 | false | {"Kotlin": 112936} | package dev.silash.kotlinHtmx.attributes.htmx
import dev.silash.kotlinHtmx.attributes.HtmlAttribute
import dev.silash.kotlinHtmx.attributes.HtmxHtmlAttributes
class HxVals : HtmlAttribute("hx-vals") {
fun normal(strategy: HxValsMap.() -> Unit) = +generateValsMap(strategy)
fun javaScript(strategy: HxValsMap.() -> Unit) = +("js:${generateValsMap(strategy)}")
fun js(strategy: HxValsMap.() -> Unit) = javaScript(strategy)
private fun generateValsMap(strategy: HxValsMap.() -> Unit) =
HxValsMap().apply(strategy).attributeText.trim(' ', ',').let {
"{ $it }"
}
class HxValsMap : HtmlAttribute("hx-vals") {
fun add(
key: String,
value: String,
) = +"$key: $value,"
}
}
fun HtmxHtmlAttributes.vals(lambda: HxVals.() -> Unit) = addEntry(HxVals(), lambda)
| 0 | Kotlin | 0 | 1 | 8f37ebbf49779cb2326dccfd5b293f3da3595561 | 848 | kotlin-htmx | MIT License |
app/src/main/kotlin/pro/stuermer/dailyexpenses/ui/settings/SettingsViewModel.kt | thebino | 590,016,472 | false | null | package pro.stuermer.dailyexpenses.ui.settings
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import pro.stuermer.dailyexpenses.data.network.Resource
import pro.stuermer.dailyexpenses.data.network.asResource
import pro.stuermer.dailyexpenses.domain.usecase.CreateSharingUseCase
import pro.stuermer.dailyexpenses.domain.usecase.GetSharingUseCase
import pro.stuermer.dailyexpenses.domain.usecase.JoinSharingUseCase
import pro.stuermer.dailyexpenses.domain.usecase.LeaveSharingUseCase
import pro.stuermer.dailyexpenses.domain.usecase.StartSyncUseCase
class SettingsViewModel(
private val getSharingUseCase: GetSharingUseCase,
private val createSharingUseCase: CreateSharingUseCase,
private val joinSharingUseCase: JoinSharingUseCase,
private val leaveSharingUseCase: LeaveSharingUseCase,
private val startSyncUseCase: StartSyncUseCase,
) : ViewModel() {
val uiState = MutableStateFlow(SettingsUiState())
init {
viewModelScope.launch(Dispatchers.IO) {
loadSharing()
}
}
fun handleEvent(event: SettingsEvent) {
when (event) {
SettingsEvent.EnableMaterialYou -> {
// TODO: enable material you colors in theme
// uiState.update { it.copy(isMaterialYouEnabled = true) }
}
SettingsEvent.DisableMaterialYou -> {
// TODO: disable material you colors in theme
//uiState.update { it.copy(isMaterialYouEnabled = false) }
}
SettingsEvent.ShowShareDialog -> {
uiState.update { it.copy(showShareDialog = true) }
}
SettingsEvent.HideShareDialog -> {
uiState.update { it.copy(showShareDialog = false) }
}
SettingsEvent.GenerateShare -> {
viewModelScope.launch(Dispatchers.IO) {
uiState.update { it.copy(isSharingLoading = true, sharingError = null) }
val result = createSharingUseCase()
result.onSuccess { sharingCode: String ->
startSyncUseCase()
uiState.update { it.copy(
isSharingLoading = false,
sharingCode = sharingCode,
sharingError = null
) }
}
result.onFailure {
uiState.update { it.copy(
isSharingLoading = false,
sharingError = "Could not create sharing group!"
) }
}
}
}
SettingsEvent.LeaveSharing -> {
uiState.update {
it.copy(
sharingCode = "", isShareingEnrolled = false
)
}
viewModelScope.launch(Dispatchers.IO) {
leaveSharingUseCase()
}
}
is SettingsEvent.JoinShare -> {
viewModelScope.launch(Dispatchers.IO) {
uiState.update { it.copy(isSharingLoading = true, sharingError = null) }
val result = joinSharingUseCase(event.code)
result.onSuccess {
if (it) {
startSyncUseCase()
uiState.update {
it.copy(
isSharingLoading = false,
sharingError = null
)
}
} else {
uiState.update { it.copy(
isSharingLoading = false,
sharingError = "Could not join sharing group!"
) }
}
}
result.onFailure {
uiState.update { it.copy(
isSharingLoading = false,
sharingError = "Could not join sharing group!"
) }
}
}
}
is SettingsEvent.CodeChanged -> {
uiState.update { it.copy(sharingCode = event.code) }
}
}
}
private suspend fun loadSharing() {
getSharingUseCase().asResource().collect { result ->
when (result) {
is Resource.Error -> {
// TODO: show error?
uiState.update { it.copy(isSharingLoading = false) }
}
is Resource.Loading -> {
uiState.update { it.copy(isSharingLoading = true) }
}
is Resource.Success -> {
uiState.update {
it.copy(
sharingCode = result.data.firstOrNull()?.code ?: "",
isSharingLoading = false,
isShareingEnrolled = result.data.isNotEmpty(),
)
}
}
}
}
}
}
| 9 | Kotlin | 0 | 0 | 9ef7eb2eead8e11ad554a818f6a629fbb2d41116 | 5,457 | DailyExpenses | Apache License 2.0 |
src/main/kotlin/io/puharesource/simplemavenrepo/FileExtensions.kt | Puharesource | 102,220,397 | false | null | package io.puharesource.simplemavenrepo
import org.apache.commons.codec.digest.DigestUtils
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
// Checksum
internal fun File.createMd5ChecksumFile() : File? {
if (!exists()) {
return null
}
val checksumFile = File(parent, name + ".md5")
if (!checksumFile.exists()) {
checksumFile.createNewFile()
checksumFile.writeText(getMd5Checksum())
}
return checksumFile
}
internal fun File.createSha1ChecksumFile() : File? {
if (!exists()) {
return null
}
val checksumFile = File(parent, name + ".sha1")
if (!checksumFile.exists()) {
checksumFile.createNewFile()
checksumFile.writeText(getSha1Checksum())
}
return checksumFile
}
internal fun File.createChecksumFiles() {
createMd5ChecksumFile()
createSha1ChecksumFile()
}
internal fun File.getMd5Checksum() : String = DigestUtils.md5Hex(readBytes())
internal fun File.getSha1Checksum() : String = DigestUtils.sha1Hex(readBytes())
// Other
internal fun File.getLastModifiedString() : String = SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").format(Date(lastModified())) | 0 | Kotlin | 1 | 3 | 24e2df8e9930c56174035160aa6428511f7bf463 | 1,188 | SimpleMavenRepository | Apache License 2.0 |
Kubo-Telegram/src/main/kotlin/io/github/ranolp/kubo/telegram/client/TelegramClientOption.kt | RanolP | 102,352,053 | false | {"Kotlin": 62165} | package io.github.ranolp.kubo.telegram.client
import io.github.ranolp.kubo.general.Option
import io.github.ranolp.kubo.telegram.Telegram
import java.nio.file.Path
import java.nio.file.Paths
class TelegramClientOption(val apiId: Int, val apiHash: String, val phoneNumber: String,
val appVersion: String = "Kubo Based App", val deviceModel: String = "Unknown",
val systemVersion: String = "Unknown", val langCode: String = "EN",
val authKeyFile: Path = Paths.get("auth_key"),
val nearestDcFile: Path = Paths.get("nearest_data_center")) : Option(Telegram.CLIENT_SIDE) {} | 0 | Kotlin | 1 | 3 | 24fc06a182b6cb18ec2132ba639e992d7ad2e727 | 601 | Kubo | MIT License |
src/main/kotlin/com/raycoarana/poitodiscover/domain/PoiType.kt | raycoarana | 146,994,891 | false | null | package com.raycoarana.poitodiscover.domain
enum class PoiType(val highId: Int, val tsdId: Int, val image: String) {
ResidentialArea(0, 2001, "000_image.png"),
Hidden(1, 2002, "001_image.png"),
Fixed(2, 2003, "002_image.png"),
Photo(3, 2004, "003_image.png"),
Semaphores(4, 2005, "004_image.png"),
SectionEnd(5, 2006, "005_image.png"),
SectionStart(6, 2007, "006_image.png"),
Tunnel(7, 2008, "007_image.png"),
Mercadona(8, 2009, "008_mercadona.png"),
Unknown(-1, -1, "");
fun getResId() = highId + 1
fun getCategoryId() = highId + 1000
} | 0 | Kotlin | 0 | 9 | e580b5ba6f5e872eae2b3136996ac6361f1b4541 | 587 | poi-to-discover-media | Apache License 2.0 |
src/main/kotlin/com/github/plplmax/simulator/kitchen/CookOf.kt | plplmax | 538,049,460 | false | {"Kotlin": 26178} | package com.github.plplmax.simulator.kitchen
import androidx.compose.runtime.State
import com.github.plplmax.simulator.order.Order
import com.github.plplmax.simulator.server.Server
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import kotlin.time.Duration
class CookOf(
private val server: Server,
private val state: KitchenState,
private val interval: State<Duration>
) : Cook {
override suspend fun startWork(): Unit = withContext(Dispatchers.Default) {
while (isActive) {
val processingOrder = state.waitingOrders.removeFirstOrNull()
if (processingOrder == null) {
delay(50)
} else {
state.currentOrderId = processingOrder.id()
delay(interval.value.inWholeMilliseconds)
server.completeOrder(processingOrder)
}
}
}
override fun makeOrder(order: Order) {
state.waitingOrders.add(order)
server.afterOrderMaked()
}
}
| 0 | Kotlin | 0 | 1 | 8950a388d99b1c7ddb67b459a15cbfbee79a2ec1 | 1,087 | fast-food-simulator | MIT License |
lib/sisyphus-protobuf/src/main/kotlin/com/bybutter/sisyphus/protobuf/primitives/TimestampExtension.kt | zhi-re | 290,148,776 | true | {"Kotlin": 1090965, "ANTLR": 8164} | package com.bybutter.sisyphus.protobuf.primitives
import com.bybutter.sisyphus.protobuf.invoke
import com.bybutter.sisyphus.protobuf.primitives.internal.MutableDuration
import com.bybutter.sisyphus.protobuf.primitives.internal.MutableTimestamp
import com.bybutter.sisyphus.string.leftPadding
import com.bybutter.sisyphus.string.rightPadding
import java.math.BigInteger
import java.time.Instant
import java.time.LocalDateTime
import java.time.Month
import java.time.OffsetDateTime
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.format.DateTimeParseException
import java.util.concurrent.TimeUnit
import kotlin.math.abs
import kotlin.math.sign
private const val nanosPerSecond = 1000000000L
private val nanosPerSecondBigInteger = nanosPerSecond.toBigInteger()
private val defaultOffset = OffsetDateTime.now().offset
fun java.sql.Timestamp.toProto(): Timestamp = Timestamp {
seconds = TimeUnit.MILLISECONDS.toSeconds([email protected])
nanos = [email protected]
}
fun Timestamp.toSql(): java.sql.Timestamp {
val result = java.sql.Timestamp(TimeUnit.SECONDS.toMillis(seconds))
result.nanos = nanos
return result
}
fun LocalDateTime.toProto(): Timestamp = Timestamp {
seconds = [email protected](defaultOffset).epochSecond
nanos = [email protected]
}
fun Timestamp.toLocalDateTime(offset: ZoneOffset = defaultOffset): LocalDateTime {
return LocalDateTime.ofEpochSecond(seconds, nanos, offset)
}
operator fun Timestamp.Companion.invoke(value: String): Timestamp {
return Timestamp {
val instant = ZonedDateTime.parse(value).toInstant()
seconds = instant.epochSecond
nanos = instant.nano
}
}
fun Timestamp.Companion.tryParse(value: String): Timestamp? {
return try {
invoke(value)
} catch (e: DateTimeParseException) {
null
}
}
operator fun Timestamp.Companion.invoke(
year: Int,
month: Month,
day: Int,
hour: Int = 0,
minute: Int = 0,
second: Int = 0,
nano: Int = 0,
zoneId: ZoneId = ZoneId.systemDefault()
): Timestamp {
val instant = ZonedDateTime.of(year, month.value, day, hour, minute, second, nano, zoneId).toInstant()
return Timestamp {
this.seconds = instant.epochSecond
this.nanos = instant.nano
}
}
operator fun Timestamp.Companion.invoke(
year: Int,
month: Int,
day: Int,
hour: Int = 0,
minute: Int = 0,
second: Int = 0,
nano: Int = 0,
zoneId: ZoneId = ZoneId.systemDefault()
): Timestamp {
val instant = ZonedDateTime.of(year, month, day, hour, minute, second, nano, zoneId).toInstant()
return Timestamp {
this.seconds = instant.epochSecond
this.nanos = instant.nano
}
}
operator fun Timestamp.Companion.invoke(instant: Instant): Timestamp {
return Timestamp {
this.seconds = instant.epochSecond
this.nanos = instant.nano
}
}
fun Timestamp.Companion.now(): Timestamp {
val instant = Instant.now()
return Timestamp {
this.seconds = instant.epochSecond
this.nanos = instant.nano
}
}
operator fun Timestamp.Companion.invoke(seconds: Long, nanos: Int = 0): Timestamp {
return Timestamp {
this.seconds = seconds
this.nanos = nanos
normalized()
}
}
operator fun Timestamp.Companion.invoke(seconds: Double): Timestamp {
return Timestamp {
this.seconds = seconds.toLong()
this.nanos = ((seconds - seconds.toLong()) * seconds.sign * nanosPerSecond).toInt()
}
}
operator fun Timestamp.Companion.invoke(nanos: BigInteger): Timestamp {
return Timestamp {
this.seconds = (nanos / nanosPerSecondBigInteger).toLong()
this.nanos = (nanos % nanosPerSecondBigInteger).toInt()
}
}
private val durationRegex = """^(-)?([0-9]+)(?:\.([0-9]+))?s$""".toRegex()
operator fun Duration.Companion.invoke(value: String): Duration {
return tryParse(value) ?: throw IllegalArgumentException("Illegal duration value '$value'.")
}
fun Duration.Companion.tryParse(value: String): Duration? {
val result = durationRegex.matchEntire(value) ?: return null
val sign = if (result.groupValues[1].isEmpty()) 1 else -1
val seconds = result.groupValues[2].toLong() * sign
val nanos = result.groupValues[3].rightPadding(9, '0').toInt() * sign
return Duration(seconds, nanos)
}
operator fun Duration.Companion.invoke(seconds: Long, nanos: Int = 0): Duration {
return Duration {
this.seconds = seconds
this.nanos = nanos
normalized()
}
}
operator fun Duration.Companion.invoke(seconds: Double): Duration {
return invoke(seconds, TimeUnit.SECONDS)
}
operator fun Duration.Companion.invoke(time: Double, unit: TimeUnit): Duration {
val nanos = (unit.toNanos(1) * time).toLong()
return Duration {
this.seconds = nanos / nanosPerSecond
this.nanos = (nanos % nanosPerSecond).toInt()
}
}
operator fun Duration.Companion.invoke(nanos: BigInteger): Duration {
return Duration {
this.seconds = (nanos / nanosPerSecondBigInteger).toLong()
this.nanos = (nanos % nanosPerSecondBigInteger).toInt()
}
}
operator fun Duration.Companion.invoke(hours: Long, minutes: Long, seconds: Long, nanos: Int = 0): Duration {
return Duration(
(
TimeUnit.HOURS.toNanos(hours) + TimeUnit.MINUTES.toNanos(minutes) + TimeUnit.SECONDS.toNanos(
seconds
) + nanos
).toBigInteger()
)
}
fun Timestamp.toBigInteger(): BigInteger {
return BigInteger.valueOf(this.seconds) * BigInteger.valueOf(nanosPerSecond) + BigInteger.valueOf(this.nanos.toLong())
}
fun Timestamp.toTime(unit: TimeUnit): Long {
val nanos = seconds * nanosPerSecond + nanos
return unit.convert(nanos, TimeUnit.NANOSECONDS)
}
fun Timestamp.toSeconds(): Long {
return toTime(TimeUnit.SECONDS)
}
fun Timestamp.toInstant(): Instant {
return Instant.ofEpochSecond(this.seconds, this.nanos.toLong())
}
fun Duration.toBigInteger(): BigInteger {
return BigInteger.valueOf(this.seconds) * BigInteger.valueOf(nanosPerSecond) + BigInteger.valueOf(this.nanos.toLong())
}
fun Duration.toTime(unit: TimeUnit): Long {
val nanos = seconds * nanosPerSecond + nanos
return unit.convert(nanos, TimeUnit.NANOSECONDS)
}
fun Duration.toSeconds(): Long {
return toTime(TimeUnit.SECONDS)
}
operator fun Timestamp.plus(duration: Duration): Timestamp {
return this {
seconds += duration.seconds
nanos += duration.nanos
normalized()
}
}
operator fun Timestamp.minus(duration: Duration): Timestamp {
return this {
seconds -= duration.seconds
nanos -= duration.nanos
normalized()
}
}
operator fun Timestamp.minus(other: Timestamp): Duration {
return Duration(this.toBigInteger() - other.toBigInteger())
}
operator fun Timestamp.compareTo(other: Timestamp): Int {
if (this.seconds != other.seconds) {
return this.seconds.compareTo(other.seconds)
}
return this.nanos.compareTo(other.nanos)
}
fun Timestamp.string(): String {
return this.toInstant().toString()
}
operator fun Duration.plus(duration: Duration): Duration {
return this {
seconds += duration.seconds
nanos += duration.nanos
normalized()
}
}
operator fun Duration.minus(duration: Duration): Duration {
return this {
seconds -= duration.seconds
nanos -= duration.nanos
normalized()
}
}
operator fun Duration.unaryPlus(): Duration {
return this {}
}
operator fun Duration.unaryMinus(): Duration {
return this {
normalized()
seconds = -seconds
nanos = -nanos
}
}
operator fun Duration.compareTo(other: Duration): Int {
if (this.seconds != other.seconds) {
return this.seconds.compareTo(other.seconds)
}
return this.nanos.compareTo(other.nanos)
}
fun Duration.string(): String = buildString {
append([email protected])
if ([email protected] != 0) {
append('.')
append(abs([email protected]).toString().leftPadding(9, '0').trimEnd('0'))
}
append('s')
}
fun abs(duration: Duration): Duration {
return duration {
normalized()
seconds = abs(seconds)
nanos = abs(nanos)
}
}
private fun MutableTimestamp.normalized() {
if (seconds.sign == 0 || nanos.sign == 0) {
return
}
if (seconds.sign != nanos.sign) {
seconds += nanos.sign
nanos = ((nanosPerSecond - abs(nanos)) * seconds.sign).toInt()
}
if (nanos >= nanosPerSecond) {
seconds += nanos / nanosPerSecond
nanos %= nanosPerSecond.toInt()
}
}
private fun MutableDuration.normalized() {
if (seconds.sign == 0 || nanos.sign == 0) {
return
}
if (seconds.sign != nanos.sign) {
seconds += nanos.sign
nanos = ((nanosPerSecond - abs(nanos)) * seconds.sign).toInt()
}
if (nanos >= nanosPerSecond) {
seconds += nanos / nanosPerSecond
nanos %= nanosPerSecond.toInt()
}
}
| 5 | Kotlin | 0 | 0 | 67f534e9c62833d32ba93bfd03fbc3c1f81f52e6 | 9,102 | sisyphus | MIT License |
app/src/main/java/com/example/rentall/ui/activity/account/UserAccountActivity.kt | shidqimlna | 321,599,621 | false | null | package com.example.rentall.ui.activity.account
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import com.example.rentall.R
import com.example.rentall.data.entity.UserEntity
import com.example.rentall.di.Injection
import com.example.rentall.ui.activity.product.NewProductActivity
import com.example.rentall.ui.activity.splash.LandingActivity
import com.example.rentall.ui.adapter.UserProductAdapter
import com.example.rentall.viewmodel.MainViewModel
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.*
import kotlinx.android.synthetic.main.activity_edit_account.*
import kotlinx.android.synthetic.main.activity_user_account.*
class UserAccountActivity : AppCompatActivity() {
private lateinit var viewModel: MainViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_user_account)
val userProductAdapter = UserProductAdapter()
viewModel = ViewModelProvider(
this,
Injection.provideViewModelFactory()
)[MainViewModel::class.java]
viewModel.getUserDetail().observe(this, { user ->
loadData(user)
})
viewModel.getUserProductList().observe(this, { products ->
userProductAdapter.setData(products)
})
with(activity_user_acc_rv_product) {
setHasFixedSize(true)
layoutManager = GridLayoutManager(context, 2)
adapter = userProductAdapter
}
activity_user_acc_btn_signout.setOnClickListener {
FirebaseAuth.getInstance().signOut()
val intent = Intent(this@UserAccountActivity, LandingActivity::class.java)
startActivity(intent)
finish()
}
activity_user_acc_btn_update.setOnClickListener {
val intent = Intent(this@UserAccountActivity, EditAccountActivity::class.java)
startActivity(intent)
finish()
}
activity_user_acc_fab_add.setOnClickListener {
val intent = Intent(this@UserAccountActivity, NewProductActivity::class.java)
startActivity(intent)
finish()
}
}
private fun loadData(userEntity: UserEntity?) {
activity_user_acc_tv_email.text = userEntity?.email
activity_user_acc_tv_username.text = userEntity?.fullname
activity_user_acc_tv_address.text = userEntity?.address
activity_user_acc_tv_phone.text = userEntity?.phone
}
} | 0 | Kotlin | 0 | 0 | 8249793477a41a391618cb3fd45bcb2f793f1f38 | 2,686 | RentAll | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/Skin.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Filled.Skin: ImageVector
get() {
if (_skin != null) {
return _skin!!
}
_skin = Builder(name = "Skin", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(24.0f, 8.0f)
verticalLineToRelative(4.15f)
curveToRelative(0.0f, 0.71f, -0.837f, 1.088f, -1.373f, 0.623f)
curveToRelative(-0.215f, -0.187f, -0.39f, -0.335f, -0.46f, -0.389f)
curveToRelative(-0.673f, -0.512f, -1.661f, -0.512f, -2.334f, 0.0f)
curveToRelative(-0.507f, 0.386f, -1.143f, 0.616f, -1.833f, 0.616f)
reflectiveCurveToRelative(-1.326f, -0.23f, -1.833f, -0.616f)
curveToRelative(-0.673f, -0.513f, -1.66f, -0.513f, -2.334f, 0.0f)
curveToRelative(-0.507f, 0.386f, -1.143f, 0.616f, -1.833f, 0.616f)
reflectiveCurveToRelative(-1.326f, -0.23f, -1.833f, -0.616f)
curveToRelative(-0.673f, -0.513f, -1.66f, -0.513f, -2.334f, 0.0f)
curveToRelative(-0.507f, 0.386f, -1.143f, 0.616f, -1.833f, 0.616f)
reflectiveCurveToRelative(-1.326f, -0.23f, -1.833f, -0.616f)
curveToRelative(-0.673f, -0.512f, -1.661f, -0.512f, -2.334f, 0.0f)
curveToRelative(-0.065f, 0.049f, -0.219f, 0.182f, -0.412f, 0.35f)
curveToRelative(-0.548f, 0.479f, -1.407f, 0.094f, -1.41f, -0.634f)
lineTo(0.002f, 8.004f)
curveToRelative(-0.002f, -1.106f, 0.894f, -2.004f, 2.0f, -2.004f)
horizontalLineToRelative(19.998f)
curveToRelative(1.105f, 0.0f, 2.0f, 0.895f, 2.0f, 2.0f)
close()
moveTo(1.5f, 15.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(6.5f, 18.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(17.5f, 18.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(12.0f, 15.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(22.5f, 15.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(1.5f, 21.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(12.0f, 21.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
moveTo(22.5f, 21.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
close()
}
}
.build()
return _skin!!
}
private var _skin: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,438 | icons | MIT License |
app/src/main/kotlin/com/subtlefox/currencyrates/di/ViewModelKey.kt | Subtle-fox | 177,306,258 | false | null | package com.subtlefox.currencyrates.di
import androidx.lifecycle.ViewModel
import dagger.MapKey
import kotlin.reflect.KClass
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
| 0 | Kotlin | 0 | 0 | cdcaf7d6ccef790aa903de419ffbc6206dc3c4d8 | 199 | currency-exchange-rates | Apache License 2.0 |
app/src/main/java/projects/kyle/ledcontroller/MainContent/MainActivityListener.kt | kyletaylor1324 | 150,907,414 | false | null | package projects.kyle.ledcontroller.MainContent
interface MainActivityListener {
fun launchColorPicker()
fun launchModePicker()
}
| 0 | Kotlin | 0 | 0 | 84d2f4bad25b7da475f9c00ec430982bf20b57d0 | 140 | HitBoxController | MIT License |
app/src/main/java/com/yousfi/hayatiineApp/ui/fragment/notification/NotificationFragment.kt | yousfiriadh | 423,231,665 | false | {"Kotlin": 119026} | package com.yousfi.hayatiineApp.ui.fragment.notification
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProviders
import com.yousfi.hayatiine.ui.base.BaseFragment
import com.yousfi.hayatiineApp.R
import com.yousfi.hayatiineApp.databinding.NotificationFragmentBinding
import com.yousfi.hayatiineApp.ui.fragment.add.AddViewModel
class NotificationFragment :BaseFragment<NotificationFragmentBinding>() {
lateinit var model: NotificationViewModel
override fun setViewModel() {
model = run {
ViewModelProviders.of(this).get(NotificationViewModel::class.java)
}
}
override fun init() {
getViewDataBinding()?.viewModel = model
}
override fun getLayoutId(): Int {
return R.layout.notification_fragment
}
} | 0 | Kotlin | 0 | 0 | f04afee026ecef6f6d3b913690c2d480fc4a3eb7 | 958 | hayatiineapp | Apache License 2.0 |
app/src/main/java/com/yousfi/hayatiineApp/ui/fragment/notification/NotificationFragment.kt | yousfiriadh | 423,231,665 | false | {"Kotlin": 119026} | package com.yousfi.hayatiineApp.ui.fragment.notification
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProviders
import com.yousfi.hayatiine.ui.base.BaseFragment
import com.yousfi.hayatiineApp.R
import com.yousfi.hayatiineApp.databinding.NotificationFragmentBinding
import com.yousfi.hayatiineApp.ui.fragment.add.AddViewModel
class NotificationFragment :BaseFragment<NotificationFragmentBinding>() {
lateinit var model: NotificationViewModel
override fun setViewModel() {
model = run {
ViewModelProviders.of(this).get(NotificationViewModel::class.java)
}
}
override fun init() {
getViewDataBinding()?.viewModel = model
}
override fun getLayoutId(): Int {
return R.layout.notification_fragment
}
} | 0 | Kotlin | 0 | 0 | f04afee026ecef6f6d3b913690c2d480fc4a3eb7 | 958 | hayatiineapp | Apache License 2.0 |
composeApp/src/androidMain/kotlin/com/ibenabdallah/indicatorscmp/MainActivity.kt | ibenabdallah | 742,854,364 | false | {"Kotlin": 11471, "Swift": 693} | package com.ibenabdallah.indicatorscmp
import App
import Indicators
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import config.IIndicatorsTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
App()
}
}
}
@Preview(showBackground = true)
@Composable
fun AppAndroidPreview() {
App()
}
@Preview(showBackground = true)
@Composable
fun IndicatorsPreview() {
IIndicatorsTheme {
Indicators(
count = 7,
size = 10,
spacer = 5,
selectedColor = Color.Red,
unselectedColor = Color.Blue,
modifier = Modifier
.background(Color.White)
.padding(vertical = 5.dp),
selectedIndex = 2
)
}
} | 0 | Kotlin | 0 | 2 | 6474c56bd41dcd0c294e750406a3a98da65f7e8f | 1,228 | indicators-compose-multiplatform | Apache License 2.0 |
src/commonMain/kotlin/matt/prim/bool/bool.kt | mgroth0 | 532,381,102 | false | {"Kotlin": 47124} |
package matt.prim.bool
import matt.prim.bytestr.toByteString
fun Byte.toBooleanStrict() =
when (this) {
0.toByte() -> true
1.toByte() -> false
else -> illegalBooleanValue(this)
}
fun UByte.toBooleanStrict() =
when (this) {
0.toUByte() -> true
1.toUByte() -> false
else -> illegalBooleanValue(this)
}
fun Short.toBooleanStrict() =
when (this) {
1.toShort() -> true
0.toShort() -> false
else -> illegalBooleanValue(this)
}
fun UShort.toBooleanStrict() =
when (this) {
1.toUShort() -> true
0.toUShort() -> false
else -> illegalBooleanValue(this)
}
fun Int.toBooleanStrict() =
when (this) {
1 -> true
0 -> false
else -> illegalBooleanValue(this)
}
fun UInt.toBooleanStrict() =
when (this) {
1u -> true
0u -> false
else -> illegalBooleanValue(this)
}
fun Long.toBooleanStrict() =
when (this) {
1L -> true
0L -> false
else -> illegalBooleanValue(this)
}
fun ULong.toBooleanStrict() =
when (this) {
1UL -> true
0UL -> false
else -> illegalBooleanValue(this)
}
private fun illegalBooleanValue(value: Any): Nothing = error("A strict Boolean value must be a 0 or a 1, not $value")
fun Boolean.toByteString() = toByteArray().toByteString()
fun Boolean.toByteArray() = byteArrayOf(if (this) 1.toByte() else 0.toByte())
| 0 | Kotlin | 0 | 0 | 35f53a94d27346441a309512af0d509ef9e2e8e6 | 1,476 | prim | MIT License |
application/module/module_tv/src/main/java/afkt_replace/module/tv/feature/popular/PopularTvViewModel.kt | afkT | 343,177,221 | false | {"Kotlin": 592177} | package afkt_replace.module.tv.feature.popular
import afkt_replace.core.lib.base.app.BaseViewModel
import afkt_replace.core.lib.base.controller.loading.BaseLoadingSkeletonController
import afkt_replace.core.lib.base.repository.AbsentLiveData
import afkt_replace.core.lib.base.repository.Resource
import afkt_replace.core.lib.base.split.inter.FunctionFlowCall
import afkt_replace.core.lib.bean.base.TMDBCommon
import afkt_replace.core.lib.bean.tv.PopularTv
import afkt_replace.core.lib.ui.widget.extension.smartRefreshLoadMoreListener
import afkt_replace.core.lib.ui.widget.view_assist.loading_skeleton.PageLoadingSkeletonViewAssist
import afkt_replace.lib.tmdb.ui.adapter.PosterCoverItem
import afkt_replace.module.tv.TvNavBuild.routerTvDetails
import afkt_replace.module.tv.TvRepository
import androidx.lifecycle.*
import dev.base.state.RequestState
import dev.mvvm.command.BindingClick
import dev.utils.common.able.Getable
/**
* detail: 热门剧集 ViewModel
* @author Ttt
* 也可统一放到 TvViewModel, 拆分只是为了更加方便维护管理
*/
class PopularTvViewModel(
private val repository: TvRepository = TvRepository()
) : BaseViewModel() {
// 热门剧集 Adapter Item
val popularItem = PosterCoverItem(Getable.Get {
return@Get uiController.value?.appThemeRes
}).apply {
itemClick = object : BindingClick<TMDBCommon> {
override fun onClick(value: TMDBCommon) {
value.routerTvDetails()
}
}
}
// ==========
// = 生命周期 =
// ==========
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
// 请求热门剧集列表
resumePopularTv()
}
// ==========
// = 请求方法 =
// ==========
// onResume 请求状态控制
private val resumeRequest = RequestState<Any>()
// ==============
// = 热门剧集列表 =
// ==============
// Loading Skeleton 控制封装
var loadingSkeletonGet: Getable.Get<BaseLoadingSkeletonController<*>> = Getable.Get {
return@Get loadingSkeletonController.value
}
// 请求页数信息
private val tvPageLiveData: MutableLiveData<Int> = MutableLiveData()
private val tvListLiveData: LiveData<Resource<PopularTv>> = tvPageLiveData.switchMap {
tvPageLiveData.value?.let { page ->
repository.requestPopularTv(
viewModel = this, page = page,
devPage = popularItem.page,
flowCall = object : FunctionFlowCall {
override fun start() {
resumeRequest.setRequestIng()
loadingSkeletonGet.get()?.showIng()
}
override fun success() {
loadingSkeletonGet.get()?.showSuccess()
}
override fun error() {
loadingSkeletonGet.get()?.showFailed()
}
override fun finish() {
resumeRequest.setRequestNormal()
}
}
)
} ?: AbsentLiveData.create()
}
/**
* 请求热门剧集列表
*/
private fun requestPopularTv(refresh: Boolean) {
val page = if (refresh) {
popularItem.page.configPage
} else {
popularItem.page.nextPage
}
tvPageLiveData.postValue(page)
}
/**
* 请求热门剧集列表
* 内部校验是否存在数据
*/
private fun resumePopularTv() {
if (popularItem.items.isEmpty() && resumeRequest.isRequestNormal) {
requestPopularTv(true)
}
}
// ==============
// = initialize =
// ==============
/**
* 初始化 PopularTvFragment ViewModel 调用
* @param fragment PopularTvFragment
*/
fun initializePopularTvFragment(fragment: PopularTvFragment) {
fragment.binding.apply {
// 设置刷新和加载监听器
vidRefresh.smartRefreshLoadMoreListener { _, refresh ->
requestPopularTv(refresh)
}
// 监听数据
tvListLiveData.observe(fragment, Observer {
it.bindResource(popularItem, vidRefresh)
})
}
// 注册 Loading 骨架 type
fragment.loadingSkeletonFactory.register(
PageLoadingSkeletonViewAssist(
fragment.loadingSkeletonController.viewAssist,
fragment.loadingSkeletonController.contentAssist.contentLinear
) { requestPopularTv(true) }
)
}
} | 2 | Kotlin | 17 | 72 | 710033ee53928e30f8dc7b37aacdbde7283a7841 | 4,431 | DevComponent | Apache License 2.0 |
librettist-core/src/commonMain/kotlin/dev/bnorm/librettist/show/Advancement.kt | bnorm | 767,108,847 | false | {"Kotlin": 1393317} | package dev.bnorm.librettist.show
data class Advancement(
val direction: Direction,
) {
enum class Direction {
Forward,
Backward,
;
fun <T> toValue(forward: T, backward: T): T {
return when (this) {
Forward -> forward
Backward -> backward
}
}
}
}
| 0 | Kotlin | 0 | 6 | 54392eca81d8c1d15d93a17eba31e893d980a496 | 357 | librettist | Apache License 2.0 |
sample/src/main/java/ru/fabit/sample/MainActivity.kt | FabitMobile | 728,099,639 | false | {"Kotlin": 10498} | package ru.fabit.sample
import android.os.Bundle
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import ru.fabit.gentleman.Gentleman
import ru.fabit.gentleman.appearance.Tuxedo
import ru.fabit.gentleman.once
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
override fun onResume() {
super.onResume()
val context = this
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
Gentleman in Tuxedo {
with(context)
ask(
android.Manifest.permission.ACCESS_COARSE_LOCATION,
android.Manifest.permission.POST_NOTIFICATIONS
) retry once
await { result ->
showMessage("granted=${result.granted}")
showMessage("denied=${result.denied}")
if (result.denied.isEmpty())
button.text = "granted"
if (result.granted.isEmpty())
button.text = "denied"
}
}
}
}
private fun showMessage(text: String) {
Toast.makeText(applicationContext, text, Toast.LENGTH_SHORT).show()
}
} | 0 | Kotlin | 0 | 0 | b3b376d1cf22f3e9733910d87000d7b081b382a5 | 1,414 | Gentleman | MIT License |
mall/src/main/java/ca/six/router/demo/mall/core/MallRouter.kt | songzhw | 254,749,106 | false | null | package ca.six.router.demo.mall.core
import ca.six.router.demo.common.biz.login.ThisUser
import ca.six.router.demo.mall.biz.ItemDetailActivity
import ca.six.router.library.IRouter
import ca.six.router.library.Precondition
import ca.six.router.library.Station
import java.util.*
const val ITEM_DETAIL = "ItemDetail"
class MallRouter : IRouter {
override fun registerRoute(map: HashMap<String, Station>) {
map[ITEM_DETAIL] = Station(ITEM_DETAIL, ItemDetailActivity::class.java)
.addPrecondition(Precondition(ThisUser::hasLoggedIn, "Login"))
}
} | 0 | Kotlin | 0 | 0 | a2745b730e1ca7cb328929646f7573596bcb7147 | 573 | SixRouter | Apache License 2.0 |
kotlin/12.kt | NeonMika | 433,743,141 | false | null | class Day12 : Day<Graph<String>>("12") {
val Graph<String>.start get() = nodes["start"]!!
val Graph<String>.end get() = nodes["end"]!!
val Node<String>.isSmall get() = data[0].isLowerCase()
val Node<String>.isBig get() = !isSmall
fun Graph<String>.dfs(
cur: Node<String>,
path: List<Node<String>> = mutableListOf(),
continuePred: Graph<String>.(Node<String>, List<Node<String>>) -> Boolean
): Int = when {
cur == end -> 1
continuePred(cur, path) -> cur.undirNeighbors.sumOf { dfs(it, path + cur, continuePred) }
else -> 0
}
val bigOrNew: Graph<String>.(Node<String>, List<Node<String>>) -> Boolean =
{ node, path -> node.isBig || node !in path }
override fun dataStar1(lines: List<String>) = Graph(lines.map { it.strings("-").run { Edge(get(0), get(1)) } })
override fun dataStar2(lines: List<String>) = dataStar1(lines)
override fun star1(data: Graph<String>): Number = data.dfs(data.start, continuePred = bigOrNew)
override fun star2(data: Graph<String>): Number = data.dfs(data.start) { node, path ->
bigOrNew(node, path) || (node != start && path.filter { it.isSmall }.run { size == distinct().size })
}
}
fun main() {
Day12()()
} | 0 | Kotlin | 0 | 0 | c625d684147395fc2b347f5bc82476668da98b31 | 1,258 | advent-of-code-2021 | MIT License |
GaiaXAndroid/src/main/kotlin/com/alibaba/gaiax/render/node/GXNodeExt.kt | MXPDS6688 | 471,274,978 | true | {"Kotlin": 608909, "Objective-C": 581902, "C++": 171660, "CSS": 123633, "Java": 106171, "Objective-C++": 59923, "C": 10418, "Ruby": 2635, "Swift": 2336, "Shell": 2268, "CMake": 2213} | /*
* Copyright (c) 2021, Alibaba Group Holding Limited;
*
* 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.alibaba.gaiax.render.node
import android.view.View
/**
* @suppress
*/
fun GXNode.getGXViewById(id: String): View? {
return findViewById(this, id)
}
/**
* @suppress
*/
private fun GXNode.findViewById(viewData: GXNode, id: String): View? {
if (viewData.templateNode.layer.id == id) {
return viewData.viewRef?.get()
}
viewData.children?.forEach {
val view = findViewById(it, id)
if (view != null) {
return view
}
}
return null
}
| 0 | Kotlin | 0 | 0 | 3a0107a6be36ff3650dc5fbb482f8819f86bf0e2 | 1,131 | GaiaX | Apache License 2.0 |
2022-2023/sourcecode/W11-ThreadAndRunnableExample/src/main/kotlin/Main.kt | RafLew84 | 457,727,622 | false | null | class C : Thread(){
override fun run(){
println("wewnątrz wątku")
}
}
fun main(){
val thread = C()
thread.start()
println("poza wątkiem")
} | 0 | Jupyter Notebook | 2 | 10 | 378f252612ebac7714d6dc0164bb9d93ebb4e306 | 168 | WpumKJ | MIT License |
app/src/main/java/agency/nice/nearbypong/ui/home/HomeActivity.kt | karmarama | 131,967,924 | false | null | package agency.nice.nearbypong.ui.home
import agency.nice.nearbypong.NearbyPongApplication
import agency.nice.nearbypong.R
import agency.nice.nearbypong.helpers.PLAY_GAME
import agency.nice.nearbypong.helpers.trackEvent
import agency.nice.nearbypong.model.Game
import agency.nice.nearbypong.repositories.GameRepository
import agency.nice.nearbypong.ui.game.GameActivity
import agency.nice.nearbypong.ui.game.HomeMvp
import agency.nice.nearbypong.utils.getUserId
import agency.nice.nearbypong.utils.screenHeight
import agency.nice.nearbypong.utils.screenWidth
import agency.nice.nearbypong.widgets.Ball
import android.content.Context
import android.content.Intent
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
import android.os.CountDownTimer
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.dynamicanimation.animation.DynamicAnimation
import androidx.dynamicanimation.animation.FlingAnimation
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_home.*
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
private const val TIMEOUT_BOUNCING: Long = 3500
private const val SECOND_MILLIS: Long = 1000
private const val SHOW: Boolean = true
class HomeActivity : AppCompatActivity(), HomeMvp.View {
lateinit var presenter: HomePresenter
companion object {
fun getIntent(context: Context) = Intent(context, HomeActivity::class.java)
}
override fun onResume() {
super.onResume()
showListGames(!SHOW)
showTitle(SHOW)
showButtons(SHOW)
showBall(SHOW)
startLineAnimation(!SHOW)
ball.rotate()
ball.crazyBounce()
startAnimationTimer()
}
override fun loadGames(games: List<Game>) {
listGames.setHasFixedSize(true)
var layoutManager = LinearLayoutManager(this)
listGames.layoutManager = layoutManager
listGames.adapter = GamesAdapter(this, games)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
presenter = HomePresenter(GameRepository(NearbyPongApplication.database.gameDao()))
presenter.attachView(this)
presenter.loadGames()
play.setOnClickListener {
trackEvent(this, PLAY_GAME, getUserId())
startActivity(GameActivity.getIntent(this))
}
scores.setOnClickListener {
showListGames(SHOW)
showTitle(!SHOW)
showButtons(!SHOW)
showBall(!SHOW)
}
initBall()
}
private fun showButtons(show: Boolean) {
play.visibility = if (show) View.VISIBLE else View.GONE
scores.visibility = if (show) View.VISIBLE else View.GONE
}
private fun showTitle(show: Boolean) {
title_first.visibility = if (show) View.VISIBLE else View.GONE
title_second.visibility = if (show) View.VISIBLE else View.GONE
title_gap.visibility = if (show) View.INVISIBLE else View.GONE
title_fourth.visibility = if (show) View.VISIBLE else View.GONE
}
private fun showListGames(show: Boolean) {
title_scores.visibility = if (show) View.VISIBLE else View.GONE
listGames.visibility = if (show) View.VISIBLE else View.GONE
startLineAnimation(show)
}
private fun showBall(show: Boolean) {
ball.visibility = if (show) View.VISIBLE else View.GONE
}
private fun initBall() {
ball.bottomLimit = screenHeight
ball.sideLimit = screenWidth
ball.listener = object : Ball.BallListener {
override fun goal() {
}
override fun sendBallData(
posX: Float,
posY: Float,
velocityX: Float,
velocityY: Float
) {
}
}
}
override fun hideGamesList() {
showListGames(!SHOW)
}
private fun startLineAnimation(show: Boolean) {
if (show) {
line.visibility = View.VISIBLE
val gradientDrawable = GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM,
intArrayOf(
ContextCompat.getColor(this, R.color.colorAccent),
ContextCompat.getColor(this, R.color.colorPrimary),
ContextCompat.getColor(this, R.color.transparent)
)
)
line.background = gradientDrawable
val flingAnimationY = FlingAnimation(line, DynamicAnimation.Y).setFriction(0.1f)
flingAnimationY.addUpdateListener { _, value, _ ->
if (value <= (screenHeight / 3)) {
flingAnimationY.friction = 0.9f
}
}
line.y = screenHeight.toFloat()
line.x = (screenWidth / 2).toFloat()
flingAnimationY.setStartVelocity(-1000f).start()
} else {
line.visibility = View.GONE
}
}
private fun startAnimationTimer() {
object : CountDownTimer(TIMEOUT_BOUNCING, SECOND_MILLIS) {
override fun onTick(millisUntilFinished: Long) {
Log.d("TIMER", "seconds remaining: " + millisUntilFinished / SECOND_MILLIS)
}
override fun onFinish() {
ball.cancelFlings()
ball.animate()
.x(title_gap.x)
.y(title_gap.y)
.setDuration(SECOND_MILLIS)
.withEndAction {
ball.changeAlphaToMax()
}
.start()
}
}.start()
}
override fun onDestroy() {
presenter.detachView()
super.onDestroy()
}
override fun onBackPressed() {
if (line.visibility == View.VISIBLE) {
onResume()
} else {
super.onBackPressed()
}
}
}
| 0 | Kotlin | 0 | 2 | 86e4e8fd0b1d871f92d4754e6704354c377a4c99 | 6,185 | nearbyPong | MIT License |
customdata-pokemon/src/main/java/contacts/entities/custom/pokemon/RawContactPokemon.kt | vestrel00 | 223,332,584 | false | {"Kotlin": 1616347, "Shell": 635} | package contacts.entities.custom.pokemon
import contacts.core.Contacts
import contacts.core.entities.MutableRawContact
import contacts.core.entities.NewRawContact
import contacts.core.entities.RawContact
// Dev note: The functions that return a List instead of a Sequence are useful for Java consumers
// as they will not have to convert Sequences to List. Also, all are functions instead of properties
// with getters because there are some setters that have to be functions. So all are functions
// to keep uniformity for OCD purposes.
// region RawContact
/**
* Returns the sequence of [Pokemon]s of this RawContact.
*/
fun RawContact.pokemons(contacts: Contacts): Sequence<Pokemon> {
val customDataEntities = contacts.customDataRegistry
.customDataEntitiesFor<Pokemon>(this, PokemonMimeType)
return customDataEntities.asSequence()
}
/**
* Returns the list of [Pokemon]s of this RawContact.
*/
fun RawContact.pokemonList(contacts: Contacts): List<Pokemon> = pokemons(contacts).toList()
// endregion
// region MutableRawContact
/**
* Returns the sequence of [MutablePokemonEntity]s of this RawContact.
*/
fun MutableRawContact.pokemons(contacts: Contacts): Sequence<MutablePokemonEntity> {
val customDataEntities = contacts.customDataRegistry
.customDataEntitiesFor<MutablePokemonEntity>(this, PokemonMimeType)
return customDataEntities.asSequence()
}
/**
* Returns the list of [MutablePokemonEntity]s of this RawContact.
*/
fun MutableRawContact.pokemonList(contacts: Contacts): List<MutablePokemonEntity> =
pokemons(contacts).toList()
/**
* Adds the given [pokemon] to this RawContact.
*/
fun MutableRawContact.addPokemon(contacts: Contacts, pokemon: MutablePokemonEntity) {
contacts.customDataRegistry.putCustomDataEntityInto(this, pokemon)
}
/**
* Adds a pokemon (configured by [configurePokemon]) to this RawContact.
*/
fun MutableRawContact.addPokemon(
contacts: Contacts,
configurePokemon: NewPokemon.() -> Unit
) {
addPokemon(contacts, NewPokemon().apply(configurePokemon))
}
/**
* Removes all instances of the given [pokemon] from this RawContact.
*
* By default, all **structurally equal (same content but maybe different objects)** instances will
* be removed. Set [byReference] to true to remove all instances that are **equal by reference
* (same object)**.
*/
fun MutableRawContact.removePokemon(
contacts: Contacts,
pokemon: MutablePokemonEntity,
byReference: Boolean = false
) {
contacts.customDataRegistry.removeCustomDataEntityFrom(this, byReference, pokemon)
}
/**
* Removes all pokemons from this RawContact.
*/
fun MutableRawContact.removeAllPokemons(contacts: Contacts) {
contacts.customDataRegistry.removeAllCustomDataEntityFrom(this, PokemonMimeType)
}
// endregion
// region NewRawContact
/**
* Returns the sequence of [NewPokemon]s of this RawContact.
*/
fun NewRawContact.pokemons(contacts: Contacts): Sequence<NewPokemon> {
val customDataEntities = contacts.customDataRegistry
.customDataEntitiesFor<NewPokemon>(this, PokemonMimeType)
return customDataEntities.asSequence()
}
/**
* Returns the list of [NewPokemon]s of this RawContact.
*/
fun NewRawContact.pokemonList(contacts: Contacts): List<NewPokemon> =
pokemons(contacts).toList()
/**
* Adds the given [pokemon] to this RawContact.
*/
fun NewRawContact.addPokemon(contacts: Contacts, pokemon: NewPokemon) {
contacts.customDataRegistry.putCustomDataEntityInto(this, pokemon)
}
/**
* Adds a pokemon (configured by [configurePokemon]) to this RawContact.
*/
fun NewRawContact.addPokemon(
contacts: Contacts,
configurePokemon: NewPokemon.() -> Unit
) {
addPokemon(contacts, NewPokemon().apply(configurePokemon))
}
/**
* Removes all instances of the given [pokemon] from this RawContact.
*
* By default, all **structurally equal (same content but maybe different objects)** instances will
* be removed. Set [byReference] to true to remove all instances that are **equal by reference
* (same object)**.
*/
fun NewRawContact.removePokemon(
contacts: Contacts,
pokemon: NewPokemon,
byReference: Boolean = false
) {
contacts.customDataRegistry.removeCustomDataEntityFrom(this, byReference, pokemon)
}
/**
* Removes all pokemons from this RawContact.
*/
fun NewRawContact.removeAllPokemons(contacts: Contacts) {
contacts.customDataRegistry.removeAllCustomDataEntityFrom(this, PokemonMimeType)
}
// endregion | 26 | Kotlin | 35 | 573 | 383594d2708296f2fbc6ea1f10b117d3acd1f46a | 4,472 | contacts-android | Apache License 2.0 |
community/src/main/java/com/ekoapp/ekosdk/uikit/community/newsfeed/adapter/PostItemUnknownViewHolder.kt | amadeus-n | 467,842,651 | true | {"Kotlin": 1114879} | package com.ekoapp.ekosdk.uikit.community.newsfeed.adapter
import android.view.View
import android.widget.TextView
import androidx.core.content.ContextCompat
import com.ekoapp.ekosdk.feed.EkoPost
import com.ekoapp.ekosdk.uikit.common.views.ColorPaletteUtil
import com.ekoapp.ekosdk.uikit.common.views.ColorShade
import com.ekoapp.ekosdk.uikit.community.R
import com.ekoapp.ekosdk.uikit.community.newsfeed.util.EkoTimelineType
class PostItemUnknownViewHolder(itemView: View): EkoBasePostViewHolder(itemView, EkoTimelineType.GLOBAL) {
private val tvSomethingWentWrong: TextView = itemView.findViewById(R.id.tvSomethingWentWrong)
private val tvUnRecognizedPost: TextView = itemView.findViewById(R.id.tvUnrecognizedPost)
override fun bind(data: EkoPost?, position: Int) {
super.bind(data, position)
tvSomethingWentWrong.setTextColor(ColorPaletteUtil.getColor(ContextCompat.getColor(
tvSomethingWentWrong.context, R.color.upstraColorBase
), ColorShade.SHADE3))
tvUnRecognizedPost.setTextColor(ColorPaletteUtil.getColor(ContextCompat.getColor(
tvUnRecognizedPost.context, R.color.upstraColorBase
), ColorShade.SHADE3))
}
} | 0 | null | 0 | 0 | d4fe097da96f71ab281c9b39fafdaa901aed377c | 1,201 | ASC-UIKit-Android | Microsoft Public License |
charts/src/main/java/com/diamondedge/charts/LogarithmicAxis.kt | ellsworthrw | 482,041,188 | false | null | /**
* Copyright 2004-2022 <NAME>. All rights reserved.
*
* @author <NAME>
*/
package com.diamondedge.charts
import kotlin.math.abs
class LogarithmicAxis : DecimalAxis() {
init {
minorTickIncNum = 10
}
override fun calcMetrics(rangePix: Int, g: GraphicsContext, font: Font?) {
super.calcMetrics(rangePix, g, font)
if (isAutoScaling) {
// make minVal be an exact multiple of majorTickInc just smaller than minVal
var tickInc = nextMajorIncVal(minValue, 1.0)
minValue = Math.floor(minValue / tickInc) * tickInc
// make maxVal be an exact multiple of majorTickInc just larger than maxVal
tickInc = nextMajorIncVal(maxValue, tickInc)
maxValue = Math.ceil(maxValue / tickInc) * tickInc
adjustMinMax()
calcScale(rangePix)
}
}
override fun calcScale(rangePix: Int): Double {
val rangeVal = log10(maxValue) - log10(minValue)
scale = rangeVal / rangePix
if (scale == 0.0)
scale = 1.0
return scale
}
override fun nextMajorIncVal(pos: Double, incrementVal: Double): Double {
var incVal = Math.pow(10.0, (Math.log(pos) / LOG10).toInt().toDouble())
if (incVal == 0.0)
incVal = 1.0
return incVal
}
override fun adjustMinMax() {
// cannot have log scales with negative numbers
if (minValue < 0)
minValue = 0.0
}
/** Return data value scaled to be in pixels
*/
override fun scaleData(dataValue: Double): Int {
return (log10(dataValue) / scale).toLong().toInt()
}
override fun scalePixel(pixelValue: Int): Double {
return Math.pow(10.0, pixelValue * scale)
}
override fun toString(): String {
return "LogarithmicAxis[" + toStringParam() + "]"
}
companion object {
private val LOG10 = Math.log(10.0)
private fun log10(value: Double): Double {
var v = value
val sign = if (v < 0) -1 else 1
v = abs(v)
if (v < 10)
v += (10 - v) / 10 // make 0 correspond to 0
return Math.log(v) / LOG10 * sign
}
}
}
| 0 | Kotlin | 0 | 3 | afd51b0fe8d08f88248d16cf701b43e538b684a8 | 2,239 | DiamondCharts | Apache License 2.0 |
app/src/main/java/dev/arli/sunnyday/di/ApplicationModule.kt | alipovatyi | 614,818,086 | false | null | @file:Suppress("UnnecessaryAbstractClass")
package dev.arli.sunnyday.di
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import dev.arli.sunnyday.data.api.retrofit.di.RetrofitApiModule
@Module(
includes = [
ApplicationConfigModule::class,
RetrofitApiModule::class,
NavigatorModule::class
]
)
@InstallIn(SingletonComponent::class)
abstract class ApplicationModule
| 0 | Kotlin | 0 | 0 | f272db479e91de350368a8573df6ddebb22e0742 | 448 | sunny-day-android | Apache License 2.0 |
src/test/kotlin/org/kiwiproject/changelog/config/OutputTypeTest.kt | kiwiproject | 332,067,864 | false | {"Kotlin": 171337, "Shell": 8457} | package org.kiwiproject.changelog.config
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
@DisplayName("OutputType")
class OutputTypeTest {
@Test
fun shouldReturnAllEnumValues_ForEntriesAsString() {
val entriesAsString = OutputType.entriesAsString()
assertThat(entriesAsString)
.contains("CONSOLE, FILE, GITHUB")
}
}
| 2 | Kotlin | 0 | 1 | a6b6aceab327fa4926112b863447f30ec1b9923f | 436 | kiwiproject-changelog | MIT License |
server/src/main/kotlin/de/compeople/swn/server/tarif/TarifRouting.kt | compeople | 170,469,556 | false | null | package de.compeople.swn.server.tarif
import de.compeople.swn.tarifService.Tarif
import io.ktor.application.call
import io.ktor.http.ContentType
import io.ktor.response.respondText
import io.ktor.routing.Routing
import io.ktor.routing.get
import io.ktor.routing.route
import kotlinx.serialization.json.Json
fun Routing.tarif() {
route("tarif") {
get {
val tarif = TarifService.getTarif()
call.respondText(Json.stringify(Tarif.serializer(), tarif), ContentType.Application.Json)
}
}
}
| 0 | Kotlin | 2 | 21 | e2d742c6430703e9a385ac3cea6648812a699652 | 537 | kotlin-multiplatform-sample | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Crab.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.Crab: ImageVector
get() {
if (_crab != null) {
return _crab!!
}
_crab = Builder(name = "Crab", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(21.0f, 13.0f)
curveToRelative(1.654f, 0.0f, 3.0f, -1.346f, 3.0f, -3.0f)
verticalLineToRelative(-5.553f)
horizontalLineToRelative(-0.004f)
curveToRelative(-0.035f, -0.717f, -0.327f, -1.424f, -0.875f, -1.972f)
curveToRelative(-1.172f, -1.172f, -4.596f, -2.475f, -4.596f, -2.475f)
curveToRelative(0.0f, 0.0f, 0.825f, 1.532f, 1.114f, 3.235f)
curveToRelative(-1.703f, -0.289f, -3.235f, -1.114f, -3.235f, -1.114f)
curveToRelative(0.0f, 0.0f, 1.303f, 3.425f, 2.475f, 4.596f)
curveToRelative(0.844f, 0.844f, 2.066f, 1.08f, 3.122f, 0.708f)
verticalLineToRelative(2.575f)
curveToRelative(0.0f, 0.552f, -0.449f, 1.0f, -1.0f, 1.0f)
horizontalLineToRelative(-1.256f)
curveToRelative(-0.585f, -1.977f, -2.172f, -3.227f, -4.744f, -3.737f)
verticalLineToRelative(-1.263f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(1.025f)
curveToRelative(-0.322f, -0.017f, -0.656f, -0.025f, -1.0f, -0.025f)
reflectiveCurveToRelative(-0.678f, 0.009f, -1.0f, 0.025f)
verticalLineToRelative(-1.025f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(1.263f)
curveToRelative(-2.573f, 0.51f, -4.16f, 1.76f, -4.744f, 3.737f)
horizontalLineToRelative(-1.256f)
curveToRelative(-0.551f, 0.0f, -1.0f, -0.448f, -1.0f, -1.0f)
verticalLineToRelative(-2.575f)
curveToRelative(1.055f, 0.372f, 2.277f, 0.136f, 3.121f, -0.708f)
curveToRelative(1.172f, -1.172f, 2.475f, -4.596f, 2.475f, -4.596f)
curveToRelative(0.0f, 0.0f, -1.532f, 0.825f, -3.235f, 1.114f)
curveToRelative(0.289f, -1.703f, 1.114f, -3.235f, 1.114f, -3.235f)
curveToRelative(0.0f, 0.0f, -3.425f, 1.303f, -4.596f, 2.475f)
curveTo(0.331f, 3.023f, 0.039f, 3.73f, 0.004f, 4.447f)
horizontalLineToRelative(-0.004f)
verticalLineToRelative(5.553f)
curveToRelative(0.0f, 1.654f, 1.346f, 3.0f, 3.0f, 3.0f)
horizontalLineToRelative(1.002f)
curveToRelative(0.026f, 0.841f, 0.412f, 1.918f, 0.927f, 3.0f)
horizontalLineToRelative(-1.843f)
lineToRelative(-2.293f, 2.293f)
lineToRelative(1.414f, 1.414f)
lineToRelative(1.707f, -1.707f)
horizontalLineToRelative(2.093f)
curveToRelative(0.535f, 0.902f, 1.058f, 1.687f, 1.398f, 2.18f)
lineToRelative(-2.372f, 2.372f)
lineToRelative(1.414f, 1.414f)
lineToRelative(2.967f, -2.967f)
horizontalLineToRelative(5.172f)
lineToRelative(2.966f, 2.967f)
lineToRelative(1.414f, -1.414f)
lineToRelative(-2.354f, -2.355f)
curveToRelative(0.357f, -0.472f, 0.926f, -1.261f, 1.498f, -2.198f)
horizontalLineToRelative(1.976f)
lineToRelative(1.707f, 1.707f)
lineToRelative(1.414f, -1.414f)
lineToRelative(-2.293f, -2.293f)
horizontalLineToRelative(-1.732f)
curveToRelative(0.462f, -1.016f, 0.796f, -2.066f, 0.817f, -3.0f)
horizontalLineToRelative(1.002f)
close()
moveTo(12.0f, 9.0f)
curveToRelative(5.287f, 0.0f, 6.0f, 1.977f, 6.0f, 3.909f)
curveToRelative(0.0f, 1.745f, -1.908f, 4.65f, -2.959f, 6.05f)
lineToRelative(-0.041f, 0.041f)
horizontalLineToRelative(-5.979f)
curveToRelative(-1.276f, -1.86f, -3.021f, -4.836f, -3.021f, -6.091f)
curveToRelative(0.0f, -1.933f, 0.713f, -3.909f, 6.0f, -3.909f)
close()
}
}
.build()
return _crab!!
}
private var _crab: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,225 | icons | MIT License |
app/src/test/java/de/check24/lifeofcode/domain/TicketImplementationHandlerTest.kt | cee-dee | 544,030,442 | false | null | package de.check24.lifeofcode.domain
import de.check24.lifeofcode.model.codebase.Area
import de.check24.lifeofcode.model.codebase.QualityLevel
import de.check24.lifeofcode.model.codebase.QualityMap
import de.check24.lifeofcode.model.gamestate.GameState
import de.check24.lifeofcode.model.shared.Percent
import de.check24.lifeofcode.model.shortcuts.ShortCut
import de.check24.lifeofcode.model.shortcuts.concretions.NoCleanCodeShortCut
import de.check24.lifeofcode.model.tickets.*
import de.check24.lifeofcode.model.work.Week
import de.check24.lifeofcode.model.work.WorkLog
import de.check24.lifeofcode.model.work.WorkLogEntry
import org.junit.Assert.*
import org.junit.Test
class TicketImplementationHandlerTest {
@Test
fun `processing of first ticket keeps track of performed work hours`() {
val implementationTimeComputer = ImplementationTimeComputer()
val sut = TicketImplementationHandler(implementationTimeComputer)
val actualGameState = sut.handle(
gameState = initialGameState,
ticket = firstS1Ticket,
shortCuts = noShortCuts
)
val expectedWorkLogEntry = WorkLogEntry(
ticket = firstS1Ticket,
calendarWeek = firstCalendarWeek,
time = singleDevTime
)
val expectedTicketHistoryEntry = HandledTicket(
ticket = firstS1Ticket,
implementationStartDate = firstCalendarWeek,
readyForVerificationDate = secondCalendarWeek
)
val expectedGameState = initialGameState.copy(
availableDeveloperTime = noTime,
workLog = initialGameState.workLog.addWorkLogEntry(expectedWorkLogEntry),
ticketHistory = initialGameState.ticketHistory.addTicketToHistory(expectedTicketHistoryEntry)
)
assertEquals(expectedGameState, actualGameState)
}
@Test
fun `processing of first ticket without clean code leads to slow down effect in long run and speeds up iteration`() {
val implementationTimeComputer = ImplementationTimeComputer()
val sut = TicketImplementationHandler(implementationTimeComputer)
val actualGameState = sut.handle(
gameState = initialGameState,
ticket = firstS1Ticket,
shortCuts = noCleanCodeShortCuts
)
assertEquals(Percent(90), actualGameState.qualityMap.levels[devAreaS1]!!.percent)
assertEquals(Hours(20), actualGameState.workLog.entries.first().time)
assertEquals(Hours(20), actualGameState.availableDeveloperTime)
}
private fun WorkLog.addWorkLogEntry(workLogEntry: WorkLogEntry) =
copy(
entries = entries + workLogEntry
)
private fun TicketHistory.addTicketToHistory(expectedTicketHistoryEntry: HandledTicket) =
copy(
handledTickets = handledTickets + expectedTicketHistoryEntry
)
companion object {
private val singleDevTime = Hours(hours = 40)
private val noTime = Hours(hours = 0)
private val firstCalendarWeek = Week(week = 1)
private val secondCalendarWeek = Week(week = 2)
private val devAreaS1 = Area(name = "S1")
private val idealQualityLevels = hashMapOf(
devAreaS1 to QualityLevel(Percent(100))
)
private val idealQualityMap = QualityMap(
levels = idealQualityLevels
)
private val emptyWorkLog = WorkLog(
entries = listOf()
)
private val emptyTicketHistory = TicketHistory(
handledTickets = listOf()
)
private val firstS1Ticket = Ticket(
summary = "Setup S1 screen",
description = "Setup S1 screen, including architecture",
relativeAreas = RelativeAreas(
hashMapOf(
devAreaS1 to Percent(100)
)
),
hasToBeFinishedByEndOf = Week(week = 1),
untilReleaseTimeRequirements = UntilReleaseTimeRequirements(
idealImplementationTimeForDeveloper = singleDevTime,
idealVerificationTimeForPm = Hours(hours = 0)
)
)
private val noShortCuts = listOf<ShortCut>()
// FIXME: provide a ShortCut registry later
private val shortCutNoCleanCode = NoCleanCodeShortCut()
private val noCleanCodeShortCuts = listOf(
shortCutNoCleanCode
)
private val initialGameState = GameState(
calendarWeek = firstCalendarWeek,
availableDeveloperTime = singleDevTime,
qualityMap = idealQualityMap,
workLog = emptyWorkLog,
ticketHistory = emptyTicketHistory
)
}
}
| 9 | Kotlin | 0 | 2 | d98bd1e26df312ae875319989ac154c9b4d58810 | 4,732 | life-of-code | Apache License 2.0 |
smithy-swift-codegen/src/test/kotlin/mocks/MockHttpResponseBindingErrorGenerator.kt | smithy-lang | 242,852,561 | false | {"Kotlin": 1274133, "Swift": 964714, "Smithy": 130208, "Shell": 1807, "Objective-C": 136} | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package mocks
import software.amazon.smithy.codegen.core.Symbol
import software.amazon.smithy.model.shapes.OperationShape
import software.amazon.smithy.swift.codegen.SwiftDependency
import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator
import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingErrorGeneratable
import software.amazon.smithy.swift.codegen.integration.middlewares.handlers.MiddlewareShapeUtils
class MockHttpResponseBindingErrorGenerator : HttpResponseBindingErrorGeneratable {
override fun renderOperationError(
ctx: ProtocolGenerator.GenerationContext,
op: OperationShape,
unknownServiceErrorSymbol: Symbol
) {
val operationErrorName = MiddlewareShapeUtils.outputErrorSymbolName(op)
val rootNamespace = ctx.settings.moduleName
val httpBindingSymbol = Symbol.builder()
.definitionFile("./$rootNamespace/models/$operationErrorName+HttpResponseBinding.swift")
.name(operationErrorName)
.build()
ctx.delegator.useShapeWriter(httpBindingSymbol) { writer ->
writer.addImport(SwiftDependency.CLIENT_RUNTIME.target)
writer.openBlock("extension \$L {", "}", operationErrorName) {
writer.openBlock("public init(httpResponse: HttpResponse, decoder: ResponseDecoder? = nil, messageDecoder: MessageDecoder? = nil) throws {", "}") {
writer.write("throw ClientError.deserializationFailed(ClientError.dataNotFound(\"Invalid information in current codegen context to resolve the ErrorType\"))")
}
}
}
}
override fun renderServiceError(ctx: ProtocolGenerator.GenerationContext) {
// not yet implemented
return
}
}
| 11 | Kotlin | 26 | 26 | c0aca0602b96568a750a9525f6f2b4c2ace30ff5 | 1,909 | smithy-swift | Apache License 2.0 |
src/nativeGen/kotlin/godot/BoxShape.kt | piiertho | 237,614,467 | true | {"Kotlin": 5300589} | // DO NOT EDIT, THIS FILE IS GENERATED FROM api.json
package godot
import gdnative.godot_method_bind
import godot.core.Godot
import godot.core.Variant
import godot.core.VariantArray
import godot.core.Vector3
import kotlin.Unit
import kotlin.reflect.KCallable
import kotlinx.cinterop.CFunction
import kotlinx.cinterop.COpaquePointer
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.cstr
import kotlinx.cinterop.invoke
import kotlinx.cinterop.memScoped
import kotlinx.cinterop.reinterpret
open class BoxShape(
_handle: COpaquePointer
) : Shape(_handle) {
var extents: Vector3
get() {
return getExtents()
}
set(value) {
setExtents(value)
}
/**
* Specialized setter for extents
*/
fun extents(cb: Vector3.() -> Unit) {
val _p = extents
cb(_p)
extents = _p
}
fun getExtents(): Vector3 {
val _ret = __method_bind.getExtents.call(this._handle)
return _ret.asVector3()
}
fun setExtents(extents: Vector3) {
val _arg = Variant.new(extents)
__method_bind.setExtents.call(this._handle, listOf(_arg))
}
companion object {
fun new(): BoxShape = memScoped {
val fnPtr = checkNotNull(Godot.gdnative.godot_get_class_constructor)("BoxShape".cstr.ptr)
requireNotNull(fnPtr) { "No instance found for BoxShape" }
val fn = fnPtr.reinterpret<CFunction<() -> COpaquePointer>>()
BoxShape(
fn()
)
}
fun from(ptr: COpaquePointer): BoxShape = BoxShape(ptr)
/**
* Container for method_bind pointers for BoxShape
*/
private object __method_bind {
val getExtents: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("BoxShape".cstr.ptr,
"get_extents".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method get_extents" }
}
val setExtents: CPointer<godot_method_bind>
get() = memScoped {
val ptr = checkNotNull(Godot.gdnative.godot_method_bind_get_method)("BoxShape".cstr.ptr,
"set_extents".cstr.ptr)
requireNotNull(ptr) { "No method_bind found for method set_extents" }
}}
}
}
| 0 | null | 0 | 1 | 3a8c598040f9b47b2b8cf8f5432543f61d6f83e8 | 2,196 | godot-kotlin | MIT License |
androidApp/src/main/java/dev/vengateshm/samplekmm/android/StockApp.kt | vengateshm | 666,403,911 | false | null | package dev.vengateshm.samplekmm.android
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Scaffold
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import dev.vengateshm.samplekmm.android.presentation.home.HomeScreen
import dev.vengateshm.samplekmm.android.presentation.home.HomeViewModel
import org.koin.androidx.compose.koinViewModel
@Composable
fun StockApp() {
val navController = rememberNavController()
val scaffoldState = rememberScaffoldState()
Scaffold(
scaffoldState = scaffoldState,
) { innerPadding ->
NavHost(
modifier = Modifier.padding(innerPadding),
navController = navController,
startDestination = "home"
) {
composable("home") {
val viewModel = koinViewModel<HomeViewModel>()
HomeScreen(viewModel.uiState)
}
}
}
} | 0 | Kotlin | 0 | 0 | ef7463a5837c0ea8b4587381b5bb6b3fde8ab41f | 1,144 | kotlin-multiplatform-sample | Apache License 2.0 |
app/src/main/java/com/costular/marvelheroes/domain/model/UserEntityDiff.kt | ARFEGA | 138,232,052 | false | {"Kotlin": 47203} | package com.costular.marvelheroes.domain.model
import android.support.v7.util.DiffUtil
class UserEntityDiff: DiffUtil.ItemCallback<MarvelHeroEntity>() {
override fun areItemsTheSame(oldItem: MarvelHeroEntity?, newItem: MarvelHeroEntity?): Boolean {
return oldItem?.name == newItem?.name
}
override fun areContentsTheSame(oldItem: MarvelHeroEntity?, newItem: MarvelHeroEntity?): Boolean {
return oldItem == newItem
}
} | 0 | Kotlin | 0 | 0 | fd78efd5534963bca9fd32c277c6f385c1079c9f | 451 | marvel-super-heroes | MIT License |
inputfield/src/main/java/com/edwardstock/inputfield/form/validators/RegexValidator.kt | edwardstock | 253,946,292 | false | null | /*
* Copyright (C) by <NAME>. 2020
* @link <a href="https://github.com/edwardstock">Profile</a>
*
* The MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.edwardstock.inputfield.form.validators
import io.reactivex.Single
import java.util.concurrent.Callable
import java.util.regex.Pattern
/**
* Advanced InputField. 2020
* @author <NAME> <<EMAIL>>
*/
open class RegexValidator : BaseValidator {
private val mPattern: String
init {
_errorMessage = "Invalid data format"
}
@JvmOverloads
constructor(pattern: String, isRequired: Boolean = true) {
mPattern = pattern
_isRequired = isRequired
}
@JvmOverloads
constructor(pattern: Pattern, isRequired: Boolean = true) {
mPattern = pattern.pattern()
_isRequired = isRequired
}
override fun validate(value: CharSequence?): Single<Boolean> {
if (!isRequired && value.isNullOrEmpty()) {
return Single.just(true)
}
return Single.fromCallable(object : Callable<Boolean> {
override fun call(): Boolean {
if (value == null) {
return false
}
val result = value.toString()
return result.matches(mPattern.toRegex())
}
})
}
} | 0 | Kotlin | 0 | 0 | fa76765099d5fb4d3b03ec2631d09ea16afa8ea1 | 2,360 | advanced-input-field | MIT License |
src/main/kotlin/dev/igalaxy/nostringsattached/mixin/WorldRendererMixin.kt | malloryhayr | 494,974,441 | false | {"Kotlin": 7078, "Java": 502} | package dev.igalaxy.nostringsattached.mixin
import dev.igalaxy.nostringsattached.NoStringsAttached.Companion.config
import dev.igalaxy.nostringsattached.NoStringsAttached.Companion.dimension
import dev.igalaxy.nostringsattached.NoStringsAttached.Companion.selectedItem
import net.minecraft.client.render.RenderLayer
import net.minecraft.client.render.WorldRenderer
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.item.Items
import net.minecraft.util.math.Matrix4f
import net.minecraft.world.dimension.DimensionTypes
import org.spongepowered.asm.mixin.Mixin
import org.spongepowered.asm.mixin.injection.At
import org.spongepowered.asm.mixin.injection.Inject
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo
@Mixin(WorldRenderer::class)
class WorldRendererMixin {
@Inject(at = [At("HEAD")], method = ["method_3251(Lnet/minecraft/class_1921;Lnet/minecraft/class_4587;DDDLnet/minecraft/class_1159;)V"], cancellable = true)
private fun renderLayer(renderLayer: RenderLayer, matrices: MatrixStack, cameraX: Double, cameraY: Double, cameraZ: Double, positionMatrix: Matrix4f, ci: CallbackInfo) {
if (!config.enableMod) return;
if (renderLayer == RenderLayer.getTripwire()) {
if ((dimension == DimensionTypes.OVERWORLD || dimension == DimensionTypes.OVERWORLD_CAVES) && config.hideInOverworld ||
dimension == DimensionTypes.THE_NETHER && config.hideInNether ||
dimension == DimensionTypes.THE_END && config.hideInEnd
) {
if (!(config.showWhenHolding && selectedItem == Items.STRING)) {
ci.cancel()
}
}
}
}
} | 0 | Kotlin | 0 | 0 | e343a0288fc5c6affd6435cee9ab85082dd7f943 | 1,698 | no-strings-attached | MIT License |
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/KaFirSessionProvider.kt | JetBrains | 3,432,266 | false | {"Kotlin": 78963920, "Java": 6943075, "Swift": 4063829, "C": 2609498, "C++": 1947933, "Objective-C++": 170573, "JavaScript": 106044, "Python": 59695, "Shell": 32949, "Objective-C": 22132, "Lex": 21352, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2024 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.analysis.api.fir
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.LowMemoryWatcher
import com.intellij.util.containers.ContainerUtil
import org.jetbrains.kotlin.analysis.api.KaSession
import org.jetbrains.kotlin.analysis.api.lifetime.KaLifetimeToken
import org.jetbrains.kotlin.analysis.api.impl.base.sessions.KaBaseSessionProvider
import org.jetbrains.kotlin.analysis.api.permissions.KaAnalysisPermissionRegistry
import org.jetbrains.kotlin.analysis.low.level.api.fir.LLFirInternals
import org.jetbrains.kotlin.analysis.low.level.api.fir.api.getFirResolveSession
import org.jetbrains.kotlin.analysis.low.level.api.fir.file.structure.LLFirDeclarationModificationService
import org.jetbrains.kotlin.analysis.low.level.api.fir.sessions.LLFirSessionInvalidationListener
import org.jetbrains.kotlin.analysis.api.projectStructure.KaDanglingFileModule
import org.jetbrains.kotlin.analysis.api.projectStructure.KaModule
import org.jetbrains.kotlin.analysis.api.platform.projectStructure.KotlinProjectStructureProvider
import org.jetbrains.kotlin.analysis.api.projectStructure.isStable
import org.jetbrains.kotlin.analysis.api.platform.lifetime.KotlinReadActionConfinementLifetimeToken
import org.jetbrains.kotlin.psi.KtElement
import java.util.concurrent.ConcurrentMap
import kotlin.reflect.KClass
/**
* [KaFirSessionProvider] keeps [KaFirSession]s in a cache, which are actively invalidated with their associated underlying
* [LLFirSession][org.jetbrains.kotlin.analysis.low.level.api.fir.sessions.LLFirSession]s.
*/
internal class KaFirSessionProvider(project: Project) : KaBaseSessionProvider(project) {
// `KaFirSession`s must be soft-referenced to allow simultaneous garbage collection of an unused `KaFirSession` together
// with its `LLFirSession`.
private val cache: ConcurrentMap<KaModule, KaSession> = ContainerUtil.createConcurrentSoftValueMap()
init {
LowMemoryWatcher.register(::clearCaches, project)
}
override fun getAnalysisSession(useSiteElement: KtElement): KaSession {
val module = KotlinProjectStructureProvider.getModule(project, useSiteElement, useSiteModule = null)
return getAnalysisSession(module)
}
override fun getAnalysisSession(useSiteModule: KaModule): KaSession {
if (useSiteModule is KaDanglingFileModule && !useSiteModule.isStable) {
return createAnalysisSession(useSiteModule)
}
val identifier = tokenFactory.identifier
identifier.flushPendingChanges(project)
return cache.computeIfAbsent(useSiteModule, ::createAnalysisSession)
}
private fun createAnalysisSession(useSiteKtModule: KaModule): KaFirSession {
val firResolveSession = useSiteKtModule.getFirResolveSession(project)
val validityToken = tokenFactory.create(project, firResolveSession.useSiteFirSession.createValidityTracker())
return KaFirSession.createAnalysisSessionByFirResolveSession(firResolveSession, validityToken)
}
override fun clearCaches() {
cache.clear()
}
/**
* Note: Races cannot happen because the listener is guaranteed to be invoked in a write action.
*/
internal class SessionInvalidationListener(val project: Project) : LLFirSessionInvalidationListener {
private val analysisSessionProvider: KaFirSessionProvider
get() = getInstance(project) as? KaFirSessionProvider
?: error("Expected the analysis session provider to be a `${KaFirSessionProvider::class.simpleName}`.")
override fun afterInvalidation(modules: Set<KaModule>) {
modules.forEach { analysisSessionProvider.cache.remove(it) }
}
override fun afterGlobalInvalidation() {
// Session invalidation events currently don't report whether library modules were included in the global invalidation. This is
// by design to avoid iterating through the whole analysis session cache and to simplify the global session invalidation event.
// Nevertheless, a `KaFirSession`'s validity is based on the underlying `LLFirSession`, so removed analysis sessions for
// library modules might still be valid. This is not a problem, though, because analysis session caching is not required for
// correctness, but rather a performance optimization.
analysisSessionProvider.clearCaches()
}
}
}
private fun KClass<out KaLifetimeToken>.flushPendingChanges(project: Project) {
if (this == KotlinReadActionConfinementLifetimeToken::class &&
KaAnalysisPermissionRegistry.getInstance().isAnalysisAllowedInWriteAction &&
ApplicationManager.getApplication().isWriteAccessAllowed
) {
// We must flush modifications to publish local modifications into FIR tree
@OptIn(LLFirInternals::class)
LLFirDeclarationModificationService.getInstance(project).flushModifications()
}
}
| 184 | Kotlin | 5691 | 48,625 | bb25d2f8aa74406ff0af254b2388fd601525386a | 5,237 | kotlin | Apache License 2.0 |
src/main/kotlin/net/drleelihr/bot/lib/maimai/maiTool.kt | DrLee-lihr | 449,958,078 | false | {"Kotlin": 48817} | package net.drleelihr.bot.lib.maimai
import kotlin.math.floor
fun difficultyLevelTransform(a: Int): String {
return when (a) {
0 -> "BSC"
1 -> "ADV"
2 -> "EXP"
3 -> "MST"
4 -> "ReM"
else -> "Original"
}
}
fun difficultyFullLevelTransform(a: Int): String {
return when (a) {
0 -> "Basic"
1 -> "Advanced"
2 -> "Expert"
3 -> "Master"
4 -> "Re:Master"
else -> "Original"
}
}
val dxs2LevelTransform: (Float) -> String = { "${floor(it).toInt()}${if (it - floor(it) >= 0.65) "+" else ""}" }
infix fun Float.inLevel(s: String): Boolean {
val baseLevel: Int = s.split("+", "+")[0].toInt()
return if (baseLevel <= 6 && (s.contains("+") || s.contains("+"))) false
else if (s.contains("+") || s.contains("+")) (this >= baseLevel + 0.65 && this <= baseLevel + 0.95)
else (this >= baseLevel - 0.05 && this <= baseLevel + 0.65)
}
fun difficultyIDTransform(a: String): Int {
return when (a.lowercase()) {
"绿", "bsc", "basic", "bas" -> 0
"黄", "adv", "advanced" -> 1
"红", "exp", "expert" -> 2
"紫", "mst", "master", "mas" -> 3
"白", "rem", "re:master", "remaster" -> 4
else -> -1
}
}
fun ratingColorTransform(i: Int): String {
return when {
i in 0..999 -> "无色框"
i in 1000..1999 -> "蓝框"
i in 2000..2999 -> "绿框"
i in 3000..3999 -> "黄框"
i in 4000..4999 -> "红框"
i in 5000..5999 -> "紫框"
i in 6000..6999 -> "铜框"
i in 7000..7999 -> "银框"
i in 8000..8499 -> "金框"
i >= 8500 -> "彩"
else -> "?"
}
} | 0 | Kotlin | 0 | 1 | 719707f0dd0d8e1a56b980a60c9e32cce2508fc8 | 1,653 | bot | Apache License 2.0 |
lib/src/main/kotlin/com/lemonappdev/konsist/api/ext/list/KoReceiverTypeProviderListExt.kt | LemonAppDev | 621,181,534 | false | null | package com.lemonappdev.konsist.api.ext.list
import com.lemonappdev.konsist.api.provider.KoReceiverTypeProvider
import kotlin.reflect.KClass
/**
* List containing elements with receiver type.
*
* @param types The receiver type(s) to include.
* @return A list containing elements with the specified receiver type(s) (or any receiver type if [types] is empty).
*/
fun <T : KoReceiverTypeProvider> List<T>.withReceiverType(vararg types: String): List<T> = filter {
when {
types.isEmpty() -> it.hasReceiverType()
else -> types.any { type -> it.hasReceiverType(type) }
}
}
/**
* List containing elements without receiver type.
*
* @param types The receiver type(s) to exclude.
* @return A list containing elements without specified receiver type(s) (or none receiver type if [types] is empty).
*/
fun <T : KoReceiverTypeProvider> List<T>.withoutReceiverType(vararg types: String): List<T> = filter {
when {
types.isEmpty() -> !it.hasReceiverType()
else -> types.none { type -> it.hasReceiverType(type) }
}
}
/**
* List containing elements with receiver type.
*
* @param type The Kotlin class representing the receiver type to include.
* @param types The Kotlin class(es) representing the receiver type(s) to include.
* @return A list containing elements with the receiver type of the specified Kotlin class(es).
*/
fun <T : KoReceiverTypeProvider> List<T>.withReceiverTypeOf(type: KClass<*>, vararg types: KClass<*>): List<T> =
filter {
it.hasReceiverType(type.simpleName) ||
if (types.isNotEmpty()) {
types.any { kClass -> it.hasReceiverType(kClass.simpleName) }
} else {
false
}
}
/**
* List containing elements without receiver type.
*
* @param type The Kotlin class representing the receiver type to exclude.
* @param types The Kotlin class(es) representing the receiver type(s) to exclude.
* @return A list containing elements without receiver type of the specified Kotlin class(es).
*/
fun <T : KoReceiverTypeProvider> List<T>.withoutReceiverTypeOf(type: KClass<*>, vararg types: KClass<*>): List<T> =
filter {
!it.hasReceiverType(type.simpleName) &&
if (types.isNotEmpty()) {
types.none { kClass -> it.hasReceiverType(kClass.simpleName) }
} else {
true
}
}
| 2 | Kotlin | 0 | 6 | 72b358600332568bf58509884e5fe4e669098ca3 | 2,402 | konsist | Apache License 2.0 |
src/main/java/frc/robot/drivetrain/DrivetrainIORomi.kt | linpan0 | 799,102,890 | false | {"Kotlin": 15499} | package frc.robot.drivetrain
import edu.wpi.first.wpilibj.Encoder
import edu.wpi.first.wpilibj.drive.DifferentialDrive
import edu.wpi.first.wpilibj.romi.RomiMotor
class DrivetrainIORomi(leftPWM: Int, rightPWM: Int, leftEncoderID: Pair<Int, Int>, rightEncoderID: Pair<Int, Int>) : DrivetrainIO {
private val leftMotor = RomiMotor(leftPWM)
private val rightMotor = RomiMotor(rightPWM)
private val leftEncoder = Encoder(leftEncoderID.first, leftEncoderID.second)
private val rightEncoder = Encoder(rightEncoderID.first, rightEncoderID.second)
private val diffDrive = DifferentialDrive(leftMotor, rightMotor)
init {
leftEncoder.distancePerPulse = DrivetrainConstants.DISTANCE_CONVERSION_FACTOR
rightEncoder.distancePerPulse = DrivetrainConstants.DISTANCE_CONVERSION_FACTOR
rightMotor.inverted = true
diffDrive.isSafetyEnabled = false
}
override fun updateInputs(inputs: DrivetrainIO.DrivetrainIOInputs) {
inputs.leftSpeed = leftMotor.get()
inputs.leftDistance = leftEncoder.distance
inputs.leftVelocity = leftEncoder.rate
inputs.leftInverted = leftMotor.inverted
inputs.rightSpeed = rightMotor.get()
inputs.rightDistance = rightEncoder.distance
inputs.rightVelocity = rightEncoder.rate
inputs.rightInverted = rightMotor.inverted
}
override fun setLeftSpeed(speed: Double) = leftMotor.set(speed)
override fun setLeftVolts(volts: Double) = leftMotor.setVoltage(volts)
override fun setRightSpeed(speed: Double) = rightMotor.set(speed)
override fun setRightVolts(volts: Double) = rightMotor.setVoltage(volts)
override fun tankDrive(leftSpeed: Double, rightSpeed: Double) = diffDrive.tankDrive(leftSpeed, rightSpeed)
override fun resetDriveEncoders() {
leftEncoder.reset()
rightEncoder.reset()
}
} | 0 | Kotlin | 0 | 0 | cb56a88dd9648af47d50e4ec80039696a38117be | 1,791 | Math526Project | MIT License |
src/main/kotlin/de/oncoding/pcshop/componentservice/controller/CpuCoolerController.kt | tbelmega | 201,328,513 | false | null | package de.oncoding.pcshop.componentservice.controller
import de.oncoding.pcshop.componentservice.CpuCoolerRepository
import de.oncoding.pcshop.componentservice.model.pccomponents.CpuCooler
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
@RestController
class CpuCoolerController(
val cpuCoolerRepository: CpuCoolerRepository
) {
@GetMapping(value = ["/api/v1/cpucoolers"])
fun getCpuCoolers(
@RequestParam(required = false) socket: String?
): List<CpuCooler> {
return cpuCoolerRepository.findAll().filter {
socket == null || it.supportedCpuSockets.map {
it.name.toLowerCase()
}.contains(socket)
}
}
// faulty implementation
// @GetMapping(value = ["/api/v1/cpucoolers"])
// fun getCpuCoolers(
// @RequestParam socket: String
// ): List<CpuCooler> {
// return cpuCoolerRepository.findAll().filter {
// it.supportedCpuSockets.map {
// it.name.toLowerCase()
// }.contains(socket)
// }
// }
// @GetMapping(value = ["/api/v1/cpucoolers"])
// fun getCpuCoolers(): List<CpuCooler> {
// return cpuCoolerRepository.findAll()
// }
}
| 0 | Kotlin | 0 | 0 | a2580e53396c4a65a6327ddc2b7e9a62c728dd5a | 1,347 | pcshop-component-service | MIT License |
android/src/main/java/com/qrcodescannerlite/ScannerFragment.kt | AndrewTkachuk42 | 730,614,713 | false | {"Kotlin": 14312, "TypeScript": 9828, "Swift": 6396, "Ruby": 3777, "Objective-C": 2907, "JavaScript": 2122, "Objective-C++": 822, "C": 103} | // replace with your package
package com.qrcodescannerlite
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.OptIn
import androidx.camera.core.CameraSelector
import androidx.camera.core.ExperimentalGetImage
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.google.common.util.concurrent.ListenableFuture
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.facebook.react.bridge.Arguments
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.WritableMap
import java.util.concurrent.Executors
import com.google.mlkit.vision.barcode.BarcodeScanner
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage
class ScannerFragment(private val reactContext: ReactApplicationContext) : Fragment() {
private var isScanning = false
private lateinit var cameraPreviewLayout: CameraPreviewLayout
private lateinit var cameraSelector: CameraSelector
private lateinit var processCameraProviderFuture: ListenableFuture<ProcessCameraProvider>
private lateinit var processCameraProvider: ProcessCameraProvider
private lateinit var cameraPreview: Preview
private lateinit var imageAnalysis: ImageAnalysis
private lateinit var events: Events
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): CameraPreviewLayout {
super.onCreateView(inflater, container, savedInstanceState)
cameraPreviewLayout = CameraPreviewLayout(requireNotNull(context))
events = Events(reactContext, id)
return cameraPreviewLayout
}
override fun onDestroyView() {
super.onDestroyView()
unbindCamera()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// do any logic that should happen in an `onCreate` method, e.g:
// customView.onCreate(savedInstanceState);
start()
}
private fun start() {
initCamera()
buildInputAnalyser()
processCameraProviderFuture.addListener({
processCameraProvider = processCameraProviderFuture.get()
bindCamera()
}, ContextCompat.getMainExecutor(requireNotNull(context)))
}
private fun initCamera() {
cameraSelector =
CameraSelector.Builder().requireLensFacing(CameraSelector.LENS_FACING_BACK).build()
processCameraProviderFuture = ProcessCameraProvider.getInstance(requireNotNull(context))
cameraPreview = Preview.Builder()
.setTargetRotation(cameraPreviewLayout.previewView.display.rotation)
.build()
cameraPreview.setSurfaceProvider(cameraPreviewLayout.previewView.surfaceProvider)
}
private fun buildInputAnalyser() {
val barcodeScanner: BarcodeScanner = BarcodeScanning.getClient(
BarcodeScannerOptions.Builder()
.setBarcodeFormats(Barcode.FORMAT_QR_CODE)
.build()
)
imageAnalysis = ImageAnalysis.Builder()
.setTargetRotation(cameraPreviewLayout.previewView.display.rotation)
.build()
val cameraExecutor = Executors.newSingleThreadExecutor()
imageAnalysis.setAnalyzer(cameraExecutor) { imageProxy ->
processImageProxy(barcodeScanner, imageProxy)
}
}
@OptIn(ExperimentalGetImage::class) private fun processImageProxy(
barcodeScanner: BarcodeScanner,
imageProxy: ImageProxy
) {
val inputImage =
InputImage.fromMediaImage(imageProxy.image!!, imageProxy.imageInfo.rotationDegrees)
barcodeScanner.process(inputImage)
.addOnSuccessListener { barcodes ->
if (barcodes.isNotEmpty()) {
onBarcodeScanned(barcodes.first())
}
}
.addOnFailureListener {
events.sendReadError(it.message)
}.addOnCompleteListener {
imageProxy.close()
}
}
private fun onBarcodeScanned(barcode: Barcode) {
events.sendQrCodeScanned(prepareBarcodeData(barcode))
}
private fun prepareBarcodeData(barcode: Barcode): WritableMap {
return Arguments.createMap().apply {
putString("type", barcode.valueType.toString())
putString("data", barcode.rawValue)
}
}
private fun bindCamera(){
if (isScanning) {
return
}
try {
processCameraProvider.bindToLifecycle(this, cameraSelector, cameraPreview, imageAnalysis)
isScanning = true
} catch (error: Throwable) {
events.sendInitializationError(error.message)
}
}
fun unbindCamera(){
if (!isScanning) {
return
}
processCameraProvider.unbindAll()
isScanning = false
}
fun resumeScan() {
bindCamera()
}
}
| 0 | Kotlin | 0 | 2 | ff749e9a8f7d9244eb1595ef8c20874721d2fcfb | 4,932 | react-native-qr-code-scanner-lite | MIT License |
app/src/main/java/com/andre_max/droidhub/ui/log_in/LoginViewModel.kt | Andre-max | 324,688,034 | false | null | package com.andre_max.droidhub.ui.log_in
import androidx.annotation.IdRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.andre_max.droidhub.R
import com.andre_max.droidhub.utils.FirebaseUtils
import timber.log.Timber
class LoginViewModel : ViewModel() {
val email = MutableLiveData("")
val password = MutableLiveData("")
val shouldNavigate = MutableLiveData<Int>()
private var _isLoading = MutableLiveData(false)
val isLoading: LiveData<Boolean> = _isLoading
fun verifyInput() {
_isLoading.value = true
val inputMap = mapOf("Email" to email.value, "Password" to password.value)
for (entry in inputMap) {
if (entry.value.isNullOrEmpty()) return
}
loginAccount(email.value!!, password.value!!)
}
fun navigate(@IdRes navigationId: Int) {
shouldNavigate.value = navigationId
}
private fun loginAccount(email: String, password: String) {
FirebaseUtils.firebaseAuth.signInWithEmailAndPassword(email, password)
.addOnSuccessListener {
Timber.d("Success: Sign in was successful")
navigate(R.id.homeFragment)
}
.addOnFailureListener {
Timber.e(it)
}
.addOnCompleteListener {
_isLoading.value = false
}
}
} | 0 | Kotlin | 1 | 0 | 7985745fa849122284b204c7d3ced78d30e94b08 | 1,430 | DroidHub | Apache License 2.0 |
app/src/main/java/com/mytests/testExam/domain/useCases/animalFacts/AnimalFactsUseCases.kt | FredNekrasov | 766,574,196 | false | {"Kotlin": 46367} | package com.mytests.testExam.domain.useCases.animalFacts
import com.mytests.testExam.domain.useCases.animalFacts.get.IGetAnimalFactsUseCase
import com.mytests.testExam.domain.useCases.animalFacts.update.IUpdateFactUseCase
data class AnimalFactsUseCases(
val getFacts: IGetAnimalFactsUseCase,
val updateFact: IUpdateFactUseCase
) | 0 | Kotlin | 0 | 1 | 2b1129429abfb21aa7d49aa9293798fd6e27d90f | 338 | my-tests | MIT License |
app/src/main/java/com/app/skyss_companion/view/widgets/StopGroupListItem.kt | martinheitmann | 339,335,251 | false | null | package com.app.skyss_companion.view.widgets
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.app.skyss_companion.model.StopGroup
import com.app.skyss_companion.view.bookmark.ServiceModeIcons
import com.app.skyss_companion.view.bookmark.StopGroupTitle
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun StopGroupListItem(stopGroup: StopGroup, onTap: (StopGroup) -> Unit) {
val serviceModes = stopGroup.serviceModes ?: emptyList()
val title = stopGroup.description ?: ""
Card(
modifier = Modifier.padding(bottom = 8.dp),
onClick = { onTap(stopGroup) }
) {
Box(modifier = Modifier.padding(all = 16.dp)) {
Row(
modifier = Modifier.fillMaxWidth()
) {
ServiceModeIcons(serviceModes = serviceModes)
Spacer(modifier = Modifier.width(8.dp))
StopGroupTitle(title = title)
}
}
}
} | 0 | Kotlin | 0 | 1 | a4a79e658643731cd76617cdb9458aa1f742d4c3 | 1,147 | bus-companion | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.