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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/java/com/metriql/service/jdbc/QueryService.kt | metriql | 370,169,788 | false | null | package com.metriql.service.jdbc
import com.metriql.service.task.TaskQueueService
import io.trino.execution.QueryInfo
import io.trino.server.BasicQueryInfo
import org.rakam.server.http.HttpService
import org.rakam.server.http.RakamHttpRequest
import javax.ws.rs.DELETE
import javax.ws.rs.GET
import javax.ws.rs.Path
@Path("/v1/query")
class QueryService(val taskQueueService: TaskQueueService) : HttpService() {
@GET
@Path("/")
fun listActiveQueries(): List<BasicQueryInfo> {
TODO()
}
@GET
@Path("/*")
fun activeQuery(): QueryInfo {
TODO()
}
@DELETE
@Path("/*")
fun cancelQuery(request: RakamHttpRequest) {
TODO()
}
}
| 30 | Kotlin | 19 | 253 | 10fa42434c19d1dbfb9a3d04becea679bb82d0f1 | 694 | metriql | Apache License 2.0 |
modules/ktorium-stdlib/src/commonTest/kotlinX/StandardTest.kt | ktorium | 316,943,260 | false | {"Kotlin": 75228, "JavaScript": 203} | package org.ktorium.kotlin.stdlib
import org.ktorium.kotlin.ExperimentalKtoriumAPI
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
@ExperimentalKtoriumAPI
internal class StandardTest {
@Test
fun applyIf_trueCondition_callBlock() {
val values = mutableListOf<String>()
val defaultValue = "default-value"
values.applyIf(true) {
add(defaultValue)
}
assertTrue(values.contains(defaultValue))
}
@Test
fun applyIf_falseCondition_callBlock() {
val values = mutableListOf<String>()
val result = values.applyIf(false) {
throw IllegalStateException()
}
assertEquals(values, result)
}
@Test
fun alsoIf_trueCondition_callBlock() {
val values = mutableListOf<String>()
val defaultValue = "default-value"
values.alsoIf(true) {
it.add(defaultValue)
}
assertTrue(values.contains(defaultValue))
}
@Test
fun alsoIf_falseCondition_callBlock() {
val value = mutableListOf<String>()
val result = value.alsoIf(false) {
it.add("default-value")
}
assertEquals(value, result)
}
@Test
fun letIf_trueCondition_callBlock() {
val value = "value"
val defaultValue = "default-value"
val result = value.letIf(true) {
defaultValue
}
assertEquals(defaultValue, result)
}
@Test
fun letIf_falseCondition_callBlock() {
val value = "value"
val result = value.letIf(false) {
"default-value"
}
assertNull(result)
}
@Test
fun runIf_trueCondition_callBlock() {
val value = "value"
val defaultValue = "default-value"
val result = value.runIf(true) {
defaultValue
}
assertEquals(defaultValue, result)
}
@Test
fun runIf_falseCondition_callBlock() {
val value = "value"
val result = value.runIf(false) {
"default-value"
}
assertNull(result)
}
@Test
fun getOrThrow_nullValue_throwException() {
val value: String? = null
assertFailsWith(Exception::class) {
value.getOrThrow(RuntimeException())
}
}
@Test
fun getOrThrow_notNullValue_returnThis() {
val value = "value"
val result = value.getOrThrow(Exception())
assertSame(value, result)
}
@Test
fun getOrDefault_nullValue_returnDefault() {
val value: String? = null
val defaultValue = "default-value"
val result = value.getOrDefault(defaultValue)
assertEquals(defaultValue, result)
}
@Test
fun getOrDefault_notNullValue_returnThis() {
val value = "value"
val result = value.getOrDefault("default-value")
assertSame(value, result)
}
@Test
fun getOrElse_nullValue_callBlock() {
val value: String? = null
val defaultValue = "default-value"
val result = value.getOrElse { defaultValue }
assertEquals(defaultValue, result)
}
@Test
fun getOrElse_notNullValue_returnThis() {
val value = "value"
val result = value.getOrElse { throw IllegalStateException() }
assertSame(value, result)
}
@Test
fun isNull_nullValue_returnTrue() {
val value: String? = null
assertTrue(value.isNull())
}
@Test
fun isNull_notNullValue_returnFalse() {
val value = "value".getOrDefault(null)
assertFalse(value.isNull())
}
@Test
fun isNotNull_nullValue_returnTrue() {
val value: String? = null.getOrDefault(null)
assertFalse(value.isNotNull())
}
@Test
fun isNotNull_notNullValue_returnFalse() {
val value = "value".getOrDefault(null)
assertTrue(value.isNotNull())
}
@Test
fun safeAsOrNull_nullValue_returnNull() {
val value: String? = null
val result = value.safeAsOrNull<Int>()
assertNull(result)
}
@Test
fun safeAsOrNull_notNullValue_returnThis() {
val value = "value"
val result = value.safeAsOrNull<String>()
assertSame(value, result)
}
@Test
fun safeAsOrDefault_nullValue_returnDefault() {
val value: String? = null
val defaultValue = "default-value"
val result = value.safeAsOrDefault(defaultValue)
assertEquals(defaultValue, result)
}
@Test
fun safeAsOrDefault_notNullValue_returnThis() {
val value = "value"
val result = value.safeAsOrDefault("default-value")
assertSame(value, result)
}
@Test
fun safeAsOrElse_nullValue_callBlock() {
val value: String? = null
val defaultValue = "default-value"
val result = value.safeAsOrElse { defaultValue }
assertEquals(defaultValue, result)
}
@Test
fun safeAsOrElse_notNullValue_returnThis() {
val value = "value"
val defaultValue = "default-value"
val result = value.safeAsOrElse {
defaultValue
}
assertSame(value, result)
}
@Test
fun safeAsOrThrow_nullValue_throwException() {
val value: String? = null
assertFailsWith(Exception::class) {
value.safeAsOrThrow(RuntimeException())
}
}
@Test
fun safeAsOrThrow_notNullValue_returnThis() {
val value = "value"
val result = value.safeAsOrThrow<String>(Exception())
assertSame(value, result)
}
@Test
fun unsafeCast_nullValue_throwException() {
val value: String? = null
assertFailsWith(Exception::class) {
value.unsafeCast<Int>()
}
}
@Test
fun unsafeCast_notNullValue_returnThis() {
val value = "value"
val result = value.unsafeCast<String>()
assertSame(value, result)
}
@Test
fun unsafeCast_notSameCast_throwException() {
val value = "value"
assertFailsWith(Exception::class) {
value.unsafeCast<Int>()
}
}
}
| 0 | Kotlin | 0 | 1 | 019ed2c96f545f5a725053d37074bca462efb4d5 | 6,328 | ktorium-kotlin | Apache License 2.0 |
desktopData/src/main/kotlin/com/intelligentbackpack/desktopdata/storage/DesktopStorage.kt | IntelligentBackpack | 629,745,884 | false | null | package com.intelligentbackpack.desktopdata.storage
/**
* Shared preferences storage for desktop module
*/
interface DesktopStorage {
/**
* Save backpack hash
*/
fun isBackpackSaved(): Boolean
/**
* Save backpack hash
*
* @param hash backpack hash
*/
fun saveBackpack(hash: String)
/**
* Get backpack hash
*/
fun getBackpack(): String
/**
* Delete backpack hash
*/
fun deleteBackpack()
}
| 3 | Kotlin | 1 | 0 | b6bf23af5c6e56c4d356f2f26828239d975237cb | 477 | IntelligentBackpackApp | MIT License |
complete/android/app/src/main/kotlin/com/codelab/awesomedrawingquiz/MainActivity.kt | googlecodelabs | 272,842,941 | false | null | package com.codelab.awesomedrawingquiz
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
} | 2 | Dart | 39 | 55 | f6eee5a42e0fae528e27a6e7af6635ad5dd4763c | 134 | admob-ads-in-flutter | Apache License 2.0 |
complete/android/app/src/main/kotlin/com/codelab/awesomedrawingquiz/MainActivity.kt | googlecodelabs | 272,842,941 | false | null | package com.codelab.awesomedrawingquiz
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
} | 2 | Dart | 39 | 55 | f6eee5a42e0fae528e27a6e7af6635ad5dd4763c | 134 | admob-ads-in-flutter | Apache License 2.0 |
feature/accountdetails/src/main/java/org/expenny/feature/accountdetails/view/AccountDetailsTypeSelectionCarousel.kt | expenny-application | 712,607,222 | false | {"Kotlin": 933192} | package org.expenny.feature.accountdetails.view
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import org.expenny.core.common.types.AccountType
import org.expenny.core.ui.extensions.icon
import org.expenny.core.ui.extensions.label
import org.expenny.core.ui.components.ExpennyChip
@Composable
internal fun AccountDetailsTypeSelectionCarousel(
modifier: Modifier = Modifier,
listState: LazyListState,
types: List<AccountType>,
selection: AccountType,
onTypeSelect: (AccountType) -> Unit,
) {
LazyRow(
modifier = modifier,
state = listState,
horizontalArrangement = Arrangement.spacedBy(8.dp)
) {
items(types) { type ->
ExpennyChip(
modifier = Modifier.height(48.dp),
isSelected = type == selection,
onClick = {
onTypeSelect(type)
},
label = {
ChipLabel(text = type.label)
},
leadingIcon = {
ChipIcon(painter = type.icon)
}
)
}
}
}
| 0 | Kotlin | 3 | 40 | 7cdd7fdb51ca9ee1caf13354fac3bf819d031065 | 1,434 | expenny-android | Apache License 2.0 |
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/action/GHPRReRequestReviewAction.kt | allotria | 40,114,891 | true | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.github.pullrequest.ui.details.action
import com.intellij.collaboration.messages.CollaborationToolsBundle
import com.intellij.collaboration.util.CollectionDelta
import com.intellij.openapi.progress.EmptyProgressIndicator
import org.jetbrains.plugins.github.pullrequest.data.service.GHPRSecurityService
import org.jetbrains.plugins.github.pullrequest.ui.details.model.GHPRMetadataModel
import org.jetbrains.plugins.github.pullrequest.ui.details.model.GHPRReviewFlowViewModel
import org.jetbrains.plugins.github.pullrequest.ui.details.model.GHPRStateModel
import java.awt.event.ActionEvent
internal class GHPRReRequestReviewAction(
stateModel: GHPRStateModel,
securityService: GHPRSecurityService,
private val metadataModel: GHPRMetadataModel,
private val reviewFlowVm: GHPRReviewFlowViewModel,
) : GHPRStateChangeAction(CollaborationToolsBundle.message("review.details.action.rerequest"), stateModel, securityService) {
override fun actionPerformed(event: ActionEvent) = stateModel.submitTask {
val delta = CollectionDelta(metadataModel.reviewers, reviewFlowVm.reviewerAndReviewState.value.keys)
metadataModel.adjustReviewers(EmptyProgressIndicator(), delta)
}
} | 0 | null | 0 | 0 | 9b9e3972a437d1a08fc73370fb09b9f45527dd2a | 1,333 | intellij-community | Apache License 2.0 |
app/src/main/java/com/example/gitandroid/MainActivity.kt | payamkhederzadeh | 456,250,673 | false | {"Kotlin": 1477} | package com.example.gitandroid
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
android.widget.Toast.makeText(this, "salam", Toast.LENGTH_SHORT).show()
android.widget.Toast.makeText(this, "hi", Toast.LENGTH_SHORT).show()
}
} | 0 | Kotlin | 0 | 0 | d9bbec79ff739e425d3a627a16da3f9c48f64889 | 460 | my-first-project | MIT License |
src/main/kotlin/com/github/secretx33/whisperjsontosrt/model/SubtitleEntry.kt | SecretX33 | 640,121,315 | false | null | package com.github.secretx33.whisperjsontosrt.model
data class SubtitleEntry(
val start: Double,
val end: Double,
val text: String,
) | 0 | Kotlin | 0 | 1 | 99f0fafe0419c6be8c39e5d1fed9c024200299f9 | 146 | WhisperJsonToSrt | MIT License |
sample/src/main/kotlin/vipsffm/SampleHelper.kt | lopcode | 838,313,812 | false | {"Java": 1318877, "Kotlin": 81132, "Shell": 6395, "C": 461} | package vipsffm
import app.photofox.vipsffm.jextract.VipsRaw
import java.nio.file.Files
import java.nio.file.Path
object SampleHelper {
fun runCatching(vipsFunction: () -> Int): Result<Unit> {
val result = vipsFunction()
if (result != 0) {
val error = VipsRaw.vips_error_buffer().getString(0)
return Result.failure(
RuntimeException("failed to run vips command: $error")
)
}
return Result.success(Unit)
}
fun validate(
path: Path,
expectedSizeBoundsKb: LongRange
): Result<Unit> {
if (!Files.exists(path)) {
return Result.failure(
RuntimeException("wrote thumbnail, but failed to find at \"$path\"")
)
}
val fileSizeKb = Files.size(path) / 1000
if (!expectedSizeBoundsKb.contains(fileSizeKb)) {
return Result.failure(
RuntimeException("unexpected resulting thumbnail size ${fileSizeKb}kb")
)
}
val bytes = Files.readAllBytes(path)
if (bytes.all { it == 0.toByte() }) {
return Result.failure(
RuntimeException("file all zeroes")
)
}
return Result.success(Unit)
}
} | 5 | Java | 1 | 19 | 9acf6ed18aae0b076308ec97804412510e2f56ed | 1,282 | vips-ffm | Apache License 2.0 |
src/main/kotlin/com/github/paololupo/kanagawatheme/listeners/MyProjectManagerListener.kt | PaoloLupo | 512,225,573 | false | {"Kotlin": 6838} | package com.github.paololupo.kanagawatheme.listeners
import com.intellij.openapi.components.service
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
import com.github.paololupo.kanagawatheme.services.MyProjectService
internal class MyProjectManagerListener : ProjectManagerListener {
override fun projectOpened(project: Project) {
project.service<MyProjectService>()
}
}
| 0 | Kotlin | 0 | 0 | ee256c074cb4b29aa10e286d0783732e888b07b7 | 444 | Kanagawa-Theme-Intellij | Apache License 2.0 |
app/src/main/java/com/aayar94/foodrecipes/data/Repository.kt | AAyar94 | 646,751,480 | false | null | package com.aayar94.foodrecipes.data
import com.aayar94.foodrecipes.data.local.LocalDataSource
import com.aayar94.foodrecipes.data.remote.RemoteDataSource
import dagger.hilt.android.scopes.ActivityRetainedScoped
import javax.inject.Inject
@ActivityRetainedScoped
class Repository @Inject constructor(
private val remoteDataSource: RemoteDataSource,
private val localDataSource: LocalDataSource
) {
val remote = remoteDataSource
val local = localDataSource
} | 0 | Kotlin | 0 | 1 | 7410f3c68d050d8a6d9d0364fc7d7495ac62b1ff | 476 | Food_Recipes | MIT License |
app/src/main/java/com/ericafenyo/eyenight/ui/profile/ProfileActivity.kt | ericafenyo | 152,482,181 | false | null | /*
* Copyright (C) 2018 Eric Afenyo
*
* 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.ericafenyo.eyenight.ui.profile
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.ericafenyo.eyenight.R
class ProfileActivity : AppCompatActivity() {
companion object {
/**
* Returns a newly created Intent that can be used to launch the activity.
*
* @param packageContext A Context of the application package that will start this class.
* Example [android.app.Activity].
*/
fun getStartIntent(packageContext: Context): Intent {
val intent = Intent(packageContext, ProfileActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
return intent
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.profile_activity)
}
}
| 0 | Kotlin | 1 | 0 | 62e060e9e61a487bccabaff078f4f8df5429a199 | 1,537 | parse-user | Apache License 2.0 |
community-family-component/src/main/java/com/kotlin/android/community/family/component/comm/FamilyCommViewModel.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.community.family.component.comm
import androidx.lifecycle.viewModelScope
import com.kotlin.android.api.base.BaseUIModel
import com.kotlin.android.community.family.component.repository.FamilyCommRepository
import com.kotlin.android.core.BaseViewModel
import com.kotlin.android.app.data.entity.common.CommonResult
import com.kotlin.android.app.data.entity.common.CommonResultExtend
import com.kotlin.android.user.afterLogin
import kotlinx.coroutines.launch
/**
* @author ZhouSuQiang
* @email [email protected]
* @date 2020/9/9
*/
open class FamilyCommViewModel<E> : BaseViewModel() {
protected val mFamilyCommRepository by lazy { FamilyCommRepository() }
private val mCommJoinFamilyUIModel = BaseUIModel<CommonResultExtend<CommonResult, E>>()
val mCommJoinFamilyUISate = mCommJoinFamilyUIModel.uiState
private val mCommOutFamilyUIModel = BaseUIModel<CommonResultExtend<CommonResult, E>>()
val mCommOutFamilyUISate = mCommOutFamilyUIModel.uiState
/**
* 加入家族
*/
fun joinFamily(id: Long, extend: E) {
afterLogin {
viewModelScope.launch(main) {
mCommJoinFamilyUIModel.emitUIState(showLoading = true)
val result = withOnIO {
mFamilyCommRepository.joinFamily(id, extend)
}
mCommJoinFamilyUIModel.checkResultAndEmitUIState(result = result)
}
}
}
/**
* 退出家族
*/
fun outFamily(id: Long, extend: E) {
afterLogin {
viewModelScope.launch(main) {
mCommOutFamilyUIModel.emitUIState(showLoading = true)
val result = withOnIO {
mFamilyCommRepository.outFamily(id, extend)
}
mCommOutFamilyUIModel.checkResultAndEmitUIState(result = result)
}
}
}
} | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 1,882 | Mtime | Apache License 2.0 |
src/Day03.kt | mjossdev | 574,439,750 | false | {"Kotlin": 81859} | fun main() {
fun Char.getPriority(): Int = if (isLowerCase()) {
1 + (this - 'a')
} else {
27 + (this - 'A')
}
data class Rucksack(val compartment1: Set<Char>, val compartment2: Set<Char>) {
fun commonItem(): Char = compartment1.intersect(compartment2).single()
fun allItems() = compartment1.union(compartment2)
}
fun String.toRucksack(): Rucksack {
val n = length / 2
return Rucksack(take(n).toSet(), takeLast(n).toSet())
}
fun getBadge(rucksacks: List<Rucksack>): Char {
val commonItems = rucksacks.first().allItems().toMutableSet()
rucksacks.drop(1).forEach {
commonItems.retainAll(it.allItems())
}
return commonItems.single()
}
fun part1(input: List<String>): Int = input.sumOf { it.toRucksack().commonItem().getPriority() }
fun part2(input: List<String>): Int = input.map { it.toRucksack() }.chunked(3).sumOf { getBadge(it).getPriority() }
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(part1(testInput) == 157)
check(part2(testInput) == 70)
val input = readInput("Day03")
println(part1(input))
println(part2(input))
}
| 0 | Kotlin | 0 | 0 | afbcec6a05b8df34ebd8543ac04394baa10216f0 | 1,263 | advent-of-code-22 | Apache License 2.0 |
RickMortyAndroidApp/app/src/main/kotlin/io/github/brunogabriel/rickmorty/di/AppModule.kt | brunogabriel | 437,544,186 | false | null | package io.github.brunogabriel.rickmorty.di
import android.app.Application
import android.content.Context
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
internal abstract class AppModule {
companion object {
@Singleton
@Provides
fun providesContext(context: Application): Context = context
}
} | 0 | Kotlin | 0 | 3 | 6e40b2cdc157cf07a5b4574e9c308335112deb4d | 362 | rick-and-morty-app | MIT License |
kotlin-typescript/src/main/generated/typescript/JSDocAllType.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
package typescript
sealed external interface JSDocAllType : JSDocType {
override val kind: SyntaxKind.JSDocAllType
}
| 12 | Kotlin | 145 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 167 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/goldze/mvvmhabit/aioui/zixun/ZixunActivity.kt | fengao1004 | 505,038,355 | false | {"Java Properties": 2, "Gradle": 6, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Text": 4, "Ignore List": 4, "Proguard": 3, "Java": 214, "XML": 141, "Kotlin": 158} | package com.goldze.mvvmhabit.aioui.zixun
import android.os.Bundle
import com.goldze.mvvmhabit.BR
import com.goldze.mvvmhabit.R
import com.goldze.mvvmhabit.databinding.ActivityKnowsBinding
import com.goldze.mvvmhabit.databinding.ActivityZixunBinding
import me.goldze.mvvmhabit.base.BaseActivity
class ZixunActivity : BaseActivity<ActivityZixunBinding, ZixunModel>() {
override fun initContentView(savedInstanceState: Bundle?): Int {
return R.layout.activity_zixun
}
override fun initVariableId(): Int {
return BR.viewModel
}
override fun initData() {
super.initData()
binding.brRootView.setPageTitle("咨询服务")
}
} | 1 | null | 1 | 1 | 1099bd7bfcf8a81d545567ae875b3528aa5fb1cd | 672 | AIO | Apache License 2.0 |
core/models/src/main/kotlin/flow/models/forum/CategoryModel.kt | andrikeev | 503,060,387 | false | null | package flow.models.forum
data class CategoryModel(
val category: Category,
val isBookmark: Boolean = false,
val newTopicsCount: Int = 0,
)
| 0 | Kotlin | 2 | 8 | a850db05575d58cd7676823f6185311c595c4dd0 | 153 | Flow | MIT License |
link/src/main/java/com/stripe/android/link/LinkActivity.kt | stripe | 6,926,049 | false | null | package com.stripe.android.link
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.annotation.VisibleForTesting
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.stripe.android.link.theme.DefaultLinkTheme
import com.stripe.android.link.ui.LinkAppBar
import com.stripe.android.link.ui.signup.SignUpBody
import com.stripe.android.link.ui.verification.VerificationBody
import com.stripe.android.link.ui.wallet.WalletBody
internal class LinkActivity : ComponentActivity() {
private val viewModel: LinkActivityViewModel by viewModels {
LinkActivityViewModel.Factory(application) { requireNotNull(starterArgs) }
}
@VisibleForTesting
lateinit var navController: NavHostController
private val starterArgs: LinkActivityContract.Args? by lazy {
LinkActivityContract.Args.fromIntent(intent)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
navController = rememberNavController()
viewModel.navigator.navigationController = navController
DefaultLinkTheme {
Surface {
Column(
Modifier
.fillMaxWidth()
.padding(horizontal = 20.dp)
) {
val linkAccount by viewModel.linkAccount.collectAsState(initial = null)
LinkAppBar(
email = linkAccount?.email,
onCloseButtonClick = { dismiss() }
)
NavHost(navController, viewModel.startDestination) {
composable(LinkScreen.Loading.route) {
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
composable(
LinkScreen.SignUp.route,
arguments = listOf(
navArgument(LinkScreen.SignUp.emailArg) {
type = NavType.StringType
nullable = true
}
)
) { backStackEntry ->
val email =
backStackEntry.arguments?.getString(LinkScreen.SignUp.emailArg)
SignUpBody(viewModel.injector, email)
}
composable(LinkScreen.Verification.route) {
linkAccount?.let { account ->
VerificationBody(
account,
viewModel.injector
)
}
}
composable(LinkScreen.Wallet.route) {
linkAccount?.let { account ->
WalletBody(
account,
viewModel.injector
)
}
}
composable(LinkScreen.PaymentMethod.route) {
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(),
contentAlignment = Alignment.Center
) {
Text(text = "<Placholder>\nAdd new payment method")
}
}
}
}
}
}
}
viewModel.navigator.onDismiss = ::dismiss
viewModel.setupPaymentLauncher(this)
}
override fun onDestroy() {
super.onDestroy()
viewModel.unregisterFromActivity()
}
private fun dismiss(result: LinkActivityResult = LinkActivityResult.Canceled) {
setResult(
result.resultCode,
Intent().putExtras(LinkActivityContract.Result(result).toBundle())
)
finish()
}
}
| 64 | Kotlin | 522 | 935 | bec4fc5f45b5401a98a310f7ebe5d383693936ea | 5,728 | stripe-android | MIT License |
app/src/main/kotlin/com/globallogic/kotlin_rssreader/MainActivity.kt | GlobalLogicLatam | 92,772,020 | false | null | /*
* Copyright (C) 2017 Globallogic
*
* 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.globallogic.kotlin_rssreader
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Html
import android.util.Log
import android.view.View
import android.view.ViewGroup
import com.globallogic.kotlin_rssreader.model.Item
import com.globallogic.kotlin_rssreader.model.Rss
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.view_item.view.*
import okhttp3.Call
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
class MainActivity : AppCompatActivity() {
// like a static variable in java
companion object {
val URL: String = "https://www.dropbox.com/s/bpio3vvgkt9lq5y/feed.xml?dl=1"
val TAG: String = "MainActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
getRss(URL) { rss ->
runOnUiThread {
val list = rss.channel.items
recycler.layoutManager = LinearLayoutManager(this)
recycler.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL))
recycler.adapter = RssAdapter(list) { item ->
// open the link in a browser
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(item.link)
startActivity(intent)
}
}
}
}
}
class RssAdapter(val items: List<Item>?, val listener: (Item) -> Unit) : RecyclerView.Adapter<RssAdapter.RssViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RssViewHolder {
return RssViewHolder(parent.inflate(R.layout.view_item))
}
override fun onBindViewHolder(holder: RssViewHolder, position: Int) {
with(holder.itemView) {
val item = items!![position]
view_title.text = item.title
view_description.text = Html.fromHtml(item.description)
view_date.text = item.getPubDate()
setOnClickListener { listener(item) }
}
}
override fun getItemCount() = items!!.size
class RssViewHolder(view: View) : RecyclerView.ViewHolder(view)
}
fun getRss(url: String, listener: (Rss) -> Unit) {
val httpClient = OkHttpClient()
val request = Request.Builder().url(url).build()
httpClient.newCall(request).enqueue(object : okhttp3.Callback {
override fun onFailure(call: Call?, e: IOException?) {
Log.d(MainActivity.TAG, "Error", e)
}
override fun onResponse(call: Call?, response: Response?) {
val rss = Rss.parseFromXml(response!!.body().string())
listener(rss)
}
})
} | 0 | Kotlin | 0 | 2 | 74d6d290b7ba89b62719eb4806acdce771fa1f32 | 3,623 | android-kotlin-rssreader | Apache License 2.0 |
src/main/kotlin/xd/arkosammy/monkeyconfig/groups/MutableSettingGroup.kt | ArkoSammy12 | 810,454,497 | false | {"Kotlin": 96084, "Java": 4442} | package xd.arkosammy.monkeyconfig.groups
import xd.arkosammy.monkeyconfig.settings.ConfigSetting
import xd.arkosammy.monkeyconfig.types.SerializableType
import xd.arkosammy.monkeyconfig.util.SettingLocation
/**
* A [SettingGroup] that supports adding and removing [ConfigSetting] instances from it.
*/
interface MutableSettingGroup : SettingGroup {
/**
* Adds a [ConfigSetting] to this [SettingGroup].
*/
fun <T, S : SerializableType<*>> addConfigSetting(setting: ConfigSetting<T, S>)
/**
* Removes a [ConfigSetting] from this [SettingGroup] by its [SettingLocation].
*
* @return `true` if the setting was successfully removed, `false` otherwise.
*/
fun removeConfigSetting(settingLocation: SettingLocation) : Boolean = false
/**
* Transforms this [MutableSettingGroup] into an immutable [SettingGroup].
*
* The resulting [SettingGroup] will not be an instance of [MutableSettingGroup] and will contain the same [ConfigSetting]s as this [MutableSettingGroup]. If the [configSettings] argument is not `null`, the resulting [SettingGroup] will contain the [ConfigSetting]s passed to this method instead.
*
* @param configSettings An optional [List] of [ConfigSetting]s to be included in the returned [SettingGroup]. If `null`, the [ConfigSetting]s of this [MutableSettingGroup] will be used.
* @return An immutable [SettingGroup] with the same or specified [ConfigSetting]s.
*/
fun toImmutable(configSettings: List<ConfigSetting<*, *>>? = null) : SettingGroup
} | 0 | Kotlin | 1 | 0 | 8be81f40611d3b35abe7fe06b04778fc472e45c2 | 1,556 | Monkey-Config | MIT License |
gdx-backend-bytecoder/src/main/kotlin/com/squins/gdx/backends/bytecoder/api/web/HTMLAudioElement.kt | tommyettinger | 317,685,017 | true | {"Kotlin": 170646, "Java": 149688, "HTML": 2606, "JavaScript": 334} | package com.squins.gdx.backends.bytecoder.api.web
import de.mirkosertic.bytecoder.api.OpaqueMethod
import de.mirkosertic.bytecoder.api.OpaqueProperty
import de.mirkosertic.bytecoder.api.web.HTMLElement
/**
* Represents Web Audio element
*/
interface HTMLAudioElement: HTMLElement {
@OpaqueProperty("loop")
fun setLooping(loop : Boolean)
@OpaqueProperty("loop")
fun isLoop() : Boolean
@OpaqueProperty("volume")
fun setVolume(volume: Float)
@OpaqueProperty("volume")
fun getVolume() : Float
@OpaqueProperty("currentTime")
fun setCurrentTime(currentTime: Int)
@OpaqueProperty("currentTime")
fun getCurrentTime() : Int
@OpaqueProperty("paused")
fun isPaused() : Boolean
@OpaqueProperty("ended")
fun isEnded() : Boolean
fun play()
fun pause()
@OpaqueMethod("stop")
fun dispose()
@OpaqueProperty("src")
fun setSrc(url: String)
}
| 0 | Kotlin | 0 | 0 | aed4b4d484c51a93def6ef7ade13f27fb9bbafe6 | 928 | gdx-backend-bytecoder | Apache License 2.0 |
app/src/main/java/io/horizontalsystems/bankwallet/core/providers/AppConfigProvider.kt | fahimaltinordu | 312,207,740 | true | {"Kotlin": 1883211, "Java": 33448, "Ruby": 5803, "Shell": 2024} | package io.horizontalsystems.bankwallet.core.providers
import io.horizontalsystems.bankwallet.BuildConfig
import io.horizontalsystems.bankwallet.R
import io.horizontalsystems.bankwallet.core.App
import io.horizontalsystems.bankwallet.core.IAppConfigProvider
import io.horizontalsystems.bankwallet.entities.*
import io.horizontalsystems.core.IBuildConfigProvider
import io.horizontalsystems.core.ILanguageConfigProvider
import io.horizontalsystems.core.entities.Currency
import java.math.BigDecimal
class AppConfigProvider : IAppConfigProvider, ILanguageConfigProvider, IBuildConfigProvider {
override val companyWebPageLink: String = "https://horizontalsystems.io"
override val appWebPageLink: String = "https://unstoppable.money"
override val appGithubLink: String = "https://github.com/horizontalsystems/unstoppable-wallet-android"
override val companyTwitterLink: String = "https://twitter.com/UnstoppableByHS"
override val companyTelegramLink: String = "https://t.me/PlusbitWallet"
override val companyRedditLink: String = "https://reddit.com/r/UNSTOPPABLEWallet/"
override val btcCoreRpcUrl: String = "https://btc.horizontalsystems.xyz/rpc"
override val reportEmail = "[email protected]"
override val walletHelpTelegramGroup = "PlusBitWallet"
override val cryptoCompareApiKey = App.instance.getString(R.string.cryptoCompareApiKey)
override val infuraProjectId = App.instance.getString(R.string.infuraProjectId)
override val infuraProjectSecret = App.instance.getString(R.string.infuraSecretKey)
override val etherscanApiKey = App.instance.getString(R.string.etherscanKey)
override val guidesUrl = App.instance.getString(R.string.guidesUrl)
override val faqUrl = App.instance.getString(R.string.faqUrl)
override val fiatDecimal: Int = 2
override val maxDecimal: Int = 8
override val feeRateAdjustForCurrencies: List<String> = listOf("USD","EUR")
override val currencies: List<Currency> = listOf(
Currency(code = "USD", symbol = "\u0024", decimal = 2),
Currency(code = "EUR", symbol = "\u20AC", decimal = 2),
Currency(code = "GBP", symbol = "\u00A3", decimal = 2),
Currency(code = "JPY", symbol = "\u00A5", decimal = 2)
)
override val featuredCoins: List<Coin>
get() = listOf(
Coin("WILC", "Wrapped ILCoin", "WILC", 8, CoinType.Erc20("0xc98a910ede52e7d5308525845f19e17470dbccf7")),
Coin("WETH", "Wrapped Ethereum", "WETH", 18, CoinType.Erc20("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2")),
Coin("ETH", "Ethereum", "ETH", 18, CoinType.Ethereum),
)
override val ethereumCoin: Coin
get() = featuredCoins[2]
override val otherCoins: List<Coin>
get() = listOf(
Coin("WBTC", "Wrapped Bitcoin", "WBTC", 8, CoinType.Erc20("0x2260fac5e5542a773aa44fbcfedf7c193bc2c599")),
Coin("USDT", "Tether USD", "USDT", 6, CoinType.Erc20("0xdAC17F958D2ee523a2206206994597C13D831ec7")),
Coin("DAI", "Dai", "DAI", 18, CoinType.Erc20("0x6b175474e89094c44da98b954eedeac495271d0f")),
Coin("BUSD", "Binance USD", "BUSD", 18, CoinType.Erc20("0x4fabb145d64652a948d72533023f6e7a623c7c53")),
)
override val binanceCoin: Coin
get() = featuredCoins[2]
// ILanguageConfigProvider
override val localizations: List<String>
get() {
val coinsString = "de,en,es,fa,fr,ko,ru,tr,zh"
return coinsString.split(",")
}
// IBuildConfigProvider
override val testMode: Boolean = BuildConfig.testMode
override val skipRootCheck: Boolean = BuildConfig.skipRootCheck
}
| 0 | Kotlin | 0 | 4 | d3094c4afaa92a5d63ce53583bc07c8fb343f90b | 3,700 | WILC-wallet-android | MIT License |
src/main/kotlin/com/github/kropp/gradle/thanks/ThanksPlugin.kt | kropp | 115,663,130 | false | null | package com.github.kropp.gradle.thanks
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.component.ComponentIdentifier
import org.gradle.api.artifacts.result.DependencyResult
import org.gradle.api.artifacts.result.ResolutionResult
import org.gradle.api.artifacts.result.ResolvedArtifactResult
import org.gradle.api.artifacts.result.ResolvedDependencyResult
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.kotlin.dsl.task
import org.gradle.maven.MavenModule
import org.gradle.maven.MavenPomArtifact
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import javax.xml.parsers.DocumentBuilderFactory
class ThanksPlugin : Plugin<ProjectInternal> {
private val ENV_VAR = "GITHUB_TOKEN"
private val pluginRepos = mutableSetOf<String>()
override fun apply(project: ProjectInternal) {
project.pluginManager.pluginContainer.all {
val pluginClassName = this::class.qualifiedName
if (pluginClassName != null) {
resolvePluginRepo(pluginClassName)?.let { pluginRepos += it }
}
}
project.task("thanks") {
description = "Star Github repositories from dependencies"
doLast {
withToken(project) { token ->
project.allprojects.findDependenciesAndStar(token) { allDependencies }
// project.allprojects.findDependenciesAndStar(token) { root.dependencies }
}
}
}
}
private fun resolvePluginRepo(className: String): String? {
return when(className) {
"org.gradle.kotlin.dsl.plugins.dsl.KotlinDslPlugin" -> "gradle/kotlin-dsl"
"com.github.kropp.gradle.thanks.ThanksPlugin" -> "kropp/gradle-plugin-thanks"
else -> if (className.startsWith("org.gradle")) "gradle/gradle" else null
}
}
private fun withToken(project: Project, action: (String) -> Unit) {
val token = project.properties["GithubToken"] as? String ?: System.getenv(ENV_VAR)
if (token.isNullOrEmpty()) {
println("Github API token not found. Please set -PGithubToken parameter or environment variable $ENV_VAR")
} else {
action(token)
}
}
private fun Set<Project>.findDependenciesAndStar(token: String, dependencies: ResolutionResult.() -> Set<DependencyResult>) {
val repositories = pluginRepos + this.flatMap { it.getRepositories(dependencies) }.toSet()
if (repositories.any()) {
println("Starring Github repositories from dependencies and plugins")
} else {
println("No Github repositories found in dependencies and plugins")
}
loop@ for (repository in repositories) {
try {
if (repository.isStarred(token)) {
println(" \u2b50 $repository")
} else {
val response = repository.star(token)
when (response) {
401 -> { println("Authentication failed. Please check Github token."); break@loop }
204 -> println(" \uD83C\uDF1F $repository")
else -> println(" \u274c $repository ($response)")
}
}
} catch (e: IOException) {
println(" \u274c $repository (${e.message})")
}
}
}
private fun Project.getRepositories(dependencies: ResolutionResult.() -> Set<DependencyResult>): List<String> {
val dependencyIds = configurations.filter { it.isCanBeResolved }.flatMap { it.incoming.resolutionResult.dependencies() }
.filterIsInstance<ResolvedDependencyResult>().map { it.selected.id }
return getPoms(this, dependencyIds).mapNotNull { readGithubProjectsFromPom(it) }
}
private fun getPoms(project: Project, ids: List<ComponentIdentifier>) =
project.dependencies
.createArtifactResolutionQuery()
.forComponents(ids)
.withArtifacts(MavenModule::class.java, MavenPomArtifact::class.java)
.execute()
.resolvedComponents
.flatMap {
it.getArtifacts(MavenPomArtifact::class.java)
.filterIsInstance<ResolvedArtifactResult>()
.map { it.file.absolutePath }
}
private fun readGithubProjectsFromPom(filename: String): String? {
val document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(filename)
val scm = document.getElementsByTagName("scm").asSequence().firstOrNull() ?: return null
val url = scm.childNodes.asSequence().filter { it.textContent.contains("github.com") }.firstOrNull()?.textContent
return url?.substringAfter("github.com")?.removePrefix("/")?.removePrefix(":")?.removeSuffix(".git")?.removeSuffix("/issues")
}
private val GITHUB_API = "https://api.github.com"
private fun String.isStarred(token: String) = httpRequestResponse("GET", "$GITHUB_API/user/starred/$this", token) == 204
private fun String.star(token: String) = httpRequestResponse("PUT", "$GITHUB_API/user/starred/$this", token)
private fun httpRequestResponse(method: String, url: String, token: String): Int? {
val httpCon = URL(url).openConnection() as? HttpURLConnection ?: return null
httpCon.setRequestProperty("Authorization", "token $token")
httpCon.requestMethod = method
httpCon.connectTimeout = 10_000
httpCon.readTimeout = 10_000
httpCon.connect()
return httpCon.responseCode
}
} | 0 | Kotlin | 0 | 4 | 5b335868774fbca81c5b2abce3ff15c1298aed39 | 5,241 | gradle-plugin-thanks | MIT License |
03_ejemplos/EjemploSQLite/src/app.kt | egibide-programacion | 92,039,721 | false | null | import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
/**
* Created by widemos on 26/5/17.
*/
fun main(args: Array<String>) {
// Conectar
var conexion: Connection? = null
try {
val controlador = "org.sqlite.JDBC"
val cadenaconex = "jdbc:sqlite:corredores.sqlite"
Class.forName(controlador)
conexion = DriverManager.getConnection(cadenaconex)
} catch (ex: ClassNotFoundException) {
println("No se ha podido cargar el driver JDBC")
} catch (ex: SQLException) {
println("Error de conexión")
}
// Leer datos
val lista = ArrayList<Corredor>()
try {
val st = conexion?.createStatement()
val sql = "SELECT * FROM corredores"
val rs = st?.executeQuery(sql)
while (rs!!.next()) {
val c = Corredor(
rs.getLong("id"),
rs.getString("nombre"),
rs.getInt("dorsal"),
rs.getInt("categoria")
)
lista.add(c)
}
} catch (ex: SQLException) {
println("Error al recuperar los datos")
}
// Mostrar los datos
println("Recuperados: ${lista.size} registros")
for (corredor in lista) {
println(corredor)
}
// Desconectar
conexion?.close()
}
| 0 | Kotlin | 12 | 4 | e240e328d684f3d27e6e2bc4e9b83c9f3d7ee4fa | 1,350 | kotlin | Apache License 2.0 |
src/main/kotlin/org/bonitasoft/example/DeployAdminApplicationTestData.kt | bonitasoft-labs | 300,656,896 | false | null | /*
* Copyright 2021 Bonitasoft S.A.
* 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.bonitasoft.example
import com.github.javafaker.Faker
import org.bonitasoft.engine.api.APIClient
import org.bonitasoft.example.processes.*
import java.util.function.Consumer
class DeployAdminApplicationTestData : Consumer<APIClient> {
override fun accept(apiClient: APIClient) {
val faker = Faker()
DeployEmployeeBDM().deploy(apiClient)
Organization().deploy(apiClient)
val calledProcess = BigData(100).apply {
deploy(apiClient)
}
StartXProcessesWithData(calledProcess.name, calledProcess.version, 1).deploy(apiClient)
val formName = "custompage_${faker.dog().breed()}"
GeneratedPage(formName, "form").deploy(apiClient)
(1..12).forEach {
GeneratedProcessWithForms("GeneratedProcessWithForms-${faker.animal().name()}-$it", formName).deploy(apiClient)
}
(1..12).forEach {
ProcessNotEnabled("ProcessNotEnabled-${faker.rickAndMorty().character()}-$it").deploy(apiClient)
}
(1..12).forEach {
ProcessHavingConfigurationIssues("ProcessHavingConfigurationIssues-${faker.dune().planet()}-$it").deploy(apiClient)
}
(1..12).forEach {
GeneratedPage("custompage_${faker.dog().breed().replace(" ", "")}$it", "form").deploy(apiClient)
}
(1..12).forEach {
GeneratedRestApiExt("custompage_${faker.dog().name().replace(" ", "")}$it").deploy(apiClient)
}
(1..12).forEach {
GeneratedApplication("app_${faker.dog().name().replace(" ", "")}$it").deploy(apiClient)
}
(1..12).forEach {
EnabledProcessHavingConfigurationIssues("EnabledProcessHavingConfigurationIssues-${faker.animal().name()}-$it").deploy(apiClient)
}
}
}
| 2 | Kotlin | 1 | 0 | d095693b6c7942c6cf5c6a6131095d20654fc7d1 | 2,385 | bonita-test-processes | Apache License 2.0 |
src/main/kotlin/com/exerro/sketchup/api/SketchHost.kt | exerro | 301,201,441 | false | null | package com.exerro.sketchup.api
import com.exerro.sketchup.application.SketchSnapshot
interface SketchHost {
@Deprecated("Will be replaced by a streamed model snapshot")
fun constantSnapshot(): SketchSnapshot // TODO: replace event system to support this
}
| 0 | Kotlin | 0 | 0 | d2c04ed6c220604c7ebd32f7e84a08031e2c23b9 | 267 | sketch-up | MIT License |
app/src/main/java/com/demo/features/viewAllOrder/interf/ColorListOnCLick.kt | DebashisINT | 614,693,263 | false | null | package com.demo.features.viewAllOrder.interf
import com.demo.app.domain.NewOrderGenderEntity
import com.demo.features.viewAllOrder.model.ProductOrder
interface ColorListOnCLick {
fun colorListOnCLick(size_qty_list: ArrayList<ProductOrder>, adpPosition:Int)
} | 0 | Kotlin | 0 | 0 | 80c611bcf95487eb57f7c6563f955265e55832df | 265 | FSM_APP_ANDROIDX_TestingUpdate | Apache License 2.0 |
app/src/main/java/com/smtm/mvvm/data/repository/user/UserRemoteDataSource.kt | asus4862 | 293,993,826 | false | null | package com.smtm.mvvm.data.repository.user
import com.smtm.mvvm.data.remote.request.ConnectRequest
import com.smtm.mvvm.data.remote.request.GithubUserRequest
import com.smtm.mvvm.data.remote.request.TokenRequest
import com.smtm.mvvm.data.remote.response.ConnectResponse
import com.smtm.mvvm.data.remote.response.TokenResponse
import com.smtm.mvvm.data.repository.user.model.UserResponse
import io.reactivex.Single
/**
**/
interface UserRemoteDataSource {
fun getUsers(userSearchRequest: GithubUserRequest): Single<UserResponse>
fun getToken(tokenRequest: TokenRequest): Single<TokenResponse>
fun getConnect(authorization: String, connectRequest: ConnectRequest): Single<ConnectResponse>
} | 0 | Kotlin | 0 | 0 | c535bd319d7a77fb9d5df8524313026d1b3ce2da | 708 | MVVMArchitecture | Apache License 2.0 |
guide/src/main/kotlin/captureOutput.kt | arrow-kt | 557,761,845 | false | null | package arrow.website
import java.io.*
val STDOUT_ENABLED_DEFAULT =
try { java.lang.Boolean.getBoolean("kotlinx.knit.test.stdout") }
catch (e: SecurityException) { false }
/**
* Captures stdout and stderr of the specified block of code.
*
* The [name] is used to display which test is being run.
* When [stdoutEnabled] is true, then everything is displayed to stdout when then code runs, too.
*/
public inline fun captureOutput(
name: String,
stdoutEnabled: Boolean = STDOUT_ENABLED_DEFAULT,
main: (out: PrintStream) -> Unit
): List<String> {
val oldOut = System.out
val oldErr = System.err
val logOut = if (stdoutEnabled) oldOut else NullOut
val bytesOut = ByteArrayOutputStream()
val tee = TeeOutput(bytesOut, logOut)
val ps = PrintStream(tee)
logOut.println("--- Running $name")
System.setErr(ps)
System.setOut(ps)
val bytes: ByteArray
try {
try {
main(logOut)
} catch (e: Throwable) {
System.err.print("Exception in thread \"main\" ")
e.printStackTrace()
}
// capture output
bytes = bytesOut.toByteArray()
if (tee.flushLine()) logOut.println()
logOut.println("--- done")
} finally {
System.setOut(oldOut)
System.setErr(oldErr)
}
return ByteArrayInputStream(bytes).bufferedReader().readLines()
}
object NullOut : PrintStream(NullOutputStream())
class NullOutputStream : OutputStream() {
override fun write(b: Int) = Unit
}
class TeeOutput(
private val bytesOut: OutputStream,
private val oldOut: PrintStream
) : OutputStream() {
val limit = 200
var lineLength = 0
fun flushLine(): Boolean {
if (lineLength > limit)
oldOut.print(" ($lineLength chars in total)")
val result = lineLength > 0
lineLength = 0
return result
}
override fun write(b: Int) {
bytesOut.write(b)
if (b == 0x0d || b == 0x0a) { // new line
flushLine()
oldOut.write(b)
} else {
lineLength++
if (lineLength <= limit)
oldOut.write(b)
}
}
}
| 13 | Kotlin | 7 | 6 | b27f53e4a2f28875cd2243d15f2d3624de67ca2c | 2,002 | arrow-website | Apache License 2.0 |
app/src/main/java/com/elvinliang/aviation/utils/Utils.kt | ElvinCWLiang | 497,921,490 | false | null | package com.elvinliang.aviation.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import androidx.annotation.DrawableRes
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.ui.Modifier
import androidx.compose.ui.composed
import com.elvinliang.aviation.presentation.component.settings.AircraftLabel
import com.elvinliang.aviation.presentation.component.settings.SettingsConfig
import com.elvinliang.aviation.remote.dto.PlaneModel
import com.elvinliang.aviation.remote.dto.Posts
import java.io.IOException
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import retrofit2.Response
/* for loading test data */
fun getJsonDataFromAsset(context: Context, fileName: String): String? {
val jsonString: String
try {
jsonString = context.assets.open(fileName).bufferedReader().use { it.readText() }
} catch (ioException: IOException) {
ioException.printStackTrace()
return null
}
return jsonString
}
fun Double?.orZero(): Double {
return this ?: 0.0
}
fun Int?.orZero(): Int {
return this ?: 0
}
fun Float?.toIntOrZero(): Int {
return this?.toInt() ?: 0
}
fun Int?.toFloatOrZero(): Float {
return this?.toFloat() ?: 0F
}
fun Float?.orZero(): Float {
return this ?: 0F
}
fun String?.orUnknown(): String {
return this ?: "N/A"
}
fun Long.toTime(): String {
return this.toString()
}
fun Modifier.clickableWithoutRipple(
interactionSource: MutableInteractionSource,
onClick: () -> Unit
) = composed(
factory = {
this.then(
Modifier.clickable(
interactionSource = interactionSource,
indication = null,
onClick = { onClick() }
)
)
}
)
object BitmapGenerator {
fun createBitMap(
@DrawableRes
ImageResource: Int,
city: String = "",
name: String = "",
rotate: Float = 90F,
size: Int = 20,
type: Int,
context: Context,
): Bitmap {
val src = BitmapFactory.decodeResource(context.resources, ImageResource)
println("evlog ${src.width} ${src.height}")
val width = src.width + size * 2
val height = src.height + size * 2
val result = Bitmap.createBitmap(width, height, src.config)
val canvas = Canvas(result)
val textPaint = Paint()
textPaint.textAlign = Paint.Align.CENTER
val xPos = canvas.width / 2
textPaint.textSize = size.toFloat()
canvas.drawText(
if (type == AircraftLabel.CALLSIGN.ordinal || type == AircraftLabel.ALL.ordinal
) {
city
} else {
""
},
xPos.toFloat(), size.toFloat(), textPaint
)
canvas.drawText(
if (type == AircraftLabel.ALL.ordinal
) {
name
} else {
""
},
xPos.toFloat(), size.toFloat() * 2 + src.height, textPaint
)
canvas.save()
canvas.rotate(rotate, canvas.width.toFloat() / 2, canvas.height.toFloat() / 2)
canvas.drawBitmap(src, size.toFloat(), size.toFloat(), null)
canvas.restore()
return result
}
}
object AircraftListMapper {
fun createAircraftList(settingsConfig: SettingsConfig, planeModelList: List<PlaneModel>): List<PlaneModel> {
val planeList = planeModelList.toMutableList()
planeList.removeIf {
it.geo_altitude != null &&
it.geo_altitude!! < settingsConfig.altitudeScope.first ||
it.geo_altitude!! > settingsConfig.altitudeScope.second
}
planeList.removeIf {
it.velocity != null &&
it.velocity!! < settingsConfig.speedScope.first ||
it.velocity!! > settingsConfig.speedScope.second
}
return planeList
}
}
object ResponseMapper {
fun createMapper(response: Response<Posts>): List<PlaneModel> {
val aircraftList = ArrayList<PlaneModel>()
response.body()?.let { list ->
for (i in list.states.indices) {
val aircraft = PlaneModel(
icao24 = list.states[i][0] as String,
callsign = (list.states[i][1] as String)
.replace("\\s".toRegex(), ""),
list.states[i][2] as String,
(list.states[i][3] as Double).toInt(),
(list.states[i][4] as Double).toInt(),
list.states[i][5] as Double,
list.states[i][6] as Double,
(list.states[i][7] as Double?)?.toFloat(),
(list.states[i][8] as Boolean),
(list.states[i][9] as Double?)?.toFloat(),
(list.states[i][10] as Double?)?.toFloat(),
(list.states[i][11] as Double?)?.toFloat(),
null,
(list.states[i][13] as Double?)?.toFloat(),
list.states[i][14] as String?, (list.states[i][15] as Boolean),
(list.states[i][16] as Double).toInt(),
// ,(list.states[i][17] as Double).toInt()
(list.time)
)
aircraftList.add(aircraft)
}
}
return aircraftList
}
}
object Timer {
fun createTimer(duration: Long) = flow {
while (true) {
emit(1)
delay(duration)
}
}
}
| 0 | Kotlin | 0 | 1 | 83a048394cba5f8a849c26e346a3c393c12e427d | 5,710 | LinkFlight | MIT License |
lavaplayer/src/main/java/com/sedmelluq/discord/lavaplayer/manager/AudioPlayer.kt | mixtape-bot | 397,835,411 | true | {"Kotlin": 781109, "Java": 315803} | package com.sedmelluq.discord.lavaplayer.manager
import com.sedmelluq.discord.lavaplayer.filter.PcmFilterFactory
import com.sedmelluq.discord.lavaplayer.manager.event.AudioEvent
import com.sedmelluq.discord.lavaplayer.track.AudioTrack
import com.sedmelluq.discord.lavaplayer.track.playback.AudioFrameProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
/**
* An audio player that is capable of playing audio tracks and provides audio frames from the currently playing track.
*/
interface AudioPlayer : AudioFrameProvider, CoroutineScope {
/**
* The [AudioTrack] that is currently playing, or null if nothing is playing.
*/
val playingTrack: AudioTrack?
/**
* The current volume of this player.
*/
var volume: Int
/**
* Whether the player is paused.
*/
var isPaused: Boolean
/**
* The event flow for this player.
*/
val events: Flow<AudioEvent>
/**
* @param track The track to start playing
*/
fun playTrack(track: AudioTrack?)
/**
* @param track The track to start playing, passing null will stop the current track and return false
* @param noInterrupt Whether to only start if nothing else is playing
* @return True if the track was started
*/
fun startTrack(track: AudioTrack?, noInterrupt: Boolean): Boolean
/**
* Stop currently playing track.
*/
fun stopTrack()
/**
* Configures the filter factory for this player.
*/
fun setFilterFactory(factory: PcmFilterFactory?)
/**
* Sets the frame buffer duration for this player.
*/
fun setFrameBufferDuration(duration: Int)
/**
* Destroy the player and stop playing track.
*/
fun destroy()
/**
* Check if the player should be "cleaned up" - stopped due to nothing using it, with the given threshold.
*
* @param threshold Threshold in milliseconds to use
*/
fun checkCleanup(threshold: Long)
}
| 0 | Kotlin | 0 | 6 | 06b02d8e711930c52d8ca67ad6347a17ca352ba2 | 2,010 | lavaplayer | Apache License 2.0 |
libs/serialization/serialization-amqp/src/main/kotlin/net/corda/internal/serialization/amqp/custom/EnumSetSerializer.kt | corda | 346,070,752 | false | null | package net.corda.internal.serialization.amqp.custom
import net.corda.internal.serialization.amqp.standard.MapSerializer
import net.corda.serialization.BaseProxySerializer
import net.corda.v5.base.util.uncheckedCast
import java.util.EnumSet
/**
* A serializer that writes out an [EnumSet] as a type, plus list of instances in the set.
*/
class EnumSetSerializer : BaseProxySerializer<EnumSet<*>, EnumSetSerializer.EnumSetProxy>() {
override val type: Class<EnumSet<*>> get() = EnumSet::class.java
override val proxyType: Class<EnumSetProxy> get() = EnumSetProxy::class.java
override val withInheritance: Boolean get() = true
override fun toProxy(obj: EnumSet<*>): EnumSetProxy
= EnumSetProxy(elementType(obj), obj.toList())
private fun elementType(set: EnumSet<*>): Class<*> {
return if (set.isEmpty()) {
EnumSet.complementOf(set).first().javaClass
} else {
set.first().javaClass
}
}
override fun fromProxy(proxy: EnumSetProxy): EnumSet<*> {
return if (proxy.elements.isEmpty()) {
EnumSet.noneOf(uncheckedCast<Class<*>, Class<MapSerializer.EnumJustUsedForCasting>>(proxy.clazz))
} else {
EnumSet.copyOf(uncheckedCast<List<Any>, List<MapSerializer.EnumJustUsedForCasting>>(proxy.elements))
}
}
data class EnumSetProxy(val clazz: Class<*>, val elements: List<Any>)
}
| 82 | Kotlin | 7 | 24 | 17f5d2e5585a8ac56e559d1c099eaee414e6ec5a | 1,413 | corda-runtime-os | Apache License 2.0 |
core/src/test/kotlin/enfasys/android/core/BaseRepositoryTest.kt | enfasys-tech | 232,678,700 | false | {"Kotlin": 60105} | package enfasys.android.core
import enfasys.android.core.usecase.FailureDescription
import enfasys.android.core.usecase.NoDataInServerResponseError
import enfasys.android.core.usecase.NoMessageInServerResponseError
import enfasys.android.core.usecase.Result
import kotlinx.coroutines.runBlocking
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue
class BaseRepositoryTest {
private val data = 322
private val message = "Error"
@Test
fun `safeCall returns success when response data is different from null and response is success`() =
runBlocking {
val response = NetworkResponse(success = true, data = data, message = null)
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(true)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeCall { response }
assertTrue(result is Result.Success)
assertEquals(Result.success(data), result)
assertFalse(logger.wasCalled)
}
@Test
fun `safeCall returns failure when response data is null and response is success`() =
runBlocking {
val response = NetworkResponse(success = true, data = null, message = null)
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(true)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeCall { response }
assertTrue(result is Result.Failure)
assertEquals(
FailureDescription.WithThrowable(NoDataInServerResponseError),
result.failureDescription
)
assertTrue(logger.wasCalled)
}
@Test
fun `safeCall returns failure when response is not success and there is a non-null message`() =
runBlocking {
val response = NetworkResponse(success = false, data = null, message = message)
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(true)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeCall { response }
assertTrue(result is Result.Failure)
assertEquals(FailureDescription.WithFeature(message), result.failureDescription)
assertFalse(logger.wasCalled)
}
@Test
fun `safeCall returns failure when response is not success and there is a null message`() =
runBlocking {
val response = NetworkResponse(success = false, data = null, message = null)
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(true)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeCall { response }
assertTrue(result is Result.Failure)
assertEquals(
FailureDescription.WithThrowable(NoMessageInServerResponseError),
result.failureDescription
)
assertTrue(logger.wasCalled)
}
@Test
fun `safeCall returns failure and logs exception when block() throws an exception and there is a connection available`() =
runBlocking {
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(true)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeCall<Int> { throw Exception(message) }
assertTrue(result is Result.Failure)
assertTrue(result.failureDescription is FailureDescription.WithThrowable)
assertTrue(logger.wasCalled)
}
@Test
fun `safeCall returns failure when block() throws an exception and there is not a connection available`() =
runBlocking {
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(false)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeCall<Int> { throw Exception() }
assertTrue(result is Result.Failure)
assertEquals(FailureDescription.NetworkConnectionError, result.failureDescription)
assertFalse(logger.wasCalled)
}
@Test
fun `safeEmptyCall returns success when response is success`() =
runBlocking {
val response = NetworkResponse<Empty>(success = true, data = null, message = null)
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(true)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeEmptyCall { response }
assertTrue(result is Result.Success)
assertEquals(Result.success(), result)
assertFalse(logger.wasCalled)
}
@Test
fun `safeEmptyCall returns failure when response is not success and there is a non-null message`() =
runBlocking {
val response = NetworkResponse<Empty>(success = false, data = null, message = message)
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(true)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeEmptyCall { response }
assertTrue(result is Result.Failure)
assertEquals(FailureDescription.WithFeature(message), result.failureDescription)
assertFalse(logger.wasCalled)
}
@Test
fun `safeEmptyCall returns failure when response is not success and there is a null message`() =
runBlocking {
val response = NetworkResponse<Empty>(success = false, data = null, message = null)
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(true)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeEmptyCall { response }
assertTrue(result is Result.Failure)
assertEquals(
FailureDescription.WithThrowable(NoMessageInServerResponseError),
result.failureDescription
)
assertTrue(logger.wasCalled)
}
@Test
fun `safeEmptyCall returns failure and logs exception when block() throws an exception and there is a connection available`() =
runBlocking {
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(true)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeEmptyCall { throw Exception(message) }
assertTrue(result is Result.Failure)
assertTrue(result.failureDescription is FailureDescription.WithThrowable)
assertTrue(logger.wasCalled)
}
@Test
fun `safeEmptyCall returns failure when block() throws an exception and there is not a connection available`() =
runBlocking {
val logger = FakeLogger()
val networkVerifier = FakeNetworkVerifier(false)
val repository = FakeBaseRepository(logger, networkVerifier)
val result = repository.safeEmptyCall { throw Exception() }
assertTrue(result is Result.Failure)
assertEquals(FailureDescription.NetworkConnectionError, result.failureDescription)
assertFalse(logger.wasCalled)
}
}
| 0 | Kotlin | 0 | 0 | 1ad3e9f7e1a5b058f3bca3f08c712f5042397115 | 7,546 | core-android | Apache License 2.0 |
domain/src/main/java/com/lighthouse/domain/entity/response/vo/TokenVO.kt | soma-lighthouse | 658,620,687 | false | {"Kotlin": 442318} | package com.lighthouse.domain.entity.response.vo
data class TokenVO(
val accessToken: String,
val expiresIn: Long,
val refreshToken: String,
val refreshTokenExpiresIn: Long,
)
| 0 | Kotlin | 0 | 0 | 2109f0e2f50e4502c2778bc2a831272785eaf7a7 | 193 | FE-lingo-talk | Apache License 2.0 |
domain/src/main/java/com/mperezc/domain/usecases/RateUseCase.kt | MOccam | 589,286,826 | false | null | package com.mperezc.domain.usecases
import com.mperezc.domain.model.RateMapModel
import kotlinx.coroutines.flow.Flow
interface RateUseCase {
suspend fun getRate(): Flow<Result<RateMapModel>>
} | 0 | Kotlin | 0 | 0 | be729c54c7e6116cc8045a2da6b3355d6f23670f | 199 | GNBTrades | Apache License 2.0 |
felles/src/main/kotlin/no/nav/helsearbeidsgiver/felles/EventTypes.kt | navikt | 495,713,363 | false | null | package no.nav.helsearbeidsgiver.felles
enum class BehovType {
PAUSE,
FULLT_NAVN,
VIRKSOMHET,
INNTEKT,
ARBEIDSFORHOLD,
JOURNALFOER,
ARBEIDSGIVERE,
HENT_TRENGER_IM,
PREUTFYLL,
PERSISTER_IM,
HENT_PERSISTERT_IM
}
enum class NotisType {
NOTIFIKASJON,
NOTIFIKASJON_TRENGER_IM
}
| 0 | Kotlin | 0 | 2 | 7a72f63b858b6b16365cfd78e38518ac294d1fe1 | 327 | helsearbeidsgiver-inntektsmelding | MIT License |
core/src/main/java/nick/core/util/Resource.kt | jaswindersandhu | 189,632,252 | false | null | package nick.core.util
sealed class Resource<out T> {
object Loading : Resource<Unit>()
data class Success<out T>(val data: T? = null) : Resource<T>()
data class Error<out T>(val throwable: Throwable) : Resource<T>()
} | 0 | Kotlin | 0 | 0 | 8efcb2570c85dc64fd14a3d5d7f36f7a8d852dc8 | 231 | IAmJob | The Unlicense |
app/src/main/java/com/nativeboys/password/manager/data/repositories/fields/FieldRepositoryImpl.kt | EvangelosBoudis | 347,924,640 | false | null | package com.nativeboys.password.manager.data.repositories.fields
import com.nativeboys.password.manager.data.FieldData
import com.nativeboys.password.manager.data.storage.FieldDao
import javax.inject.Inject
class FieldRepositoryImpl @Inject constructor(
private val fieldDao: FieldDao
): FieldRepository {
override suspend fun findAllFieldsByCategoryId(categoryId: String): List<FieldData> {
return fieldDao.findAllByCategoryId(categoryId)
}
} | 0 | Kotlin | 0 | 0 | b392cf151d1967b6dc5d56fef6f5f0bfaaa7fb07 | 467 | digital-bit-security | Apache License 2.0 |
src/main/kotlin/io/acari/http/SupportRouter.kt | Unthrottled | 178,487,158 | false | {"Kotlin": 109281, "TypeScript": 68140, "Dockerfile": 687, "Shell": 624, "JavaScript": 272} | package io.acari.http
import io.vertx.core.json.JsonObject
import io.vertx.reactivex.core.Vertx
import io.vertx.reactivex.ext.web.Router
import io.vertx.reactivex.micrometer.PrometheusScrapingHandler
fun mountSupportingRoutes(vertx: Vertx, router: Router, configuration: JsonObject): Router {
router.route("/metrics").handler(PrometheusScrapingHandler.create())
return router
}
| 0 | Kotlin | 0 | 1 | 6dc41adc14b6aaf332a6d98b7b4a6b086e077e5c | 385 | SOGoS-API | MIT License |
layerscaffold/src/main/java/com/appsoluut/layerscaffold/LayerScaffold.kt | appsoluut | 671,345,118 | false | null | package com.appsoluut.layerscaffold
import androidx.compose.foundation.gestures.Orientation
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.contentColorFor
import androidx.compose.material.swipeable
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.collapse
import androidx.compose.ui.semantics.contentDescription
import androidx.compose.ui.semantics.expand
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.offset
import com.appsoluut.layerscaffold.LayerScaffoldDefaults.FrontLayerHeaderElevation
import kotlin.math.roundToInt
import kotlinx.coroutines.launch
@Composable
@ExperimentalMaterialApi
fun LayerScaffold(
backLayerContent: @Composable () -> Unit,
frontLayerContent: @Composable () -> Unit,
modifier: Modifier = Modifier,
bottomBar: @Composable () -> Unit = {},
scaffoldState: LayerScaffoldState = rememberLayerScaffoldState(initialValue = LayerValue.Revealed),
gesturesEnabled: Boolean = true,
headerHeight: Dp = LayerScaffoldDefaults.HeaderHeight,
backLayerPeekHeight: Dp = LayerScaffoldDefaults.BackLayerPeekHeight,
backLayerBackgroundColor: Color = MaterialTheme.colors.primary,
backLayerContentColor: Color = contentColorFor(backLayerBackgroundColor),
frontLayerPeekHeight: Dp? = null,
frontLayerBackgroundColor: Color = MaterialTheme.colors.surface,
frontLayerContentColor: Color = contentColorFor(frontLayerBackgroundColor),
frontLayerHeaderElevation: Dp = FrontLayerHeaderElevation,
frontLayerHeader: @Composable () -> Unit = {},
frontLayerHandle: @Composable () -> Unit = { LayerHandle() },
) {
val headerHeightPx: Float
val backLayerPeekHeightPx: Float
var frontLayerPeekHeightPx: Float
with(LocalDensity.current) {
headerHeightPx = headerHeight.toPx()
backLayerPeekHeightPx = backLayerPeekHeight.toPx()
frontLayerPeekHeightPx = frontLayerPeekHeight?.toPx() ?: -1f
}
val calculateBackLayerConstraints: (Constraints) -> Constraints = {
it.copy(minWidth = 0, minHeight = 0).offset(vertical = -headerHeightPx.roundToInt())
}
// Back layer
Surface(
color = backLayerBackgroundColor,
contentColor = backLayerContentColor
) {
val scope = rememberCoroutineScope()
Stack(
modifier = modifier.fillMaxSize(),
bottomBar = bottomBar,
backLayer = backLayerContent,
frontLayerHandle = frontLayerHandle,
frontLayerHeader = frontLayerHeader,
calculateBackLayerConstraints = calculateBackLayerConstraints
) { constraints, backLayerHeight, combinedHeaderHeight, bottomBarHeight ->
val fullHeight = constraints.maxHeight.toFloat()
val revealedHeight = fullHeight - headerHeightPx
if (frontLayerPeekHeightPx < 0) {
frontLayerPeekHeightPx = combinedHeaderHeight
}
val peekHeight = fullHeight - frontLayerPeekHeightPx - bottomBarHeight
val concealedContentDescription = stringResource(id = R.string.layerscaffold_cd_concealed)
val revealedContentDescription = stringResource(id = R.string.layerscaffold_cd_revealed)
val peekingContentDescription = stringResource(id = R.string.layerscaffold_cd_peeking)
val nestedScroll = if (gesturesEnabled) {
Modifier.nestedScroll(scaffoldState.nestedScrollConnection)
} else {
Modifier
}
val swipeable = Modifier
.then(nestedScroll)
.swipeable(
state = scaffoldState,
anchors = mapOf(
backLayerPeekHeightPx to LayerValue.Concealed,
revealedHeight to LayerValue.Revealed,
peekHeight to LayerValue.Peeking,
),
orientation = Orientation.Vertical,
enabled = gesturesEnabled
)
.semantics {
when (scaffoldState.currentValue) {
LayerValue.Concealed -> {
collapse {
if (scaffoldState.confirmStateChange(LayerValue.Revealed)) {
scope.launch { scaffoldState.reveal() }
}
true
}
contentDescription = concealedContentDescription
}
LayerValue.Revealed -> {
expand {
if (scaffoldState.confirmStateChange(LayerValue.Concealed)) {
scope.launch { scaffoldState.conceal() }
}
true
}
contentDescription = revealedContentDescription
}
LayerValue.Peeking -> {
expand {
if (scaffoldState.confirmStateChange(LayerValue.Revealed)) {
scope.launch { scaffoldState.reveal() }
}
true
}
contentDescription = peekingContentDescription
}
}
}
// Front layer
Surface(
modifier = Modifier
.offset { IntOffset(0, scaffoldState.offset.value.roundToInt()) }
.then(swipeable),
color = frontLayerBackgroundColor,
contentColor = frontLayerContentColor
) {
FrontLayer(
modifier = Modifier.padding(bottom = backLayerPeekHeight),
handle = frontLayerHandle,
header = frontLayerHeader,
content = frontLayerContent,
headerElevation = frontLayerHeaderElevation
)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 6653c7452f12de71062d1b548bc8e724be10d21d | 6,924 | layerscaffold | MIT License |
app/src/main/java/io/github/zwieback/familyfinance/business/operation/service/provider/FlowOfFundsOperationViewProvider.kt | zwieback | 111,666,879 | false | null | package io.github.zwieback.familyfinance.business.operation.service.provider
import android.content.Context
import com.mikepenz.iconics.typeface.IIcon
import io.github.zwieback.familyfinance.core.adapter.EntityProvider
import io.github.zwieback.familyfinance.core.model.OperationView
import io.github.zwieback.familyfinance.core.model.type.OperationType
@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
class FlowOfFundsOperationViewProvider(context: Context) : EntityProvider<OperationView>(context) {
private val incomeProvider: IncomeOperationViewProvider =
IncomeOperationViewProvider(context)
private val expenseProvider: ExpenseOperationViewProvider =
ExpenseOperationViewProvider(context)
private val transferProvider: TransferOperationViewProvider =
TransferOperationViewProvider(context)
override fun provideDefaultIcon(operation: OperationView): IIcon {
return determineProvider(operation).provideDefaultIcon(operation)
}
override fun provideDefaultIconColor(operation: OperationView): Int {
return determineProvider(operation).provideDefaultIconColor(operation)
}
override fun provideTextColor(operation: OperationView): Int {
return determineProvider(operation).provideTextColor(operation)
}
private fun determineProvider(operation: OperationView): EntityProvider<OperationView> {
return when (operation.type) {
OperationType.EXPENSE_OPERATION -> expenseProvider
OperationType.INCOME_OPERATION -> incomeProvider
OperationType.TRANSFER_EXPENSE_OPERATION,
OperationType.TRANSFER_INCOME_OPERATION -> transferProvider
}
}
}
| 0 | Kotlin | 0 | 0 | a640c6ce73ca195f2ee5e41ed71fbf6169d9bb3e | 1,694 | FamilyFinance | Apache License 2.0 |
app/src/main/java/com/example/cryptoapp/data/model/AuthModel.kt | oguz-sahin | 349,560,332 | false | null | package com.example.cryptoapp.data.model
data class AuthModel(val email: String, val password: String, val confirmPassword: String = "") | 0 | Kotlin | 0 | 3 | 4a6ded7c2c6243fee9ad6a66c8619a80451ccde3 | 137 | CryptoApp | Apache License 2.0 |
myblog-kt/src/main/kotlin/com/site/blog/controller/ConfigController.kt | yzqdev | 394,679,800 | false | {"Kotlin": 453510, "Java": 239310, "Vue": 114812, "HTML": 47519, "TypeScript": 29771, "Go": 22465, "Less": 8160, "JavaScript": 7120, "CSS": 4588, "SCSS": 979} | package com.site.blog.controller
import com.site.blog.aop.LogOperationEnum
import com.site.blog.aop.SysLogAnnotation
import com.site.blog.constants.HttpStatusEnum
import com.site.blog.model.dto.AjaxResultPage
import com.site.blog.model.entity.BlogConfig
import com.site.blog.service.BlogConfigService
import com.site.blog.util.BaseResult.getResultByHttp
import com.site.blog.util.ResultDto
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.util.CollectionUtils
import org.springframework.web.bind.annotation.*
import java.time.LocalDateTime
@RestController
@RequestMapping("/v2/admin")
@Tag(name = "配置信息")
class ConfigController(val blogConfigService: BlogConfigService) {
/**
* 返回系统配置信息
* @param
* @return com.site.blog.pojo.dto.AjaxResultPage<com.site.blog.entity.BlogConfig>
* @date 2019/8/29 19:30
</com.site.blog.entity.BlogConfig> */
@GetMapping("/blogConfig/list")
fun blogConfig(): ResultDto<AjaxResultPage<BlogConfig?>>
{
val ajaxResultPage = AjaxResultPage<BlogConfig?>()
val list = blogConfigService.query().orderByDesc("update_time").list()
if (CollectionUtils.isEmpty(list)) {
ajaxResultPage.code = 500
return getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR, false, ajaxResultPage)
}
ajaxResultPage.list = list
return getResultByHttp(HttpStatusEnum.OK, true, ajaxResultPage)
}
/**
* 修改系统信息
* @param blogConfig
* @return com.site.blog.pojo.dto.Result
* @date 2019/8/29 19:45
*/
@PostMapping("/blogConfig/edit")
fun updateBlogConfig(@RequestBody blogConfig: BlogConfig): ResultDto<String> {
blogConfig.updateTime = LocalDateTime.now()
val flag = blogConfigService.updateById(blogConfig)
return if (flag) {
getResultByHttp(HttpStatusEnum.OK)
} else {
getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR)
}
}
/**
* 新增系统信息项
* @param blogConfig
* @return com.site.blog.pojo.dto.Result
* @date 2019/8/30 10:57
*/
@PostMapping("/blogConfig/add")
@SysLogAnnotation(title = "添加配置", opType = LogOperationEnum.ADD)
fun addBlogConfig(@RequestBody blogConfig: BlogConfig): ResultDto<*> {
blogConfig.createTime = LocalDateTime.now()
blogConfig.updateTime = LocalDateTime.now()
val flag = blogConfigService.save(blogConfig)
return if (flag) {
getResultByHttp(HttpStatusEnum.OK)
} else {
getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR)
}
}
/**
* 删除配置信息项
* @param configField
* @return com.site.blog.pojo.dto.Result
* @date 2019/8/30 11:21
*/
@DeleteMapping("/blogConfig/del/{id}")
@SysLogAnnotation(title = "删除配置", opType = LogOperationEnum.DELETE)
fun delBlogConfig(@PathVariable("id") configField: String?): ResultDto<String> {
val flag = blogConfigService.removeById(configField)
return if (flag) {
getResultByHttp(HttpStatusEnum.OK)
} else {
getResultByHttp(HttpStatusEnum.INTERNAL_SERVER_ERROR)
}
}
} | 0 | Kotlin | 2 | 4 | 7f367dbe7883722bf1d650504265254d5224f69b | 3,220 | mild-blog | MIT License |
src/main/kotlin/no/nav/dagpenger/oppdrag/iverksetting/UuidUtils.kt | navikt | 596,541,750 | false | {"Kotlin": 141753, "Dockerfile": 120} | package no.nav.dagpenger.oppdrag.iverksetting
import java.nio.ByteBuffer
import java.util.Base64
import java.util.UUID
object UuidUtils {
fun UUID.komprimer(): String {
val bb: ByteBuffer = ByteBuffer.allocate(java.lang.Long.BYTES * 2)
bb.putLong(this.mostSignificantBits)
bb.putLong(this.leastSignificantBits)
val array: ByteArray = bb.array()
return Base64.getEncoder().encodeToString(array)
}
fun String.dekomprimer(): UUID {
val byteBuffer: ByteBuffer = ByteBuffer.wrap(Base64.getDecoder().decode(this))
return UUID(byteBuffer.long, byteBuffer.long)
}
}
| 10 | Kotlin | 0 | 0 | e48d362f10013e5d01263c6556b1d9d7c358ca72 | 634 | dp-oppdrag | MIT License |
sample/shared/src/commonMain/kotlin/com/keyflare/sample/shared/feature/tech/TechComponent.kt | keyflare | 701,713,018 | false | {"Kotlin": 136692, "Ruby": 6618} | package com.keyflare.sample.shared.feature.tech
import com.keyflare.sample.shared.core.RootRouter
class TechComponent(
private val rootRouter: RootRouter,
) {
fun onBackClick() {
rootRouter.onBack()
}
}
| 0 | Kotlin | 0 | 0 | 01bb8d5f03b1b8143b3e6cdebbd9fa9eaea8ccaf | 226 | elastik | MIT License |
algorithms-kotlin/src/test/kotlin/io/github/brunogabriel/datastructure/BinaryTreeTest.kt | brunogabriel | 294,995,479 | false | null | package io.github.brunogabriel.datastructure
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class BinaryTreeTest {
private val sampleNodes = listOf(10, 4, 14, 3, 5, 2, 7, 6, 12, 11, 13, 15, 17, 18)
@Test
fun `testing numberOfNodes`() {
assertThat(BinaryTree<Int>().numberOfNodes()).isEqualTo(0)
assertThat(
BinaryTree<Int>().apply {
insert(10)
}.numberOfNodes()
).isEqualTo(1)
assertThat(
BinaryTree<Int>().apply {
insert(10)
insert(8)
}.numberOfNodes()
).isEqualTo(2)
assertThat(
BinaryTree<Int>().apply {
insert(10)
insert(11)
}.numberOfNodes()
).isEqualTo(2)
assertThat(
BinaryTree<Int>().apply {
sampleNodes.forEach { insert(it) }
}.numberOfNodes()
).isEqualTo(14)
}
@Test
fun `testing height`() {
assertThat(BinaryTree<Int>().height()).isEqualTo(0)
assertThat(
BinaryTree<Int>().apply {
insert(10)
}.height()
).isEqualTo(1)
assertThat(
BinaryTree<Int>().apply {
insert(10)
insert(8)
}.height()
).isEqualTo(2)
assertThat(
BinaryTree<Int>().apply {
insert(10)
insert(11)
}.height()
).isEqualTo(2)
assertThat(
BinaryTree<Int>().apply {
sampleNodes.forEach { insert(it) }
}.height()
).isEqualTo(5)
}
}
| 0 | Kotlin | 0 | 3 | 050a7093c0f2cf3864157c74adb84a969dea8882 | 1,696 | algorithms | MIT License |
ktor-client/ktor-client-core/posix/src/io/ktor/client/engine/HttpClientEngineNative.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.engine
import io.ktor.util.*
import io.ktor.utils.io.*
import kotlinx.coroutines.*
import kotlin.coroutines.*
/**
* Create call context with the specified [parentJob] to be used during call execution in the engine. Call context
* inherits [coroutineContext], but overrides job and coroutine name so that call job's parent is [parentJob] and
* call coroutine's name is "call-context".
*/
internal actual suspend fun HttpClientEngine.createCallContext(parentJob: Job): CoroutineContext {
parentJob.makeShared()
val callJob = Job(parentJob).apply {
makeShared()
}
attachToUserJob(callJob)
return (functionContext() + callJob + CALL_COROUTINE).apply {
makeShared()
}
}
private suspend inline fun functionContext(): CoroutineContext = coroutineContext
| 302 | Kotlin | 774 | 9,308 | 9244f9a4a406f3eca06dc05d9ca0f7d7ec74a314 | 945 | ktor | Apache License 2.0 |
src/main/kotlin/Problem11.kt | jimmymorales | 496,703,114 | false | {"Kotlin": 67323} | /**
* Largest product in a grid
*
* In the 20×20 grid below, four numbers along a diagonal line have been marked in red.
*
* 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
* 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
* 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
* 52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
* 22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
* 24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
* 32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
* 67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
* 24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
* 21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
* 78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
* 16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
* 86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
* 19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
* 04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
* 88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
* 04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
* 20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
* 20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
* 01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
*
* The product of these numbers is 26 × 63 × 78 × 14 = 1788696.
*
* What is the greatest product of four adjacent numbers in the same direction (up, down, left, right, or diagonally) in
* the 20×20 grid?
*/
fun main() {
println(largestProduct(grid, 4))
}
fun largestProduct(matrix: Array<Array<Int>>, n: Int): Long {
var maxP = 0L
for (i in matrix.indices) {
for (j in matrix[i].indices) {
if (matrix[i][j] == 0) continue
if (matrix.size - i >= n) {
val pv = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i + offset][j] }
if (pv > maxP) {
maxP = pv
}
}
if (matrix[i].size - j >= n) {
val ph = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i][j + offset] }
if (ph > maxP) {
maxP = ph
}
}
if (matrix.size - i >= n && matrix[i].size - j >= n) {
val pdr = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i + offset][j + offset] }
if (pdr > maxP) {
maxP = pdr
}
}
if (matrix.size - i >= n && j >= n - 1) {
val pdl = (0 until n).fold(initial = 1L) { acc, offset -> acc * matrix[i + offset][j - offset] }
if (pdl > maxP) {
maxP = pdl
}
}
}
}
return maxP
}
private val grid = arrayOf(
arrayOf(8, 2, 22, 97, 38, 15, 0, 40, 0, 75, 4, 5, 7, 78, 52, 12, 50, 77, 91, 8),
arrayOf(49, 49, 99, 40, 17, 81, 18, 57, 60, 87, 17, 40, 98, 43, 69, 48, 4, 56, 62, 0),
arrayOf(81, 49, 31, 73, 55, 79, 14, 29, 93, 71, 40, 67, 53, 88, 30, 3, 49, 13, 36, 65),
arrayOf(52, 70, 95, 23, 4, 60, 11, 42, 69, 24, 68, 56, 1, 32, 56, 71, 37, 2, 36, 91),
arrayOf(22, 31, 16, 71, 51, 67, 63, 89, 41, 92, 36, 54, 22, 40, 40, 28, 66, 33, 13, 80),
arrayOf(24, 47, 32, 60, 99, 3, 45, 2, 44, 75, 33, 53, 78, 36, 84, 20, 35, 17, 12, 50),
arrayOf(32, 98, 81, 28, 64, 23, 67, 10, 26, 38, 40, 67, 59, 54, 70, 66, 18, 38, 64, 70),
arrayOf(67, 26, 20, 68, 2, 62, 12, 20, 95, 63, 94, 39, 63, 8, 40, 91, 66, 49, 94, 21),
arrayOf(24, 55, 58, 5, 66, 73, 99, 26, 97, 17, 78, 78, 96, 83, 14, 88, 34, 89, 63, 72),
arrayOf(21, 36, 23, 9, 75, 0, 76, 44, 20, 45, 35, 14, 0, 61, 33, 97, 34, 31, 33, 95),
arrayOf(78, 17, 53, 28, 22, 75, 31, 67, 15, 94, 3, 80, 4, 62, 16, 14, 9, 53, 56, 92),
arrayOf(16, 39, 5, 42, 96, 35, 31, 47, 55, 58, 88, 24, 0, 17, 54, 24, 36, 29, 85, 57),
arrayOf(86, 56, 0, 48, 35, 71, 89, 7, 5, 44, 44, 37, 44, 60, 21, 58, 51, 54, 17, 58),
arrayOf(19, 80, 81, 68, 5, 94, 47, 69, 28, 73, 92, 13, 86, 52, 17, 77, 4, 89, 55, 40),
arrayOf(4, 52, 8, 83, 97, 35, 99, 16, 7, 97, 57, 32, 16, 26, 26, 79, 33, 27, 98, 66),
arrayOf(88, 36, 68, 87, 57, 62, 20, 72, 3, 46, 33, 67, 46, 55, 12, 32, 63, 93, 53, 69),
arrayOf(4, 42, 16, 73, 38, 25, 39, 11, 24, 94, 72, 18, 8, 46, 29, 32, 40, 62, 76, 36),
arrayOf(20, 69, 36, 41, 72, 30, 23, 88, 34, 62, 99, 69, 82, 67, 59, 85, 74, 4, 36, 16),
arrayOf(20, 73, 35, 29, 78, 31, 90, 1, 74, 31, 49, 71, 48, 86, 81, 16, 23, 57, 5, 54),
arrayOf(1, 70, 54, 71, 83, 51, 54, 69, 16, 92, 33, 48, 61, 43, 52, 1, 89, 19, 67, 48),
) | 0 | Kotlin | 0 | 0 | e881cadf85377374e544af0a75cb073c6b496998 | 4,751 | project-euler | MIT License |
src/main/kotlin/io/github/yusaka39/easySlackbot/bot/Bot.kt | yusaka39 | 122,588,000 | false | null | package io.github.yusaka39.easySlackbot.bot
import RtmApiSlackFactory
import io.github.yusaka39.easySlackbot.lib.logger
import io.github.yusaka39.easySlackbot.router.AnnotationBasedMessageRouterFactory
import io.github.yusaka39.easySlackbot.router.HandlerType
import io.github.yusaka39.easySlackbot.router.MessageRouterFactory
import io.github.yusaka39.easySlackbot.scheduler.AnnotationBasedSchedulerServiceFactory
import io.github.yusaka39.easySlackbot.scheduler.SchedulerService
import io.github.yusaka39.easySlackbot.scheduler.SchedulerServiceFactory
import io.github.yusaka39.easySlackbot.slack.Message
import io.github.yusaka39.easySlackbot.slack.SlackFactory
class Bot internal constructor(
slackToken: String,
messageRouterFactory: MessageRouterFactory,
schedulerServiceFactory: SchedulerServiceFactory,
slackFactory: SlackFactory
) {
constructor(slackToken: String, searchPackage: String) : this(
slackToken,
AnnotationBasedMessageRouterFactory(searchPackage),
AnnotationBasedSchedulerServiceFactory(searchPackage),
RtmApiSlackFactory()
)
private val logger by this.logger()
private val messageRouter = messageRouterFactory.create()
private val scheduler: SchedulerService = schedulerServiceFactory.create()
private val slack = slackFactory.create(slackToken).apply {
fun runActionForMessage(message: Message, type: HandlerType) {
try {
val handler = [email protected](message, type) ?: return
handler.generateActionForMessage(message).run(this)
} catch (e: Exception) {
[email protected]("Exception is caused while executing handler for message: \"${message.text}\".", e)
}
}
this.onReceiveMessage { message, _ ->
[email protected]("Received message \"${message.text}\".")
runActionForMessage(message, HandlerType.ListenTo)
}
this.onReceiveReply { message, _ ->
[email protected]("Received message \"${message.text}\".")
runActionForMessage(message, HandlerType.RespondTo)
}
this.onReceiveDirectMessage { message, _ ->
[email protected]("Received message \"${message.text}\".")
runActionForMessage(message, HandlerType.RespondTo)
}
}
fun run() {
this.slack.startService()
this.scheduler.start(this.slack)
this.logger.info("Bot service is started.")
}
fun kill() {
this.scheduler.stop()
this.slack.stopService()
this.logger.info("Bot service is killed.")
}
}
| 1 | null | 2 | 5 | e69f59fc0ba4d656f60566fdff599a334d5fa9bc | 2,669 | easy-slackbot | MIT License |
library-feature-flag/src/main/java/com/chucker/featureflag/internal/ui/FeatureFlagViewModel.kt | esafirm | 391,568,099 | false | null | package com.chucker.featureflag.internal.ui
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.chucker.featureflag.api.FeatureFlagModule
import com.chucker.featureflag.api.ManagedFeatureFlag
import com.chucker.featureflag.api.SimpleManagerFeatureFlag
class FeatureFlagViewModel : ViewModel() {
private val originalFeatureFlag by lazy {
FeatureFlagModule.store.getAll().map {
SimpleManagerFeatureFlag(it.first)
}
}
val featureFlags = MutableLiveData<List<ManagedFeatureFlag>>()
fun loadFlags(filter: String = "") {
featureFlags.postValue(originalFeatureFlag.filter { flag ->
val name = flag.name.lowercase()
name.contains(filter.lowercase())
})
}
} | 10 | Kotlin | 1 | 1 | 59f43a4c7201436bb7efaa9ad1e008a51b806cc6 | 778 | Chucker | Apache License 2.0 |
redwood-treehouse-host/src/commonTest/kotlin/app/cash/redwood/treehouse/FakeCodeListener.kt | cashapp | 305,409,146 | false | {"Kotlin": 1589288, "Swift": 14180, "Java": 1583, "Objective-C": 1499, "HTML": 235, "C": 43} | /*
* Copyright (C) 2023 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.redwood.treehouse
class FakeCodeListener(
private val eventLog: EventLog,
) : CodeListener() {
override fun onInitialCodeLoading(view: TreehouseView<*>) {
eventLog += "codeListener.onInitialCodeLoading($view)"
}
override fun onCodeLoaded(view: TreehouseView<*>, initial: Boolean) {
eventLog += "codeListener.onCodeLoaded($view, initial = $initial)"
}
}
| 103 | Kotlin | 51 | 1,277 | 7ac2071dde901e6d5c14f6c9923cf65c0ab9c820 | 991 | redwood | Apache License 2.0 |
src/main/kotlin/com/coderskitchen/jsr380examples/User.kt | coders-kitchen | 461,432,352 | false | {"Kotlin": 1181} | package com.coderskitchen.jsr380examples
import jakarta.validation.constraints.NotNull
import jakarta.validation.constraints.Size
import org.hibernate.validator.constraints.Range
data class User(
@get:Size(min=5, max= 30, message = "Name must be between 5 and 30 characters")
@get:NotNull(message = "Name cannot be null")
val name: String?,
@get:Range(min = 18, max = 150, message = "Age must be between 18 and 150")
val age: Int,
@get:Size(min=10, max=200, message = "About Me must be between 10 and 200 characters")
val aboutMe: String
) | 0 | Kotlin | 0 | 0 | a3c3476ad0ec9c9279eb138b346758939fbeb03c | 570 | jsr-380-examples | MIT License |
graphlite/src/commonMain/kotlin/pl/makenika/graphlite/Schema.kt | armatys | 277,562,442 | false | {"C": 8751654, "Java": 434676, "Kotlin": 185359, "C++": 119284, "Makefile": 1760} | /*
* Copyright (c) 2020 Mateusz Armatys
*
* 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 pl.makenika.graphlite
internal typealias FieldValidator<S, T> = FieldMap<out S>.(T) -> Boolean
public abstract class Schema(
public val schemaHandle: SchemaHandle,
public val schemaVersion: Long
) {
public constructor(handleValue: String, version: Long) : this(
SchemaHandle(handleValue),
version
)
private val fields = mutableMapOf<FieldHandle, Field<*, *>>()
private val fieldValidators = mutableMapOf<FieldHandle, FieldValidator<*, *>>()
private var isFrozen = false
protected val <S : Schema> S.optional: OptionalFieldBuilder<S>
get() = OptionalFieldBuilder(this)
internal fun <F : Field<S, *>, S : Schema> addField(field: F): F {
if (isFrozen) error("Schema is already frozen.")
check(fields.put(field.handle, field) == null) {
"Field with name \"${field.handle.value}\" has been already added."
}
return field
}
internal fun freeze() {
isFrozen = true
}
@Suppress("UNCHECKED_CAST")
internal fun <S : Schema> getFields(): Map<String, Field<S, Any?>> =
fields as Map<String, Field<S, Any?>>
@Suppress("UNCHECKED_CAST")
internal fun <S : Schema, T> getValidator(field: Field<S, T>): FieldValidator<S, T>? {
return fieldValidators[field.handle] as FieldValidator<S, T>?
}
protected fun <S : Schema> S.blobField(name: String): Field<S, ByteArray> {
return addField(Field.blob(name))
}
protected fun <S : Schema> S.doubleField(name: String): IndexableScalarField<S, Double> {
return addField(Field.double(name))
}
protected fun <S : Schema> S.geoField(name: String): IndexableField<S, GeoBounds> {
return addField(Field.geo(name))
}
protected fun <S : Schema> S.longField(name: String): IndexableScalarField<S, Long> {
return addField(Field.long(name))
}
protected fun <S : Schema> S.textField(
name: String,
fts: Boolean = true
): IndexableScalarField<S, String> {
return if (fts) {
addField(Field.textFts(name))
} else {
addField(Field.text(name))
}
}
protected fun <F : Field<S, T>, S : Schema, T> F.onValidate(validator: FieldValidator<S, T>): F {
@Suppress("UNCHECKED_CAST")
check(fieldValidators.put(handle, validator as FieldValidator<*, *>) == null) {
"Validator for field \"${handle.value}\" has been already added."
}
return this
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null) return false
if (other !is Schema) return false
if (schemaHandle != other.schemaHandle) return false
if (schemaVersion != other.schemaVersion) return false
if (fields != other.fields) return false
return true
}
override fun hashCode(): Int {
var result = schemaHandle.hashCode()
result = 31 * result + schemaVersion.hashCode()
result = 31 * result + fields.hashCode()
return result
}
override fun toString(): String {
return "Schema(handle='$schemaHandle', version=$schemaVersion)"
}
}
public fun <S : Schema> S.fieldMap(builderFn: (S.(FieldMapBuilder<S>) -> Unit)? = null): FieldMap<S> {
val b = FieldMapBuilder(this)
builderFn?.invoke(this, b)
return b.build()
}
public operator fun <S : Schema> S.invoke(builderFn: (S.(FieldMapBuilder<S>) -> Unit)? = null): FieldMap<S> =
fieldMap(builderFn)
internal class SchemaWithId(
val schemaId: String,
schemaHandle: SchemaHandle,
schemaVersion: Long
) : Schema(schemaHandle, schemaVersion)
| 0 | C | 0 | 0 | a95026b88e0ac485cd2da13c121b0d42bbaabbe2 | 4,301 | GraphLite | Apache License 2.0 |
src/main/kotlin/com/imoonday/entity/render/feature/StatusEffectLayer.kt | iMoonDay | 759,188,611 | false | {"Kotlin": 472450, "Java": 57363} | package com.imoonday.entity.render.feature
import com.imoonday.skill.Skills
import com.imoonday.init.isConfined
import com.imoonday.init.isDisarmed
import com.imoonday.init.isSilenced
import net.minecraft.client.render.OverlayTexture
import net.minecraft.client.render.TexturedRenderLayers
import net.minecraft.client.render.VertexConsumerProvider
import net.minecraft.client.render.entity.EntityRendererFactory
import net.minecraft.client.render.entity.feature.FeatureRenderer
import net.minecraft.client.render.entity.feature.FeatureRendererContext
import net.minecraft.client.render.entity.model.EntityModel
import net.minecraft.client.util.ModelIdentifier
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.entity.LivingEntity
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import net.minecraft.registry.Registries
import net.minecraft.util.math.Direction
import net.minecraft.util.math.RotationAxis
/**
* from Twilight Forest
*/
class StatusEffectLayer<T : LivingEntity, M : EntityModel<T>>(
renderer: FeatureRendererContext<T, M>,
private val context: EntityRendererFactory.Context,
) : FeatureRenderer<T, M>(renderer) {
override fun render(
matrices: MatrixStack,
vertexConsumers: VertexConsumerProvider,
light: Int,
entity: T,
limbAngle: Float,
limbDistance: Float,
tickDelta: Float,
animationProgress: Float,
headYaw: Float,
headPitch: Float,
) {
var delta = tickDelta
var horizonOffset = 0f
if (entity.isSilenced) {
renderEffects(matrices, vertexConsumers, entity, delta, silenceModelId, horizonOffset, 4)
horizonOffset += 0.5f
}
delta -= 10
if (entity.isDisarmed) {
renderEffects(matrices, vertexConsumers, entity, delta, disarmModelId, horizonOffset, 4)
horizonOffset += 0.5f
}
delta -= 10
if (entity.isConfined) {
renderEffects(matrices, vertexConsumers, entity, delta, confinementModelId, horizonOffset, 4)
}
}
private fun renderEffects(
stack: MatrixStack,
provider: VertexConsumerProvider,
entity: T,
tickDelta: Float,
modelIdentifier: ModelIdentifier,
horizonOffset: Float,
count: Int,
) {
val age: Float = entity.age + tickDelta
val rotateAngleY = age / -20.0f
stack.pop()
for (c in 0 until count) {
stack.push()
stack.multiply(RotationAxis.POSITIVE_Y.rotationDegrees(rotateAngleY * (180f / Math.PI.toFloat()) + (c * (360f / count))))
val scale = (entity.width * 1.2f).coerceAtMost(1.0f)
stack.translate(-0.5, (entity.height - scale) * 0.5, -0.5)
stack.translate(0f, 0f, (entity.width).coerceAtLeast(0.75f) + horizonOffset)
stack.scale(scale, scale, scale)
val model = context.modelManager.getModel(modelIdentifier)
for (dir in Direction.entries) {
context.itemRenderer.renderBakedItemQuads(
stack,
provider.getBuffer(TexturedRenderLayers.getEntityTranslucentCull()),
model.getQuads(null, dir, entity.random).ifEmpty {
model.getQuads(null, null, entity.random)
},
ItemStack.EMPTY,
0xF000F0,
OverlayTexture.DEFAULT_UV
)
}
stack.pop()
}
stack.push()
}
companion object {
val silenceModelId = ModelIdentifier(Registries.ITEM.getId(Skills.PRIMARY_SILENCE.item), "inventory")
val disarmModelId = ModelIdentifier(Registries.ITEM.getId(Skills.DISARM.item), "inventory")
val confinementModelId = ModelIdentifier(Registries.ITEM.getId(Items.BARRIER), "inventory")
}
} | 0 | Kotlin | 0 | 0 | 3a2660afca6d625c6ce4c08553817eac7960bfec | 3,934 | AdvancedSkills | Creative Commons Zero v1.0 Universal |
data/src/main/java/com/mahmoudalim/data/database/CurrencyDatabase.kt | MhmoudAlim | 471,442,598 | false | null | package com.mahmoudalim.data.database
import androidx.room.Database
import androidx.room.RoomDatabase
/**
* Created by <NAME> on 21/03/2022.
*/
@Database(entities = [HistoryEntity::class], version = 2)
abstract class CurrencyDatabase : RoomDatabase() {
abstract fun historyDao(): HistoryDao
} | 0 | Kotlin | 0 | 0 | 19b6d1b73bd99f3cb301a58717eaf034e9fef82e | 302 | Currency | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Text.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.Text: ImageVector
get() {
if (_text != null) {
return _text!!
}
_text = Builder(name = "Text", defaultWidth = 512.0.dp, defaultHeight = 512.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(19.0f, 0.0f)
horizontalLineToRelative(-14.0f)
arcToRelative(5.006f, 5.006f, 0.0f, false, false, -5.0f, 5.0f)
verticalLineToRelative(14.0f)
arcToRelative(5.006f, 5.006f, 0.0f, false, false, 5.0f, 5.0f)
horizontalLineToRelative(14.0f)
arcToRelative(5.006f, 5.006f, 0.0f, false, false, 5.0f, -5.0f)
verticalLineToRelative(-14.0f)
arcToRelative(5.006f, 5.006f, 0.0f, false, false, -5.0f, -5.0f)
close()
moveTo(17.0f, 10.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, -1.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(8.0f)
horizontalLineToRelative(1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, 2.0f)
horizontalLineToRelative(-4.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f)
horizontalLineToRelative(1.0f)
verticalLineToRelative(-8.0f)
horizontalLineToRelative(-2.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.0f, 1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -2.0f, 0.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, 3.0f, -3.0f)
horizontalLineToRelative(6.0f)
arcToRelative(3.0f, 3.0f, 0.0f, false, true, 3.0f, 3.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f)
close()
}
}
.build()
return _text!!
}
private var _text: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,859 | icons | MIT License |
app/src/main/java/in/sarangal/kotlinsupplementsample/MainActivity.kt | thesarangal | 374,148,747 | false | {"Kotlin": 38587} | package `in`.sarangal.kotlinsupplementsample
import `in`.sarangal.kotlinsupplement.toast
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/* Show Toast */
toast(
"Welcome to KotlinSupplement"
)
}
} | 0 | Kotlin | 0 | 0 | f6b037efb1960a7c70248fc1d6c5bdc7592e1655 | 455 | kotlinsupplement | MIT License |
template/app/src/commonMain/kotlin/kotli/app/feature/showcases/presentation/dataflow/room/crud/RoomCrudRoute.kt | kotlitecture | 790,159,970 | false | {"Kotlin": 482571, "Swift": 543, "JavaScript": 313, "HTML": 234} | package kotli.app.feature.showcases.presentation.dataflow.room.crud
import kotli.app.feature.showcases.domain.Showcase
import kotlinx.serialization.Serializable
@Serializable
object RoomCrudRoute {
val screen = Showcase.Screen("Room CRUD", this)
} | 0 | Kotlin | 3 | 55 | b96c8867f393bedba65b2f6f8a40e806bf07bcd9 | 255 | template-multiplatform-compose | MIT License |
src/day08.kts | miedzinski | 434,902,353 | false | null | fun Int(word: String): Int = word.fold(0) { acc, c -> acc or (1 shl (c - 'a')) }
val input = generateSequence(::readLine).map {
val words = it.split(' ')
val delimiterIndex = words.indexOf("|")
val signals: List<Int> = words.subList(0, delimiterIndex).map { Int(it) }
val output: List<Int> = words.subList(delimiterIndex + 1, words.size).map { Int(it) }
Pair(signals, output)
}.toList()
fun part1(): Int {
val counts = MutableList(10) { 0 }
for ((_, output) in input) {
for (digit in output) {
when (digit.countOneBits()) {
2 -> counts[1]++
3 -> counts[7]++
4 -> counts[4]++
7 -> counts[8]++
}
}
}
return counts.sum()
}
println("part1: ${part1()}")
fun List<Int>.ofCount(length: Int): List<Int> = filter { it.countOneBits() == length }
fun Int.contains(other: Int) = and(other) == other
fun List<Int>.decode(): Map<Int, Int> {
val digits = MutableList(10) { 0 }
digits[1] = ofCount(2).single()
digits[4] = ofCount(4).single()
digits[7] = ofCount(3).single()
digits[8] = ofCount(7).single()
digits[9] = ofCount(6).single { it.contains(digits[4]) }
digits[3] = ofCount(5).single { it.contains(digits[1]) }
val e = digits[8] and digits[9].inv()
digits[2] = ofCount(5).single { it.contains(e) }
val b = digits[9] and digits[3].inv()
digits[5] = ofCount(5).single { it.contains(b) }
digits[6] = ofCount(6).single { it.contains(e) && !it.contains(digits[1]) }
digits[0] = ofCount(6).single { it != digits[9] && it != digits[6] }
return digits.withIndex().associate { (digit, segments) -> segments to digit }
}
fun part2(): Int = input.sumOf { (signals, output) ->
val digits = signals.decode()
output.asReversed()
.withIndex()
.sumOf { (idx, segments) ->
val digit = digits[segments]!!
val exp = generateSequence(1) { it * 10 }.elementAt(idx)
digit * exp
}
}
println("part2: ${part2()}")
| 0 | Kotlin | 0 | 0 | 6f32adaba058460f1a9bb6a866ff424912aece2e | 2,060 | aoc2021 | The Unlicense |
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/project/workday/command/snapshotshore/WorkdayConfigurationSnapshotEntityCache.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: Robert Bosch Power Tools GmbH, 2018 - 2023
*
* ************************************************************************
*/
package com.bosch.pt.iot.smartsite.project.workday.command.snapshotshore
import com.bosch.pt.csm.cloud.common.command.snapshotstore.AbstractSnapshotEntityCache
import com.bosch.pt.iot.smartsite.project.workday.domain.WorkdayConfigurationId
import com.bosch.pt.iot.smartsite.project.workday.shared.model.WorkdayConfiguration
import com.bosch.pt.iot.smartsite.project.workday.shared.repository.WorkdayConfigurationRepository
import org.springframework.stereotype.Component
import org.springframework.web.context.annotation.RequestScope
@Component
@RequestScope
open class WorkdayConfigurationSnapshotEntityCache(
private val repository: WorkdayConfigurationRepository
) : AbstractSnapshotEntityCache<WorkdayConfigurationId, WorkdayConfiguration>() {
override fun loadOneFromDatabase(identifier: WorkdayConfigurationId) =
repository.findOneWithDetailsByIdentifier(identifier)
}
| 0 | Kotlin | 3 | 9 | 9f3e7c4b53821bdfc876531727e21961d2a4513d | 1,120 | bosch-pt-refinemysite-backend | Apache License 2.0 |
app/src/main/java/com/kieronquinn/app/classicpowermenu/utils/extensions/Extensions+SharedPreferences.kt | KieronQuinn | 410,362,831 | false | {"Kotlin": 810491, "Java": 281044, "AIDL": 22512} | package com.kieronquinn.app.classicpowermenu.utils.extensions
import android.content.SharedPreferences
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow
fun <T> SharedPreferences.getPreferenceAsFlow(key: String, setting: () -> T) = callbackFlow {
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, changedKey ->
if(key == changedKey){
trySend(setting())
}
}
trySend(setting())
registerOnSharedPreferenceChangeListener(listener)
awaitClose {
unregisterOnSharedPreferenceChangeListener(listener)
}
} | 8 | Kotlin | 23 | 693 | e17f14a85f85d4eefabaf847abfadd1af32291c1 | 619 | ClassicPowerMenu | Apache License 2.0 |
app/src/main/java/com/example/movies/utils/Constants.kt | Malekel3alamy | 847,017,405 | false | {"Kotlin": 66791} | package com.example.movies.utils
class Constants {
companion object{
val API_KEY = "e3f0be7913d1463dfc7ac61258de2945"
val BASE_URL = "https://api.themoviedb.org/3/"
val QUERY_PAGE_SIZE = 40
const val SEARCH_TIME_DELAY = 5000L
}
} | 0 | Kotlin | 0 | 0 | de2b3228965a6da9df026706dec6430855e9d043 | 275 | Movies | MIT License |
app/src/main/java/com/nidhin/upstoxclient/feature_portfolio/domain/GenerateGeminiResponse.kt | nidhinrejoice | 755,244,627 | false | {"Kotlin": 104754} | package com.nidhin.upstoxclient.feature_portfolio.domain
import com.google.ai.client.generativeai.type.GenerateContentResponse
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class GenerateGeminiResponse @Inject constructor(
private val portfolioRepository: IPortfolioRepository
) {
suspend operator fun invoke(prompt: String): Flow<GenerateContentResponse> {
return portfolioRepository.getLatestNewsFromGemini(prompt)
}
} | 0 | Kotlin | 0 | 0 | 4f4d2794b9eebf028048f59effaaea37084c0ade | 460 | UpstoxTicker | Apache License 2.0 |
theme/public/src/main/kotlin/com/adjectivemonk2/pixels/theme/Shape.kt | Sripadmanabans | 300,346,280 | false | null | package com.adjectivemonk2.pixels.theme
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Shapes
import androidx.compose.ui.unit.dp
public val shapes: Shapes = Shapes(
small = RoundedCornerShape(FOUR.dp),
medium = RoundedCornerShape(FOUR.dp),
large = RoundedCornerShape(ZERO.dp)
)
| 11 | null | 0 | 2 | c925014bad38c7eb659282806289f8f453b78f30 | 332 | Pixels | Apache License 2.0 |
app/src/main/java/com/andremion/hostel/app/internal/injection/module/AppModule.kt | andremion | 128,673,410 | false | null | /*
* Copyright (c) 2018. <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.andremion.hostel.app.internal.injection.module
import android.content.Context
import com.andremion.hostel.app.internal.injection.DaggerApplication
import com.andremion.hostel.scheduler.AppSchedulers
import dagger.Module
import dagger.Provides
import io.reactivex.Scheduler
import io.reactivex.android.schedulers.AndroidSchedulers
import javax.inject.Singleton
@Module
internal class AppModule {
@Provides
@Singleton
internal fun providesContext(application: DaggerApplication): Context = application
@Provides
@Singleton
internal fun provideSchedulers() = object : AppSchedulers {
override val main: Scheduler
get() = AndroidSchedulers.mainThread()
}
}
| 0 | Kotlin | 0 | 4 | c2cf659c24b2891a0bf192925d82c0f797259fd4 | 1,314 | Hostel | Apache License 2.0 |
zenkey-sdk/src/main/kotlin/com/xci/zenkey/sdk/internal/model/exception/ProviderNotFoundException.kt | Surfndez | 218,922,486 | false | {"Kotlin": 461719} | package com.xci.zenkey.sdk.internal.model.exception
import com.xci.zenkey.sdk.internal.Json
import com.xci.zenkey.sdk.internal.model.DiscoveryResponse
import com.xci.zenkey.sdk.internal.network.stack.HttpResponse
import com.xci.zenkey.sdk.internal.network.stack.JsonConverter
import org.json.JSONException
import org.json.JSONObject
/**
* An exception throw when the OpenId discovery failed because the Carrier isn't supported.
*/
internal class ProviderNotFoundException(
val discoverUiEndpoint: String?
) : Exception() {
companion object {
fun from(response: HttpResponse<DiscoveryResponse>): ProviderNotFoundException {
try {
return object : JsonConverter<ProviderNotFoundException> {
override fun convert(json: String): ProviderNotFoundException {
var discoverUIEndpoint: String? = null
val jsonObject = JSONObject(json)
if (jsonObject.has(Json.KEY_REDIRECT_URI)) {
discoverUIEndpoint = jsonObject.getString(Json.KEY_REDIRECT_URI)
}
return ProviderNotFoundException(discoverUIEndpoint)
}
}.convert(response.rawBody)
} catch (e: JSONException) {
e.printStackTrace()
return ProviderNotFoundException(null)
}
}
}
}
| 0 | null | 3 | 0 | 3b981cf3ccda02f5de5c4ddb2d41883077bc86b0 | 1,442 | sp-sdk-android | Apache License 2.0 |
app/src/main/java/com/bruno13palhano/shopdanimanagement/ui/screens/common/ErrorReponseUtil.kt | bruno13palhano | 670,001,130 | false | {"Kotlin": 1278676} | package com.bruno13palhano.shopdanimanagement.ui.screens.common
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
@Composable
fun getErrors() = listOf(
stringResource(id = DataError.InsertDatabase.resourceId),
stringResource(id = DataError.UpdateDatabase.resourceId),
stringResource(id = DataError.DeleteDatabase.resourceId),
stringResource(id = DataError.InsertServer.resourceId),
stringResource(id = DataError.UpdateServer.resourceId),
stringResource(id = DataError.DeleteServer.resourceId),
stringResource(id = DataError.LoginDatabase.resourceId),
stringResource(id = DataError.LoginServer.resourceId),
stringResource(id = DataError.FillMissingFields.resourceId),
stringResource(id = DataError.InsufficientItemsStock.resourceId)
)
@Composable
fun getUserResponse() = listOf(
stringResource(id = UserResponse.OKResponse.resourceId),
stringResource(id = UserResponse.WrongPasswordValidation.resourceId),
stringResource(id = UserResponse.UserNullOrInvalid.resourceId),
stringResource(id = UserResponse.UsernameAlreadyExist.resourceId),
stringResource(id = UserResponse.EmailAlreadyExist.resourceId),
stringResource(id = UserResponse.IncorrectUsernameOrPassword.resourceId),
stringResource(id = UserResponse.LoginServerError.resourceId),
stringResource(id = UserResponse.InsertServerError.resourceId),
stringResource(id = UserResponse.UpdateServerError.resourceId),
stringResource(id = UserResponse.FillMissingFields.resourceId)
) | 0 | Kotlin | 0 | 2 | a2214a1757f205534613770580543d9045a7d6e1 | 1,551 | shop-dani-management | MIT License |
protocol/notify/src/main/kotlin/com/walletconnect/notify/client/cacao/CacaoSigner.kt | WalletConnect | 435,951,419 | false | {"Kotlin": 2461647, "Java": 4366, "Shell": 1892} | package com.walletconnect.notify.client.cacao
import com.walletconnect.android.utils.cacao.CacaoSignerInterface
import com.walletconnect.notify.client.Notify
object CacaoSigner : CacaoSignerInterface<Notify.Model.Cacao.Signature> | 78 | Kotlin | 70 | 197 | 743ff1e06def59a721a299a8e76c67e96b9441f6 | 231 | WalletConnectKotlinV2 | Apache License 2.0 |
app/src/main/java/com/awscherb/cardkeeper/ui/cards/CardsAdapter.kt | LateNightProductions | 66,697,395 | false | null | package com.awscherb.cardkeeper.ui.cards
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.awscherb.cardkeeper.R
import com.awscherb.cardkeeper.data.model.ScannedCode
import com.google.zxing.BarcodeFormat.AZTEC
import com.google.zxing.BarcodeFormat.DATA_MATRIX
import com.google.zxing.BarcodeFormat.QR_CODE
import com.google.zxing.WriterException
import com.journeyapps.barcodescanner.BarcodeEncoder
class CardsAdapter constructor(
private val context: Context,
private val onClickListener: (ScannedCode) -> Unit,
private val deleteListener: (ScannedCode) -> Unit
) : RecyclerView.Adapter<CardViewHolder>() {
private val encoder: BarcodeEncoder = BarcodeEncoder()
var items: List<ScannedCode> = arrayListOf()
set(value) {
field = value
notifyDataSetChanged()
}
override fun getItemCount() = items.size
//================================================================================
// Adapter methods
//================================================================================
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = CardViewHolder(
LayoutInflater.from(context).inflate(
R.layout.adapter_code,
parent,
false
)
)
override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
val item = items[position]
holder.apply {
// Set title
codeTitle.text = item.title
// Set image scaleType according to barcode type
when (item.format) {
QR_CODE, AZTEC, DATA_MATRIX -> codeImage.scaleType = ImageView.ScaleType.FIT_CENTER
else -> codeImage.scaleType = ImageView.ScaleType.FIT_XY
}
// Load image
try {
codeImage.setImageBitmap(
encoder.encodeBitmap(item.text, item.format, 200, 200)
)
} catch (e: WriterException) {
e.printStackTrace()
}
itemView.setOnClickListener { onClickListener(item) }
// Setup delete
itemView.setOnLongClickListener {
deleteListener(item)
true
}
}
}
}
class CardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val codeTitle: TextView = itemView.findViewById(R.id.adapter_card_title)
val codeImage: ImageView = itemView.findViewById(R.id.adapter_card_image)
} | 1 | Kotlin | 19 | 99 | 465a581c8f5fd1da24e0a5932d7b81ed90b0b1ab | 2,712 | CardKeeper | Apache License 2.0 |
src/main/kotlin/com/pineypiney/game_engine/objects/components/CaretRendererComponent.kt | PineyPiney | 491,900,499 | false | {"Kotlin": 564450, "GLSL": 31735} | package com.pineypiney.game_engine.objects.components
import com.pineypiney.game_engine.objects.GameObject
import com.pineypiney.game_engine.objects.util.shapes.VertexShape
import com.pineypiney.game_engine.rendering.RendererI
import com.pineypiney.game_engine.resources.shaders.Shader
import glm_.vec2.Vec2
import glm_.vec3.Vec3
import glm_.vec4.Vec4
class CaretRendererComponent(parent: GameObject, colour: Vec4, shader: Shader = defaultShader, shape: VertexShape = VertexShape.centerSquareShape): ColourRendererComponent(parent, colour, shader, shape), UpdatingAspectRatioComponent {
val textField get() = parent.parent?.getComponent<TextFieldComponent>()!!
override fun render(renderer: RendererI<*>, tickDelta: Double) {
positionTextAndCaret()
super.render(renderer, tickDelta)
}
private fun positionTextAndCaret(){
val w = textField.textBox.getComponent<TextRendererComponent>()!!.text.getWidth(0..<textField.caret)
val ar = (textField.parent.getComponent<RenderedComponent>()!!.renderSize * Vec2(textField.parent.transformComponent.worldScale)).run { y / x }
val x = (w * ar) + textField.textBox.position.x
if(x < 0f){
textField.textBox.translate(Vec3(-x, 0f, 0f))
parent.position = Vec3(0f, 0f, 0f)
}
else if(x > 1f){
textField.textBox.translate(Vec3(1f - x, 0f, 0f))
parent.position = Vec3(1f, 0f, 0f)
}
else {
parent.position = Vec3(x, 0f, 0f)
}
}
override fun updateAspectRatio(renderer: RendererI<*>) {
positionTextAndCaret()
}
} | 0 | Kotlin | 0 | 0 | b8b0248fca747bd0b1853e7d8056facfcb9c479b | 1,631 | GameEngine | MIT License |
DSLs/kubernetes/dsl/src/main/kotlin-gen/dev/forkhandles/k8s/rbac/roleRef.kt | fork-handles | 649,794,132 | false | {"Kotlin": 575626, "Shell": 2264, "Just": 1042, "Nix": 740} | // GENERATED
package dev.forkhandles.k8s.rbac
import io.fabric8.kubernetes.api.model.rbac.ClusterRoleBinding as rbac_ClusterRoleBinding
import io.fabric8.kubernetes.api.model.rbac.RoleBinding as rbac_RoleBinding
import io.fabric8.kubernetes.api.model.rbac.RoleRef as rbac_RoleRef
fun rbac_ClusterRoleBinding.roleRef(block: rbac_RoleRef.() -> Unit = {}) {
if (roleRef == null) {
roleRef = rbac_RoleRef()
}
roleRef.block()
}
fun rbac_RoleBinding.roleRef(block: rbac_RoleRef.() -> Unit = {}) {
if (roleRef == null) {
roleRef = rbac_RoleRef()
}
roleRef.block()
}
| 0 | Kotlin | 0 | 9 | 68221cee577ea16dc498745606d07b0fb62f5cb7 | 604 | k8s-dsl | MIT License |
app/src/androidTest/java/com/exercise/testexercise/ribs/splash/SplashInteractorTest.kt | llOldmenll | 364,664,985 | false | null | package com.exercise.testexercise.ribs.splash
import com.uber.rib.core.RibTestBasePlaceholder
import com.uber.rib.core.InteractorHelper
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations
class SplashInteractorTest : RibTestBasePlaceholder() {
@Mock internal lateinit var presenter: SplashInteractor.SplashPresenter
@Mock internal lateinit var router: SplashRouter
private var interactor: SplashInteractor? = null
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
interactor = TestSplashInteractor.create(presenter)
}
/**
* TODO: Delete this example and add real tests.
*/
@Test
fun anExampleTest_withSomeConditions_shouldPass() {
// Use InteractorHelper to drive your interactor's lifecycle.
InteractorHelper.attach<SplashInteractor.SplashPresenter, SplashRouter>(interactor!!, presenter, router, null)
InteractorHelper.detach(interactor!!)
throw RuntimeException("Remove this test and add real tests.")
}
} | 0 | Kotlin | 0 | 0 | 82a2d8de8b32e65188c82ae42ab0c26b35f55dec | 1,030 | TestExercise | Apache License 2.0 |
innsender/src/main/kotlin/no/nav/soknad/innsending/consumerapis/HealthRequestInterface.kt | navikt | 406,355,715 | false | null | package no.nav.soknad.innsending.consumerapis
interface HealthRequestInterface {
fun ping(): String
fun isReady(): String
fun isAlive(): String
}
| 3 | Kotlin | 0 | 3 | 2918f03faf9ec74670412e8e59e712d07f203fca | 154 | innsending-api | MIT License |
app/src/main/java/com/insiderser/android/movies/di/SingletonComponent.kt | insiderser | 216,079,464 | false | null | /*
* Copyright (c) 2019 Oleksandr Bezushko
*
* 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.insiderser.android.movies.di
import android.app.Activity
import androidx.fragment.app.Fragment
import com.insiderser.android.movies.MoviesApp
import com.insiderser.android.movies.api.tmdb.TmdbUriBuilder
import com.insiderser.android.movies.data.database.AppDatabase
import com.insiderser.android.movies.data.preferences.PreferencesHelper
import com.insiderser.android.movies.data.repository.DiscoverRepository
import com.insiderser.android.movies.data.repository.GenresRepository
import com.insiderser.android.movies.ui.details.basic.BasicDetailsViewModel
import com.insiderser.android.movies.ui.details.full.FullMovieDetailsViewModel
import com.insiderser.android.movies.ui.main.DiscoverViewModel
import com.insiderser.android.movies.ui.main.FavouritesViewModel
import com.insiderser.android.movies.ui.main.MainViewModel
import com.insiderser.android.movies.ui.main.SearchViewModel
import com.insiderser.android.movies.ui.main.SortByDialogViewModel
import com.insiderser.android.movies.ui.recommendations.RecommendationsViewModel
import com.insiderser.android.movies.ui.reviews.ReviewsViewModel
import com.insiderser.android.movies.utils.ImageWidthProvider
import com.insiderser.android.movies.utils.system.LocaleInfoProvider
import com.insiderser.android.movies.utils.system.NetworkInfoProvider
import dagger.Component
import javax.inject.Singleton
@Singleton
@Component(modules = [ContextModule::class, DatabaseModule::class, APIModule::class])
interface SingletonComponent {
fun getMainViewModel(): MainViewModel
fun getDiscoverViewModel(): DiscoverViewModel
fun getFavouritesViewModel(): FavouritesViewModel
fun getSearchViewModel(): SearchViewModel
fun getSortByViewModel(): SortByDialogViewModel
fun getBasicMovieDetailsViewModel(): BasicDetailsViewModel
fun getFullMovieDetailsViewModel(): FullMovieDetailsViewModel
fun getRecommendationsViewModel(): RecommendationsViewModel
fun getReviewsViewModel(): ReviewsViewModel
val database: AppDatabase
val localeInfoProvider: LocaleInfoProvider
val networkInfoProvider: NetworkInfoProvider
val preferencesHelper: PreferencesHelper
val discoverRepository: DiscoverRepository
val genresRepository: GenresRepository
val imageWidthProvider: ImageWidthProvider
val tmdbUriBuilder: TmdbUriBuilder
}
val Activity.injector get() = (application as MoviesApp).injector
val Fragment.injector get() = (requireActivity().application as MoviesApp).injector | 0 | Kotlin | 0 | 0 | c942b813e2e910aaa5db4af37b830ddb35c8796d | 3,690 | Movies | MIT License |
Corona-Warn-App/src/main/java/be/sciensano/coronalert/http/service/DynamicTextsService.kt | covid-be-app | 281,650,940 | false | null | package be.sciensano.coronalert.http.service
import be.sciensano.coronalert.http.responses.DynamicNews
import be.sciensano.coronalert.http.responses.DynamicTexts
import retrofit2.http.GET
interface DynamicTextsService {
@GET("dynamictext/dynamicTextsV2.json")
suspend fun getDynamicTexts(): DynamicTexts
@GET("dynamictext/dynamicNews.json")
suspend fun getDynamicNews(): DynamicNews
}
| 13 | Kotlin | 10 | 55 | d556b0b9f29e76295b59be2a1ba89bc4cf6ec33b | 405 | cwa-app-android | Apache License 2.0 |
app/src/main/java/com/delet_dis/elementarylauncher/presentation/views/clockView/ClockView.kt | delet-dis | 370,617,699 | false | {"Kotlin": 149325} | package com.delet_dis.elementarylauncher.presentation.views.clockView
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.LifecycleOwner
import com.delet_dis.elementarylauncher.R
import com.delet_dis.elementarylauncher.databinding.ClockViewBinding
import com.delet_dis.elementarylauncher.presentation.views.clockView.viewModel.ClockViewViewModel
import dagger.hilt.android.AndroidEntryPoint
import dagger.hilt.android.internal.managers.ViewComponentManager
import dagger.hilt.android.qualifiers.ActivityContext
import javax.inject.Inject
/**
* Custom view used to display the clock widget.
*/
@AndroidEntryPoint
class ClockView @JvmOverloads constructor(
@ActivityContext context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
private val binding: ClockViewBinding
@Inject
lateinit var viewModel: ClockViewViewModel
private var parentActivityCallback: ParentActivityCallback
init {
inflate(getBasePurifiedContext(), R.layout.clock_view, this).also { view ->
binding = ClockViewBinding.bind(view)
}
parentActivityCallback = getBasePurifiedContext() as ParentActivityCallback
initCardViewOnClicksCallbacks()
initDateObserver()
initTimeObserver()
initIsAlarmEnabledObserver()
initAlarmTimeObserver()
}
private fun initCardViewOnClicksCallbacks() =
with(binding.cardView) {
setOnClickListener {
parentActivityCallback.callToHideHomescreenBottomSheet()
}
setOnLongClickListener {
parentActivityCallback.callHomescreenBottomSheet()
true
}
}
private fun initDateObserver() =
viewModel.dateLiveData.observe(getBasePurifiedContext() as LifecycleOwner, { dateStamp ->
binding.dateStamp.text = dateStamp
})
private fun initTimeObserver() =
viewModel.timeLiveData.observe(getBasePurifiedContext() as LifecycleOwner, { timeStamp ->
binding.timeStamp.text = timeStamp
})
private fun initIsAlarmEnabledObserver() =
viewModel.isAlarmEnabled.observe(
getBasePurifiedContext() as LifecycleOwner,
{ isAlarmEnabled ->
binding.alarmImage.visibility = if (isAlarmEnabled) {
View.VISIBLE
} else {
View.GONE
}
binding.alarmStamp.visibility = if (isAlarmEnabled) {
View.VISIBLE
} else {
View.GONE
}
})
private fun initAlarmTimeObserver() =
viewModel.nextAlarmTriggerTime.observe(
getBasePurifiedContext() as LifecycleOwner,
{ alarmStamp ->
binding.alarmStamp.text = alarmStamp
})
private fun getBasePurifiedContext() =
(context as ViewComponentManager.FragmentContextWrapper).baseContext
interface ParentActivityCallback {
fun callHomescreenBottomSheet()
fun callToHideHomescreenBottomSheet()
}
}
| 0 | Kotlin | 1 | 7 | 40a7cb7c0ee385c416c4ef08e614ba2fbcdbf992 | 3,293 | ElementaryLauncher | MIT License |
app/src/main/java/net/pfiers/osmfocus/service/basemap/builtinBaseMaps.kt | ubipo | 310,888,250 | false | null | package net.pfiers.osmfocus.service.basemap
import net.pfiers.osmfocus.R
private const val ATTR_CARTO = "Base map © CARTO"
private val MAX_ZOOM_CARTO =
21 // Actually 30 but that wouldn't be very courteous for a public tileserver
private fun urlCarto(name: String) = "https://a.basemaps.cartocdn.com/rastertiles/$name/"
val builtinBaseMaps = listOf(
BuiltinBaseMap(
R.string.base_map_default,
"Base map © OpenStreetMap Foundation",
"https://a.tile.openstreetmap.org/",
19
),
BuiltinBaseMap(
R.string.base_map_carto_belgium,
"Tiles courtesy of GEO-6",
"https://tile.openstreetmap.be/osmbe/",
18
),
BuiltinBaseMap(
R.string.base_map_cartodb_voyager_w_labels,
ATTR_CARTO,
urlCarto("voyager_labels_under"),
MAX_ZOOM_CARTO
),
BuiltinBaseMap(
R.string.base_map_cartodb_voyager_wo_labels,
ATTR_CARTO,
urlCarto("voyager_nolabels"),
MAX_ZOOM_CARTO
),
BuiltinBaseMap(
R.string.base_map_cartodb_positron_w_labels,
ATTR_CARTO,
urlCarto("light_all"),
MAX_ZOOM_CARTO
),
BuiltinBaseMap(
R.string.base_map_cartodb_positron_wo_labels,
ATTR_CARTO,
urlCarto("light_nolabels"),
MAX_ZOOM_CARTO
),
BuiltinBaseMap(
R.string.base_map_cartodb_dark_matter_w_labels,
ATTR_CARTO,
urlCarto("dark_all"),
MAX_ZOOM_CARTO
),
BuiltinBaseMap(
R.string.base_map_cartodb_dark_matter_wo_labels,
ATTR_CARTO,
urlCarto("dark_nolabels"),
MAX_ZOOM_CARTO
),
)
| 7 | null | 5 | 43 | 53cfdeff366aa23627ea2b6d824c949bc052f25c | 1,643 | osmfocus | Apache License 2.0 |
features/ui/login/src/main/java/br/com/programadorthi/login/bloc/AuthenticationState.kt | programadorthi | 210,706,168 | false | null | package br.com.programadorthi.login.bloc
sealed class AuthenticationState {
object AuthenticationUninitialized : AuthenticationState()
object AuthenticationAuthenticated : AuthenticationState()
object AuthenticationUnauthenticated : AuthenticationState()
object AuthenticationLoading : AuthenticationState()
}
| 0 | Kotlin | 1 | 18 | 1d0844a916df9101408b5f2a5cdeb498199309ac | 330 | android-bloc | Apache License 2.0 |
android/src/main/kotlin/com/klarna/mobile/sdk/flutter/core/util/MethodCallExtensions.kt | klarna | 263,862,690 | false | null | package com.klarna.mobile.sdk.flutter.core.util
import io.flutter.plugin.common.MethodCall
internal fun <T> MethodCall.requireArgument(key: String): T {
return argument<T>(key) ?: throw IllegalArgumentException("Argument $key can not be null.")
} | 1 | Kotlin | 9 | 9 | f866fe26ca8a9d5c92a2bb78ec9916c751e2b99a | 252 | klarna-mobile-sdk-flutter | Apache License 2.0 |
api/src/main/java/com/poketmoney/api/PoketMoneyClient.kt | afnancal | 494,757,400 | false | {"Kotlin": 106163} | package com.poketmoney.api
import com.poketmoney.api.services.PoketMoneyAPI
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
/**
* Bismillah
* Created by Md. <NAME> on 28/02/22.
*/
object PoketMoneyClient {
private var authToken: String? = null
private val authInterceptor = Interceptor { chain ->
var req = chain.request()
authToken?.let {
req = req.newBuilder()
.header("Authorization", "Token $it")
.build()
}
chain.proceed(req)
}
private val okHttpBuilder = OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.connectTimeout(2, TimeUnit.SECONDS)
private val retrofitBuilder = Retrofit.Builder()
.baseUrl("https://conduit.productionready.io/api/")
.addConverterFactory(MoshiConverterFactory.create())
val publicApi = retrofitBuilder
.client(okHttpBuilder.build())
.build()
.create(PoketMoneyAPI::class.java)
val authApi = retrofitBuilder
.client(okHttpBuilder.addInterceptor(authInterceptor).build())
.build()
.create(PoketMoneyAPI::class.java)
/*********************************************************************************************************************/
// For Offer18 User Signup
private val retrofitOffer18 = Retrofit.Builder()
.baseUrl("https://api.offer18.com/api/m/")
.addConverterFactory(MoshiConverterFactory.create())
val apiOffer18 = retrofitOffer18
.client(okHttpBuilder.build())
.build()
.create(PoketMoneyAPI::class.java)
// For MSG91 sms sent
private val retrofitMSG91 = Retrofit.Builder()
.baseUrl("https://api.msg91.com/api/v5/")
.addConverterFactory(MoshiConverterFactory.create())
val apiMSG91 = retrofitMSG91
.client(okHttpBuilder.build())
.build()
.create(PoketMoneyAPI::class.java)
private val retrofitPoketMoneyAPI = Retrofit.Builder()
.baseUrl("https://www.poketmoney.org/app/restapi/")
.addConverterFactory(MoshiConverterFactory.create())
val apiPoketMoney = retrofitPoketMoneyAPI
.client(okHttpBuilder.build())
.build()
.create(PoketMoneyAPI::class.java)
} | 0 | Kotlin | 0 | 0 | b1fab26c55ff485e131376e649a68c7f253b37f0 | 2,387 | PoketMoney | Apache License 2.0 |
api/src/main/java/com/poketmoney/api/PoketMoneyClient.kt | afnancal | 494,757,400 | false | {"Kotlin": 106163} | package com.poketmoney.api
import com.poketmoney.api.services.PoketMoneyAPI
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.util.concurrent.TimeUnit
/**
* Bismillah
* Created by Md. <NAME> on 28/02/22.
*/
object PoketMoneyClient {
private var authToken: String? = null
private val authInterceptor = Interceptor { chain ->
var req = chain.request()
authToken?.let {
req = req.newBuilder()
.header("Authorization", "Token $it")
.build()
}
chain.proceed(req)
}
private val okHttpBuilder = OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.connectTimeout(2, TimeUnit.SECONDS)
private val retrofitBuilder = Retrofit.Builder()
.baseUrl("https://conduit.productionready.io/api/")
.addConverterFactory(MoshiConverterFactory.create())
val publicApi = retrofitBuilder
.client(okHttpBuilder.build())
.build()
.create(PoketMoneyAPI::class.java)
val authApi = retrofitBuilder
.client(okHttpBuilder.addInterceptor(authInterceptor).build())
.build()
.create(PoketMoneyAPI::class.java)
/*********************************************************************************************************************/
// For Offer18 User Signup
private val retrofitOffer18 = Retrofit.Builder()
.baseUrl("https://api.offer18.com/api/m/")
.addConverterFactory(MoshiConverterFactory.create())
val apiOffer18 = retrofitOffer18
.client(okHttpBuilder.build())
.build()
.create(PoketMoneyAPI::class.java)
// For MSG91 sms sent
private val retrofitMSG91 = Retrofit.Builder()
.baseUrl("https://api.msg91.com/api/v5/")
.addConverterFactory(MoshiConverterFactory.create())
val apiMSG91 = retrofitMSG91
.client(okHttpBuilder.build())
.build()
.create(PoketMoneyAPI::class.java)
private val retrofitPoketMoneyAPI = Retrofit.Builder()
.baseUrl("https://www.poketmoney.org/app/restapi/")
.addConverterFactory(MoshiConverterFactory.create())
val apiPoketMoney = retrofitPoketMoneyAPI
.client(okHttpBuilder.build())
.build()
.create(PoketMoneyAPI::class.java)
} | 0 | Kotlin | 0 | 0 | b1fab26c55ff485e131376e649a68c7f253b37f0 | 2,387 | PoketMoney | Apache License 2.0 |
src/main/kotlin/org/idaesbasic/powerline/PowerLineController.kt | BenHerbst | 418,058,933 | false | {"Kotlin": 23824, "Java": 657, "Batchfile": 54} | package org.idaesbasic.powerline
import org.idaesbasic.MainView
import tornadofx.Controller
class PowerLineController : Controller() {
val mainView: MainView by inject()
} | 10 | Kotlin | 5 | 138 | bc4b0db4eca43b0ed1181c297f84516d97716cf5 | 177 | idaesbasic | Apache License 2.0 |
codelabs/compose/Composequadrant/app/src/main/java/com/example/composequadrant/MainActivity.kt | radude89 | 745,171,363 | false | {"Kotlin": 430359} | package com.example.composequadrant
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.composequadrant.ui.theme.ComposeQuadrantTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeQuadrantTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
GridView()
}
}
}
}
}
@Composable
fun GridView() {
Column(Modifier.fillMaxWidth()) {
RowContentView(
firstCardTitle = stringResource(id = R.string.card1_title),
firstCardDescription = stringResource(id = R.string.card1_description),
firstCardColor = Color(0xFFEADDFF),
secondCardTitle = stringResource(id = R.string.card2_title),
secondCardDescription = stringResource(id = R.string.card2_description),
secondCardColor = Color(0xFFD0BCFF),
modifier = Modifier.weight(1f)
)
RowContentView(
firstCardTitle = stringResource(id = R.string.card3_title),
firstCardDescription = stringResource(id = R.string.card3_description),
firstCardColor = Color(0xFFB69DF8),
secondCardTitle = stringResource(id = R.string.card4_title),
secondCardDescription = stringResource(id = R.string.card4_description),
secondCardColor = Color(0xFFF6EDFF),
modifier = Modifier.weight(1f)
)
}
}
@Composable
fun RowContentView(
firstCardTitle: String,
firstCardDescription: String,
firstCardColor: Color,
secondCardTitle: String,
secondCardDescription: String,
secondCardColor: Color,
modifier: Modifier = Modifier
) {
Row(modifier) {
Card(
title = firstCardTitle,
message = firstCardDescription,
color = firstCardColor,
modifier = Modifier.weight(1f)
)
Card(
title = secondCardTitle,
message = secondCardDescription,
color = secondCardColor,
modifier = Modifier.weight(1f)
)
}
}
@Composable
private fun Card(
title: String,
message: String,
color: Color,
modifier: Modifier = Modifier
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier
.fillMaxSize()
.background(color)
.padding(16.dp)
) {
Text(
text = title,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(bottom = 16.dp)
)
Text(
text = message,
textAlign = TextAlign.Justify
)
}
}
@Preview(showBackground = true)
@Composable
fun Preview() {
ComposeQuadrantTheme {
GridView()
}
} | 0 | Kotlin | 0 | 0 | 92c9c1028feb236ab179dee6b0296c84ccea2d4e | 4,065 | android-personal-projects | MIT License |
codelabs/compose/Composequadrant/app/src/main/java/com/example/composequadrant/MainActivity.kt | radude89 | 745,171,363 | false | {"Kotlin": 430359} | package com.example.composequadrant
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.composequadrant.ui.theme.ComposeQuadrantTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeQuadrantTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
GridView()
}
}
}
}
}
@Composable
fun GridView() {
Column(Modifier.fillMaxWidth()) {
RowContentView(
firstCardTitle = stringResource(id = R.string.card1_title),
firstCardDescription = stringResource(id = R.string.card1_description),
firstCardColor = Color(0xFFEADDFF),
secondCardTitle = stringResource(id = R.string.card2_title),
secondCardDescription = stringResource(id = R.string.card2_description),
secondCardColor = Color(0xFFD0BCFF),
modifier = Modifier.weight(1f)
)
RowContentView(
firstCardTitle = stringResource(id = R.string.card3_title),
firstCardDescription = stringResource(id = R.string.card3_description),
firstCardColor = Color(0xFFB69DF8),
secondCardTitle = stringResource(id = R.string.card4_title),
secondCardDescription = stringResource(id = R.string.card4_description),
secondCardColor = Color(0xFFF6EDFF),
modifier = Modifier.weight(1f)
)
}
}
@Composable
fun RowContentView(
firstCardTitle: String,
firstCardDescription: String,
firstCardColor: Color,
secondCardTitle: String,
secondCardDescription: String,
secondCardColor: Color,
modifier: Modifier = Modifier
) {
Row(modifier) {
Card(
title = firstCardTitle,
message = firstCardDescription,
color = firstCardColor,
modifier = Modifier.weight(1f)
)
Card(
title = secondCardTitle,
message = secondCardDescription,
color = secondCardColor,
modifier = Modifier.weight(1f)
)
}
}
@Composable
private fun Card(
title: String,
message: String,
color: Color,
modifier: Modifier = Modifier
) {
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = modifier
.fillMaxSize()
.background(color)
.padding(16.dp)
) {
Text(
text = title,
fontWeight = FontWeight.Bold,
modifier = Modifier
.padding(bottom = 16.dp)
)
Text(
text = message,
textAlign = TextAlign.Justify
)
}
}
@Preview(showBackground = true)
@Composable
fun Preview() {
ComposeQuadrantTheme {
GridView()
}
} | 0 | Kotlin | 0 | 0 | 92c9c1028feb236ab179dee6b0296c84ccea2d4e | 4,065 | android-personal-projects | MIT License |
app/src/main/java/edu/umsl/nasaviewer/NASAAccessLogDBHelper.kt | dautry1 | 156,419,783 | false | null | package edu.umsl.nasaviewer
import android.content.ContentValues
import android.content.Context
import android.database.Cursor
import android.database.DatabaseUtils
import android.database.sqlite.SQLiteConstraintException
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteOpenHelper
import java.util.ArrayList
// this code was ripped and modified from https://www.tutorialkart.com/kotlin-android/android-sqlite-example-application/
class NASAAccessLogDBHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(SQL_CREATE_ENTRIES)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// upgrade policy is to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES)
onCreate(db)
}
override fun onDowngrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
onUpgrade(db, oldVersion, newVersion)
}
@Throws(SQLiteConstraintException::class)
fun insertNASALog(log: NASAAccessLogModel): Boolean {
// Gets the data repository in write mode
val db = writableDatabase
// Create a new map of values, where column names are the keys
val values = ContentValues()
val entrynum = DatabaseUtils.queryNumEntries(db, DBContract.NASAEntry.TABLE_NAME) + 1
values.put(DBContract.NASAEntry.COLUMN_ENTRYNUM, entrynum.toString()) // arbitrary number
values.put(DBContract.NASAEntry.COLUMN_NASAID, log.nasaid) // NASA assigned ID
values.put(DBContract.NASAEntry.COLUMN_TIME, log.time) // date and time
// Insert the new row, returning the primary key value of the new row
val newRowId = db.insert(DBContract.NASAEntry.TABLE_NAME, null, values)
return true
}
@Throws(SQLiteConstraintException::class)
fun deleteNASALog(entrynum: String): Boolean {
// Gets the data repository in write mode
val db = writableDatabase
// Define 'where' part of query.
val selection = DBContract.NASAEntry.COLUMN_ENTRYNUM + " LIKE ?"
// Specify arguments in placeholder order.
val selectionArgs = arrayOf(entrynum)
// Issue SQL statement.
db.delete(DBContract.NASAEntry.TABLE_NAME, selection, selectionArgs)
return true
}
fun readNASALog(entrynum: String): ArrayList<NASAAccessLogModel> {
val nasa = ArrayList<NASAAccessLogModel>()
val db = writableDatabase
var cursor: Cursor? = null
try {
cursor = db.rawQuery("select * from " + DBContract.NASAEntry.TABLE_NAME + " WHERE " + DBContract.NASAEntry.COLUMN_ENTRYNUM + "='" + entrynum + "'", null)
} catch (e: SQLiteException) {
// if table not yet present, create it
db.execSQL(SQL_CREATE_ENTRIES)
return ArrayList()
}
var nasaid: String
var time: String
if (cursor!!.moveToFirst()) {
while (!cursor.isAfterLast) {
nasaid = cursor.getString(cursor.getColumnIndex(DBContract.NASAEntry.COLUMN_NASAID))
time = cursor.getString(cursor.getColumnIndex(DBContract.NASAEntry.COLUMN_TIME))
nasa.add(NASAAccessLogModel(entrynum, nasaid, time))
cursor.moveToNext()
}
}
cursor.close()
return nasa
}
fun readAllNASALog(): ArrayList<NASAAccessLogModel> {
val users = ArrayList<NASAAccessLogModel>()
val db = writableDatabase
var cursor: Cursor? = null
try {
cursor = db.rawQuery("select * from " + DBContract.NASAEntry.TABLE_NAME, null)
} catch (e: SQLiteException) {
db.execSQL(SQL_CREATE_ENTRIES)
return ArrayList()
}
var entrynum: String
var nasaid: String
var time: String
if (cursor!!.moveToFirst()) {
while (!cursor.isAfterLast) {
entrynum = cursor.getString(cursor.getColumnIndex(DBContract.NASAEntry.COLUMN_ENTRYNUM))
nasaid = cursor.getString(cursor.getColumnIndex(DBContract.NASAEntry.COLUMN_NASAID))
time = cursor.getString(cursor.getColumnIndex(DBContract.NASAEntry.COLUMN_TIME))
users.add(NASAAccessLogModel(entrynum, nasaid, time))
cursor.moveToNext()
}
}
cursor.close()
return users
}
companion object {
// If you change the database schema, you must increment the database version.
const val DATABASE_VERSION = 1
const val DATABASE_NAME = "NASAAccessLog.db"
private const val SQL_CREATE_ENTRIES =
"CREATE TABLE " + DBContract.NASAEntry.TABLE_NAME + " (" +
DBContract.NASAEntry.COLUMN_ENTRYNUM + " TEXT PRIMARY KEY," +
DBContract.NASAEntry.COLUMN_NASAID + " TEXT," +
DBContract.NASAEntry.COLUMN_TIME + " TEXT)"
private const val SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS " + DBContract.NASAEntry.TABLE_NAME
}
} | 0 | Kotlin | 0 | 0 | 5a3aad3f0f1879a8ced209c9e21a875a4a5e0c7e | 5,240 | Android-Nasa-Viewer | MIT License |
kmpauth-firebase/src/androidMain/kotlin/com/mmk/kmpauth/firebase/apple/AppleButtonUiContainer.kt | mirzemehdi | 736,339,532 | false | {"Kotlin": 63838, "Ruby": 2229, "Swift": 1650} | package com.mmk.kmpauth.firebase.apple
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.mmk.kmpauth.core.UiContainerScope
import com.mmk.kmpauth.firebase.oauth.OAuthContainer
import dev.gitlive.firebase.auth.FirebaseUser
import dev.gitlive.firebase.auth.OAuthProvider
/**
* AppleButton Ui Container Composable that handles all sign-in functionality for Apple.
* Child of this Composable can be any view or Composable function.
* You need to call [UiContainerScope.onClick] function on your child view's click function.
*
* [onResult] callback will return [Result] with [FirebaseUser] type.
* @param requestScopes list of request scopes type of [AppleSignInRequestScope].
* Example Usage:
* ```
* //Apple Sign-In with Custom Button and authentication with Firebase
* AppleButtonUiContainer(onResult = onFirebaseResult) {
* Button(onClick = { this.onClick() }) { Text("Apple Sign-In (Custom Design)") }
* }
*
* ```
*
*/
@Composable
public actual fun AppleButtonUiContainer(
modifier: Modifier,
requestScopes: List<AppleSignInRequestScope>,
onResult: (Result<FirebaseUser?>) -> Unit,
content: @Composable UiContainerScope.() -> Unit,
) {
val oathProviderRequestScopes = requestScopes.map {
when (it) {
AppleSignInRequestScope.Email -> "email"
AppleSignInRequestScope.FullName -> "name"
}
}
val oAuthProvider = OAuthProvider(provider = "apple.com", scopes = oathProviderRequestScopes)
OAuthContainer(
modifier = modifier,
oAuthProvider = oAuthProvider,
onResult = onResult,
content = content
)
} | 5 | Kotlin | 4 | 88 | 808ebfaac2ea65c079ae4c506f139f06c7c60dad | 1,663 | KMPAuth | Apache License 2.0 |
app/src/main/java/com/ayala/dam/firebasenotesfragments/MainActivity.kt | jaidis | 162,309,714 | false | null | package com.ayala.dam.firebasenotesfragments
import android.annotation.SuppressLint
import android.app.Activity
import android.app.Dialog
import android.content.DialogInterface
import android.graphics.*
import android.graphics.BitmapFactory.decodeResource
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.util.Log
import android.view.*
import android.widget.Adapter
import com.ayala.dam.firebasenotes.Nota
import com.google.firebase.database.*
// TODO: FIREBASE LIBRERIAS
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.content_main.*
import kotlinx.android.synthetic.main.dialog.view.*
import org.json.JSONObject
import java.util.*
class MainActivity : AppCompatActivity() {
companion object {
lateinit var prefs: Prefs
}
private lateinit var activityAdapter: MainActivity
private lateinit var adaptador: DatosAdapterNotas
var notas: MutableList<Nota> = ArrayList()
private lateinit var dbReference: DatabaseReference
private lateinit var database: FirebaseDatabase
private val p = Paint()
private var view: View? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
activityAdapter = this
recyclerViewFragmentNotes.layoutManager = LinearLayoutManager(applicationContext)
recyclerViewFragmentNotes.layoutManager = GridLayoutManager(applicationContext, 1)
adaptador = DatosAdapterNotas(activityAdapter, notas, applicationContext!!)
recyclerViewFragmentNotes.adapter = adaptador
fab.setOnClickListener { showDialog() }
// TODO: Asignamos las preferencias, en este caso cargar/guardar los tokens
prefs = Prefs(applicationContext)
if (MainActivity.prefs.token.equals(""))
{
MainActivity.prefs.token = (Random().nextInt((999999999 + 1) - 1) + 1).toString()
}
firebaseLoad()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
return when (item.itemId) {
R.id.action_settings -> true
else -> super.onOptionsItemSelected(item)
}
}
fun message(msg: String) {
Snackbar.make(findViewById(android.R.id.content), msg, Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
fun showDialog() {
var builder: AlertDialog.Builder = AlertDialog.Builder(this)
var inflater: LayoutInflater = layoutInflater
var view: View = inflater.inflate(R.layout.dialog, null)
builder.setView(view)
builder.setNegativeButton("No", object : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
message("Canceled")
dialog!!.dismiss()
}
})
builder.setPositiveButton("Yes", object : DialogInterface.OnClickListener {
override fun onClick(dialog: DialogInterface?, which: Int) {
firebaseNewContent(view.et_title.text.toString(), view.et_note.text.toString())
}
})
var dialog: Dialog = builder.create()
dialog.show()
}
private fun initSwipe() {
val simpleItemTouchCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val position = viewHolder.adapterPosition
if (direction == ItemTouchHelper.LEFT) {
adaptador!!.removeItem(position)
} else {
adaptador!!.removeItem(position)
}
}
private fun removeView() {
if (view!!.parent != null) {
(view!!.parent as ViewGroup).removeView(view)
}
}
@SuppressLint("PrivateResource")
override fun onChildDraw(c: Canvas, recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, dX: Float, dY: Float, actionState: Int, isCurrentlyActive: Boolean) {
val icon: Bitmap
if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE) {
val itemView = viewHolder.itemView
val height = itemView.bottom.toFloat() - itemView.top.toFloat()
val width = height / 3
if (dX > 0) {
p.color = Color.parseColor("#388E3C")
val background = RectF(itemView.left.toFloat(), itemView.top.toFloat(), dX, itemView.bottom.toFloat())
c.drawRect(background, p)
icon = decodeResource(resources, R.drawable.abc_ic_menu_copy_mtrl_am_alpha)
val icon_dest = RectF(itemView.left.toFloat() + width, itemView.top.toFloat() + width, itemView.left.toFloat() + 2 * width, itemView.bottom.toFloat() - width)
c.drawBitmap(icon, null, icon_dest, p)
} else {
p.color = Color.parseColor("#D32F2F")
val background = RectF(itemView.right.toFloat() + dX, itemView.top.toFloat(), itemView.right.toFloat(), itemView.bottom.toFloat())
c.drawRect(background, p)
icon = decodeResource(resources, R.drawable.abc_ic_menu_cut_mtrl_alpha)
val icon_dest = RectF(itemView.right.toFloat() - 2 * width, itemView.top.toFloat() + width, itemView.right.toFloat() - width, itemView.bottom.toFloat() - width)
c.drawBitmap(icon, null, icon_dest, p)
}
}
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
}
}
val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback)
itemTouchHelper.attachToRecyclerView(recyclerViewFragmentNotes)
}
fun firebaseLoad() {
notas.clear()
notas.add(Nota("1", "Cargando notas", "Cargando notas"))
database = FirebaseDatabase.getInstance()
dbReference = database.getReference("notas")
val menuListener = object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
Log.d("FIREBASE-NOTAS", "Cargando datos")
notas.clear()
// val gson= Gson()
for (item in dataSnapshot.children) {
try {
val registro = JSONObject(item.getValue().toString())
val titulo = registro["title"].toString().replace("_", " ")
val descripcion = registro["note"].toString().replace("_", " ")
notas.add(Nota(item.key!!, titulo, descripcion))
} catch (e: Exception) {
Log.d("FIREBASE-NOTAS", e.message.toString())
}
}
if (notas.size == 0) {
notas.add(Nota("1", "No se ha encontrado ninguna nota", "No se ha encontrado ninguna nota"))
message("No se ha encontrado ninguna nota")
}
Log.d("FIREBASE-NOTAS", notas.toString())
recyclerViewFragmentNotes.adapter = DatosAdapterNotas(activityAdapter, notas, applicationContext!!)
// initSwipe()
}
override fun onCancelled(databaseError: DatabaseError) {
println("loadPost:onCancelled ${databaseError.toException()}")
}
}
dbReference.child( MainActivity.prefs.token).addValueEventListener(menuListener)
}
fun firebaseNewContent(title: String, note: String) {
try {
val titulo = title.replace(" ", "_")
val descripcion = note.replace(" ", "_")
var nota = Nota((Random().nextInt((999999999 + 1) - 1) + 1).toString(), titulo, descripcion)
dbReference.child( MainActivity.prefs.token).push().setValue(nota)
message("Nota guardada con éxito")
} catch (e: Exception) {
message(e.message.toString())
}
}
}
| 0 | Kotlin | 0 | 0 | 7e6fcc9fe3c5c0a9f6b56a4e66e4f518719b1b24 | 9,259 | FirebaseNotesFragments | MIT License |
core/app_database/src/androidTest/java/tw/com/deathhit/core/app_database/AttractionImageItemDaoTest.kt | Deathhit | 748,190,483 | false | {"Kotlin": 197443} | package tw.com.deathhit.core.app_database
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import tw.com.deathhit.core.app_database.config.buildAppDatabase
import tw.com.deathhit.core.app_database.config.generateAttractionEntity
import tw.com.deathhit.core.app_database.config.generateAttractionId
import tw.com.deathhit.core.app_database.config.generateAttractionImageEntities
import tw.com.deathhit.core.app_database.entity.AttractionImageEntity
import tw.com.deathhit.core.app_database.entity.AttractionImageRemoteOrderEntity
import tw.com.deathhit.core.app_database.view.AttractionImageItemView
@OptIn(ExperimentalCoroutinesApi::class)
class AttractionImageItemDaoTest {
private lateinit var appDatabase: AppDatabase
private val attractionDao get() = appDatabase.attractionDao()
private val attractionImageDao get() = appDatabase.attractionImageDao()
private val attractionImageItemDao get() = appDatabase.attractionImageItemDao()
private val attractionImageRemoteOrderDao get() = appDatabase.attractionImageRemoteOrderDao()
@Before
fun setup() {
val context = ApplicationProvider.getApplicationContext<Context>()
appDatabase = buildAppDatabase(context)
}
@Test
fun getAttractionImageItemsFlow() = runTest {
//Given
val attractionId = generateAttractionId()
val attraction = generateAttractionEntity(attractionId = attractionId)
val attractionImages = generateAttractionImageEntities(attractionId = attractionId)
val attractionImageRemoteOrders =
attractionImages.mapIndexed { index, attractionImageEntity ->
AttractionImageRemoteOrderEntity(
attractionId = attractionImageEntity.attractionId,
imageUrl = attractionImageEntity.imageUrl,
remoteOrder = index
)
}
attractionDao.upsert(listOf(attraction))
attractionImageDao.upsert(attractionImages)
attractionImageRemoteOrderDao.upsert(attractionImageRemoteOrders)
advanceUntilIdle()
//When
val attractionImageItems =
attractionImageItemDao.getEntitiesListFlow(attractionId = attractionId).first()
//Then
attractionImageItems.forEachIndexed { index, attractionImageItem ->
attractionImageItem.assertEqualsToEntity(attractionImages[index])
}
}
private fun AttractionImageItemView.assertEqualsToEntity(entity: AttractionImageEntity) {
assert(attractionId == entity.attractionId)
assert(imageUrl == entity.imageUrl)
}
} | 0 | Kotlin | 0 | 0 | d76f4a3f3d3f0310e3a8b551efa11f46c3c54a30 | 2,871 | TaipeiTour | Apache License 2.0 |
core/app_database/src/androidTest/java/tw/com/deathhit/core/app_database/AttractionImageItemDaoTest.kt | Deathhit | 748,190,483 | false | {"Kotlin": 197443} | package tw.com.deathhit.core.app_database
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import tw.com.deathhit.core.app_database.config.buildAppDatabase
import tw.com.deathhit.core.app_database.config.generateAttractionEntity
import tw.com.deathhit.core.app_database.config.generateAttractionId
import tw.com.deathhit.core.app_database.config.generateAttractionImageEntities
import tw.com.deathhit.core.app_database.entity.AttractionImageEntity
import tw.com.deathhit.core.app_database.entity.AttractionImageRemoteOrderEntity
import tw.com.deathhit.core.app_database.view.AttractionImageItemView
@OptIn(ExperimentalCoroutinesApi::class)
class AttractionImageItemDaoTest {
private lateinit var appDatabase: AppDatabase
private val attractionDao get() = appDatabase.attractionDao()
private val attractionImageDao get() = appDatabase.attractionImageDao()
private val attractionImageItemDao get() = appDatabase.attractionImageItemDao()
private val attractionImageRemoteOrderDao get() = appDatabase.attractionImageRemoteOrderDao()
@Before
fun setup() {
val context = ApplicationProvider.getApplicationContext<Context>()
appDatabase = buildAppDatabase(context)
}
@Test
fun getAttractionImageItemsFlow() = runTest {
//Given
val attractionId = generateAttractionId()
val attraction = generateAttractionEntity(attractionId = attractionId)
val attractionImages = generateAttractionImageEntities(attractionId = attractionId)
val attractionImageRemoteOrders =
attractionImages.mapIndexed { index, attractionImageEntity ->
AttractionImageRemoteOrderEntity(
attractionId = attractionImageEntity.attractionId,
imageUrl = attractionImageEntity.imageUrl,
remoteOrder = index
)
}
attractionDao.upsert(listOf(attraction))
attractionImageDao.upsert(attractionImages)
attractionImageRemoteOrderDao.upsert(attractionImageRemoteOrders)
advanceUntilIdle()
//When
val attractionImageItems =
attractionImageItemDao.getEntitiesListFlow(attractionId = attractionId).first()
//Then
attractionImageItems.forEachIndexed { index, attractionImageItem ->
attractionImageItem.assertEqualsToEntity(attractionImages[index])
}
}
private fun AttractionImageItemView.assertEqualsToEntity(entity: AttractionImageEntity) {
assert(attractionId == entity.attractionId)
assert(imageUrl == entity.imageUrl)
}
} | 0 | Kotlin | 0 | 0 | d76f4a3f3d3f0310e3a8b551efa11f46c3c54a30 | 2,871 | TaipeiTour | Apache License 2.0 |
spinner/src/main/java/com/lavergne/spinner/Constants.kt | remylavergne | 210,926,819 | false | null | package com.lavergne.spinner
const val NO_VALID_INDEX = 0
const val DEFAULT_THEME = android.R.layout.simple_list_item_1 | 0 | Kotlin | 0 | 3 | a668cb72a0df8d32549af35395d8901c1f211f5e | 121 | spinner-android | MIT License |
model-api/src/commonMain/kotlin/org/modelix/model/api/SimpleLanguage.kt | JetBrains | 109,820,403 | false | null | /*
* Copyright 2003-2021 JetBrains s.r.o.
*
* 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.modelix.model.api
class SimpleLanguage(private val name: String) : ILanguage {
override fun getUID(): String = name
private val concepts: MutableList<SimpleConcept> = ArrayList()
override fun getConcepts(): List<SimpleConcept> = concepts
fun addConcept(concept: SimpleConcept) {
val currentLang = concept.language
if (currentLang != null) throw IllegalStateException("concept ${concept.getShortName()} was already added to language ${currentLang.getName()}")
concept.language = this
concepts.add(concept)
}
override fun getName() = name
}
| 187 | Kotlin | 43 | 63 | f9901b1f879e41448cb359ebdd0f444e0e56b549 | 1,213 | MPS-extensions | Apache License 2.0 |
src/main/kotlin/com/nullman/gadget_collection_tool/controller/ItemController.kt | nullman | 233,671,854 | false | null | package com.nullman.gadget_collection_tool.controller
import com.nullman.gadget_collection_tool.model.Item
import com.nullman.gadget_collection_tool.repository.ItemRepository
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.*
import org.springframework.web.server.ResponseStatusException
import java.util.*
@RestController
@RequestMapping("/item")
class ItemController(private val repository: ItemRepository) {
@GetMapping
fun findAll() = repository.findAll()
@GetMapping("/{id}")
fun findById(@PathVariable id: UUID) = repository.findById(id).orElseThrow {
throw ItemNotFoundException("Item not found with id: $id")
}
@GetMapping("/query/{name}")
fun findByName(@PathVariable name: String) = repository.findByName(name).orElseThrow {
throw ItemNotFoundException("Item not found with name: $name")
}
@GetMapping("/bucket/{id}")
fun findAllByBucketId(@PathVariable id: UUID) = repository.findAllByBucketId(id)
@PostMapping()
fun create(@RequestBody item: Item) =
when {
repository.findByName(item.name).isPresent ->
throw BucketNameExistsException("Bucket name exists: ${item.name}")
else ->
repository.save(item)
}
@PutMapping("/{id}")
fun update(@PathVariable id: UUID, @RequestBody item: Item) =
when {
id != item.id ->
throw ItemIdNotMatchedException("Item URL id: $id does not match Bucket object id: ${item.id}")
repository.findByName(item.name).orElse(item).id != id ->
throw ItemIdNotMatchedException("Item name exists: ${item.name}")
else ->
repository.save(item)
}
@DeleteMapping("/{id}")
fun delete(@PathVariable id: UUID) = repository.deleteById(id)
}
class ItemNotFoundException(message: String) : ResponseStatusException(HttpStatus.NOT_FOUND, message)
class ItemNameExistsException(message: String) : ResponseStatusException(HttpStatus.FORBIDDEN, message)
class ItemIdNotMatchedException(message: String) : ResponseStatusException(HttpStatus.FORBIDDEN, message)
| 0 | Kotlin | 0 | 0 | 5cc40c9c18f04a1a450e47688e3c91a81ea5f01d | 2,227 | gadget-collection-tool | Creative Commons Attribution 3.0 Unported |
src/main/kotlin/com/examples/abbasdgr8/model/domain/Organization.kt | abbasdgr8 | 293,219,115 | false | null | package com.examples.abbasdgr8.model.domain
import java.util.*
data class Organization(
val _id: Int,
val url: String,
val external_id: String,
val name: String,
val alias: String,
val domain_names: List<String>,
val created_at: Date,
val details: String,
val shared_tickets: Boolean,
val tags: List<String>
) | 0 | Kotlin | 0 | 0 | a979c79ee61fe014458085396cf624df7022577a | 391 | ticketing-search-app | Apache License 2.0 |
app/src/main/java/id/ac/ui/cs/mobileprogramming/bungaamalia/ryoudiary/dao/RecipeDao.kt | bungamaku | 314,575,356 | false | null | package id.ac.ui.cs.mobileprogramming.bungaamalia.ryoudiary.dao
import androidx.room.*
import id.ac.ui.cs.mobileprogramming.bungaamalia.ryoudiary.data.Recipe
import kotlinx.coroutines.flow.Flow
@Dao
interface RecipeDao {
@Query("SELECT * FROM recipe_table ORDER BY id ASC")
fun getAllRecipes(): Flow<List<Recipe>>
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun insertRecipe(recipe: Recipe)
@Update
fun updateRecipe(vararg recipe: Recipe)
@Delete
fun deleteRecipe(vararg recipe: Recipe)
} | 0 | Kotlin | 0 | 0 | 25d1b2256e842944292bef9c6280ddc740425a49 | 537 | ryoudiary | MIT License |
src/main/kotlin/com/dkanen/GenericDispatcher.kt | prufrock | 239,387,222 | false | null | package com.dkanen
class GenericDispatcher<T> : Dispatcher<T> {
private val subscriberList: MutableList<(T) -> Unit> = mutableListOf()
override fun subscribe(subscriberFunction: (T) -> Unit) {
subscriberList.add(subscriberFunction)
}
override fun subscribe(newSubscriber: GenericSubscriber<T>) {
subscriberList.add { event -> newSubscriber.receive(event)}
}
override fun broadcast(event: T) {
subscriberList.map { subscriber -> subscriber(event)}
}
} | 0 | Kotlin | 0 | 0 | 1abb3ad9baaa5f1fe7b83a332c5d2e1bd51d102c | 507 | adventure-venture | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/sbma/linkup/presentation/screenstates/UserConnectionsScreenState.kt | ericaskari-metropolia | 694,027,591 | false | {"Kotlin": 323836, "HTML": 71958, "TypeScript": 19773, "Dockerfile": 577, "JavaScript": 256} | package com.sbma.linkup.presentation.screenstates
import com.sbma.linkup.connection.Connection
import com.sbma.linkup.user.User
data class UserConnectionsScreenState(
val connections: Map<Connection, User>
) | 0 | Kotlin | 1 | 1 | 436d8f46fc76a9d6af2ab5e997dc673d9ee1bf08 | 213 | sbma | MIT License |
app/src/main/java/com/freeankit/ankitmvvmsample/viewmodel/ItemPeopleViewModel.kt | ArchitectAK | 112,737,829 | false | null | package com.freeankit.ankitmvvmsample.viewmodel
import android.content.Context
import android.databinding.BaseObservable
import android.databinding.BindingAdapter
import android.view.View
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.freeankit.ankitmvvmsample.model.People
import com.freeankit.ankitmvvmsample.view.PeopleDetailActivity
/**
*@author by <NAME> (<EMAIL>) on 12/1/17 (MM/DD/YYYY )
**/
class ItemPeopleViewModel(private var people: People, private val context: Context) : BaseObservable() {
fun getFullName(): String {
people.fullName = people.name.title + "." + people.name.first + " " + people.name.last
return people.fullName!!
}
fun getCell(): String {
return people.cell
}
fun getMail(): String {
return people.email
}
fun getPictureProfile(): String {
return people.picture.medium
}
@BindingAdapter("imageUrl")
fun setImageUrl(imageView: ImageView, url: String) {
Glide.with(imageView.context).load(url).into(imageView)
}
fun onItemClick(view: View) {
context.startActivity(PeopleDetailActivity.launchDetail(view.context, people))
}
fun setPeople(people: People) {
this.people = people
notifyChange()
}
} | 0 | Kotlin | 2 | 5 | 022c6d50453b75f236b78a4dd599900b6bf87c30 | 1,296 | RxKotlin-MVVM-Android | Apache License 2.0 |
src/main/kotlin/tests/retest1/task2/ui/screens/BestUi.kt | WoWaster | 461,575,032 | false | null | package tests.retest1.task2.ui.screens
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import kotlinx.coroutines.launch
import tests.retest1.task2.ViewModel
import tests.retest1.task2.ui.components.PostColumnWithWaiting
import tests.retest1.task2.ui.components.TopBar
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun BestUi(viewModel: ViewModel) {
val model by remember { viewModel.model }
LaunchedEffect(Unit) {
launch {
viewModel.getBest()
}
}
Scaffold(topBar = {
TopBar(viewModel)
}) { innerPadding ->
Box(
modifier = Modifier.padding(innerPadding).fillMaxSize(),
contentAlignment = Alignment.TopCenter
) {
PostColumnWithWaiting(model.posts.value)
}
}
}
| 2 | Kotlin | 0 | 0 | 9482493704f4a27cf47fbb03d4c1b1c33035c7f5 | 1,236 | spbu-kotlin-homeworks | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.