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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
source/app/src/main/java/io/github/alanrb/opentv/domain/entities/WatchProviderModel.kt | alanrb | 375,899,889 | false | null | package io.github.alanrb.opentv.domain.entities
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
/**
* Created by Tuong (Alan) on 6/15/21.
* Copyright (c) 2021 Buuuk. All rights reserved.
*/
@Parcelize
data class WatchProviderModel(
@SerializedName("display_priority")
val displayPriority: Int,
@SerializedName("logo_path")
val logoPath: String,
@SerializedName("provider_name")
val providerName: String,
@SerializedName("provider_id")
val providerId: Int
) : Parcelable | 0 | Kotlin | 0 | 0 | b5773464b4e8cd40910ef5575870e4bc3a1a7452 | 576 | open-tv | Apache License 2.0 |
defitrack-rest/defitrack-protocol-service/src/main/java/io/defitrack/protocol/quickswap/staking/QuickswapDualFarmingMarketProvider.kt | decentri-fi | 426,174,152 | false | null | package io.defitrack.protocol.quickswap.staking
import io.defitrack.common.network.Network
import io.defitrack.common.utils.AsyncUtils.lazyAsync
import io.defitrack.common.utils.Refreshable.Companion.refreshable
import io.defitrack.conditional.ConditionalOnCompany
import io.defitrack.erc20.TokenInformationVO
import io.defitrack.evm.contract.ERC20Contract
import io.defitrack.market.farming.FarmingMarketProvider
import io.defitrack.market.farming.domain.FarmingMarket
import io.defitrack.market.lending.domain.PositionFetcher
import io.defitrack.protocol.Company
import io.defitrack.protocol.Protocol
import io.defitrack.protocol.quickswap.QuickswapService
import io.defitrack.protocol.quickswap.apr.QuickswapAPRService
import io.defitrack.protocol.quickswap.contract.DualRewardFactoryContract
import io.defitrack.protocol.quickswap.contract.QuickswapDualRewardPoolContract
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.channelFlow
import kotlinx.coroutines.launch
import org.springframework.stereotype.Service
import java.math.BigDecimal
import java.util.*
@Service
@ConditionalOnCompany(Company.QUICKSWAP)
class QuickswapDualFarmingMarketProvider(
private val quickswapService: QuickswapService,
private val quickswapAPRService: QuickswapAPRService,
) : FarmingMarketProvider() {
val dualStakingFactory = lazyAsync {
DualRewardFactoryContract(
getBlockchainGateway(),
quickswapService.getDualRewardFactory(),
)
}
override suspend fun produceMarkets(): Flow<FarmingMarket> = channelFlow {
val dualPools = dualStakingFactory.await().getStakingTokens().map {
dualStakingFactory.await().stakingRewardsInfoByStakingToken(it)
}
dualPools.map {
QuickswapDualRewardPoolContract(
getBlockchainGateway(),
it
)
}.forEach { pool ->
launch {
try {
val stakedToken = getToken(pool.stakingTokenAddress())
val rewardTokenA = getToken(pool.rewardsTokenAddressA())
val rewardTokenB = getToken(pool.rewardsTokenAddressB())
val ended = Date(pool.periodFinish().toLong() * 1000).before(Date())
val market = create(
identifier = pool.address,
name = "${stakedToken.name} Dual Reward Pool",
stakedToken = stakedToken.toFungibleToken(),
rewardTokens = listOf(
rewardTokenA.toFungibleToken(),
rewardTokenB.toFungibleToken()
),
marketSize = refreshable {
getMarketSize(stakedToken.toFungibleToken(), pool.address)
},
apr = getApr(pool, stakedToken),
balanceFetcher = PositionFetcher(
pool.address,
{ user -> ERC20Contract.balanceOfFunction(user) }
),
rewardsFinished = ended
)
send(market)
} catch (ex: Exception) {
ex.printStackTrace()
}
}
}
}
override fun getProtocol(): Protocol {
return Protocol.QUICKSWAP
}
private suspend fun getApr(
pool: QuickswapDualRewardPoolContract,
stakedTokenInformation: TokenInformationVO
): BigDecimal {
return (quickswapAPRService.getDualPoolAPR(pool.address) + quickswapAPRService.getLPAPR(
stakedTokenInformation.address
))
}
override fun getNetwork(): Network {
return Network.POLYGON
}
} | 53 | null | 7 | 9 | e65843453e4c44f5c2626870ceb923eb7ab3c4d0 | 3,833 | defi-hub | MIT License |
app/src/test/java/com/mateuszcholyn/wallet/frontend/view/screen/backup/backupV1/impo/BackupV1JsonReaderTest.kt | mateusz-nalepa | 467,673,984 | false | {"Kotlin": 643422} | package com.mateuszcholyn.wallet.frontend.view.screen.backup.backupV1.impo
import com.mateuszcholyn.wallet.frontend.view.screen.backup.backupV1.BackupCategoryV1
import com.mateuszcholyn.wallet.frontend.view.screen.backup.backupV1.BackupExpenseV1
import com.mateuszcholyn.wallet.frontend.view.screen.backup.backupV1.BackupWalletV1
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.shouldBe
import kotlinx.coroutines.test.runTest
import org.junit.Test
import java.math.BigDecimal
class BackupV1JsonReaderTest {
@Test
fun shouldReadBackupV1() = runTest {
// given
val backupJson = """{
"categories" : [ {
"id" : "categoryId",
"name" : "categoryName",
"expenses" : [ {
"expenseId" : "expenseId",
"amount" : 50,
"description" : "desc",
"paidAt" : 7
} ]
} ],
"version" : 1
}"""
// when
val backupWalletV1 = BackupV1JsonReader.readBackupWalletV1(backupJson)
// then
val expectedBackupWalletV1 =
BackupWalletV1(
categories = listOf(
BackupCategoryV1(
id = "categoryId",
name = "categoryName",
expenses = listOf(
BackupExpenseV1(
expenseId = "expenseId",
amount = BigDecimal("50"), description = "desc",
paidAt = 7,
)
)
)
)
)
backupWalletV1 shouldBe expectedBackupWalletV1
}
@Test
fun shouldThrowExceptionOnVersionGreaterThan1() = runTest {
// given
val backupJson = """{
"version" : 2
}"""
// when
val throwable =
shouldThrow<BackupWalletV1NotSupportedVersionException> {
BackupV1JsonReader.readBackupWalletV1(backupJson)
}
// then
throwable.message shouldBe "Not supported backup version. Expected 1. Got: 2"
}
} | 0 | Kotlin | 0 | 0 | 3213bca91abc9aae68f43b5b2b627561ee1437b9 | 2,103 | wallet | Apache License 2.0 |
LargeDynamicProject/common/commonA/src/main/java/com/devrel/experiment/large/dynamic/feature/common/a/Foo1836.kt | skimarxall | 212,285,318 | false | null | package com.devrel.experiment.large.dynamic.feature.common.a
annotation class Foo1836Fancy
@Foo1836Fancy
class Foo1836 {
fun foo0(){
Foo1835().foo8()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
fun foo6(){
foo5()
}
fun foo7(){
foo6()
}
fun foo8(){
foo7()
}
} | 1 | null | 1 | 1 | e027d45a465c98c5ddbf33c68deb09a6e5975aab | 403 | app-bundle-samples | Apache License 2.0 |
apps/etterlatte-beregning/src/main/kotlin/sanksjon/SanksjonRoutes.kt | navikt | 417,041,535 | false | {"Kotlin": 5788367, "TypeScript": 1519740, "Handlebars": 21334, "Shell": 12214, "HTML": 1734, "Dockerfile": 676, "CSS": 598, "PLpgSQL": 556} | package no.nav.etterlatte.sanksjon
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.ApplicationCall
import io.ktor.server.application.call
import io.ktor.server.request.receive
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.delete
import io.ktor.server.routing.get
import io.ktor.server.routing.post
import io.ktor.server.routing.route
import io.ktor.util.pipeline.PipelineContext
import no.nav.etterlatte.klienter.BehandlingKlient
import no.nav.etterlatte.libs.ktor.route.BEHANDLINGID_CALL_PARAMETER
import no.nav.etterlatte.libs.ktor.route.behandlingId
import no.nav.etterlatte.libs.ktor.route.withBehandlingId
import no.nav.etterlatte.libs.ktor.token.brukerTokenInfo
import org.slf4j.LoggerFactory
import java.util.UUID
private val logger = LoggerFactory.getLogger("sanksjonRoute")
const val SANKSJONID_CALL_PARAMETER = "id"
inline val PipelineContext<*, ApplicationCall>.sanksjonId: UUID
get() =
call.parameters[SANKSJONID_CALL_PARAMETER].let { UUID.fromString(it) } ?: throw NullPointerException(
"Sanksjon id er ikke i path params",
)
fun Route.sanksjon(
sanksjonService: SanksjonService,
behandlingKlient: BehandlingKlient,
) {
route("/api/beregning/sanksjon/{$BEHANDLINGID_CALL_PARAMETER}") {
get {
withBehandlingId(behandlingKlient, skrivetilgang = false) {
logger.info("Henter sanksjoner for behandlingId=$it")
val sanksjoner = sanksjonService.hentSanksjon(it)
when (sanksjoner) {
null -> call.response.status(HttpStatusCode.NoContent)
else -> call.respond(sanksjoner)
}
}
}
post {
withBehandlingId(behandlingKlient, skrivetilgang = true) {
logger.info("Oppdaterer eller oppretter sanksjon for behandlingId=$it")
val sanksjon = call.receive<LagreSanksjon>()
sanksjonService.opprettEllerOppdaterSanksjon(it, sanksjon, brukerTokenInfo)
call.respond(HttpStatusCode.OK)
}
}
route("{$SANKSJONID_CALL_PARAMETER}") {
delete {
withBehandlingId(behandlingKlient, skrivetilgang = true) {
logger.info("Sletter sanksjon for behandlingId=$it med sanksjonId=$sanksjonId")
sanksjonService.slettSanksjon(behandlingId, sanksjonId, brukerTokenInfo)
call.respond(HttpStatusCode.OK)
}
}
}
}
}
| 9 | Kotlin | 0 | 6 | bfc4d2a6577eb204d0859288a180fa873a75a370 | 2,596 | pensjon-etterlatte-saksbehandling | MIT License |
analyzer/src/main/kotlin/AnalyzerResultBuilder.kt | oss-review-toolkit | 107,540,288 | false | null | /*
* Copyright (C) 2017-2019 HERE Europe B.V.
* Copyright (C) 2020 Bosch.IO GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
* License-Filename: LICENSE
*/
package org.ossreviewtoolkit.analyzer
import org.ossreviewtoolkit.model.AnalyzerResult
import org.ossreviewtoolkit.model.CuratedPackage
import org.ossreviewtoolkit.model.DependencyGraph
import org.ossreviewtoolkit.model.Identifier
import org.ossreviewtoolkit.model.OrtIssue
import org.ossreviewtoolkit.model.Package
import org.ossreviewtoolkit.model.Project
import org.ossreviewtoolkit.model.ProjectAnalyzerResult
import org.ossreviewtoolkit.model.createAndLogIssue
import org.ossreviewtoolkit.model.utils.DependencyGraphConverter
import org.ossreviewtoolkit.utils.core.log
class AnalyzerResultBuilder(private val curationProvider: PackageCurationProvider = PackageCurationProvider.EMPTY) {
private val projects = sortedSetOf<Project>()
private val packages = sortedSetOf<CuratedPackage>()
private val issues = sortedMapOf<Identifier, List<OrtIssue>>()
private val dependencyGraphs = sortedMapOf<String, DependencyGraph>()
fun build() = DependencyGraphConverter.convert(AnalyzerResult(projects, packages, issues, dependencyGraphs))
fun addResult(projectAnalyzerResult: ProjectAnalyzerResult): AnalyzerResultBuilder {
// TODO: It might be, e.g. in the case of PIP "requirements.txt" projects, that different projects with
// the same ID exist. We need to decide how to handle that case.
val existingProject = projects.find { it.id == projectAnalyzerResult.project.id }
if (existingProject != null) {
val existingDefinitionFileUrl = existingProject.let {
"${it.vcsProcessed.url}/${it.definitionFilePath}"
}
val incomingDefinitionFileUrl = projectAnalyzerResult.project.let {
"${it.vcsProcessed.url}/${it.definitionFilePath}"
}
val issue = createAndLogIssue(
source = "analyzer",
message = "Multiple projects with the same id '${existingProject.id.toCoordinates()}' " +
"found. Not adding the project defined in '$incomingDefinitionFileUrl' to the " +
"analyzer results as it duplicates the project defined in " +
"'$existingDefinitionFileUrl'."
)
val projectIssues = issues.getOrDefault(existingProject.id, emptyList())
issues[existingProject.id] = projectIssues + issue
} else {
projects += projectAnalyzerResult.project
addPackages(projectAnalyzerResult.packages)
if (projectAnalyzerResult.issues.isNotEmpty()) {
issues[projectAnalyzerResult.project.id] = projectAnalyzerResult.issues
}
}
return this
}
/**
* Add the given [packageSet] to this builder. This function can be used for packages that have been obtained
* independently of a [ProjectAnalyzerResult].
*/
fun addPackages(packageSet: Set<Package>): AnalyzerResultBuilder {
packages += packageSet.map { pkg ->
val curations = curationProvider.getCurationsFor(pkg.id)
curations.fold(pkg.toCuratedPackage()) { cur, packageCuration ->
log.debug {
"Applying curation '$packageCuration' to package '${pkg.id.toCoordinates()}'."
}
packageCuration.apply(cur)
}
}
return this
}
/**
* Add a [DependencyGraph][graph] with all dependencies detected by the [PackageManager] with the given
* [name][packageManagerName] to the result produced by this builder.
*/
fun addDependencyGraph(packageManagerName: String, graph: DependencyGraph): AnalyzerResultBuilder {
dependencyGraphs[packageManagerName] = graph
return this
}
}
| 270 | null | 174 | 739 | 3765d43a90c2d18fdeddbcf8a500697c9a6b2204 | 4,483 | ort | Apache License 2.0 |
covid19/src/main/java/com/pshetye/covid19/models/Calculated.kt | techeretic | 249,215,978 | false | null | package com.pshetye.covid19.models
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class Calculated(
val cases_per_million_population: Double?,
val death_rate: Double?,
val recovered_vs_death_ratio: Double?,
val recovery_rate: Double?
) | 5 | Kotlin | 0 | 1 | b41539a896e2562890081117a03950ccf53b1e8b | 282 | ApiModeler | MIT License |
sample/src/main/java/com/stfalcon/mvphelpersample/common/di/components/AppComponent.kt | stfalcon-studio | 93,720,449 | false | null | package com.stfalcon.mvphelpersample.common.di.components
import com.stfalcon.mvphelpersample.App
import com.stfalcon.mvphelpersample.common.di.factories.ActivitiesInjectorFactories
import com.stfalcon.mvphelpersample.common.di.factories.FragmentsInjectorFactories
import com.stfalcon.mvphelpersample.common.di.modules.AppModule
import dagger.BindsInstance
import dagger.Component
import dagger.android.support.AndroidSupportInjectionModule
import javax.inject.Singleton
/*
* Created by troy379 on 07.06.17.
*/
@Singleton
@Component(modules = arrayOf(
AndroidSupportInjectionModule::class,
ActivitiesInjectorFactories::class,
FragmentsInjectorFactories::class,
AppModule::class
))
interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance fun application(application: App): Builder
fun build(): AppComponent
}
fun inject(app: App)
} | 1 | null | 7 | 17 | 1e60a39032d62ef80249497b4af3864364b61474 | 924 | MVPHelper | Apache License 2.0 |
src/backend/ci/ext/tencent/process/biz-process-tencent/src/main/kotlin/com/tencent/devops/process/service/pipelineExport/pojo/CheckoutAtomParam.kt | terlinhe | 281,661,499 | true | {"Kotlin": 45598476, "Vue": 6397657, "Java": 5707849, "Go": 3274290, "JavaScript": 1968867, "Lua": 856156, "HTML": 649832, "Dart": 551043, "TypeScript": 411134, "SCSS": 405673, "Shell": 403216, "C++": 149772, "CSS": 95042, "Python": 79300, "Mustache": 65146, "Smarty": 46819, "C": 33502, "Less": 24714, "Dockerfile": 22944, "Makefile": 19753, "Objective-C": 18613, "C#": 9787, "Swift": 8479, "Batchfile": 8243, "Ruby": 6807, "Starlark": 3608, "PowerShell": 840, "VBScript": 189} | package com.tencent.devops.process.service.pipelineExport.pojo
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.tencent.devops.common.api.enums.RepositoryConfig
import com.tencent.devops.common.api.enums.RepositoryType
@JsonInclude(JsonInclude.Include.NON_NULL)
data class CheckoutAtomParam(
/**
* 代码库, 必选, 默认: ID, options: 按代码库选择[ID] | 按代码库别名输入[NAME] | 按仓库URL输入[URL]
*/
var repositoryType: CheckoutRepositoryType? = null,
/**
* 按代码库选择, 当 [repositoryType] = [ID] 时必选
*/
var repositoryHashId: String? = null,
/**
* 按代码库别名输入, 当 [repositoryType] = [NAME] 时必选
*/
var repositoryName: String? = null,
/**
* 代码库链接, 当 [repositoryType] = [URL] 时必选
*/
var repositoryUrl: String? = null,
/**
* 授权类型, 默认: TICKET,
* 当 [repositoryType] = [URL] 时必选, single,
*
* options:
*
* EMPTY[空] | TICKET[凭证] | ACCESS_TOKEN[access token] | USERNAME_PASSWORD[username/password] |
* START_USER_TOKEN[流水线启动人token] | PERSONAL_ACCESS_TOKEN[工蜂personal_access_token]
*/
var authType: AuthType? = null,
var authUserId: String? = null,
/**
* 代码库凭证, 当 [repositoryType] = [URL] 和 [authType] = [TICKET] 时必选
*/
var ticketId: String? = null,
/**
* access token, 当 [repositoryType] = [URL] 和 [authType] = [ACCESS_TOKEN] 时必选
*/
var accessToken: String? = null,
/**
* 工蜂personal_access_token, 当 [repositoryType] = [URL] 和 [authType] = [PERSONAL_ACCESS_TOKEN] 时必选
*/
var personalAccessToken: String? = null,
/**
* username, 当 [repositoryType] = [URL] 和 [authType] = [USERNAME_PASSWORD] 时必选
*/
var username: String? = null,
/**
* password, 当 [repositoryType] = [URL] 和 [authType] = [USERNAME_PASSWORD] 时必选
*/
var password: String? = null,
/**
* 指定拉取方式, 默认: BRANCH, single, options: BRANCH[BRANCH] | TAG[TAG] | COMMIT_ID[COMMIT_ID]
*/
var pullType: String? = null,
/**
* 分支/TAG/COMMIT, 必选, 默认: master
*/
var refName: String? = null,
/**
* 代码保存路径
*/
var localPath: String? = null,
/**
* 拉取策略, 默认: REVERT_UPDATE,
*
* options:
*
* Revert Update[REVERT_UPDATE] | Fresh Checkout[FRESH_CHECKOUT] | Increment Update[INCREMENT_UPDATE]
*/
var strategy: String? = null,
/**
* git fetch的depth参数值
*/
var fetchDepth: Int? = null,
/**
* 启用拉取指定分支, 默认: false
*/
val enableFetchRefSpec: Boolean? = null,
/**
* 插件配置的分支不需要设置,默认会设置.配置的分支必须存在,否则会报错, 当 [enableFetchRefSpec] = [true] 时必选
*/
val fetchRefSpec: String? = null,
/**
* 是否开启Git Lfs, 默认: true
*/
var enableGitLfs: Boolean? = null,
/**
* lfs并发上传下载的数量
*/
val lfsConcurrentTransfers: Int? = null,
/**
* MR事件触发时执行Pre-Merge, 必选, 默认: true
*/
var enableVirtualMergeBranch: Boolean? = null,
/**
* 启用子模块, 默认: true
*/
var enableSubmodule: Boolean? = null,
/**
* 子模块路径当 [enableSubmodule] = [true] 时必选
*/
var submodulePath: String? = null,
/**
* 执行git submodule update后面是否带上--remote参数, 默认: false, 当 [enableSubmodule] = [true] 时必选
*/
var enableSubmoduleRemote: Boolean? = null,
/**
* 执行git submodule update后面是否带上--recursive参数, 默认: true, 当 [enableSubmodule] = [true] 时必选
*/
var enableSubmoduleRecursive: Boolean? = null,
/**
* AutoCrlf配置值, 默认: false, single, options: false[false] | true[true] | input[input]
*/
var autoCrlf: String? = null,
/**
* 是否开启Git Clean, 必选, 默认: true, 当 [strategy] = [REVERT_UPDATE] 时必选
*/
var enableGitClean: Boolean? = null,
/**
* 清理没有版本跟踪的ignored文件, 必选, 默认: true, 当 [strategy] = [REVERT_UPDATE] 和 [enableGitClean] = [true] 时必选
*/
val enableGitCleanIgnore: Boolean? = null,
/**
* 清理没有版本跟踪的嵌套仓库, 必选, 默认: false, 当 [strategy] = [REVERT_UPDATE] 和 [enableGitClean] = [true] 时必选
*/
val enableGitCleanNested: Boolean? = null,
/**
* 拉取代码库以下路径
*/
var includePath: String? = null,
/**
* 排除代码库以下路径
*/
var excludePath: String? = null,
// 非前端传递的参数
@JsonProperty("pipeline.start.type")
val pipelineStartType: String? = null,
val hookEventType: String? = null,
val hookSourceBranch: String? = null,
val hookTargetBranch: String? = null,
val hookSourceUrl: String? = null,
val hookTargetUrl: String? = null,
@JsonProperty("git_mr_number")
val gitMrNumber: String? = null,
// 重试时检出的commitId
var retryStartPoint: String? = null,
/**
* 是否持久化凭证, 默认: true
*/
var persistCredentials: Boolean? = null,
/**
* 是否开启调试, 必选, 默认: false
*/
var enableTrace: Boolean? = null,
/**
* 是否开启部分克隆,部分克隆只有git版本大于2.22.0才可以使用
*/
var enablePartialClone: Boolean? = null,
/**
* 归档的缓存路径
*/
val cachePath: String? = null
) {
constructor(input: GitCodeRepoAtomParam) : this(
pullType = input.pullType?.name,
refName = input.getBranch(),
localPath = input.localPath,
includePath = input.includePath,
excludePath = input.excludePath,
fetchDepth = input.fetchDepth,
strategy = input.strategy?.name,
enableSubmodule = input.enableSubmodule,
submodulePath = input.submodulePath,
enableSubmoduleRemote = input.enableSubmoduleRemote,
enableSubmoduleRecursive = input.enableSubmoduleRecursive,
enableVirtualMergeBranch = input.enableVirtualMergeBranch,
autoCrlf = input.autoCrlf,
enableFetchRefSpec = null,
enableGitClean = input.enableGitClean,
enableGitLfs = input.enableGitLfs,
authType = null,
username = null,
password = null,
ticketId = null,
personalAccessToken = null,
accessToken = null,
persistCredentials = null,
fetchRefSpec = null,
enablePartialClone = null,
cachePath = null,
lfsConcurrentTransfers = null,
enableGitCleanIgnore = input.enableGitCleanIgnore,
enableGitCleanNested = null,
enableTrace = null
)
constructor(input: GitCodeRepoCommonAtomParam) : this(
pullType = input.pullType?.name,
refName = input.getBranch(),
localPath = input.localPath,
includePath = input.includePath,
excludePath = input.excludePath,
fetchDepth = input.fetchDepth,
strategy = input.strategy?.name,
enableSubmodule = input.enableSubmodule,
submodulePath = null,
enableSubmoduleRemote = input.enableSubmoduleRemote,
enableSubmoduleRecursive = null,
enableVirtualMergeBranch = input.enableVirtualMergeBranch,
autoCrlf = null,
enableFetchRefSpec = null,
enableGitClean = input.enableGitClean,
enableGitLfs = input.enableGitLfs,
authType = null,
username = input.username,
password = input.password,
ticketId = input.ticketId,
personalAccessToken = null,
accessToken = input.accessToken,
persistCredentials = null,
fetchRefSpec = null,
enablePartialClone = null,
cachePath = null,
lfsConcurrentTransfers = null,
enableGitCleanIgnore = null,
enableGitCleanNested = null,
enableTrace = null
)
enum class AuthType {
TICKET,
ACCESS_TOKEN,
USERNAME_PASSWORD,
START_USER_TOKEN,
// 工蜂专有授权类型
PERSONAL_ACCESS_TOKEN,
EMPTY,
// 指定授权用户
AUTH_USER_TOKEN
}
enum class CheckoutRepositoryType {
ID,
NAME,
URL
}
@JsonIgnore
fun getRepositoryConfig(): RepositoryConfig {
return RepositoryConfig(
repositoryHashId = repositoryHashId,
repositoryName = repositoryName,
repositoryType = kotlin.runCatching { RepositoryType.valueOf(repositoryType?.name ?: "ID") }
.getOrDefault(RepositoryType.ID)
)
}
}
| 0 | Kotlin | 0 | 0 | dccbcb9f44260f80ebfa1c2dad0c401222f7f93c | 8,182 | bk-ci | MIT License |
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/LegendreQ.kt | Danilo-Araujo-Silva | 271,904,885 | false | null | package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions
import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction
/**
*````
*
* Name: LegendreQ
*
* Full name: System`LegendreQ
*
* LegendreQ[n, z] gives the Legendre function of the second kind Q (z).
* n
* m
* LegendreQ[n, m, z] gives the associated Legendre function of the second kind Q (z).
* Usage: n
*
* Options: None
*
* Listable
* NumericFunction
* Protected
* Attributes: ReadProtected
*
* local: paclet:ref/LegendreQ
* Documentation: web: http://reference.wolfram.com/language/ref/LegendreQ.html
*
* Definitions: None
*
* Own values: None
*
* Down values: None
*
* Up values: None
*
* Sub values: None
*
* Default value: None
*
* Numeric values: None
*/
fun legendreQ(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction {
return MathematicaFunction("LegendreQ", arguments.toMutableList(), options)
}
| 2 | Kotlin | 0 | 3 | 4fcf68af14f55b8634132d34f61dae8bb2ee2942 | 1,442 | mathemagika | Apache License 2.0 |
NewsApp/app/src/main/java/com/example/newsapp/Loginpageactivity.kt | ZinnurovArtur | 345,687,900 | false | null | package com.example.newsapp
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.SignInButton
import com.google.android.gms.common.api.ApiException
import com.google.android.material.snackbar.Snackbar
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.GoogleAuthProvider
/**
* Login page validation of user credentials
*/
class Loginpageactivity : AppCompatActivity() {
private var mAuth = FirebaseAuth.getInstance()
private lateinit var googleSignInClient: GoogleSignInClient
companion object {
private const val RC_SIGN_IN = 120 // Sign in code
}
/**
* initialise elements of layout and initialise Google services
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.loginpage)
val loginfield = findViewById<EditText>(R.id.login_field)
val passwordField = findViewById<EditText>(R.id.text_input_password_toggle)
val button = findViewById<AppCompatButton>(R.id.button_login)
val registerButton = findViewById<AppCompatButton>(R.id.button_register)
val googlebutton = findViewById<SignInButton>(R.id.google_button)
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
googleSignInClient = GoogleSignIn.getClient(this, gso)
button.setOnClickListener { view ->
if (!loginfield.text.toString().isEmpty() && !passwordField.text.toString().isEmpty()) {
mAuth.signInWithEmailAndPassword(
loginfield.text.toString(),
passwordField.text.toString()
).addOnCompleteListener(
this
) { task ->
if (task.isSuccessful) {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
/**
* for email verification uncomment because email shoudl be real
*
*
if (user!!.isEmailVerified) {
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
else{
Toast.makeText(this, "Email is not verified", Toast.LENGTH_LONG).show()
}
**/
} else {
Snackbar.make(view, "Something went wrong", Snackbar.LENGTH_LONG).show()
}
}
} else {
Snackbar.make(view, "Cannot be null ", Snackbar.LENGTH_LONG).show()
}
}
// start register activity to start registration
registerButton.setOnClickListener { view ->
val intent = Intent(this, RegisterActivity::class.java)
startActivity(intent)
}
//Sign in by google account button
googlebutton.setOnClickListener { view ->
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
}
/**
* Asynchronous call to get result of registration
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
if (task.isSuccessful) {
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d("auth", "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w("auth", "Google sign in failed", e)
}
} else {
Log.w("auth", "Google sign in failed")
}
}
}
/**
* Sign in by Google
* @param idToken unique device token
*
* This implementation was made by Firebase documentation
*
*/
private fun firebaseAuthWithGoogle(idToken: String) {
val credential = GoogleAuthProvider.getCredential(idToken, null)
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d("auth", "signInWithCredential:success")
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
} else {
// If sign in fails, display a message to the user.
Log.w("auth", "signInWithCredential:failure", task.exception)
}
}
}
} | 0 | Kotlin | 0 | 1 | d3f4881402fc20ab5bf9858c5bc6020b3d93bc19 | 5,768 | NOVOSTI.IO | MIT License |
compiler-plugin/src/main/kotlin/com/lhwdev/ktui/plugin/compiler/util/global.kt | ppwasin | 328,231,754 | true | {"Kotlin": 516602} | package com.lhwdev.ktui.plugin.compiler.util
import org.jetbrains.kotlin.backend.common.extensions.IrPluginContext
@PublishedApi
internal var providedContext: IrPluginContext? = null
val pluginContext: IrPluginContext get() = providedContext!!
inline val context get() = pluginContext
inline val builtIns get() = context.builtIns
inline val irBuiltIns get() = context.irBuiltIns
inline fun provideContext(context: IrPluginContext, block: () -> Unit) {
providedContext = context
try {
block()
} finally {
providedContext = null
}
}
| 0 | null | 0 | 0 | a2559a1c036d72eb2b2a26616bef1df07dcf7671 | 547 | kt-ui | Apache License 2.0 |
Foodtruck/app/src/main/java/com/example/foodtruck/ui/vendor/fragments/FoodtruckCreationScreen.kt | Build-Week-FoodTruck-TrackR | 215,889,839 | false | null | package com.example.foodtruck.ui.vendor.fragments
import android.app.Dialog
import android.os.Bundle
import android.view.*
import android.widget.CheckBox
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.DialogFragment
import com.example.foodtruck.R
import com.example.foodtruck.data.source.local.model.Foodtruck
import com.example.foodtruck.data.source.local.model.Menu
import com.example.foodtruck.util.createAlert
import com.example.foodtruck.util.setVisibilityToGone
import com.example.foodtruck.util.setVisibilityToVisible
import com.jaredrummler.materialspinner.MaterialSpinner
import kotlinx.android.synthetic.main.fullscreen_dialog_foodtruck_creation.*
class FoodtruckCreationScreen: DialogFragment(), Toolbar.OnMenuItemClickListener, MenuCreationScreen.MenuItemReceiver {
lateinit var listener: FoodtruckReceiver
private var createdMenu: Menu? = null
private var currentPosition: Int? = null
interface FoodtruckReceiver{
fun receiveFoodtruck(foodtruck: Foodtruck, tag: String, position: Int?)
}
override fun receivePotentialMenu(menu: Menu?) {
menu?.let{
createdMenu = it
//successfully created a new menu, hide create button, show view and delete buttons
btn_create_menu.setVisibilityToGone()
btn_edit_menu.setVisibilityToVisible()
btn_delete_menu.setVisibilityToVisible()
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setFoodtruckLayout()
top_toolbar.setNavigationOnClickListener {
context!!.createAlert({d, i -> dismiss() }, {d, i-> }).show() //stay on the fragment
}
top_toolbar.setOnMenuItemClickListener(this)
btn_create_menu.setOnClickListener {
val m = MenuCreationScreen()
m.listener = this
m.show(fragmentManager!!, "menu creation")
}
btn_delete_menu.setOnClickListener {
//Are you sure you are deleting the menu?
context!!.createAlert({d, i -> createdMenu = null
btn_create_menu.setVisibilityToVisible()
btn_edit_menu.setVisibilityToGone()
btn_delete_menu.setVisibilityToGone()}, { d, i-> }).show()
}
btn_edit_menu.setOnClickListener {
//we definitely have a menu, that we can load into the menu creation screen
val m = MenuCreationScreen()
m.listener = this
val bundle = Bundle()
bundle.putSerializable("menu_edit", createdMenu)
m.arguments = bundle
m.show(fragmentManager!!, "edit menu")
}
}
private fun setFoodtruckLayout() {
val bundle = arguments
if(bundle != null){
val foodtruck = bundle.get("foodTruckToEdit") as Foodtruck
et_foodtruck_name.setText(foodtruck.name)
et_foodtruck_model.setText(foodtruck.cuisines)
foodtruck.menu?.let{
createdMenu = it
btn_create_menu.setVisibilityToGone()
btn_edit_menu.setVisibilityToVisible()
btn_delete_menu.setVisibilityToVisible()
}
currentPosition = bundle.get("foodTruckToEditPosition") as Int
}
}
override fun onMenuItemClick(item: MenuItem?): Boolean {
val foodtruckName = et_foodtruck_name.text.toString()
val foodtruckModel = et_foodtruck_model.text.toString()
val mondayCheckbox = grid_layout.findViewById<CheckBox>(R.id.checkbox_monday)
val tuesdayCheckbox = grid_layout.findViewById<CheckBox>(R.id.checkbox_tuesday)
val wednesdayCheckbox = grid_layout.findViewById<CheckBox>(R.id.checkbox_wednesday)
val thursdayCheckbox = grid_layout.findViewById<CheckBox>(R.id.checkbox_thursday)
val fridayCheckbox = grid_layout.findViewById<CheckBox>(R.id.checkbox_friday)
val saturdayCheckbox = grid_layout.findViewById<CheckBox>(R.id.checkbox_saturday)
val sundayCheckbox = grid_layout.findViewById<CheckBox>(R.id.checkbox_sunday)
if(foodtruckName == ""){
textInputLayout.error = "Food truck must have a name."
}
if(foodtruckModel == ""){
text_input_truck_model.error = "Food truck must have cuisines."
}
if(foodtruckName != "" && foodtruckModel != ""){
//pass this data back to the activity
val foodtruck = Foodtruck(foodtruckName, foodtruckModel, 0.0, 0.0, createdMenu)
listener.receiveFoodtruck(foodtruck, tag!!, currentPosition)
dismiss()
}
return false
}
override fun onCreate(savedInstanceState: Bundle?) {
setStyle(STYLE_NORMAL, R.style.AppTheme_FullScreenDialog)
super.onCreate(savedInstanceState)
}
override fun onStart() {
super.onStart()
if(dialog != null){
val width = ViewGroup.LayoutParams.MATCH_PARENT
val height = ViewGroup.LayoutParams.MATCH_PARENT
(dialog as Dialog).window!!.setLayout(width, height)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
super.onCreateView(inflater, container, savedInstanceState)
val view = inflater.inflate(R.layout.fullscreen_dialog_foodtruck_creation, container, false)
val spinnerList = listOf<MaterialSpinner>(view.findViewById(R.id.spinner1), view.findViewById(R.id.spinner2),
view.findViewById(R.id.spinner3), view.findViewById(R.id.spinner4), view.findViewById(R.id.spinner5), view.findViewById(R.id.spinner6)
, view.findViewById(R.id.spinner7), view.findViewById(R.id.spinner8), view.findViewById(R.id.spinner9), view.findViewById(R.id.spinner10),
view.findViewById(R.id.spinner11), view.findViewById(R.id.spinner12), view.findViewById(R.id.spinner13), view.findViewById(R.id.spinner14))
spinnerList.forEachIndexed { index, materialSpinner ->
setSpinnerItemsAndIndex(materialSpinner, (index+1)%2 == 0)
}
return view
}
private fun setSpinnerItemsAndIndex(spinner: MaterialSpinner, isEven: Boolean){
spinner.setItems(
"00:00",
"01:00",
"02:00",
"03:00",
"04:00",
"05:00",
"06:00",
"07:00",
"08:00",
"09:00",
"10:00",
"11:00",
"12:00",
"13:00",
"14:00",
"15:00",
"16:00",
"17:00",
"18:00",
"19:00",
"20:00",
"21:00",
"22:00",
"23:00")
if(!isEven){
spinner.selectedIndex = 9
} else{
spinner.selectedIndex = 21
}
}
} | 0 | Kotlin | 1 | 0 | 76b215d943e9f9d0331cfd221bc5cc5800663554 | 7,035 | AND | MIT License |
core/common/src/main/java/com/lelestacia/lelenime/core/common/itemAnime/AnimeList.kt | Kamil-Malik | 628,208,142 | false | null | package com.harissabil.anidex.ui.components.items
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.ColorMatrix
import androidx.compose.ui.graphics.FilterQuality
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.CachePolicy
import coil.request.ImageRequest
import com.harissabil.anidex.R
import com.harissabil.anidex.data.remote.anime.dto.Data
import com.harissabil.anidex.ui.theme.spacing
@Composable
fun AnimeList(
anime: Data,
onAnimeClicked: (String) -> Unit,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.fillMaxWidth()
.clickable { onAnimeClicked(anime.mal_id.toString()) }
.padding(8.dp)
) {
AsyncImage(
model = ImageRequest.Builder(context = LocalContext.current)
.data(data = anime.images.jpg.image_url)
.memoryCachePolicy(CachePolicy.ENABLED)
.memoryCacheKey(anime.mal_id.toString())
.diskCachePolicy(CachePolicy.ENABLED)
.diskCacheKey(anime.mal_id.toString())
.allowHardware(false)
.allowRgb565(true)
.crossfade(enable = true)
.build(),
contentDescription = "Cover Image from Anime ${anime.title}",
contentScale = ContentScale.Crop,
colorFilter = ColorFilter.colorMatrix(
colorMatrix = ColorMatrix().apply {
setToSaturation(sat = 0.85F)
}
),
filterQuality = FilterQuality.Medium,
modifier = Modifier
.width(100.dp)
.aspectRatio(5f / 7f)
.clip(RoundedCornerShape(MaterialTheme.spacing.small))
.clickable {
onAnimeClicked(anime.mal_id.toString())
}
)
Column(
modifier = Modifier
.padding(
start = 16.dp,
end = 8.dp
)
) {
Text(
text = anime.title,
style = MaterialTheme.typography.titleMedium,
fontWeight = FontWeight.Bold,
maxLines = 2,
overflow = TextOverflow.Ellipsis
)
Row(
modifier = Modifier.padding(top = 8.dp)
) {
Column(
verticalArrangement = Arrangement.spacedBy(4.dp),
modifier = Modifier.padding(end = 8.dp)
) {
Text(
text = "Score",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold
)
Text(
text = "Episode",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold
)
Text(
text = "Status",
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.Bold
)
}
Column(
verticalArrangement = Arrangement.spacedBy(4.dp)
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(
id = R.string.information_value,
(anime.score ?: 0)
),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold
)
Icon(
imageVector = Icons.Default.Star,
contentDescription = "Star Icon",
modifier = Modifier
.padding(start = 2.dp)
.size(16.dp)
)
}
Text(
text =
if (anime.episodes != null) {
stringResource(
id = R.string.information_value,
anime.episodes.toString()
)
} else {
stringResource(id = R.string.information_value, "Unknown")
},
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold
)
Text(
text = stringResource(id = R.string.information_value, anime.status),
style = MaterialTheme.typography.titleSmall,
fontWeight = FontWeight.SemiBold
)
}
}
}
}
} | 1 | null | 0 | 7 | 4bb4ff8a3e0c1137fe815ac7ce82babcb13cc5d1 | 6,260 | lelenime | Apache License 2.0 |
src/main/kotlin/org/randomcat/agorabot/commands/Archive.kt | randomnetcat | 291,139,813 | false | {"Kotlin": 799573, "Nix": 17514} | @file:OptIn(ExperimentalPathApi::class)
package org.randomcat.agorabot.commands
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.toImmutableList
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.channel.concrete.Category
import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel
import net.dv8tion.jda.api.utils.SplitUtil
import org.randomcat.agorabot.commands.base.*
import org.randomcat.agorabot.commands.base.requirements.discord.BaseCommandExecutionReceiverGuilded
import org.randomcat.agorabot.commands.base.requirements.discord.currentChannel
import org.randomcat.agorabot.commands.base.requirements.discord.currentGuild
import org.randomcat.agorabot.commands.base.requirements.discord.currentMessageEvent
import org.randomcat.agorabot.commands.base.requirements.discord_ext.InGuild
import org.randomcat.agorabot.commands.base.requirements.permissions.permissions
import org.randomcat.agorabot.commands.base.requirements.permissions.senderHasPermission
import org.randomcat.agorabot.permissions.BotScope
import org.randomcat.agorabot.permissions.GuildScope
import org.randomcat.agorabot.permissions.LogicalOrPermission
import org.randomcat.agorabot.util.DiscordPermission
import org.randomcat.agorabot.util.await
import org.slf4j.LoggerFactory
import java.nio.file.Files
import java.nio.file.Path
import java.time.Instant
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.copyToRecursively
private val ARCHIVE_PERMISSION = GuildScope.command("archive")
private val FORCE_PERMISSION = BotScope.admin()
private val OVERALL_PERMISSION = LogicalOrPermission(listOf(ARCHIVE_PERMISSION, FORCE_PERMISSION))
private val LOGGER = LoggerFactory.getLogger("AgoraBotArchiveCommand")
interface DiscordArchiver {
suspend fun createArchiveFrom(
guild: Guild,
channelIds: Set<String>,
): Path
/**
* The file extension of the resulting archive format, or null if the archiver produces a directory rather than a
* file.
*/
val archiveExtension: String?
}
private fun formatCurrentDate(): String {
return DateTimeFormatter.ISO_LOCAL_DATE_TIME.withZone(ZoneOffset.UTC).format(Instant.now())
}
private sealed interface RecursiveChannelsResult {
data class Success(val channels: ImmutableList<GuildChannel>) : RecursiveChannelsResult
data class NotFound(val channelId: String) : RecursiveChannelsResult
}
private fun recursiveChannels(guild: Guild, channelIds: Set<String>): RecursiveChannelsResult {
val out = mutableListOf<GuildChannel>()
for (channelId in channelIds) {
val channel = guild.getGuildChannelById(channelId) ?: return RecursiveChannelsResult.NotFound(channelId)
out.add(channel)
if (channel is Category) {
when (val subResult = recursiveChannels(guild, channel.channels.map { it.id }.toSet())) {
is RecursiveChannelsResult.Success -> out.addAll(subResult.channels)
is RecursiveChannelsResult.NotFound -> return subResult
}
}
}
return RecursiveChannelsResult.Success(out.distinctBy { it.id }.toImmutableList())
}
class ArchiveCommand(
strategy: BaseCommandStrategy,
private val archiver: DiscordArchiver,
private val localStorageDir: Path,
) : BaseCommand(strategy) {
init {
Files.createDirectories(localStorageDir)
}
override fun BaseCommandImplReceiver.impl() {
matchFirst {
args(RemainingStringArgs("marker_or_id"))
.requires(InGuild)
.permissions(OVERALL_PERMISSION) cmd@{ (args) ->
val isStoreLocally = args.contains("store_locally")
val isAll = args.contains("all")
val isForce = args.contains("force")
val rawIds = args - listOf("store_locally", "all", "force")
if (!isStoreLocally) {
respond("Uploading archives is currently not supported")
return@cmd
}
if (isStoreLocally && !senderHasPermission(BotScope.admin())) {
respond("Archives can only be stored locally by bot admins.")
return@cmd
}
if (isForce) {
if (!senderHasPermission(FORCE_PERMISSION)) {
respond("Only a bot admin can forcibly archive a server.")
return@cmd
}
} else {
if (!senderHasPermission(ARCHIVE_PERMISSION)) {
respond("You do not have permission: need $ARCHIVE_PERMISSION")
return@cmd
}
}
if (rawIds.isEmpty() && !isAll) {
respond("Must provide IDs or \"all\".")
return@cmd
}
val channels = if (isAll) {
currentGuild.channels
} else {
when (val channelResult = recursiveChannels(currentGuild, channelIds = rawIds.toSet())) {
is RecursiveChannelsResult.Success -> channelResult.channels
is RecursiveChannelsResult.NotFound -> {
respond("Unknown channel ID: ${channelResult.channelId}")
return@cmd
}
}
}
doArchive(
channels = channels.distinctBy { it.id },
storeArchiveResult = { path ->
if (isStoreLocally) {
withContext(Dispatchers.IO) {
val extension = archiver.archiveExtension
val fileName = if (extension != null) {
"archive_${formatCurrentDate()}.${archiver.archiveExtension}"
} else {
"archive_${formatCurrentDate()}"
}
path.copyToRecursively(localStorageDir.resolve(fileName), followLinks = false)
respond("Stored archive locally at $fileName")
LOGGER.info("Stored archive of guild ${currentGuild.id} (${currentGuild.name}) at $fileName")
}
} else {
TODO("uploading not supported")
}
},
force = isForce,
)
}
}
}
private suspend fun BaseCommandExecutionReceiverGuilded.doArchive(
channels: List<GuildChannel>,
storeArchiveResult: suspend BaseCommandExecutionReceiverGuilded.(Path) -> Unit,
force: Boolean,
) {
val member = currentMessageEvent.member ?: error("Member should exist because this is in a Guild")
if (!force) {
for (channel in channels) {
if (
!member.hasPermission(channel, DiscordPermission.VIEW_CHANNEL) ||
!member.hasPermission(channel, DiscordPermission.MESSAGE_HISTORY)
) {
respond("You do not have permission to read in the channel <#${channel.id}>.")
return
}
}
}
val channelNamesString = channels.joinToString(", ") { "<#${it.id}>" }
val statusParts = SplitUtil.split(
"Running archive job for channels $channelNamesString...",
Message.MAX_CONTENT_LENGTH,
true,
SplitUtil.Strategy.onChar(',')
)
val statusMessage = currentChannel.sendMessage(statusParts.first()).await()
for (part in statusParts.drop(1)) {
currentChannel.sendMessage(part).await()
}
fun markFailed() {
statusMessage.editMessage("Archive job failed!").queue()
}
fun markFailedWith(e: Throwable) {
markFailed()
LOGGER.error("Error while archiving channels $channelNamesString", e)
}
try {
withContext(Dispatchers.IO) {
try {
storeArchiveResult(
archiver.createArchiveFrom(
guild = currentGuild,
channelIds = channels.map { it.id }.toSet(),
),
)
// Always replace start with a shorter string so that length cannot be an issue
statusMessage.editMessage(
statusMessage.contentRaw.replace(
"Running archive job",
"Finished archive"
).replace("...", "!")
).await()
} catch (t: Throwable) {
markFailedWith(t)
}
}
} catch (e: Exception) {
markFailedWith(e)
}
return
}
}
| 0 | Kotlin | 3 | 6 | b2a6e64b81d8678cd5c99e6355f68b757725e427 | 9,597 | AgoraBot | MIT License |
src/main/kotlin/com/tuk/oriddle/quizGame/application/port/in/QuizGameUseCase.kt | Team-Oriddle | 731,663,342 | false | {"Kotlin": 111258} | package com.tuk.oriddle.quizGame.application.port.`in`
import com.tuk.oriddle.quizGame.adapter.`in`.message.dto.ChatReceiveMessage
import com.tuk.oriddle.quizGame.adapter.`in`.message.dto.CheckAnswerMessage
import com.tuk.oriddle.quizRoom.domain.QuizRoom
import com.tuk.oriddle.user.domain.UserId
import java.util.*
interface QuizGameUseCase {
fun initQuizRoomProgressData(quizRoom: QuizRoom)
fun checkAnswer(quizRoomId: UUID, answerMessage: CheckAnswerMessage, userId: UserId)
fun sendChatMessage(quizRoomId: UUID, message: ChatReceiveMessage, userId: UserId)
}
| 2 | Kotlin | 1 | 0 | 0a4392b6290cffd0fb9e32fe95032d7baf9a6bf9 | 577 | oriddle-backend | MIT License |
app/src/main/java/com/app/freshworkstudio/data/repository/repositoryService/GiFavouriteRepository.kt | keyur9779 | 441,148,447 | false | {"Kotlin": 127655, "Java": 1411} | package com.app.freshworkstudio.data.repository.repositoryService
import com.app.freshworkstudio.model.entity.GifFavourite
import kotlinx.coroutines.flow.Flow
/**
* Service method for favourite gif list
*
* */
interface GiFavouriteRepository {
suspend fun delete(data: GifFavourite)
fun loadFavGif(success: () -> Unit): Flow<List<GifFavourite>>
} | 0 | Kotlin | 0 | 0 | cd87a22403ad295e005e443911f617e8123ae1f6 | 359 | KotlinArchitecture | Apache License 2.0 |
core/time/time-impl/src/main/kotlin/com/francescsoftware/weathersample/core/time/impl/ZoneIdProviderImpl.kt | fvilarino | 355,724,548 | false | {"Kotlin": 574824, "Shell": 60} | package com.francescsoftware.weathersample.core.time.impl
import com.francescsoftware.weathersample.core.time.api.ZoneIdProvider
import java.time.ZoneId
import javax.inject.Inject
internal class ZoneIdProviderImpl @Inject constructor() : ZoneIdProvider {
override val zoneId: ZoneId
get() = ZoneId.systemDefault()
}
| 10 | Kotlin | 1 | 33 | ae2e6ad24f6dacb2f6211cdf7684928264f5ebd7 | 330 | Weather-Sample | Apache License 2.0 |
demo/src/main/java/com/rozetkapay/demo/RozetkaPayDemoApp.kt | rozetkapay | 869,498,229 | false | {"Kotlin": 223681} | package com.rozetkapay.demo
import android.app.Application
import com.rozetkapay.sdk.RozetkaPaySdk
import com.rozetkapay.sdk.init.RozetkaPaySdkMode
import com.rozetkapay.sdk.init.RozetkaPaySdkValidationRules
class RozetkaPayDemoApp : Application() {
override fun onCreate() {
super.onCreate()
RozetkaPaySdk.init(
appContext = this,
mode = RozetkaPaySdkMode.Development,
enableLogging = true,
validationRules = RozetkaPaySdkValidationRules()
)
}
} | 0 | Kotlin | 0 | 0 | da2574a3a8a6a9e2f04a2b47a75221c8d4c8faa8 | 529 | android-sdk | MIT License |
src/main/kotlin/org/emgen/ExpressionParser.kt | emilancius | 234,365,097 | false | null | package org.emgen
import java.math.BigDecimal
import java.util.*
import kotlin.collections.ArrayList
import org.emgen.extensions.StringExtensions.charIn
import org.emgen.extensions.StringExtensions.remove
import org.emgen.extensions.CharExtensions.operator
import org.emgen.extensions.CharExtensions.toOperator
class ExpressionParser {
companion object {
fun parseExpression(expression: String): Expression {
val output = ArrayList<Token>()
val stack = Stack<Operator>()
for (token in createTokens(expression.remove(" "))) {
if (token is Operator) {
if (token == Operator.LEFT_PARENTHESIS) {
stack.push(token)
} else if (token == Operator.RIGHT_PARENTHESIS) {
for (index in stack.indices) {
if (stack.empty() || stack.peek() == Operator.LEFT_PARENTHESIS) {
break
}
output.add(stack.pop())
}
stack.pop()
} else {
for (index in stack.indices) {
if (
stack.empty() ||
stack.peek() == Operator.LEFT_PARENTHESIS ||
stack.peek() == Operator.RIGHT_PARENTHESIS
) {
break
}
val precedence = token.precedence - stack.peek().precedence
if (
(Associativity.LEFT.isAssociative(token) && precedence < 1) ||
(Associativity.RIGHT.isAssociative(token) && precedence < 0)
) {
output.add(stack.pop())
}
}
stack.push(token)
}
} else {
output.add(token)
}
}
repeat(stack.size) { output.add(stack.pop()) }
return Expression(output)
}
private fun createTokens(expression: String): List<Token> = expression
.toCharArray()
.mapIndexed { index, char ->
if (char.operator() && !isUnarySign(index, expression)) {
" $char "
} else {
char.toString()
}
}
.joinToString("")
.replace(Regex("\\s+"), " ")
.trim()
.split(" ")
.map {
if (it.length == 1 && it[0].operator()) {
it[0].toOperator()
} else {
Operand(BigDecimal(it))
}
}
private fun isUnarySign(index: Int, expression: String): Boolean =
expression.charIn(index) == '-' && !numeric(expression.charIn(index - 1)) && numeric(expression.charIn(index + 1))
private fun numeric(char: Char?): Boolean = char != null && char in '0'..'9'
}
}
| 1 | Kotlin | 2 | 0 | f73f335268f6cc41f6ccb18c69036081514c3aa5 | 3,234 | sono-core | MIT License |
frontend/app/src/main/java/kr/ac/kpu/lbs_platform/fragment/FollowingFragment.kt | Lenend-KPU | 323,903,267 | false | null | package kr.ac.kpu.lbs_platform.fragment
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kr.ac.kpu.lbs_platform.R
import kr.ac.kpu.lbs_platform.adapter.FollowingAdapter
import kr.ac.kpu.lbs_platform.global.Profile
import kr.ac.kpu.lbs_platform.global.RequestHelper
import kr.ac.kpu.lbs_platform.poko.remote.FriendRequest
class FollowingFragment(val selectedProfile: kr.ac.kpu.lbs_platform.poko.remote.Profile) : Fragment(), Invalidatable {
lateinit var followingRecyclerView: RecyclerView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val inflated = inflater.inflate(R.layout.fragment_follower, container, false)
followingRecyclerView = inflated.findViewById(R.id.followerRecyclerView)
followingRecyclerView.layoutManager = LinearLayoutManager(this.activity)
getFriendsFromServer(followingRecyclerView)
return inflated
}
fun getFriendsFromServer(recyclerView: RecyclerView) {
Log.i(this::class.java.name, "getFriendsFromServer")
val profileNumber = selectedProfile!!.pk
RequestHelper.Builder(FriendRequest::class)
.apply {
this.currentFragment = this@FollowingFragment
this.destFragment = null
this.urlParameter = "profiles/$profileNumber/friends/"
this.method = com.android.volley.Request.Method.GET
this.onSuccessCallback = {
Log.i("FollowerFragment", it.toString())
recyclerView.adapter = FollowingAdapter(it, this@FollowingFragment)
}
}
.build()
.request()
}
override fun invalidateRecyclerView() {
getFriendsFromServer(followingRecyclerView)
}
} | 0 | Kotlin | 1 | 16 | 76807894f65be1e9c9905ceb3c91b9235b1abf3e | 2,224 | LBS-Platform | MIT License |
app/src/main/java/ro/alexmamo/firemag/presentation/shopping_cart/components/ShoppingCartTopBar.kt | alexmamo | 569,800,514 | false | null | package ro.alexmamo.firemag.presentation.shopping_cart.components
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.colorResource
import ro.alexmamo.firemag.R
import ro.alexmamo.firemag.core.AppConstants.SHOPPING_CART_SCREEN
@Composable
@ExperimentalMaterial3Api
fun ShoppingCartTopBar(
navigateBack: () -> Unit
) {
TopAppBar(
title = {
Text(
text = SHOPPING_CART_SCREEN,
color = Color.White
)
},
navigationIcon = {
IconButton(
onClick = navigateBack
) {
Icon(
imageVector = Icons.Filled.ArrowBack,
contentDescription = null
)
}
},
colors = TopAppBarDefaults.smallTopAppBarColors(
containerColor = colorResource(R.color.primary),
navigationIconContentColor = Color.White,
actionIconContentColor = Color.White
)
)
} | 0 | Kotlin | 1 | 9 | d648c129c9d9f0841b898b6c178170e404f35024 | 1,195 | FireMag | Apache License 2.0 |
app/src/main/java/com/aleksandrovych/purchasepal/whatToBuy/add/AddWhatToBuyViewModel.kt | DreHubOff | 766,229,895 | false | {"Kotlin": 68684} | package com.aleksandrovych.purchasepal.whatToBuy.add
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.aleksandrovych.purchasepal.domain.SaveWhatToBuyInteractor
import com.aleksandrovych.purchasepal.whatToBuy.WhatToBuy
import com.aleksandrovych.purchasepal.whatToBuy.suggestion.WhatToBuySuggestion
import com.aleksandrovych.purchasepal.whatToBuy.suggestion.WhatToBuySuggestionDao
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import javax.inject.Inject
@HiltViewModel
class AddWhatToBuyViewModel @Inject constructor(
private val whatToBuySuggestionDao: WhatToBuySuggestionDao,
private val saveWhatToBuyInteractor: SaveWhatToBuyInteractor,
) : ViewModel() {
private val coroutineExceptionHandler: CoroutineExceptionHandler =
CoroutineExceptionHandler { _, throwable -> throwable.printStackTrace() }
val suggestionsFlow: MutableStateFlow<List<String>> = MutableStateFlow(emptyList())
fun requestSuggestions(input: String?) {
viewModelScope.launch(coroutineExceptionHandler + Dispatchers.Default) {
suggestionsFlow.emit(
if (input.isNullOrEmpty()) {
emptyList()
} else {
whatToBuySuggestionDao
.get(WhatToBuySuggestion.processInput(input))
.map(WhatToBuySuggestion::title)
}
)
}
}
fun saveNewItem(item: WhatToBuy, dismissCallback: () -> Unit) {
viewModelScope.launch(coroutineExceptionHandler + Dispatchers.Default) {
saveWhatToBuyInteractor(item)
withContext(Dispatchers.Main) { dismissCallback() }
}
}
} | 1 | Kotlin | 0 | 0 | 1712cde2dc746588b934654c7b3d4794ead9aa31 | 1,916 | Purchase-pal | MIT License |
src/main/kotlin/org/microjservice/lark/api/MessageApi.kt | MicroJService | 358,535,254 | false | null | package org.microjservice.lark.api
import io.micronaut.http.MediaType
import io.micronaut.http.annotation.Body
import io.micronaut.http.annotation.Post
import io.micronaut.http.annotation.QueryValue
import io.micronaut.http.client.annotation.Client
import org.microjservice.lark.api.models.MessageRequest
/**
* Message API
*
* @author <NAME>
* @since 0.1.0
*/
@Client(value = "\${lark.endpoint}/im/v1")
interface MessageApi {
@Post(value = "/messages", produces = [MediaType.APPLICATION_JSON])
fun send(@QueryValue("receive_id_type") receiveIdType: MessageRequest.ReceiveIdType, @Body messageRequest: MessageRequest)
} | 1 | Kotlin | 1 | 2 | 6f4d4befc3373b486616c19a632e2c9bbb8997c6 | 634 | lark-api | Apache License 2.0 |
coroutines/src/main/kotlin/com/treefrogapps/kotlin/coroutines/flow/FlowExtensions.kt | TreeFrogApps | 299,406,523 | false | null | package com.treefrogapps.kotlin.coroutines.flow
import kotlinx.coroutines.flow.*
fun <T> Flow<T>.first(): Flow<T> = take(1)
inline fun <T> Flow<T>.firstIf(crossinline block: suspend (T) -> Boolean): Flow<T> = take(1).filter(block)
inline fun <T> Flow<T>.firstOrDefault(default: T, crossinline block: suspend (T) -> Boolean): Flow<T> =
take(1)
.filter(block)
.onEmpty { emit(default) }
fun <T> Flow<T>.doOnSubscribe(action: () -> Unit): Flow<T> = flow {
action()
collect { emit(it) }
}
fun <T> Flow<T>.doOnComplete(action: () -> Unit): Flow<T> = flow {
emitAll(this@doOnComplete)
action()
}
fun <T> Flow<T>.doFinally(action: () -> Unit): Flow<T> = flow {
try {
emitAll(this@doFinally)
} finally {
action()
}
}
fun <T> Flow<T>.andThen(other: Flow<T>): Flow<T> = onCompletion { if(it == null) emitAll(other) }
/**
* Chain flows together that will run sequentially in the order provided
*
* @param links the array of [Flow] to concat
* @return the first [Flow] element with
*/
fun <T> chainFlow(vararg links: Flow<T>): Flow<T> = flow { links.forEach { emitAll(it) } }
fun <T> Flow<T>.doOnEach(action: (t: T) -> Unit): Flow<T> = flow {
collect { action(it); emit(it) }
}
fun <T> Flow<T>.doAfterEach(action: (t: T) -> Unit): Flow<T> = flow {
collect { emit(it); action(it) }
}
/**
* Returns a [Flow] whose values are generated with [transform] function by combining
* the most recently emitted values by each flow.
*/
fun <T1, T2, T3, T4, T5, R> combine(
flow: Flow<T1>,
flow2: Flow<T2>,
flow3: Flow<T3>,
flow4: Flow<T4>,
flow5: Flow<T5>,
transform: suspend (T1, T2, T3, T4, T5) -> R
): Flow<R> = combine(
combine(flow, flow2, flow3, ::Triple),
combine(flow4, flow5, ::Pair)
) { t1, t2 ->
transform(
t1.first,
t1.second,
t1.third,
t2.first,
t2.second
)
}
fun <T1, T2, T3, T4, T5, T6, R> combine(
flow: Flow<T1>,
flow2: Flow<T2>,
flow3: Flow<T3>,
flow4: Flow<T4>,
flow5: Flow<T5>,
flow6: Flow<T6>,
transform: suspend (T1, T2, T3, T4, T5, T6) -> R
): Flow<R> = combine(
combine(flow, flow2, flow3, ::Triple),
combine(flow4, flow5, flow6, ::Triple)
) { t1, t2 ->
transform(
t1.first,
t1.second,
t1.third,
t2.first,
t2.second,
t2.third
)
}
fun <T1, T2, T3, T4, T5, T6, T7, R> combine(
flow: Flow<T1>,
flow2: Flow<T2>,
flow3: Flow<T3>,
flow4: Flow<T4>,
flow5: Flow<T5>,
flow6: Flow<T6>,
flow7: Flow<T7>,
transform: suspend (T1, T2, T3, T4, T5, T6, T7) -> R
): Flow<R> = combine(
combine(flow, flow2, flow3, ::Triple),
combine(flow4, flow5, flow6, ::Triple),
flow7,
) { t1, t2, t3 ->
transform(
t1.first,
t1.second,
t1.third,
t2.first,
t2.second,
t2.third,
t3
)
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, R> combine(
flow: Flow<T1>,
flow2: Flow<T2>,
flow3: Flow<T3>,
flow4: Flow<T4>,
flow5: Flow<T5>,
flow6: Flow<T6>,
flow7: Flow<T7>,
flow8: Flow<T8>,
transform: suspend (T1, T2, T3, T4, T5, T6, T7, T8) -> R
): Flow<R> = combine(
combine(flow, flow2, flow3, ::Triple),
combine(flow4, flow5, flow6, ::Triple),
combine(flow7, flow8, ::Pair),
) { t1, t2, t3 ->
transform(
t1.first,
t1.second,
t1.third,
t2.first,
t2.second,
t2.third,
t3.first,
t3.second
)
}
fun <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> combine(
flow: Flow<T1>,
flow2: Flow<T2>,
flow3: Flow<T3>,
flow4: Flow<T4>,
flow5: Flow<T5>,
flow6: Flow<T6>,
flow7: Flow<T7>,
flow8: Flow<T8>,
flow9: Flow<T9>,
transform: suspend (T1, T2, T3, T4, T5, T6, T7, T8, T9) -> R
): Flow<R> = combine(
combine(flow, flow2, flow3, ::Triple),
combine(flow4, flow5, flow6, ::Triple),
combine(flow7, flow8, flow9, ::Triple),
) { t1, t2, t3 ->
transform(
t1.first,
t1.second,
t1.third,
t2.first,
t2.second,
t2.third,
t3.first,
t3.second,
t3.third
)
}
inline fun <T1, reified T2, R> combine(
flow: Flow<T1>,
flow2: Iterable<Flow<T2>>,
crossinline transform: suspend (T1, Array<T2>) -> R
): Flow<R> =
combine(flow, combine(flow2) { it })
{ t1, t2 -> transform(t1, t2) }
inline fun <T1, T2, reified T3, R> combine(
flow: Flow<T1>,
flow2: Flow<T2>,
flow3: Iterable<Flow<T3>>,
crossinline transform: suspend (T1, T2, Array<T3>) -> R
): Flow<R> =
combine(flow, flow2, combine(flow3) { it })
{ t1, t2, t3 -> transform(t1, t2, t3) }
| 0 | Kotlin | 0 | 2 | 7a793adedcc28028ad54df756ffc16f1f727703a | 4,720 | kotlinlibs | Apache License 2.0 |
smart-phone-sms-backend/src/main/kotlin/com/houkunlin/sms/entity/CustomMessage.kt | houkunlin | 308,576,470 | false | {"TypeScript": 133298, "Kotlin": 26914, "Dart": 13796, "JavaScript": 11261, "Less": 7885, "HTML": 6114, "Swift": 404, "Objective-C": 38} | package com.houkunlin.sms.entity
data class Client2ServerMessage(var name: String? = null) {
}
data class Server2ClientMessage(var responseMessage: String? = null)
| 1 | TypeScript | 0 | 0 | 36f19216c97c728a8d6d839abf3e294fa0adffd6 | 167 | smart-phone-sms | Apache License 2.0 |
backend/src/main/kotlin/com/project/nanuriserver/global/security/jwt/JwtExtract.kt | hackersground-kr | 847,204,786 | false | {"Kotlin": 75137, "TypeScript": 69688, "Bicep": 5862, "HTML": 1652, "CSS": 1371, "Shell": 89} | package com.project.nanuriserver.global.security.jwt
import com.project.nanuriserver.domain.user.domain.repository.jpa.UserJpaRepository
import com.project.nanuriserver.domain.user.exception.UserNotFoundException
import com.project.nanuriserver.global.security.jwt.config.JwtProperties
import com.project.nanuriserver.global.security.jwt.exception.error.JwtErrorType
import com.project.nanuriserver.domain.user.client.dto.User
import com.project.nanuriserver.global.security.auth.CustomUserDetails
import io.jsonwebtoken.ExpiredJwtException
import io.jsonwebtoken.Jwts
import io.jsonwebtoken.MalformedJwtException
import io.jsonwebtoken.UnsupportedJwtException
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.stereotype.Component
import java.util.*
import javax.crypto.SecretKey
import javax.crypto.spec.SecretKeySpec
@Component
class JwtExtract(
private val jwtProvider: JwtProvider,
private val userJpaRepository: UserJpaRepository
) {
fun checkTokenInfo(token: String): JwtErrorType {
try {
Jwts.parser().verifyWith(jwtProvider.secretKey).build().parseSignedClaims(token)
return JwtErrorType.OK
} catch (e: ExpiredJwtException) {
return JwtErrorType.ExpiredJwtException
} catch (e: java.security.SignatureException) {
return JwtErrorType.SignatureException
} catch (e: MalformedJwtException) {
return JwtErrorType.MalformedJwtException
} catch (e: UnsupportedJwtException) {
return JwtErrorType.UnsupportedJwtException
} catch (e: IllegalArgumentException) {
e.printStackTrace()
return JwtErrorType.IllegalArgumentException
} catch (e: Exception) {
e.printStackTrace()
return JwtErrorType.UNKNOWN_EXCEPTION
}
}
fun getAuthentication(token: String): Authentication {
val t = getToken(token)
val user = findUserByEmail(getUsername(t))
val details = CustomUserDetails(user)
return UsernamePasswordAuthenticationToken(details, null, details.authorities)
}
fun getToken(token: String): String {
return token.removePrefix("Bearer ")
}
fun getUsername(token: String): String {
return Jwts.parser().verifyWith(jwtProvider.secretKey).build().parseSignedClaims(token).payload.get(
"phoneNumber",
String::class.java
)
}
fun findUserByEmail(phoneNumber: String): User {
val optionalUserEntity = userJpaRepository.findByPhoneNumber(phoneNumber)
return optionalUserEntity.map { userEntity -> User.toUser(userEntity) }?.orElseThrow { UserNotFoundException }
?: throw UserNotFoundException
}
}
| 0 | Kotlin | 3 | 2 | 10faf92c3a3ea48bdf7ab991d532e405ad88d223 | 2,853 | hg-Team-azure-love | MIT License |
app/src/test/java/com/azyoot/relearn/util/UrlProcessingTest.kt | mzsolt90 | 242,523,252 | false | null | package com.azyoot.relearn.util
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import java.net.URLEncoder
@RunWith(RobolectricTestRunner::class)
class UrlProcessingTest {
private val urlProcessing = UrlProcessing()
@Test
fun `Given url with fragments When stripFragmentFromUrl called Then no more fragments in result`() {
val url = "http://wiktionary.org/бог#Russian"
val result = urlProcessing.stripFragmentFromUrl(url)
assertThat(result).isEqualTo("http://wiktionary.org/бог")
}
@Test
fun `Given url with no fragments When stripFragmentFromUrl called Then url is unchanged`() {
val url = "http://wiktionary.org/бог"
val result = urlProcessing.stripFragmentFromUrl(url)
assertThat(result).isEqualTo(url)
}
@Test
fun `Given url with no scheme When ensureStartsWithHttpsScheme called Then https is prepended`() {
val url = "wiktionary.org/бог"
val result = urlProcessing.ensureStartsWithHttpsScheme(url)
assertThat(result).isEqualTo("https://wiktionary.org/бог")
}
@Test
fun `Given url with http When ensureStartsWithHttpsScheme called Then http is replaced to https`() {
val url = "http://wiktionary.org/бог"
val result = urlProcessing.ensureStartsWithHttpsScheme(url)
assertThat(result).isEqualTo("https://wiktionary.org/бог")
}
@Test
fun `Given url with https When ensureStartsWithHttpsScheme called Then url is unchanged`() {
val url = "https://wiktionary.org/бог"
val result = urlProcessing.ensureStartsWithHttpsScheme(url)
assertThat(result).isEqualTo(url)
}
@Test
fun `Given invalid url When isValidUrl called Then url is not valid`() {
InvalidUrl.values().forEach {
val result = urlProcessing.isValidUrl(it.url)
assertThat(result).isEqualTo(false)
}
}
@Test
fun `Given valid url When isValidUrl called Then url valid`() {
val result = urlProcessing.isValidUrl("https://google.com")
assertThat(result).isEqualTo(true)
}
@Test
fun `Given url encoded url When decoded Then original is returned`() {
val url = URLEncoder.encode("http://wiktionary.org/бог", "UTF-8")
val decoded = urlProcessing.urlDecode(url)
assertThat(decoded).isEqualTo("http://wiktionary.org/бог")
}
@Test
fun `Given partially url encoded url When decoded Then only encoded part is decoded`() {
val url =
"https://en.m.wiktionary.org/wiki/%D0%B4%D0%B2%D0%B8%D0%BD%D1%83%D1%82%D1%8C#Russian"
val decoded = urlProcessing.urlDecode(url)
assertThat(decoded).isEqualTo("https://en.m.wiktionary.org/wiki/двинуть#Russian")
}
enum class InvalidUrl(val url: String) {
INVALID_SCHEME("://wiktionary.org/бог"),
NO_HOST("https://Search"),
SHORT_TLD("https://wiktionary.o")
}
} | 0 | Kotlin | 0 | 1 | d2ede681453f8aa142503192b3efdddc0999b673 | 3,048 | ReLearn | MIT License |
백준/숫자 카드.kt | jisungbin | 382,889,087 | false | null | import java.io.BufferedReader
import java.io.BufferedWriter
import java.io.InputStreamReader
import java.io.OutputStreamWriter
fun main() {
val br = BufferedReader(InputStreamReader(System.`in`))
val bw = BufferedWriter(OutputStreamWriter(System.out))
br.readLine()
val ownCards = br.readLine()!!.split(" ").map { it.toInt() }.toMutableList()
br.readLine()
val cardNumbers = br.readLine()!!.split(" ").map { it.toInt() }
val groupedCards = ownCards.groupBy { it }
val haveCardCounts = mutableListOf<Int>()
cardNumbers.forEach { number ->
if (groupedCards.containsKey(number)) {
haveCardCounts.add(groupedCards.getValue(number).size)
} else {
haveCardCounts.add(0)
}
}
bw.write("${haveCardCounts.joinToString(" ")}\n")
br.close()
bw.flush()
bw.close()
}
| 0 | Kotlin | 1 | 9 | 215a0b0087f6ddbb65c7ac231a749f8e7d8bd827 | 861 | algorithm-code | MIT License |
app/src/androidTestDeviceDebug/kotlin/de/digitalService/useID/IdentificationAttributeConsentTest.kt | digitalservicebund | 486,188,046 | false | null | package de.digitalService.useID
import androidx.compose.ui.test.*
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import de.digitalService.useID.ui.components.NavigationIcon
import de.digitalService.useID.ui.screens.identification.IdentificationAttributeConsent
import de.digitalService.useID.ui.screens.identification.IdentificationAttributeConsentViewModelInterface
import de.digitalService.useID.ui.screens.identification.ProviderInfoDialogContent
import de.digitalService.useID.util.setContentUsingUseIdTheme
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.Rule
import org.junit.Test
@HiltAndroidTest
class IdentificationAttributeConsentTest {
@get:Rule(order = 0)
var hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1)
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Test
fun correctUsage() {
val viewModel: IdentificationAttributeConsentViewModelInterface = mockk(relaxUnitFun = true)
val testIdentificationProviderString = "testIdentificationProviderString"
val testRequiredReadAttributes = listOf(
R.string.cardAttribute_dg01,
R.string.cardAttribute_dg02,
R.string.cardAttribute_dg03,
R.string.cardAttribute_dg04,
R.string.cardAttribute_dg05
)
every { viewModel.identificationProvider } returns testIdentificationProviderString
every { viewModel.requiredReadAttributes } returns testRequiredReadAttributes
every { viewModel.shouldShowInfoDialog } returns false
every { viewModel.backAllowed } returns true
composeTestRule.activity.setContentUsingUseIdTheme {
IdentificationAttributeConsent(viewModel = viewModel)
}
testRequiredReadAttributes.forEach { testId ->
val attributeText = composeTestRule.activity.getString(testId)
composeTestRule.onNodeWithText(attributeText, substring = true).assertIsDisplayed()
}
val buttonText = composeTestRule.activity.getString(R.string.identification_attributeConsent_continue)
composeTestRule.onNodeWithText(buttonText).performClick()
verify(exactly = 1) { viewModel.onPinButtonClicked() }
}
@Test
fun dialogTest() {
val viewModel: IdentificationAttributeConsentViewModelInterface = mockk(relaxUnitFun = true)
val testIdentificationProviderString = "testIdentificationProviderString"
val testRequiredReadAttributes = listOf(
R.string.cardAttribute_dg01,
R.string.cardAttribute_dg02,
R.string.cardAttribute_dg03,
R.string.cardAttribute_dg04,
R.string.cardAttribute_dg05
)
val testIssue = "ISSUE"
val testIssueUrl = "ISSUE_URL"
val testSubject = "SUBJECT"
val testSubjectUrl = "SUBJECT_URL"
val testTerms = "TERMS"
every { viewModel.identificationProvider } returns testIdentificationProviderString
every { viewModel.requiredReadAttributes } returns testRequiredReadAttributes
every { viewModel.shouldShowInfoDialog } returns true
every { viewModel.infoDialogContent } returns ProviderInfoDialogContent(
testIssue,
testIssueUrl,
testSubject,
testSubjectUrl,
testTerms
)
every { viewModel.backAllowed } returns false
composeTestRule.activity.setContentUsingUseIdTheme {
IdentificationAttributeConsent(viewModel = viewModel)
}
testRequiredReadAttributes.forEach { testId ->
val attributeText = composeTestRule.activity.getString(testId)
composeTestRule.onNodeWithText(attributeText, substring = true).assertIsDisplayed()
}
composeTestRule.onNodeWithText(testIssue).assertIsDisplayed()
composeTestRule.onNodeWithText(testIssueUrl).assertIsDisplayed()
composeTestRule.onAllNodesWithText(testSubject).assertCountEquals(2)
composeTestRule.onNodeWithText(testSubjectUrl).assertIsDisplayed()
composeTestRule.onNodeWithText(testTerms).assertIsDisplayed()
val cancelButtonTag = "infoDialogCancel"
composeTestRule.onNodeWithTag(cancelButtonTag).performClick()
verify(exactly = 1) { viewModel.onInfoDialogDismissalRequest() }
}
@Test
fun hasCancelButton() {
val viewModel: IdentificationAttributeConsentViewModelInterface = mockk(relaxUnitFun = true)
val testIdentificationProviderString = "testIdentificationProviderString"
val testRequiredReadAttributes = listOf(
R.string.cardAttribute_dg01,
R.string.cardAttribute_dg02,
R.string.cardAttribute_dg03,
R.string.cardAttribute_dg04,
R.string.cardAttribute_dg05
)
val testIssue = "ISSUE"
val testIssueUrl = "ISSUE_URL"
val testSubject = "SUBJECT"
val testSubjectUrl = "SUBJECT_URL"
val testTerms = "TERMS"
every { viewModel.identificationProvider } returns testIdentificationProviderString
every { viewModel.requiredReadAttributes } returns testRequiredReadAttributes
every { viewModel.shouldShowInfoDialog } returns false
every { viewModel.infoDialogContent } returns ProviderInfoDialogContent(
testIssue,
testIssueUrl,
testSubject,
testSubjectUrl,
testTerms
)
every { viewModel.backAllowed } returns false
composeTestRule.activity.setContentUsingUseIdTheme {
IdentificationAttributeConsent(viewModel = viewModel)
}
val navigationButtonTag = NavigationIcon.Cancel.name
composeTestRule.onNodeWithTag(navigationButtonTag).assertIsDisplayed()
}
@Test
fun hasBacksButton() {
val viewModel: IdentificationAttributeConsentViewModelInterface = mockk(relaxUnitFun = true)
val testIdentificationProviderString = "testIdentificationProviderString"
val testRequiredReadAttributes = listOf(
R.string.cardAttribute_dg01,
R.string.cardAttribute_dg02,
R.string.cardAttribute_dg03,
R.string.cardAttribute_dg04,
R.string.cardAttribute_dg05
)
val testIssue = "ISSUE"
val testIssueUrl = "ISSUE_URL"
val testSubject = "SUBJECT"
val testSubjectUrl = "SUBJECT_URL"
val testTerms = "TERMS"
every { viewModel.identificationProvider } returns testIdentificationProviderString
every { viewModel.requiredReadAttributes } returns testRequiredReadAttributes
every { viewModel.shouldShowInfoDialog } returns false
every { viewModel.infoDialogContent } returns ProviderInfoDialogContent(
testIssue,
testIssueUrl,
testSubject,
testSubjectUrl,
testTerms
)
every { viewModel.backAllowed } returns false
composeTestRule.activity.setContentUsingUseIdTheme {
IdentificationAttributeConsent(viewModel = viewModel)
}
val navigationButtonTag = NavigationIcon.Cancel.name
composeTestRule.onNodeWithTag(navigationButtonTag).assertIsDisplayed()
}
}
| 2 | Kotlin | 2 | 5 | bfb1bea70b827563f80ff9828439de37197a431f | 7,410 | useid-app-android | MIT License |
widgets/src/commonMain/kotlin/dev/icerock/moko/widgets/SwitchWidget.kt | ATchernov | 223,135,697 | true | {"Kotlin": 225543, "Swift": 103744, "Ruby": 1136} | /*
* Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.widgets
import dev.icerock.moko.mvvm.livedata.MutableLiveData
import dev.icerock.moko.widgets.core.RequireId
import dev.icerock.moko.widgets.core.Styled
import dev.icerock.moko.widgets.core.VFC
import dev.icerock.moko.widgets.core.View
import dev.icerock.moko.widgets.core.ViewFactoryContext
import dev.icerock.moko.widgets.core.Widget
import dev.icerock.moko.widgets.core.WidgetDef
import dev.icerock.moko.widgets.core.WidgetScope
import dev.icerock.moko.widgets.style.ColorStyle
import dev.icerock.moko.widgets.style.background.Background
import dev.icerock.moko.widgets.style.view.Backgrounded
import dev.icerock.moko.widgets.style.view.MarginValues
import dev.icerock.moko.widgets.style.view.Margined
import dev.icerock.moko.widgets.style.view.Padded
import dev.icerock.moko.widgets.style.view.PaddingValues
import dev.icerock.moko.widgets.style.view.SizeSpec
import dev.icerock.moko.widgets.style.view.Sized
import dev.icerock.moko.widgets.style.view.WidgetSize
expect var switchWidgetViewFactory: VFC<SwitchWidget>
@WidgetDef
class SwitchWidget(
val factory: VFC<SwitchWidget>,
override val style: Style,
override val id: Id,
val state: MutableLiveData<Boolean>
) : Widget(), Styled<SwitchWidget.Style>, RequireId<SwitchWidget.Id> {
override fun buildView(viewFactoryContext: ViewFactoryContext): View {
return factory(viewFactoryContext, this)
}
/**
* @property size @see dev.icerock.moko.widgets.style.view.Sized
* @property padding @see dev.icerock.moko.widgets.style.view.Padded
* @property margins @see dev.icerock.moko.widgets.style.view.Margined
* @property background @see dev.icerock.moko.widgets.style.view.Backgrounded
* @property switchColor switch background, might be null if default
*/
data class Style(
override val size: WidgetSize = WidgetSize.Const(
width = SizeSpec.WRAP_CONTENT,
height = SizeSpec.WRAP_CONTENT
),
override val padding: PaddingValues? = null,
override val margins: MarginValues? = null,
override val background: Background? = null,
val switchColor: ColorStyle? = null
) : Widget.Style, Sized, Padded, Margined, Backgrounded
interface Id : WidgetScope.Id
}
| 0 | null | 0 | 0 | 560af260a9813724fd8e53b5c7ea0691e3b5fb46 | 2,385 | moko-widgets | Apache License 2.0 |
solar/src/main/java/com/chiksmedina/solar/bold/facesemotionsstickers/FaceScanCircle.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.bold.facesemotionsstickers
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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 com.chiksmedina.solar.bold.FacesEmotionsStickersGroup
val FacesEmotionsStickersGroup.FaceScanCircle: ImageVector
get() {
if (_faceScanCircle != null) {
return _faceScanCircle!!
}
_faceScanCircle = Builder(
name = "FaceScanCircle", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(10.8011f, 2.5697f)
curveTo(10.8792f, 2.9544f, 10.6305f, 3.3297f, 10.2458f, 3.4078f)
curveTo(6.8116f, 4.1048f, 4.1048f, 6.8116f, 3.4077f, 10.2457f)
curveTo(3.3296f, 10.6305f, 2.9544f, 10.8791f, 2.5696f, 10.801f)
curveTo(2.1848f, 10.7229f, 1.9362f, 10.3477f, 2.0143f, 9.9629f)
curveTo(2.825f, 5.9691f, 5.9692f, 2.825f, 9.963f, 2.0144f)
curveTo(10.3477f, 1.9363f, 10.723f, 2.1849f, 10.8011f, 2.5697f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(2.5698f, 13.199f)
curveTo(2.9545f, 13.1209f, 3.3298f, 13.3695f, 3.4079f, 13.7543f)
curveTo(4.105f, 17.1885f, 6.8117f, 19.8952f, 10.2459f, 20.5923f)
curveTo(10.6307f, 20.6704f, 10.8793f, 21.0456f, 10.8012f, 21.4304f)
curveTo(10.7231f, 21.8151f, 10.3479f, 22.0638f, 9.9631f, 21.9857f)
curveTo(5.9693f, 21.175f, 2.8252f, 18.0309f, 2.0145f, 14.0371f)
curveTo(1.9364f, 13.6524f, 2.185f, 13.2772f, 2.5698f, 13.199f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(13.1989f, 2.5696f)
curveTo(13.277f, 2.1848f, 13.6523f, 1.9362f, 14.037f, 2.0143f)
curveTo(18.0308f, 2.825f, 21.175f, 5.9691f, 21.9857f, 9.9628f)
curveTo(22.0638f, 10.3476f, 21.8152f, 10.7228f, 21.4304f, 10.801f)
curveTo(21.0456f, 10.8791f, 20.6704f, 10.6305f, 20.5923f, 10.2457f)
curveTo(19.8952f, 6.8115f, 17.1884f, 4.1048f, 13.7542f, 3.4077f)
curveTo(13.3695f, 3.3296f, 13.1208f, 2.9544f, 13.1989f, 2.5696f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(21.4304f, 13.199f)
curveTo(21.8152f, 13.2772f, 22.0638f, 13.6524f, 21.9857f, 14.0371f)
curveTo(21.175f, 18.0309f, 18.0308f, 21.175f, 14.037f, 21.9857f)
curveTo(13.6523f, 22.0637f, 13.277f, 21.8151f, 13.1989f, 21.4304f)
curveTo(13.1208f, 21.0456f, 13.3695f, 20.6704f, 13.7542f, 20.5923f)
curveTo(17.1884f, 19.8952f, 19.8952f, 17.1885f, 20.5923f, 13.7543f)
curveTo(20.6704f, 13.3695f, 21.0456f, 13.1209f, 21.4304f, 13.199f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(11.9999f, 19.5828f)
curveTo(16.1878f, 19.5828f, 19.5827f, 16.1879f, 19.5827f, 12.0f)
curveTo(19.5827f, 7.8122f, 16.1878f, 4.4172f, 11.9999f, 4.4172f)
curveTo(7.8121f, 4.4172f, 4.4171f, 7.8122f, 4.4171f, 12.0f)
curveTo(4.4171f, 16.1879f, 7.8121f, 19.5828f, 11.9999f, 19.5828f)
close()
moveTo(8.9407f, 14.5387f)
curveTo(9.1745f, 14.2233f, 9.6197f, 14.1572f, 9.9351f, 14.391f)
curveTo(10.5247f, 14.828f, 11.2355f, 15.0805f, 11.9999f, 15.0805f)
curveTo(12.7643f, 15.0805f, 13.4751f, 14.828f, 14.0647f, 14.391f)
curveTo(14.3801f, 14.1572f, 14.8253f, 14.2233f, 15.0591f, 14.5387f)
curveTo(15.2929f, 14.8542f, 15.2268f, 15.2994f, 14.9114f, 15.5332f)
curveTo(14.0904f, 16.1417f, 13.0857f, 16.5023f, 11.9999f, 16.5023f)
curveTo(10.9141f, 16.5023f, 9.9094f, 16.1417f, 9.0885f, 15.5332f)
curveTo(8.7731f, 15.2994f, 8.7069f, 14.8542f, 8.9407f, 14.5387f)
close()
moveTo(15.3174f, 10.4005f)
curveTo(15.3174f, 11.0876f, 14.9461f, 11.6446f, 14.488f, 11.6446f)
curveTo(14.03f, 11.6446f, 13.6587f, 11.0876f, 13.6587f, 10.4005f)
curveTo(13.6587f, 9.7135f, 14.03f, 9.1565f, 14.488f, 9.1565f)
curveTo(14.9461f, 9.1565f, 15.3174f, 9.7135f, 15.3174f, 10.4005f)
close()
moveTo(9.5118f, 11.6446f)
curveTo(9.9699f, 11.6446f, 10.3412f, 11.0876f, 10.3412f, 10.4005f)
curveTo(10.3412f, 9.7135f, 9.9699f, 9.1565f, 9.5118f, 9.1565f)
curveTo(9.0538f, 9.1565f, 8.6825f, 9.7135f, 8.6825f, 10.4005f)
curveTo(8.6825f, 11.0876f, 9.0538f, 11.6446f, 9.5118f, 11.6446f)
close()
}
}
.build()
return _faceScanCircle!!
}
private var _faceScanCircle: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 6,510 | SolarIconSetAndroid | MIT License |
solar/src/main/java/com/chiksmedina/solar/bold/facesemotionsstickers/FaceScanCircle.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.bold.facesemotionsstickers
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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 com.chiksmedina.solar.bold.FacesEmotionsStickersGroup
val FacesEmotionsStickersGroup.FaceScanCircle: ImageVector
get() {
if (_faceScanCircle != null) {
return _faceScanCircle!!
}
_faceScanCircle = Builder(
name = "FaceScanCircle", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(10.8011f, 2.5697f)
curveTo(10.8792f, 2.9544f, 10.6305f, 3.3297f, 10.2458f, 3.4078f)
curveTo(6.8116f, 4.1048f, 4.1048f, 6.8116f, 3.4077f, 10.2457f)
curveTo(3.3296f, 10.6305f, 2.9544f, 10.8791f, 2.5696f, 10.801f)
curveTo(2.1848f, 10.7229f, 1.9362f, 10.3477f, 2.0143f, 9.9629f)
curveTo(2.825f, 5.9691f, 5.9692f, 2.825f, 9.963f, 2.0144f)
curveTo(10.3477f, 1.9363f, 10.723f, 2.1849f, 10.8011f, 2.5697f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(2.5698f, 13.199f)
curveTo(2.9545f, 13.1209f, 3.3298f, 13.3695f, 3.4079f, 13.7543f)
curveTo(4.105f, 17.1885f, 6.8117f, 19.8952f, 10.2459f, 20.5923f)
curveTo(10.6307f, 20.6704f, 10.8793f, 21.0456f, 10.8012f, 21.4304f)
curveTo(10.7231f, 21.8151f, 10.3479f, 22.0638f, 9.9631f, 21.9857f)
curveTo(5.9693f, 21.175f, 2.8252f, 18.0309f, 2.0145f, 14.0371f)
curveTo(1.9364f, 13.6524f, 2.185f, 13.2772f, 2.5698f, 13.199f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(13.1989f, 2.5696f)
curveTo(13.277f, 2.1848f, 13.6523f, 1.9362f, 14.037f, 2.0143f)
curveTo(18.0308f, 2.825f, 21.175f, 5.9691f, 21.9857f, 9.9628f)
curveTo(22.0638f, 10.3476f, 21.8152f, 10.7228f, 21.4304f, 10.801f)
curveTo(21.0456f, 10.8791f, 20.6704f, 10.6305f, 20.5923f, 10.2457f)
curveTo(19.8952f, 6.8115f, 17.1884f, 4.1048f, 13.7542f, 3.4077f)
curveTo(13.3695f, 3.3296f, 13.1208f, 2.9544f, 13.1989f, 2.5696f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(21.4304f, 13.199f)
curveTo(21.8152f, 13.2772f, 22.0638f, 13.6524f, 21.9857f, 14.0371f)
curveTo(21.175f, 18.0309f, 18.0308f, 21.175f, 14.037f, 21.9857f)
curveTo(13.6523f, 22.0637f, 13.277f, 21.8151f, 13.1989f, 21.4304f)
curveTo(13.1208f, 21.0456f, 13.3695f, 20.6704f, 13.7542f, 20.5923f)
curveTo(17.1884f, 19.8952f, 19.8952f, 17.1885f, 20.5923f, 13.7543f)
curveTo(20.6704f, 13.3695f, 21.0456f, 13.1209f, 21.4304f, 13.199f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(11.9999f, 19.5828f)
curveTo(16.1878f, 19.5828f, 19.5827f, 16.1879f, 19.5827f, 12.0f)
curveTo(19.5827f, 7.8122f, 16.1878f, 4.4172f, 11.9999f, 4.4172f)
curveTo(7.8121f, 4.4172f, 4.4171f, 7.8122f, 4.4171f, 12.0f)
curveTo(4.4171f, 16.1879f, 7.8121f, 19.5828f, 11.9999f, 19.5828f)
close()
moveTo(8.9407f, 14.5387f)
curveTo(9.1745f, 14.2233f, 9.6197f, 14.1572f, 9.9351f, 14.391f)
curveTo(10.5247f, 14.828f, 11.2355f, 15.0805f, 11.9999f, 15.0805f)
curveTo(12.7643f, 15.0805f, 13.4751f, 14.828f, 14.0647f, 14.391f)
curveTo(14.3801f, 14.1572f, 14.8253f, 14.2233f, 15.0591f, 14.5387f)
curveTo(15.2929f, 14.8542f, 15.2268f, 15.2994f, 14.9114f, 15.5332f)
curveTo(14.0904f, 16.1417f, 13.0857f, 16.5023f, 11.9999f, 16.5023f)
curveTo(10.9141f, 16.5023f, 9.9094f, 16.1417f, 9.0885f, 15.5332f)
curveTo(8.7731f, 15.2994f, 8.7069f, 14.8542f, 8.9407f, 14.5387f)
close()
moveTo(15.3174f, 10.4005f)
curveTo(15.3174f, 11.0876f, 14.9461f, 11.6446f, 14.488f, 11.6446f)
curveTo(14.03f, 11.6446f, 13.6587f, 11.0876f, 13.6587f, 10.4005f)
curveTo(13.6587f, 9.7135f, 14.03f, 9.1565f, 14.488f, 9.1565f)
curveTo(14.9461f, 9.1565f, 15.3174f, 9.7135f, 15.3174f, 10.4005f)
close()
moveTo(9.5118f, 11.6446f)
curveTo(9.9699f, 11.6446f, 10.3412f, 11.0876f, 10.3412f, 10.4005f)
curveTo(10.3412f, 9.7135f, 9.9699f, 9.1565f, 9.5118f, 9.1565f)
curveTo(9.0538f, 9.1565f, 8.6825f, 9.7135f, 8.6825f, 10.4005f)
curveTo(8.6825f, 11.0876f, 9.0538f, 11.6446f, 9.5118f, 11.6446f)
close()
}
}
.build()
return _faceScanCircle!!
}
private var _faceScanCircle: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 6,510 | SolarIconSetAndroid | MIT License |
app/src/main/java/dev/marcocattaneo/playground/ui/screen/repoinfo/GithubViewModel.kt | mcatta | 533,429,271 | false | {"Kotlin": 66596} | /*
* Copyright 2021 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.marcocattaneo.playground.ui.screen.repoinfo
import androidx.lifecycle.SavedStateHandle
import dagger.hilt.android.lifecycle.HiltViewModel
import dev.marcocattaneo.playground.ui.screen.common.AbsStateViewModel
import javax.inject.Inject
@HiltViewModel
class GithubViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
githubStateMachine: GithubStateMachine
): AbsStateViewModel<GithubState, GithubAction>(githubStateMachine) | 0 | Kotlin | 0 | 5 | f3693b0bbbf96b5c138cf8611742d32dd3e4fcca | 1,050 | flow-redux-playground | Apache License 2.0 |
zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/modifiers/DelayedTileStringExample.kt | Hexworks | 94,116,947 | false | null | package org.hexworks.zircon.examples.modifiers
import org.hexworks.zircon.api.CP437TilesetResources
import org.hexworks.zircon.api.ColorThemes
import org.hexworks.zircon.api.Components
import org.hexworks.zircon.api.SwingApplications
import org.hexworks.zircon.api.application.AppConfig
import org.hexworks.zircon.api.builder.screen.ScreenBuilder
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.ComponentDecorations.box
object DelayedTileStringExample {
private val SIZE = Size.create(50, 30)
private val TILESET = CP437TilesetResources.taffer20x20()
private val THEME = ColorThemes.cyberpunk()
@JvmStatic
fun main(args: Array<String>) {
val tileGrid = SwingApplications.startTileGrid(
AppConfig.newBuilder()
.withDefaultTileset(TILESET)
.withSize(SIZE)
.withDebugMode(true)
.build()
)
val screen = ScreenBuilder.createScreenFor(tileGrid)
val panel = Components.panel()
.withDecorations(box())
.withPreferredSize(Size.create(48, 20))
.build()
screen.addComponent(panel)
val myText = "This is a very long string I'd like to add with a typewriter effect"
panel.addComponent(
Components.textBox(panel.contentSize.width)
.addParagraph(
text = myText,
withTypingEffectSpeedInMs = 200
)
)
screen.theme = THEME
screen.display()
}
}
| 42 | null | 138 | 738 | 55a0ccc19a3f1b80aecd5f1fbe859db94ba9c0c6 | 1,562 | zircon | Apache License 2.0 |
core_library_common/src/commonMain/kotlin/net/apptronic/core/commons/dataprovider/cache/DataProviderCachePersistence.kt | apptronicnet | 264,405,837 | false | null | package net.apptronic.core.commons.dataprovider.cache
import net.apptronic.core.base.subject.ValueHolder
/**
* Persistence layer for use with [PersistentProxyDataProviderCache]. Allows to simply add persistence layer to
* in-memory cache.
*/
interface DataProviderCachePersistence<K, T> {
/**
* Save cached value to persistent storage
*/
suspend fun save(key: K, value: T)
/**
* Load cached value from persistent storage
*
* @return [ValueHolder] containing value or null is value is not present in cache
*/
suspend fun load(key: K): ValueHolder<T>?
/**
* Force clear all cache
*/
fun clear() {
// implement by subclasses if needed
}
} | 2 | Kotlin | 0 | 6 | 44ef572eb80f1a76c165cba85ff31a88c313a77b | 720 | core | MIT License |
src/main/docsite/bootstrap/tabs.kt | bbodi | 29,053,020 | true | {"JavaScript": 563656, "Kotlin": 103049} | package bootstrap
import net.yested.div
import net.yested.bootstrap.form
import net.yested.Div
import net.yested.bootstrap.textInput
import net.yested.bootstrap.tabs
import net.yested.text
import net.yested.bootstrap.row
import org.w3c.dom.Element
import net.yested.bootstrap.pageHeader
/**
* Created by jean on 20.12.2014.
*/
fun createTabs(): Div {
return div {
row {
col(12) {
pageHeader { h3 { +"Tabs" } }
}
}
row {
col(4) {
div {
+"""
Tabs are based on Bootstrap Tabs.
Content of tab is rendedered upon click on a tab link. When clicking on anoother link, content is preserved.
"""
}
br()
h4 { +"Demo" }
tabs {
tab(header = text("First")) {
div {
textInput(placeholder = "Placeholder 1") { }
}
}
tab(active = true, header = text("Second")) {
div {
+"This tab is selected by default."
}
}
tab(header = text("Third")) {
a(href = "http://www.wikipedia.org") { +"Wikipedia" }
}
}
}
col(8) {
h4 { +"Code" }
code(lang = "kotlin", content="""tabs {
tab(header = text("First")) {
div {
textInput(placeholder = "Placeholder 1") { }
}
}
tab(active = true, header = text("Second")) {
div {
+"This tab is selected by default."
}
}
tab(header = text("Third")) {
a(href = "http://www.wikipedia.org") { +"Wikipedia"}
}
}""")
}
}
}
}
| 0 | JavaScript | 0 | 0 | a47f8e54830769e6fe292e5e792e375793df9474 | 1,889 | yested | MIT License |
tangem-core/src/main/java/com/tangem/commands/PurgeWalletCommand.kt | 1Crazymoney | 265,350,975 | true | {"Kotlin": 261184} | package com.tangem.commands
import com.tangem.CardSession
import com.tangem.SessionEnvironment
import com.tangem.TangemSdkError
import com.tangem.common.CompletionResult
import com.tangem.common.apdu.CommandApdu
import com.tangem.common.apdu.Instruction
import com.tangem.common.apdu.ResponseApdu
import com.tangem.common.tlv.TlvBuilder
import com.tangem.common.tlv.TlvDecoder
import com.tangem.common.tlv.TlvTag
class PurgeWalletResponse(
/**
* CID, Unique Tangem card ID number.
*/
val cardId: String,
/**
* Current status of the card [1 - Empty, 2 - Loaded, 3- Purged]
*/
val status: CardStatus
) : CommandResponse
/**
* This command deletes all wallet data. If Is_Reusable flag is enabled during personalization,
* the card changes state to ‘Empty’ and a new wallet can be created by [CreateWalletCommand].
* If Is_Reusable flag is disabled, the card switches to ‘Purged’ state.
* ‘Purged’ state is final, it makes the card useless.
* @property cardId CID, Unique Tangem card ID number.
*/
class PurgeWalletCommand : Command<PurgeWalletResponse>() {
override fun performPreCheck(session: CardSession, callback: (result: CompletionResult<PurgeWalletResponse>) -> Unit): Boolean {
if (session.environment.card?.status == CardStatus.NotPersonalized) {
callback(CompletionResult.Failure(TangemSdkError.NotPersonalized()))
return true
}
if (session.environment.card?.isActivated == true) {
callback(CompletionResult.Failure(TangemSdkError.NotActivated()))
return true
}
if (session.environment.card?.settingsMask?.contains(Settings.ProhibitPurgeWallet) == true) {
callback(CompletionResult.Failure(TangemSdkError.PurgeWalletProhibited()))
return true
}
return false
}
override fun performAfterCheck(session: CardSession,
result: CompletionResult<PurgeWalletResponse>,
callback: (result: CompletionResult<PurgeWalletResponse>) -> Unit): Boolean {
when (result) {
is CompletionResult.Failure -> {
if (result.error is TangemSdkError.InvalidParams) {
callback(CompletionResult.Failure(TangemSdkError.Pin2OrCvcRequired()))
return true
}
return false
}
else -> return false
}
}
override fun serialize(environment: SessionEnvironment): CommandApdu {
val tlvBuilder = TlvBuilder()
tlvBuilder.append(TlvTag.Pin, environment.pin1)
tlvBuilder.append(TlvTag.CardId, environment.card?.cardId)
tlvBuilder.append(TlvTag.Pin2, environment.pin2)
return CommandApdu(
Instruction.PurgeWallet, tlvBuilder.serialize(),
environment.encryptionMode, environment.encryptionKey
)
}
override fun deserialize(environment: SessionEnvironment, apdu: ResponseApdu): PurgeWalletResponse {
val tlvData = apdu.getTlvData(environment.encryptionKey)
?: throw TangemSdkError.DeserializeApduFailed()
val decoder = TlvDecoder(tlvData)
return PurgeWalletResponse(
cardId = decoder.decode(TlvTag.CardId),
status = decoder.decode(TlvTag.Status))
}
} | 0 | null | 0 | 1 | baaedaf504cc6658272becad7d88b340eacdd6e8 | 3,410 | tangem-sdk-android | MIT License |
app/src/main/java/com/vandenbreemen/trainingcardsapp/interactor/NonRandomCardsInteractor.kt | msgpo | 276,439,836 | true | {"Kotlin": 18218} | package com.vandenbreemen.trainingcardsapp.interactor
import android.graphics.Color
import com.vandenbreemen.trainingcardsapp.entity.Card
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
/**
*
* @author kevin
*/
class NonRandomCardsInteractor @Inject constructor(private val coroutineContext: CoroutineContext): CardsInteractor {
private var counter: Int = 0
override var output: CardsOutputInteractor? = null
override fun requestCard() {
CoroutineScope(coroutineContext).launch {
var num = ++counter
var red = num+10
red %= 256
Card(Color.valueOf(red.toFloat(), 0.0f, 0.0f)).apply {
output?.let { it.sendCard(this) }
}
}
}
} | 0 | null | 0 | 0 | 67792aff6e61fd75c63c5e56cc2b93e3a07771d8 | 877 | CardDeckTraining | MIT License |
app/src/main/java/pl/better/foodzilla/data/mappers/SearchMapper.kt | kambed | 612,140,416 | false | null | package pl.better.foodzilla.data.mappers
import pl.better.foodzilla.AddFavouriteSearchMutation
import pl.better.foodzilla.FavouriteSearchesQuery
import pl.better.foodzilla.RemoveFavouriteSearchMutation
import pl.better.foodzilla.data.models.search.SearchFilter
import pl.better.foodzilla.data.models.search.SearchRequest
import pl.better.foodzilla.data.models.search.SearchSort
import pl.better.foodzilla.data.models.search.SearchSortDirection
import pl.better.foodzilla.type.SortDirection
fun FavouriteSearchesQuery.SavedSearch.toSearchRequest(): SearchRequest {
return SearchRequest(
id = id,
phrase = phrase!!,
filters = filters?.map { it!!.toSearchFilter() }!!,
sort = sort?.map { it!!.toSearchSort() }!!
)
}
fun FavouriteSearchesQuery.Filter.toSearchFilter(): SearchFilter {
return SearchFilter(
attribute = attribute,
from = from,
to = to,
equals = equals,
`in` = `in`?.map { it!! },
hasOnly = hasOnly?.map { it!! }
)
}
fun FavouriteSearchesQuery.Sort.toSearchSort(): SearchSort {
return SearchSort(
attribute = attribute!!,
direction = direction?.toSearchSortDirection()!!
)
}
fun SortDirection.toSearchSortDirection(): SearchSortDirection? {
return when (this) {
SortDirection.ASC -> SearchSortDirection.ASC
SortDirection.DESC -> SearchSortDirection.DESC
else -> {null}
}
}
fun AddFavouriteSearchMutation.AddSavedSearch.toSearchRequest(): SearchRequest {
return SearchRequest(
id = id,
phrase = phrase!!,
filters = filters?.map { it!!.toSearchFilter() }!!,
sort = sort?.map { it!!.toSearchSort() }!!
)
}
fun AddFavouriteSearchMutation.Filter.toSearchFilter(): SearchFilter {
return SearchFilter(
attribute = attribute,
from = from,
to = to,
equals = equals,
`in` = `in`?.map { it!! },
hasOnly = hasOnly?.map { it!! }
)
}
fun AddFavouriteSearchMutation.Sort.toSearchSort(): SearchSort {
return SearchSort(
attribute = attribute!!,
direction = direction?.toSearchSortDirection()!!
)
}
fun RemoveFavouriteSearchMutation.DeleteSavedSearch.toSearchRequest(): SearchRequest {
return SearchRequest(
id = id,
phrase = phrase!!,
filters = filters?.map { it!!.toSearchFilter() }!!,
sort = sort?.map { it!!.toSearchSort() }!!
)
}
fun RemoveFavouriteSearchMutation.Filter.toSearchFilter(): SearchFilter {
return SearchFilter(
attribute = attribute,
from = from,
to = to,
equals = equals,
`in` = `in`?.map { it!! },
hasOnly = hasOnly?.map { it!! }
)
}
fun RemoveFavouriteSearchMutation.Sort.toSearchSort(): SearchSort {
return SearchSort(
attribute = attribute!!,
direction = direction?.toSearchSortDirection()!!
)
}
| 1 | Kotlin | 0 | 3 | 94a8993b3aefc6271cea6ffd95546cb8c02802f4 | 2,916 | FoodzillaFrontendAndroid | Apache License 2.0 |
app-impl/src/main/kotlin/be/sourcedbvba/restbucks/order/CreateOrderImpl.kt | Zidanela | 143,374,849 | true | {"Kotlin": 26692} | package be.sourcedbvba.restbucks.order
import be.sourcedbvba.restbucks.Status
import be.sourcedbvba.restbucks.domain.transaction.TransactionFactory
import be.sourcedbvba.restbucks.usecase.UseCase
import java.util.*
import java.util.function.Supplier
@UseCase
internal class CreateOrderImpl(private val transactionFactory: TransactionFactory) : CreateOrder {
override fun create(request: CreateOrderRequest, presenter: CreateOrderReceiver) {
request.validate()
val transaction = transactionFactory.start()
try {
val order = request.toOrder()
order.create()
presenter.receive(order.toResponse())
transaction.commit()
} catch(ex: Exception) {
transaction.rollback()
}
}
private fun CreateOrderRequest.validate() {
}
private fun CreateOrderRequest.toOrder() : Order {
val id = UUID.randomUUID().toString()
return Order(OrderId(id), customer, Status.OPEN, OrderItems(items.map { it.toOrderItem() }))
}
private fun CreateOrderRequestItem.toOrderItem(): OrderItem {
return OrderItem(product, quantity, size, milk)
}
private fun Order.toResponse() : CreateOrderResponse {
return CreateOrderResponse(id.value, customer, cost)
}
} | 0 | Kotlin | 0 | 0 | 521a4c03742589c76769e5227e819133144a1036 | 1,299 | clean-restbucks | Apache License 2.0 |
library/src/gen/kotlin/it/krzeminski/githubactions/actions/cachix/InstallNixActionV18.kt | krzema12 | 439,670,569 | false | null | // This file was generated using 'wrapper-generator' module. Don't change it by hand, your changes will
// be overwritten with the next wrapper code regeneration. Instead, consider introducing changes to the
// generator itself.
@file:Suppress("DEPRECATION")
package it.krzeminski.githubactions.actions.cachix
import it.krzeminski.githubactions.actions.Action
import java.util.LinkedHashMap
import kotlin.Deprecated
import kotlin.String
import kotlin.Suppress
import kotlin.collections.List
import kotlin.collections.Map
import kotlin.collections.toList
import kotlin.collections.toTypedArray
/**
* Action: Install Nix
*
* Installs Nix on GitHub Actions for the supported platforms: Linux and macOS.
*
* [Action on GitHub](https://github.com/cachix/install-nix-action)
*/
@Deprecated(
message = "This action has a newer major version: InstallNixActionV18",
replaceWith = ReplaceWith("InstallNixActionV18"),
)
public data class InstallNixActionV17(
/**
* Installation URL that will contain a script to install Nix.
*/
public val installUrl: String? = null,
/**
* Additional installer flags passed to the installer script.
*/
public val installOptions: List<String>? = null,
/**
* Set NIX_PATH environment variable.
*/
public val nixPath: String? = null,
/**
* gets appended to `/etc/nix/nix.conf` if passed.
*/
public val extraNixConfig: String? = null,
/**
* Type-unsafe map where you can put any inputs that are not yet supported by the wrapper
*/
public val _customInputs: Map<String, String> = mapOf(),
/**
* Allows overriding action's version, for example to use a specific minor version, or a newer
* version that the wrapper doesn't yet know about
*/
public val _customVersion: String? = null,
) : Action("cachix", "install-nix-action", _customVersion ?: "v17") {
@Suppress("SpreadOperator")
public override fun toYamlArguments(): LinkedHashMap<String, String> = linkedMapOf(
*listOfNotNull(
installUrl?.let { "install_url" to it },
installOptions?.let { "install_options" to it.joinToString("\n") },
nixPath?.let { "nix_path" to it },
extraNixConfig?.let { "extra_nix_config" to it },
*_customInputs.toList().toTypedArray(),
).toTypedArray()
)
}
| 33 | Kotlin | 12 | 287 | 5f45a621b9aba292541e1d47c4738aedf491d8d2 | 2,371 | github-workflows-kt | Apache License 2.0 |
src/main/kotlin/us/frollo/frollosdk/model/coredata/contacts/CRNType.kt | frollous | 261,670,220 | false | null | package us.frollo.frollosdk.model.coredata.contacts
import com.google.gson.annotations.SerializedName
import us.frollo.frollosdk.extensions.serializedName
/** Indicates the type of the Biller CRN */
enum class CRNType {
/** Fixed */
@SerializedName("fixed_crn") FIXED,
/** Variable */
@SerializedName("variable_crn") VARIABLE,
/** Intelligent */
@SerializedName("intelligent_crn") INTELLIGENT,
/** Variable */
@SerializedName("unknown") UNKNOWN;
/** Enum to serialized string */
// This override MUST be used for this enum to work with Retrofit @Path or @Query parameters
override fun toString(): String =
// Try to get the annotation value if available instead of using plain .toString()
// Fallback to super.toString() in case annotation is not present/available
serializedName() ?: super.toString()
}
| 0 | Kotlin | 0 | 1 | 236fb597fd41be9d13cf5b79fe4b684f7294cd62 | 879 | frollo-android-sdk | Apache License 2.0 |
smithy-swift-codegen/src/main/kotlin/software/amazon/smithy/swift/codegen/integration/httpResponse/bindingTraits/HTTPResponseTraitPayload.kt | smithy-lang | 242,852,561 | false | null | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package software.amazon.smithy.swift.codegen.integration.httpResponse.bindingTraits
import software.amazon.smithy.model.knowledge.HttpBinding
import software.amazon.smithy.model.shapes.Shape
import software.amazon.smithy.swift.codegen.SwiftWriter
import software.amazon.smithy.swift.codegen.integration.HttpBindingDescriptor
import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator
import software.amazon.smithy.swift.codegen.integration.httpResponse.HttpResponseBindingRenderable
class XMLHttpResponseTraitPayload(
val ctx: ProtocolGenerator.GenerationContext,
val responseBindings: List<HttpBindingDescriptor>,
val outputShape: Shape,
val writer: SwiftWriter,
val httpResponseTraitWithoutPayloadFactory: HttpResponseTraitWithoutHttpPayloadFactory? = null
) : HttpResponseBindingRenderable {
override fun render() {
val httpPayload = responseBindings.firstOrNull { it.location == HttpBinding.Location.PAYLOAD }
if (httpPayload != null) {
XMLHttpResponseTraitWithHttpPayload(ctx, httpPayload, writer, outputShape).render()
} else {
val httpResponseTraitWithoutPayload = httpResponseTraitWithoutPayloadFactory?.let {
it.construct(ctx, responseBindings, outputShape, writer)
} ?: run {
XMLHttpResponseTraitWithoutHttpPayload(ctx, responseBindings, outputShape, writer)
}
httpResponseTraitWithoutPayload.render()
}
}
}
| 7 | null | 29 | 28 | 0de17918831a547e04e86a9c306491b536ada934 | 1,605 | smithy-swift | Apache License 2.0 |
src/main/kotlin/easy/search-insert-position.kt | shevtsiv | 286,838,200 | false | null | package easy
class SearchInsertPositionSolution {
/**
* Time Complexity: O(log(n))
* Space Complexity: O(1)
*/
fun searchInsertUsingBinarySearch(nums: IntArray, target: Int): Int {
var low = 0
var high = nums.size
while (low <= high) {
val mid = (low + high) / 2
when {
nums[mid] < target -> {
low = mid + 1
}
nums[mid] > target -> {
high = mid - 1
}
else -> {
return mid
}
}
}
return low
}
/**
* Time Complexity: O(n)
* Space Complexity: O(1)
*/
fun searchInsertUsingLinearScan(nums: IntArray, target: Int): Int {
for (i in nums.indices) {
if (nums[i] >= target) {
return i
}
}
return nums.size
}
}
| 0 | Kotlin | 0 | 0 | 95d5f74069098beddf2aee14465f069302a51b77 | 953 | leet | MIT License |
feather/src/commonMain/kotlin/compose/icons/feathericons/CornerDownLeft.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.feathericons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.FeatherIcons
public val FeatherIcons.CornerDownLeft: ImageVector
get() {
if (_cornerDownLeft != null) {
return _cornerDownLeft!!
}
_cornerDownLeft = Builder(name = "CornerDownLeft", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.0f, 10.0f)
lineToRelative(-5.0f, 5.0f)
lineToRelative(5.0f, 5.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(20.0f, 4.0f)
verticalLineToRelative(7.0f)
arcToRelative(4.0f, 4.0f, 0.0f, false, true, -4.0f, 4.0f)
horizontalLineTo(4.0f)
}
}
.build()
return _cornerDownLeft!!
}
private var _cornerDownLeft: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 1,936 | compose-icons | MIT License |
presentation/src/main/kotlin/com/lukelorusso/presentation/extensions/ContextExtension.kt | lukelorusso | 277,556,469 | false | null | package com.lukelorusso.presentation.extensions
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.provider.Settings
import android.text.format.DateFormat
import android.util.DisplayMetrics
import android.view.View
import androidx.core.app.ActivityCompat
import java.util.*
@SuppressLint("ObsoleteSdkInt")
fun Activity.enableImmersiveMode(
hideNavBar: Boolean,
hideStatusBar: Boolean,
resize: Boolean
) {
if (!hideNavBar && !hideStatusBar) {
disableImmersiveMode()
return
}
var uiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
if (hideNavBar && resize) uiVisibility = (uiVisibility
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
if (hideStatusBar && resize) uiVisibility = (uiVisibility
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
if (hideNavBar) uiVisibility = (uiVisibility
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION)
if (hideStatusBar) uiVisibility = (uiVisibility
or View.SYSTEM_UI_FLAG_FULLSCREEN)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) uiVisibility = (uiVisibility
or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)
this.window.decorView.systemUiVisibility = uiVisibility
}
fun Activity.disableImmersiveMode() {
this.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_VISIBLE
}
fun Context.startActivityWithFlagNewTask(intent: Intent) {
startActivity(intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
fun Context.dpToPixel(dp: Float): Float =
dp * (resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
fun Context.pixelToDp(px: Int): Float =
px / (resources.displayMetrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT)
fun Context.isPermissionGranted(permission: String): Boolean {
val rc = ActivityCompat.checkSelfPermission(this, permission)
return rc == PackageManager.PERMISSION_GRANTED
}
fun Context?.getDeviceUdid(): String {
return this?.run {
Settings.System.getString(
this.contentResolver,
Settings.Secure.ANDROID_ID
)
} ?: ""
}
fun Context.gotoAppDetailsSettings() {
val permissionDetailsIntent = Intent()
permissionDetailsIntent.action = Settings.ACTION_APPLICATION_DETAILS_SETTINGS
permissionDetailsIntent.addCategory(Intent.CATEGORY_DEFAULT)
permissionDetailsIntent.data = Uri.parse("package:" + this.packageName)
permissionDetailsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
permissionDetailsIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)
permissionDetailsIntent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS)
startActivityWithFlagNewTask(permissionDetailsIntent)
}
fun Context.getStatusBarHeight(): Int {
return resources.getDimensionPixelSize(
resources.getIdentifier("status_bar_height", "dimen", "android")
)
}
fun Context.redirectToBrowser(url: String) {
val browserIntent = Intent(Intent.ACTION_VIEW)
browserIntent.data = Uri.parse(url)
startActivityWithFlagNewTask(browserIntent)
}
fun Context.shareImageAndText(content: Uri, text: String, popupLabel: String?) {
var intent = Intent()
intent.action = Intent.ACTION_SEND
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
intent.setDataAndType(content, this.contentResolver.getType(content))
intent.putExtra(Intent.EXTRA_STREAM, content)
if (text.isNotEmpty()) {
intent.putExtra(Intent.EXTRA_TEXT, text)
}
popupLabel?.also { intent = Intent.createChooser(intent, it) }
startActivityWithFlagNewTask(intent)
}
fun Context.shareText(text: String, popupLabel: String?) {
var intent = Intent()
intent.action = Intent.ACTION_SEND
intent.putExtra(Intent.EXTRA_TEXT, text)
intent.type = "text/plain"
popupLabel?.also { intent = Intent.createChooser(intent, it) }
startActivityWithFlagNewTask(intent)
}
/**
* Return the formatted date and time based on local system settings
*/
fun Context.getLocalizedDateTime(timeInMillis: Long): String {
val date = Date(timeInMillis)
val dateFormat = DateFormat.getMediumDateFormat(this)
val timeFormat = DateFormat.getTimeFormat(this)
return dateFormat.format(date) + " " + timeFormat.format(date)
}
| 0 | null | 2 | 4 | 932fe4a62057ae1cb43e9c249e819a2b3c69b375 | 4,402 | ColorBlindClickAndroid | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/ThumbUpOffAltRounded.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/ThumbUpOffAltRounded")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val ThumbUpOffAltRounded: SvgIconComponent
| 12 | null | 5 | 983 | 372c0e4bdf95ba2341eda473d2e9260a5dd47d3b | 222 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/me/mitul/aij/home/CollageListActivity.kt | mitulvaghamshi | 555,605,505 | false | {"Kotlin": 99663} | package me.mitul.aij.home
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.AdapterView.OnItemClickListener
import android.widget.EditText
import android.widget.ListView
import android.widget.TextView
import me.mitul.aij.R
import me.mitul.aij.adapter.AdapterCollage
import me.mitul.aij.helper.HelperCollage
import me.mitul.aij.model.Collage
import me.mitul.aij.utils.ArrayListOps
import me.mitul.aij.utils.MyTextWatcher
class CollageListActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_common_listview)
findViewById<View>(R.id.expandableListView).visibility = View.GONE
val dbHelper = HelperCollage(this)
val list: ArrayList<Collage> =
when (intent.getStringExtra("selected_or_all")) {
"ALL" -> dbHelper.selectAllCollage()
"BRANCH" -> dbHelper.selectBranchWiseCollage(
intent.getStringExtra("id_branch_collage")
)
"UNIVERSITY" -> dbHelper.selectUniversityWiseCollage(
intent.getStringExtra("id_to_find_university")
)
else -> ArrayList()
}
val listview = findViewById<ListView>(R.id.common_listview)
listview.visibility = View.VISIBLE
listview.setAdapter(AdapterCollage(this, list))
listview.isTextFilterEnabled = true
listview.onItemClickListener = OnItemClickListener { _, view, _, _ ->
startActivity(
Intent(this, DetailCollageActivity::class.java)
.putExtra(
"id_to_find",
(view.findViewById<TextView>(R.id.collage_list_item_collage_id))
.getText().toString()
)
)
}
findViewById<EditText>(R.id.edSearchCommon).addTextChangedListener(
MyTextWatcher(list, object : ArrayListOps<Collage> {
override fun onListSet(list: ArrayList<Collage>) =
listview.setAdapter(AdapterCollage(this@CollageListActivity, list))
override fun getName(item: Collage) = item.collageName!!
})
)
}
}
| 0 | Kotlin | 0 | 0 | 322df9b37045da04dfe9fb6f488a2d100540ba30 | 2,364 | AIJ | MIT License |
01-Estructurada/src/main/kotlin/Funciones.kt | joseluisgs | 509,140,631 | false | {"Kotlin": 193489, "Java": 3788} | fun main() {
val valor = miFuncion2()
println(valor)
// Parametros con valores por defecto
println(parametros("Pepe"))
println(parametros("Pepe", 23))
println(parametros("Pepe", 23, true))
// Parametros nombrados
println(parametros(edad = 25, repetidor = false, nombre = "Pedro"))
// Numero variable de parámetros
println(calificacion("Pepe", 7.0))
println(calificacion("Pepe", 7.0, 8.5))
println(calificacion("Pepe", 7.0, 8.5, 9.0))
var notas = DoubleArray(10)
println(calificacion("Pepe", *notas))
val (a, b) = notas
}
fun miFuncion(): Int {
return 1
}
fun miFuncion2() = "Esto es una expression Body"
// Parametros
/*fun parametros(nombre: String, edad:Int): String {
return "$nombre $edad"
}
// Parametros
fun parametros(nombre: String, edad:Int, repetidor: Boolean): String {
return "$nombre $edad $repetidor";
}*/
// Parametros con valores por defecto
fun parametros(nombre: String, edad: Int = 18, repetidor: Boolean = false): String {
return "$nombre $edad $repetidor"
}
// Numero indeterminado de parametros
fun calificacion(nombre: String, vararg notas: Double): String {
// for(i in notas)
return "$nombre $notas"
}
| 0 | Kotlin | 3 | 20 | 47a6bbb5cbd088eb0b01184338ece4aa8cbffdec | 1,219 | Kotlin-Bootcamp-DAMnificados-2022 | MIT License |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/quicksight/CfnDataSetCastColumnTypeOperationPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.quicksight
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.quicksight.CfnDataSet
/**
* A transform operation that casts a column to a different type.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.quicksight.*;
* CastColumnTypeOperationProperty castColumnTypeOperationProperty =
* CastColumnTypeOperationProperty.builder()
* .columnName("columnName")
* .newColumnType("newColumnType")
* // the properties below are optional
* .format("format")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-dataset-castcolumntypeoperation.html)
*/
@CdkDslMarker
public class CfnDataSetCastColumnTypeOperationPropertyDsl {
private val cdkBuilder: CfnDataSet.CastColumnTypeOperationProperty.Builder =
CfnDataSet.CastColumnTypeOperationProperty.builder()
/**
* @param columnName Column name.
*/
public fun columnName(columnName: String) {
cdkBuilder.columnName(columnName)
}
/**
* @param format When casting a column from string to datetime type, you can supply a string in a
* format supported by Amazon QuickSight to denote the source data format.
*/
public fun format(format: String) {
cdkBuilder.format(format)
}
/**
* @param newColumnType New column data type.
*/
public fun newColumnType(newColumnType: String) {
cdkBuilder.newColumnType(newColumnType)
}
public fun build(): CfnDataSet.CastColumnTypeOperationProperty = cdkBuilder.build()
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 1,905 | awscdk-dsl-kotlin | Apache License 2.0 |
cours-standard/Partie_3_diaporama_photo/Slideshow/app/src/main/java/fr/purplegiraffe/slideshow/SlideshowActivity.kt | P-Giraffe | 156,359,600 | false | null | package fr.purplegiraffe.slideshow
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_slideshow.*
class SlideshowActivity : AppCompatActivity() {
val photoList = arrayOf(R.drawable.sushi, R.drawable.chat1, R.drawable.chien1, R.drawable.chat2, R.drawable.chien2, R.drawable.chat3)
var currentPhotoIndex = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_slideshow)
}
fun previousButtonTouched(button:View) {
currentPhotoIndex = currentPhotoIndex - 1
if (currentPhotoIndex < 0) {
currentPhotoIndex = photoList.size - 1
}
imageView.setImageResource(photoList[currentPhotoIndex])
}
fun nextButtonTouched(button: View) {
currentPhotoIndex = currentPhotoIndex + 1
if (currentPhotoIndex >= photoList.size) {
currentPhotoIndex = 0
}
imageView.setImageResource(photoList[currentPhotoIndex])
}
}
| 0 | Kotlin | 9 | 10 | 9cfb906728be84ec0c0f56205e9884f7cc04c894 | 1,095 | cours-android | Apache License 2.0 |
cours-standard/Partie_3_diaporama_photo/Slideshow/app/src/main/java/fr/purplegiraffe/slideshow/SlideshowActivity.kt | P-Giraffe | 156,359,600 | false | null | package fr.purplegiraffe.slideshow
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import kotlinx.android.synthetic.main.activity_slideshow.*
class SlideshowActivity : AppCompatActivity() {
val photoList = arrayOf(R.drawable.sushi, R.drawable.chat1, R.drawable.chien1, R.drawable.chat2, R.drawable.chien2, R.drawable.chat3)
var currentPhotoIndex = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_slideshow)
}
fun previousButtonTouched(button:View) {
currentPhotoIndex = currentPhotoIndex - 1
if (currentPhotoIndex < 0) {
currentPhotoIndex = photoList.size - 1
}
imageView.setImageResource(photoList[currentPhotoIndex])
}
fun nextButtonTouched(button: View) {
currentPhotoIndex = currentPhotoIndex + 1
if (currentPhotoIndex >= photoList.size) {
currentPhotoIndex = 0
}
imageView.setImageResource(photoList[currentPhotoIndex])
}
}
| 0 | Kotlin | 9 | 10 | 9cfb906728be84ec0c0f56205e9884f7cc04c894 | 1,095 | cours-android | Apache License 2.0 |
components/resources/library/src/androidMain/kotlin/org/jetbrains/compose/resources/FontResources.android.kt | JetBrains | 293,498,508 | false | {"Kotlin": 1639423, "Shell": 12178, "Dockerfile": 4774, "Swift": 2823, "JavaScript": 2695, "Java": 1964, "PowerShell": 1708, "Groovy": 1415, "HTML": 1219, "Ruby": 404} | package org.jetbrains.compose.resources
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.Font
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
@ExperimentalResourceApi
@Composable
actual fun Font(resource: FontResource, weight: FontWeight, style: FontStyle): Font {
val path = resource.getPathByEnvironment()
return Font(path, LocalContext.current.assets, weight, style)
} | 1,182 | Kotlin | 1025 | 13,951 | 5e999e7b7d832bc992756d68d2f0a1e91b6cbfe5 | 508 | compose-multiplatform | Apache License 2.0 |
app/src/main/java/com/example/githubusers/di/DataScope.kt | nmauludina | 327,646,453 | true | {"Kotlin": 85510} | package com.example.githubusers.di
import javax.inject.Qualifier
@Qualifier
annotation class DataScope | 0 | null | 0 | 0 | dcc33a9aef31d639a65937d416b887301bfd36d3 | 104 | GithubUsers | Apache License 2.0 |
lib/src/main/kotlin/com/lemonappdev/konsist/api/provider/KoInitBlockProvider.kt | LemonAppDev | 621,181,534 | false | null | package com.lemonappdev.konsist.api.provider
import com.lemonappdev.konsist.api.declaration.KoInitBlockDeclaration
/**
* An interface representing a Kotlin declaration that provides access to init block declarations.
*/
interface KoInitBlockProvider : KoBaseProvider {
/**
* The init blocks of the declaration.
*/
val initBlocks: List<KoInitBlockDeclaration>
/**
* The number of init blocks.
*/
val numInitBlocks: Int
/**
* Determines whatever declaration has init blocks.
*/
@Deprecated("Will be removed in v0.16.0", ReplaceWith("hasInitBlocks()"))
val hasInitBlocks: Boolean
/**
* Returns the number of init blocks that satisfies the specified predicate present in the declaration.
*
* @param predicate The predicate function to determine if an init block satisfies a condition.
* @return The number of init blocks in the declaration.
*/
fun countInitBlocks(predicate: (KoInitBlockDeclaration) -> Boolean): Int
/**
* Determines whatever declaration has init blocks.
*
* @return `true` if the declaration has init block, `false` otherwise.
*/
fun hasInitBlocks(): Boolean
/**
* Determines whether the declaration has at least one init block that satisfies the provided predicate.
*
* @param predicate A function that defines the condition to be met by a init block declaration.
* @return `true` if there is a matching declaration, `false` otherwise.
*/
fun hasInitBlock(predicate: (KoInitBlockDeclaration) -> Boolean): Boolean
/**
* Determines whether the declaration has all init blocks that satisfy the provided predicate.
*
* Note that if the init blocks contains no elements, the function returns `true` because there are no elements in it
* that do not match the predicate.
*
* @param predicate A function that defines the condition to be met by init block declarations.
* @return `true` if all init block declarations satisfy the predicate, `false` otherwise.
*/
fun hasAllInitBlocks(predicate: (KoInitBlockDeclaration) -> Boolean): Boolean
}
| 6 | null | 27 | 995 | 603d19e179f59445c5f4707c1528a438e4595136 | 2,160 | konsist | Apache License 2.0 |
src/commonTest/kotlin/advent2020/day08/Day08PuzzleTest.kt | jakubgwozdz | 312,526,719 | false | null | package advent2020.day08
import advent2020.readResource
import advent2020.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
class Day08PuzzleTest {
val myPuzzleInput by lazy { readResource("day08") }
@Test
fun examplePart1() = runTest {
val sampleInput = """
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6
""".trimIndent()
val actual = part1(sampleInput)
assertEquals("5", actual)
}
@Test
fun examplePart2() = runTest {
val sampleInput = """
nop +0
acc +1
jmp +4
acc +3
jmp -3
acc -99
acc +1
jmp -4
acc +6
""".trimIndent()
val actual = part2(sampleInput)
assertEquals("8", actual)
}
@Test
fun jakubgwozdzPart1() = runTest {
val actual = part1(myPuzzleInput)
assertEquals("2080", actual)
}
@Test
fun jakubgwozdzPart2() = runTest {
val actual = part2(myPuzzleInput)
assertEquals("2477", actual)
}
}
| 0 | Kotlin | 0 | 2 | e233824109515fc4a667ad03e32de630d936838e | 1,220 | advent-of-code-2020 | MIT License |
webflows/src/main/java/com/schibsted/account/webflows/tracking/SchibstedAccountTracker.kt | schibsted | 385,551,335 | false | {"Kotlin": 237572, "Java": 3591} | package com.schibsted.account.webflows.tracking
internal object SchibstedAccountTracker {
internal fun track(event: SchibstedAccountTrackingEvent) {
SchibstedAccountTrackerStore.notifyListeners(event)
}
}
| 3 | Kotlin | 3 | 2 | 85193ec1bbd42e2cffefd81ea3541c9e5e683e28 | 222 | account-sdk-android-web | MIT License |
src/main/kotlin/dev/usbharu/hideout/core/service/media/S3MediaDataStore.kt | usbharu | 627,026,893 | false | {"Kotlin": 1337734, "Mustache": 111614, "Gherkin": 21440, "JavaScript": 1112, "HTML": 341} | /*
* Copyright (C) 2024 usbharu
*
* 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 dev.usbharu.hideout.core.service.media
import dev.usbharu.hideout.application.config.S3StorageConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.withContext
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.stereotype.Service
import software.amazon.awssdk.core.sync.RequestBody
import software.amazon.awssdk.services.s3.S3Client
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest
import software.amazon.awssdk.services.s3.model.GetUrlRequest
import software.amazon.awssdk.services.s3.model.PutObjectRequest
@Service
@ConditionalOnProperty("hideout.storage.type", havingValue = "s3")
class S3MediaDataStore(private val s3Client: S3Client, private val s3StorageConfig: S3StorageConfig) : MediaDataStore {
override suspend fun save(dataMediaSave: MediaSave): SavedMedia {
val fileUploadRequest = PutObjectRequest.builder()
.bucket(s3StorageConfig.bucket)
.key(dataMediaSave.name)
.build()
val thumbnailKey = "thumbnail-${dataMediaSave.name}"
val thumbnailUploadRequest = PutObjectRequest.builder()
.bucket(s3StorageConfig.bucket)
.key(thumbnailKey)
.build()
withContext(Dispatchers.IO) {
awaitAll(
async {
if (dataMediaSave.thumbnailInputStream != null) {
s3Client.putObject(
thumbnailUploadRequest,
RequestBody.fromBytes(dataMediaSave.thumbnailInputStream)
)
s3Client.utilities()
.getUrl(GetUrlRequest.builder().bucket(s3StorageConfig.bucket).key(thumbnailKey).build())
} else {
null
}
},
async {
s3Client.putObject(fileUploadRequest, RequestBody.fromBytes(dataMediaSave.fileInputStream))
s3Client.utilities()
.getUrl(GetUrlRequest.builder().bucket(s3StorageConfig.bucket).key(dataMediaSave.name).build())
}
)
}
return SuccessSavedMedia(
name = dataMediaSave.name,
url = "${s3StorageConfig.publicUrl}/${s3StorageConfig.bucket}/${dataMediaSave.name}",
thumbnailUrl = "${s3StorageConfig.publicUrl}/${s3StorageConfig.bucket}/$thumbnailKey"
)
}
override suspend fun save(dataSaveRequest: MediaSaveRequest): SavedMedia {
logger.info("MEDIA upload. {}", dataSaveRequest.name)
val fileUploadRequest = PutObjectRequest.builder()
.bucket(s3StorageConfig.bucket)
.key(dataSaveRequest.name)
.build()
logger.info("MEDIA upload. bucket: {} key: {}", s3StorageConfig.bucket, dataSaveRequest.name)
val thumbnailKey = "thumbnail-${dataSaveRequest.name}"
val thumbnailUploadRequest = PutObjectRequest.builder()
.bucket(s3StorageConfig.bucket)
.key(thumbnailKey)
.build()
logger.info("MEDIA upload. bucket: {} key: {}", s3StorageConfig.bucket, thumbnailKey)
withContext(Dispatchers.IO) {
awaitAll(
async {
if (dataSaveRequest.thumbnailPath != null) {
s3Client.putObject(
thumbnailUploadRequest,
RequestBody.fromFile(dataSaveRequest.thumbnailPath)
)
} else {
null
}
},
async {
s3Client.putObject(fileUploadRequest, RequestBody.fromFile(dataSaveRequest.filePath))
}
)
}
val successSavedMedia = SuccessSavedMedia(
name = dataSaveRequest.name,
url = "${s3StorageConfig.publicUrl}/${s3StorageConfig.bucket}/${dataSaveRequest.name}",
thumbnailUrl = "${s3StorageConfig.publicUrl}/${s3StorageConfig.bucket}/$thumbnailKey"
)
logger.info("SUCCESS Media upload. {}", dataSaveRequest.name)
logger.debug(
"name: {} url: {} thumbnail url: {}",
successSavedMedia.name,
successSavedMedia.url,
successSavedMedia.thumbnailUrl
)
return successSavedMedia
}
override suspend fun delete(id: String) {
val fileDeleteRequest = DeleteObjectRequest.builder().bucket(s3StorageConfig.bucket).key(id).build()
val thumbnailDeleteRequest =
DeleteObjectRequest.builder().bucket(s3StorageConfig.bucket).key("thumbnail-$id").build()
s3Client.deleteObject(fileDeleteRequest)
s3Client.deleteObject(thumbnailDeleteRequest)
}
companion object {
private val logger = LoggerFactory.getLogger(S3MediaDataStore::class.java)
}
}
| 38 | Kotlin | 0 | 9 | 5512c43ffacf0480f652465ccf5f71b559387592 | 5,679 | Hideout | Apache License 2.0 |
src/test/kotlin/de/quinesoft/bookslist/cli/CommandTest.kt | das-maximum | 494,503,261 | false | null | package de.quinesoft.bookslist.cli
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.should
import io.kotest.matchers.types.beOfType
class CommandTest : WordSpec({
"parseCommand" should {
"respond with AddCommand" {
val action = parseCommand(arrayOf("add"))
action should beOfType<AddCommand>()
}
"respond with ListComment" {
val action = parseCommand(arrayOf("list"))
action should beOfType<ListCommand>()
}
"respond with ReadComment" {
val action = parseCommand(arrayOf("read"))
action should beOfType<ReadCommand>()
}
"respond with SearchComment" {
val action = parseCommand(arrayOf("search"))
action should beOfType<SearchCommand>()
}
"respond with UnknownComment" {
val action = parseCommand(arrayOf("sfasd"))
action should beOfType<UnknownCommand>()
}
}
}) | 0 | Kotlin | 0 | 0 | 32a8871428cab247e2f0434733e7be500abf7494 | 995 | bookslist | MIT License |
src/main/java/dev/mikchan/mcnp/motd/user/manager/IUserManager.kt | MikChanNoPlugins | 723,544,621 | false | {"Kotlin": 22072} | package dev.mikchan.mcnp.motd.user.manager
import org.bukkit.OfflinePlayer
import org.bukkit.entity.Player
import java.net.InetAddress
interface IUserManager {
fun cache(player: Player)
fun get(address: InetAddress?): OfflinePlayer?
}
| 0 | Kotlin | 0 | 0 | d8abc26d9863ecb3c460446301ee3efc7f4bfdf4 | 245 | MOTD | MIT License |
app/src/main/java/com/dede/android_eggs/main/holders/WavyHolder.kt | hushenghao | 306,645,388 | false | {"Java": 532422, "Kotlin": 466397, "Python": 8564, "Ruby": 2933} | package com.dede.android_eggs.main.holders
import android.view.View
import android.widget.ImageView
import com.dede.android_eggs.R
import com.dede.android_eggs.main.entity.Egg
import com.dede.android_eggs.main.entity.Wavy
import com.dede.android_eggs.ui.adapter.VHType
import com.dede.android_eggs.ui.adapter.VHolder
import com.dede.android_eggs.util.createRepeatWavyDrawable
import com.dede.basic.requireDrawable
@VHType(viewType = Egg.VIEW_TYPE_WAVY)
class WavyHolder(view: View) : VHolder<Wavy>(view) {
private val imageView = itemView.findViewById<ImageView>(R.id.iv_icon)
@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
override fun onBindViewHolder(wavy: Wavy) {
if (!wavy.repeat) {
imageView.scaleType = ImageView.ScaleType.CENTER
imageView.setImageDrawable(context.requireDrawable(wavy.wavyRes))
} else {
imageView.scaleType = ImageView.ScaleType.FIT_XY
imageView.setImageDrawable(createRepeatWavyDrawable(context, wavy.wavyRes))
}
}
} | 1 | Kotlin | 24 | 456 | a7bc8846e86fb8d78681b9168b05c27457951678 | 1,035 | AndroidEasterEggs | Apache License 2.0 |
bidon/src/test/java/org/bidon/sdk/auction/models/AdObjectRequestBodySerializerTest.kt | bidon-io | 654,165,570 | false | {"Kotlin": 992814, "Java": 2186} | package org.bidon.sdk.auction.models
import org.bidon.sdk.config.models.json_scheme_utils.assertEquals
import org.bidon.sdk.config.models.json_scheme_utils.expectedJsonStructure
import org.bidon.sdk.utils.serializer.serialize
import org.junit.Test
/**
* Created by Bidon Team on 24/02/2023.
*/
internal class AdObjectRequestBodySerializerTest {
@Test
fun `AdObjectRequestBody Serializer full`() {
val data = AdObjectRequest(
pricefloor = 1.23,
auctionId = "aId",
orientationCode = AdObjectRequest.Orientation.Portrait.code,
banner = BannerRequest(BannerRequest.StatFormat.LeaderBoard728x90.code),
interstitial = InterstitialRequest(),
rewarded = RewardedRequest(),
)
val actual = data.serialize()
actual.assertEquals(
expectedJsonStructure {
"pricefloor" hasValue 1.23
"auction_id" hasValue "aId"
"orientation" hasValue "PORTRAIT"
"banner" hasJson expectedJsonStructure {
"format" hasValue "LEADERBOARD"
}
"interstitial" hasJson expectedJsonStructure { /* EMPTY */ }
"rewarded" hasJson expectedJsonStructure { /* EMPTY */ }
}
)
}
@Test
fun `AdObjectRequestBody Serializer only banner`() {
val data = AdObjectRequest(
pricefloor = 1.23,
auctionId = "aId",
orientationCode = AdObjectRequest.Orientation.Portrait.code,
banner = BannerRequest(BannerRequest.StatFormat.LeaderBoard728x90.code),
interstitial = null,
rewarded = null,
)
val actual = data.serialize()
actual.assertEquals(
expectedJsonStructure {
"pricefloor" hasValue 1.23
"auction_id" hasValue "aId"
"orientation" hasValue "PORTRAIT"
"banner" hasJson expectedJsonStructure {
"format" hasValue "LEADERBOARD"
}
}
)
}
@Test
fun `AdObjectRequestBody Serializer only INTERSTITIAL`() {
val data = AdObjectRequest(
pricefloor = 1.23,
auctionId = "aId",
orientationCode = AdObjectRequest.Orientation.Portrait.code,
banner = null,
interstitial = InterstitialRequest(),
rewarded = null,
)
val actual = data.serialize()
actual.assertEquals(
expectedJsonStructure {
"pricefloor" hasValue 1.23
"auction_id" hasValue "aId"
"orientation" hasValue "PORTRAIT"
"interstitial" hasJson expectedJsonStructure { /* EMPTY */ }
}
)
}
@Test
fun `AdObjectRequestBody Serializer only REWARDED`() {
val data = AdObjectRequest(
pricefloor = 1.23,
auctionId = "aId",
orientationCode = AdObjectRequest.Orientation.Portrait.code,
banner = null,
interstitial = null,
rewarded = RewardedRequest(),
)
val actual = data.serialize()
actual.assertEquals(
expectedJsonStructure {
"pricefloor" hasValue 1.23
"auction_id" hasValue "aId"
"orientation" hasValue "PORTRAIT"
"rewarded" hasJson expectedJsonStructure { /* EMPTY */ }
}
)
}
} | 0 | Kotlin | 0 | 0 | 440f8824115bd71f949ce6aac075d830af89eca3 | 3,517 | bidon_sdk_android | Apache License 2.0 |
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/plugins/Serialization.kt | navikt | 435,813,834 | false | {"Kotlin": 1636685, "TypeScript": 1434475, "SCSS": 40738, "JavaScript": 27458, "PLpgSQL": 14591, "Handlebars": 3189, "HTML": 2263, "Dockerfile": 1423, "CSS": 1145, "Shell": 396} | package no.nav.mulighetsrommet.api.plugins
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import no.nav.mulighetsrommet.serialization.json.JsonIgnoreUnknownKeys
fun Application.configureSerialization() {
install(ContentNegotiation) {
json(
JsonIgnoreUnknownKeys,
)
}
}
| 2 | Kotlin | 2 | 7 | f64f29f5ad559115c0a6705f44f36bdffb273258 | 391 | mulighetsrommet | MIT License |
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/plugins/Serialization.kt | navikt | 435,813,834 | false | {"Kotlin": 1636685, "TypeScript": 1434475, "SCSS": 40738, "JavaScript": 27458, "PLpgSQL": 14591, "Handlebars": 3189, "HTML": 2263, "Dockerfile": 1423, "CSS": 1145, "Shell": 396} | package no.nav.mulighetsrommet.api.plugins
import io.ktor.serialization.kotlinx.json.*
import io.ktor.server.application.*
import io.ktor.server.plugins.contentnegotiation.*
import no.nav.mulighetsrommet.serialization.json.JsonIgnoreUnknownKeys
fun Application.configureSerialization() {
install(ContentNegotiation) {
json(
JsonIgnoreUnknownKeys,
)
}
}
| 2 | Kotlin | 2 | 7 | f64f29f5ad559115c0a6705f44f36bdffb273258 | 391 | mulighetsrommet | MIT License |
app/src/main/java/com/example/android/firebaseui_login_sample/MainFragment.kt | ejep520 | 353,732,719 | true | {"Kotlin": 17835} | /*
* Copyright 2019, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.firebaseui_login_sample
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.contract.ActivityResultContract
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import com.example.android.firebaseui_login_sample.databinding.FragmentMainBinding
import com.firebase.ui.auth.AuthUI
import com.firebase.ui.auth.IdpResponse
import com.google.firebase.auth.FirebaseAuth
class MainFragment : Fragment() {
companion object {
const val TAG = "MainFragment"
const val SIGN_IN_RESULT_CODE = 1001
}
// Get a reference to the ViewModel scoped to this Fragment
private val viewModel by viewModels<LoginViewModel>()
private lateinit var binding: FragmentMainBinding
private lateinit var signInResult: String
private val contract = registerForActivityResult(SignInContract()) {
signInResult = it
Log.i(TAG, signInResult)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
): View {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false)
// TODO Remove the two lines below once observeAuthenticationState is implemented.
binding.welcomeText.text = viewModel.getFactToDisplay(requireContext())
binding.authButton.text = getString(R.string.login_btn)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
observeAuthenticationState()
binding.authButton.setOnClickListener {
launchSignInFlow()
}
binding.settingsBtn.setOnClickListener {
val action = MainFragmentDirections.actionMainFragmentToSettingsFragment()
findNavController().navigate(action)
}
}
/**
* Observes the authentication state and changes the UI accordingly.
* If there is a logged in user: (1) show a logout button and (2) display their name.
* If there is no logged in user: show a login button
*/
private fun observeAuthenticationState() {
val factToDisplay = viewModel.getFactToDisplay(requireContext())
viewModel.authenticationState.observe(viewLifecycleOwner, { authenticationState ->
if (authenticationState == LoginViewModel.AuthenticationState.AUTHENTICATED) {
binding.authButton.text = getText(R.string.logout_button_text)
binding.welcomeText.text = getFactWithPersonalization(factToDisplay)
binding.authButton.setOnClickListener { AuthUI.getInstance().signOut(requireContext()) }
} else {
binding.authButton.text = getText(R.string.login_button_text)
binding.authButton.setOnClickListener { launchSignInFlow() }
binding.welcomeText.text = factToDisplay
}
})
}
private fun getFactWithPersonalization(fact: String): String {
return String.format(resources.getString(
R.string.welcome_message_authed,
FirebaseAuth.getInstance().currentUser?.displayName,
Character.toLowerCase(fact[0]) + fact.substring(1)
))
}
private fun launchSignInFlow() {
// Create and launch sign-in intent. We listen to the response of this activity with
// the SIGN_IN_REQUEST_CODE
contract.launch(SIGN_IN_RESULT_CODE)
}
class SignInContract: ActivityResultContract<Int, String>() {
override fun createIntent(context: Context, input: Int?): Intent {
// Give users the option to sign in / register with their email or Google account.
// If users choose to register with their email, they will need to create a password
// as well.
val providers = arrayListOf(
AuthUI.IdpConfig.EmailBuilder().build(),
AuthUI.IdpConfig.GoogleBuilder().build()
// This is where you can provide more ways for users to register and sign in.
)
return AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build()
}
override fun parseResult(resultCode: Int, intent: Intent?): String {
return if (resultCode == Activity.RESULT_OK) "Successfully signed in user ${FirebaseAuth.getInstance().currentUser?.displayName}!"
else "Activity Failed"
}
}
} | 0 | Kotlin | 0 | 0 | 04e10f7f5d82a9c8f75ea202bbcfa1b954e28f5b | 5,579 | android-kotlin-login | Apache License 2.0 |
bilimiao-comm/src/main/java/com/a10miaomiao/bilimiao/comm/network/BiliGRPCHttp.kt | 10miaomiao | 142,169,120 | false | null | package com.a10miaomiao.bilimiao.comm.network
import android.os.Build
import com.a10miaomiao.bilimiao.comm.BilimiaoCommApp
import com.a10miaomiao.bilimiao.comm.utils.DebugMiao
import io.grpc.MethodDescriptor
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
class BiliGRPCHttp<ReqT, RespT> internal constructor(
private val grpcMethod: MethodDescriptor<ReqT, RespT>,
private val reqMessage: ReqT,
) {
var baseUrl = ApiHelper.GRPC_BASE
private val client = OkHttpClient()
var needToken = true
private fun Request.Builder.addHeaders(): Request.Builder {
val token = BilimiaoCommApp.commApp.loginInfo?.token_info?.access_token ?: ""
if (needToken && token.isNotBlank()) {
addHeader(BiliHeaders.Authorization, BiliHeaders.Identify + " " + token)
BilimiaoCommApp.commApp.loginInfo?.token_info?.let{
addHeader(BiliHeaders.BiliMid, it.mid.toString())
}
}
addHeader(BiliHeaders.UserAgent, ApiHelper.USER_AGENT)
addHeader(BiliHeaders.AppKey, BiliGRPCConfig.mobileApp)
addHeader(BiliHeaders.BiliDevice, BiliGRPCConfig.getDeviceBin())
addHeader(BiliHeaders.BiliFawkes, BiliGRPCConfig.getFawkesreqBin())
addHeader(BiliHeaders.BiliLocale, BiliGRPCConfig.getLocaleBin())
addHeader(BiliHeaders.BiliMeta, BiliGRPCConfig.getMetadataBin(token))
addHeader(BiliHeaders.BiliNetwork, BiliGRPCConfig.getNetworkBin())
addHeader(BiliHeaders.BiliRestriction, BiliGRPCConfig.getRestrictionBin())
addHeader(BiliHeaders.GRPCAcceptEncodingKey, BiliHeaders.GRPCAcceptEncodingValue)
addHeader(BiliHeaders.GRPCTimeOutKey, BiliHeaders.GRPCTimeOutValue)
addHeader(BiliHeaders.Envoriment, BiliGRPCConfig.envorienment)
addHeader(BiliHeaders.TransferEncodingKey, BiliHeaders.TransferEncodingValue)
addHeader(BiliHeaders.TEKey, BiliHeaders.TEValue)
addHeader(BiliHeaders.Buvid, BilimiaoCommApp.commApp.getBilibiliBuvid())
return this
}
private fun buildRequest(): Request {
val url = baseUrl + grpcMethod.fullMethodName.replace("interfaces", "interface")
val messageBytes = grpcMethod.streamRequest(reqMessage).readBytes()
// 校验用?第五位为数组长度
val stateBytes = byteArrayOf(0, 0, 0, 0, messageBytes.size.toByte())
// 合并两个字节数组
val bodyBytes = ByteArray(stateBytes.size + messageBytes.size)
System.arraycopy(stateBytes, 0, bodyBytes, 0, stateBytes.size)
System.arraycopy(messageBytes, 0, bodyBytes, stateBytes.size, messageBytes.size)
val body = bodyBytes.toRequestBody(
BiliHeaders.GRPCContentType.toMediaType()
)
return Request.Builder()
.url(url)
.addHeaders()
.post(body)
.build()
}
private fun parseResponse(res: Response): RespT {
val inputStream = res.body!!.byteStream()
inputStream.skip(5L)
return grpcMethod.parseResponse(inputStream)
}
fun call(): RespT {
val req = buildRequest()
val res = client.newCall(req).execute()
return parseResponse(res)
}
suspend fun awaitCall(): RespT{
return suspendCoroutine { continuation ->
val req = buildRequest()
client.newCall(req).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
continuation.resumeWithException(e)
}
override fun onResponse(call: Call, response: Response) {
try {
continuation.resume(parseResponse(response))
} catch (e: Exception) {
continuation.resumeWithException(e)
}
}
})
}
}
}
fun <ReqT, RespT> MethodDescriptor<ReqT, RespT>.request(
reqMessage: ReqT,
biliGRPCHttpBuilder: (BiliGRPCHttp<ReqT, RespT>.() -> Unit)? = null
): BiliGRPCHttp<ReqT, RespT> {
return BiliGRPCHttp(
this,
reqMessage,
).apply {
biliGRPCHttpBuilder?.invoke(this)
}
}
| 44 | null | 38 | 977 | 1d59b82ba30b4c2e83c781479d09c48c3a82cd47 | 4,359 | bilimiao2 | Apache License 2.0 |
app/src/main/java/kittoku/osc/preference/custom/LinkPreference.kt | kittoku | 173,106,265 | false | null | package kittoku.osc.preference.custom
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.util.AttributeSet
import android.widget.TextView
import androidx.preference.Preference
import androidx.preference.PreferenceViewHolder
import kittoku.osc.preference.OscPreference
internal abstract class LinkPreference(context: Context, attrs: AttributeSet) : Preference(context, attrs) {
abstract val oscPreference: OscPreference
abstract val preferenceTitle: String
abstract val preferenceSummary: String
abstract val url: String
override fun onAttached() {
super.onAttached()
title = preferenceTitle
summary = preferenceSummary
intent = Intent(Intent.ACTION_VIEW).also { it.data = Uri.parse(url) }
}
override fun onBindViewHolder(holder: PreferenceViewHolder?) {
super.onBindViewHolder(holder)
holder?.findViewById(android.R.id.summary)?.also {
it as TextView
it.maxLines = Int.MAX_VALUE
}
}
}
internal class LinkOscPreference(context: Context, attrs: AttributeSet) : LinkPreference(context, attrs) {
override val oscPreference = OscPreference.LINK_OSC
override val preferenceTitle = "Move to this app's project page"
override val preferenceSummary = "github.com/kittoku/Open-SSTP-Client"
override val url = "https://github.com/kittoku/Open-SSTP-Client"
}
| 4 | Kotlin | 29 | 90 | f624698e87503624d87aae17491df7d187e416b2 | 1,431 | Open-SSTP-Client | MIT License |
OfflineClient/cached-api/src/main/java/de/jbamberger/api/provider/backend/BackendModule.kt | JBamberger | 94,563,195 | false | null | package de.jbamberger.api.provider.backend
import dagger.Module
import dagger.Provides
import de.jbamberger.api.db.DatabaseModule
import de.jbamberger.api.net.NetModule
import retrofit2.Retrofit
import javax.inject.Singleton
/**
* Dependency Injection module to provide database related objects.
*
* @author <NAME> (<EMAIL>)
*/
@Module(includes = [DatabaseModule::class, NetModule::class])
internal class BackendModule {
@Provides
@Singleton
internal fun provideBackendApiInterface(retrofitBuilder: Retrofit.Builder): BackendApi {
return retrofitBuilder.baseUrl(BackendApi.BASE_URL).build().create(BackendApi::class.java)
}
}
| 0 | Kotlin | 0 | 1 | c5703c81a6c2ee527e8878753e3ba267f713ff12 | 657 | offlineclient | MIT License |
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/media/PlayListLine.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.remix.remix.media
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 com.woowla.compose.icon.collections.remix.remix.MediaGroup
public val MediaGroup.PlayListLine: ImageVector
get() {
if (_playListLine != null) {
return _playListLine!!
}
_playListLine = Builder(name = "PlayListLine", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(2.0f, 18.0f)
horizontalLineTo(12.0f)
verticalLineTo(20.0f)
horizontalLineTo(2.0f)
verticalLineTo(18.0f)
close()
moveTo(2.0f, 11.0f)
horizontalLineTo(16.0f)
verticalLineTo(13.0f)
horizontalLineTo(2.0f)
verticalLineTo(11.0f)
close()
moveTo(2.0f, 4.0f)
horizontalLineTo(22.0f)
verticalLineTo(6.0f)
horizontalLineTo(2.0f)
verticalLineTo(4.0f)
close()
moveTo(19.0f, 15.171f)
verticalLineTo(9.0f)
horizontalLineTo(24.0f)
verticalLineTo(11.0f)
horizontalLineTo(21.0f)
verticalLineTo(18.0f)
curveTo(21.0f, 19.657f, 19.657f, 21.0f, 18.0f, 21.0f)
curveTo(16.343f, 21.0f, 15.0f, 19.657f, 15.0f, 18.0f)
curveTo(15.0f, 16.343f, 16.343f, 15.0f, 18.0f, 15.0f)
curveTo(18.351f, 15.0f, 18.687f, 15.06f, 19.0f, 15.171f)
close()
moveTo(18.0f, 19.0f)
curveTo(18.552f, 19.0f, 19.0f, 18.552f, 19.0f, 18.0f)
curveTo(19.0f, 17.448f, 18.552f, 17.0f, 18.0f, 17.0f)
curveTo(17.448f, 17.0f, 17.0f, 17.448f, 17.0f, 18.0f)
curveTo(17.0f, 18.552f, 17.448f, 19.0f, 18.0f, 19.0f)
close()
}
}
.build()
return _playListLine!!
}
private var _playListLine: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,806 | compose-icon-collections | MIT License |
src/jvmMain/kotlin/com/beetroot/server/network/PacketDecoder.kt | BeetrootPowered | 255,452,972 | false | null | package com.beetroot.server.network
import br.com.devsrsouza.ktmcpacket.MinecraftProtocol
import br.com.devsrsouza.ktmcpacket.PacketState
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.ByteToMessageDecoder
class PacketDecoder : ByteToMessageDecoder() {
override fun decode(ctx: ChannelHandlerContext, buffer: ByteBuf, out: MutableList<Any>) {
buffer.markReaderIndex()
// TODO check whether the bytes from the packet size are readable
val packetSize = buffer.readVarInt()
// Checks and awaits whether the whole packet is not readable
if (buffer.readableBytes() < packetSize) {
buffer.resetReaderIndex()
return
}
val readerIndex = buffer.readerIndex()
val packetId = buffer.readVarInt()
val state = ctx.channel().attr(Network.STATE_ATTRIBUTE_KEY).get() ?: PacketState.HANDSHAKE
val packetType = state.clientById[packetId]
if (packetType != null && PacketBus.hasHandlers(packetType.kclass)) {
// Calculates the amount of data to read (packetSize - packetIdSize)
val dataSize = packetSize - (buffer.readerIndex() - readerIndex)
try {
// Reads into an byte array
val bytes = ByteArray(dataSize)
buffer.readBytes(bytes)
// Deserializes the packet
out.add(MinecraftProtocol.load(packetType.serializer, bytes))
} catch (ex: Exception) {
// If something goes wrong, we'll skip to the next packet
ex.printStackTrace() // TODO proper logging
buffer.readerIndex(readerIndex + packetSize)
}
} else {
// Skips to the next packet
buffer.readerIndex(readerIndex + packetSize)
return
}
}
} | 0 | Kotlin | 0 | 5 | 0e141ff3a2c32a7eb6c49867517e11830938ebc8 | 1,909 | Beetroot | MIT License |
multiplatform-compose/src/commonMain/kotlin/com/rouge41/kmm/compose/material/Text.kt | cl3m | 327,994,833 | false | null | package com.rouge41.kmm.compose.material
import com.rouge41.kmm.compose.runtime.Composable
import com.rouge41.kmm.compose.ui.text.style.TextOverflow
import com.rouge41.kmm.compose.ui.Modifier
import com.rouge41.kmm.compose.ui.graphics.Color
import com.rouge41.kmm.compose.ui.text.TextAlign
import com.rouge41.kmm.compose.ui.text.TextDecoration
import com.rouge41.kmm.compose.ui.text.TextStyle
import com.rouge41.kmm.compose.ui.text.font.FontFamily
import com.rouge41.kmm.compose.ui.text.font.FontStyle
import com.rouge41.kmm.compose.ui.text.font.FontWeight
import com.rouge41.kmm.compose.ui.unit.TextUnit
@Composable
expect fun Text(
text: String,
modifier: Modifier = Modifier,
color: Color = Color.Unspecified,
fontSize: TextUnit = TextUnit.Unspecified,
fontStyle: FontStyle? = null,
fontWeight: FontWeight? = null,
fontFamily: FontFamily? = null,
letterSpacing: TextUnit = TextUnit.Unspecified,
textDecoration: TextDecoration? = null,
textAlign: TextAlign? = null,
lineHeight: TextUnit = TextUnit.Unspecified,
overflow: TextOverflow = TextOverflow.Clip,
softWrap: Boolean = true,
maxLines: Int = Int.MAX_VALUE,
/*onTextLayout: (TextLayoutResult) -> Unit = {},*/
style: TextStyle? = null
) | 1 | Kotlin | 19 | 385 | 8d2059d69a18b76e3672db3fc9c558a31f9ca576 | 1,313 | multiplatform-compose | Apache License 2.0 |
src/test/kotlin/ajdepaul/taggedmusic/librarysources/TestJsonLibrarySource.kt | ajdepaul | 273,658,128 | false | null | /*
* Copyright © 2021 <NAME>
* Licensed under the MIT License https://ajdepaul.mit-license.org/
*/
package ajdepaul.taggedmusic.librarysources
import ajdepaul.taggedmusic.TagType
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class TestJsonLibrarySource {
@Rule
@JvmField
val tempDir = TemporaryFolder()
/** Tests the [JsonLibrarySource] constructors. */
@Test
fun testConstructor() {
val jsonFilePath = tempDir.newFile().toPath()
// initial text to test the text is overwritten
jsonFilePath.toFile().writeText("bad text")
// create the json file with default values
JsonLibrarySource(jsonFilePath, TagType(0))
// test new library source using that file
TestLibrarySourceUtil.assertDefaults(JsonLibrarySource(jsonFilePath))
}
/** Tests [JsonLibrarySource.updater]. */
@Test
fun testUpdater() {
val jsonFilePath = tempDir.newFile().toPath()
// test making changes
val songLibraryData =
TestLibrarySourceUtil.assertUpdates(JsonLibrarySource(jsonFilePath, TagType(0)))
// test changes were saved
TestLibrarySourceUtil.assertUpdated(JsonLibrarySource(jsonFilePath), songLibraryData)
}
/** Tests [JsonLibrarySource.getSongsByTags]. */
@Test
fun testGetSongsByTags() {
val jsonFilePath = tempDir.newFile().toPath()
// use util class for tests
TestLibrarySourceUtil.testGetSongsByTags(JsonLibrarySource(jsonFilePath, TagType(0)))
}
}
| 0 | Kotlin | 0 | 1 | 32cfd709c76734b690ce2999e87f95c92e4cfb08 | 1,569 | TaggedMusic | MIT License |
lib/sprout/src/main/kotlin/org/partiql/sprout/generator/target/kotlin/poems/KotlinBuilderPoem.kt | partiql | 186,474,394 | false | null | package org.partiql.sprout.generator.target.kotlin.poems
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.LambdaTypeName
import com.squareup.kotlinpoet.ParameterSpec
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.TypeVariableName
import com.squareup.kotlinpoet.asTypeName
import com.squareup.kotlinpoet.buildCodeBlock
import net.pearx.kasechange.toCamelCase
import net.pearx.kasechange.toPascalCase
import org.partiql.sprout.generator.target.kotlin.KotlinPoem
import org.partiql.sprout.generator.target.kotlin.KotlinSymbols
import org.partiql.sprout.generator.target.kotlin.spec.KotlinNodeSpec
import org.partiql.sprout.generator.target.kotlin.spec.KotlinPackageSpec
import org.partiql.sprout.generator.target.kotlin.spec.KotlinUniverseSpec
import org.partiql.sprout.generator.target.kotlin.types.Annotations
import org.partiql.sprout.model.TypeRef
/**
* Poem which creates a DSL for instantiation
*/
class KotlinBuilderPoem(symbols: KotlinSymbols) : KotlinPoem(symbols) {
override val id: String = "builder"
private val builderPackageName = "${symbols.rootPackage}.builder"
private val idProviderType = LambdaTypeName.get(returnType = String::class.asTypeName())
private val idProvider = PropertySpec.builder("_id", idProviderType).build()
// Abstract factory which can be used by DSL blocks
private val factoryName = "${symbols.rootId}Factory"
private val factoryClass = ClassName(builderPackageName, factoryName)
private val factory = TypeSpec.interfaceBuilder(factoryClass)
.addProperty(idProvider)
private val baseFactoryName = "${symbols.rootId}FactoryImpl"
private val baseFactoryClass = ClassName(builderPackageName, baseFactoryName)
private val baseFactory = TypeSpec.classBuilder(baseFactoryClass)
.addSuperinterface(factoryClass)
.addModifiers(KModifier.OPEN)
.addProperty(
idProvider.toBuilder()
.addModifiers(KModifier.OVERRIDE)
.initializer(
"{ %P }",
buildCodeBlock {
// universe-${"%08x".format(Random.nextInt())}
add("${symbols.rootId}-\${%S.format(%T.nextInt())}", "%08x", ClassName("kotlin.random", "Random"))
}
)
.build()
)
private val factoryParamDefault = ParameterSpec.builder("factory", factoryClass)
.defaultValue("%T.DEFAULT", factoryClass)
.build()
// Assume there's a <DOMAIN>.kt file in the package root containing the default builder
private val factoryDefault = ClassName(symbols.rootPackage, symbols.rootId)
// Java style builders, used by the DSL
private val buildersName = "${symbols.rootId}Builders"
private val buildersFile = FileSpec.builder(builderPackageName, buildersName)
// @file:Suppress("UNUSED_PARAMETER")
private val suppressUnused = AnnotationSpec.builder(Suppress::class)
.useSiteTarget(AnnotationSpec.UseSiteTarget.FILE)
.addMember("%S", "UNUSED_PARAMETER")
.build()
// Top-Level DSL holder, so that was close on the factory
private val dslName = "${symbols.rootId}Builder"
private val dslClass = ClassName(builderPackageName, dslName)
private val dslSpec = TypeSpec.classBuilder(dslClass)
.addProperty(
PropertySpec.builder("factory", factoryClass)
.addModifiers(KModifier.PRIVATE)
.initializer("factory")
.build()
)
.primaryConstructor(FunSpec.constructorBuilder().addParameter(factoryParamDefault).build())
// T : FooNode
private val boundedT = TypeVariableName("T", symbols.base)
// Static top-level entry point for DSL
private val dslFunc = FunSpec.builder(symbols.rootId.toCamelCase())
.addTypeVariable(boundedT)
.addParameter(factoryParamDefault)
.addParameter(
ParameterSpec.builder(
"block",
LambdaTypeName.get(
receiver = dslClass,
returnType = boundedT,
)
).build()
)
.addStatement("return %T(factory).block()", dslClass)
.build()
// Static companion object entry point for factory, similar to PIG "build"
private val factoryFunc = FunSpec.builder("create")
.addAnnotation(Annotations.jvmStatic)
.addTypeVariable(boundedT)
.addParameter(
ParameterSpec.builder(
"block",
LambdaTypeName.get(
receiver = factoryClass,
returnType = boundedT,
)
).build()
)
.addStatement("return %T.DEFAULT.block()", factoryClass)
.build()
override fun apply(universe: KotlinUniverseSpec) {
super.apply(universe)
universe.packages.add(
KotlinPackageSpec(
name = builderPackageName,
files = mutableListOf(
// Factory Interface
FileSpec.builder(builderPackageName, factoryName)
.addType(factory.addType(factoryCompanion()).build())
.build(),
// Factory Base
FileSpec.builder(builderPackageName, baseFactoryName)
.addType(baseFactory.build())
.build(),
// Java Builders
buildersFile.build(),
// DSL
FileSpec.builder(builderPackageName, dslName)
.addAnnotation(suppressUnused)
.addFunction(dslFunc)
.addType(dslSpec.build())
.build(),
)
)
)
}
override fun apply(node: KotlinNodeSpec.Product) {
val function = FunSpec.builder(symbols.camel(node.product.ref))
.apply {
node.props.forEach {
addParameter(it.name, it.type)
}
}
.returns(node.clazz)
.build()
// interface
factory.addFunction(function.toBuilder().addModifiers(KModifier.ABSTRACT).build())
// impl
baseFactory.addFunction(
function.toBuilder()
.addModifiers(KModifier.OVERRIDE)
.returns(node.clazz)
.apply {
val args = listOf("_id()") + node.props.map {
// add as function parameter
it.name
}
// Inject identifier `node(id(), props...)`
addStatement("return %T(${args.joinToString()})", node.implClazz)
}
.build()
)
// DSL Receiver and Function
val (builder, func) = node.builderToFunc()
buildersFile.addType(builder)
dslSpec.addFunction(func)
super.apply(node)
}
// --- Internal -------------------
/**
* Returns a Pair of the Java builder and the Kotlin builder receiver function
* This could be split for clarity, but it could be repetitive.
*/
private fun KotlinNodeSpec.Product.builderToFunc(): Pair<TypeSpec, FunSpec> {
// Java Builder, empty constructor
val builderName = symbols.camel(product.ref)
val builderType = ClassName(builderPackageName, "${builderName.toPascalCase()}Builder")
val builderConstructor = FunSpec.constructorBuilder()
val builder = TypeSpec.classBuilder(builderType)
// DSL Function
val funcDsl = FunSpec.builder(builderName).returns(clazz)
funcDsl.addStatement("val builder = %T(${ props.joinToString { it.name }})", builderType)
// Java builder `build(factory: Factory = DEFAULT): T`
val funcBuild = FunSpec.builder("build").addParameter(factoryParamDefault).returns(clazz)
val args = mutableListOf<String>()
// Add builder function to node interface
companion.addFunction(
FunSpec.builder("builder")
.addAnnotation(Annotations.jvmStatic)
.returns(builderType)
.addStatement("return %T()", builderType)
.build()
)
// Add all props to Java builder, DSL function, and Factory call
product.props.forEachIndexed { i, it ->
var type = symbols.typeNameOf(it.ref, mutable = true)
val name = props[i].name
val default = when (it.ref) {
is TypeRef.List -> "mutableListOf()"
is TypeRef.Set -> "mutableSetOf()"
is TypeRef.Map -> "mutableMapOf()"
else -> {
type = type.copy(nullable = true)
"null"
}
}
val para = ParameterSpec.builder(name, type).build()
// t: T = default
val paraDefault = para.toBuilder().defaultValue(default).build()
funcDsl.addParameter(paraDefault)
builderConstructor.addParameter(paraDefault)
// public var t: T
val prop = PropertySpec.builder(name, type).initializer(name).mutable().build()
builder.addProperty(prop)
// Fluent builder method, only setters for now, can add collection manipulation later
builder.addFunction(
FunSpec.builder(name)
.returns(builderType)
.addParameter(para)
.beginControlFlow("return this.apply")
.addStatement("this.%N = %N", para, para)
.endControlFlow()
.build()
)
// Add parameter to `build(factory: Factory =)` me
val assertion = if (!it.ref.nullable && default == "null") "!!" else ""
args += "$name = $name$assertion"
}
// Add block as last parameter
funcDsl.addParameter(
ParameterSpec.builder(
"block",
LambdaTypeName.get(
receiver = builderType,
returnType = Unit::class.asTypeName()
)
)
.defaultValue("{}")
.build()
)
// End of factory.foo call
funcBuild.addStatement("return factory.$builderName(${args.joinToString()})")
// Finalize Java builder
builder.addFunction(
FunSpec.builder("build")
.returns(clazz)
.addStatement("return build(%T.DEFAULT)", factoryClass)
.build()
)
builder.addFunction(funcBuild.build())
builder.primaryConstructor(builderConstructor.build())
// Finalize DSL function
funcDsl.addStatement("builder.block()")
funcDsl.addStatement("return builder.build(factory)")
return Pair(builder.build(), funcDsl.build())
}
private fun factoryCompanion() = TypeSpec.companionObjectBuilder()
.addProperty(
PropertySpec.builder("DEFAULT", factoryClass)
.initializer("%T()", baseFactoryClass)
.build()
)
.addFunction(factoryFunc)
.build()
}
| 276 | Kotlin | 61 | 526 | f7bff3d196c0b4ebd03331c13c524ec62145956a | 11,591 | partiql-lang-kotlin | Apache License 2.0 |
domain/src/test/java/com/movie/domain/repository/MockMovieRepository.kt | kaminiprasad | 729,903,395 | false | {"Kotlin": 102013} | package com.movie.domain.repository
import com.movie.domain.extension.Result
import com.movie.domain.getMovieDetail
import com.movie.domain.movieArtist
import com.movie.domain.popularMovies
import kotlinx.coroutines.flow.flow
class MockMovieRepository : Repository {
override suspend fun getPopularMovies() =
flow { emit(Result.Success(popularMovies)) }
override suspend fun getMovieById(id: Int) = flow {
emit(Result.Success(getMovieDetail()))
}
override suspend fun getMovieCredit(movieId: Int) =
flow { emit(Result.Success(movieArtist)) }
}
| 0 | Kotlin | 0 | 0 | 06c040599ab6b7d76c9220e483c71c66a1e3b80c | 588 | MovieApplication | Apache License 2.0 |
app/src/main/java/com/blackcatz/android/hnews/ui/stories/StoriesViewModel.kt | vinayagasundar | 157,092,166 | false | null | package com.blackcatz.android.hnews.ui.stories
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.blackcatz.android.hnews.mvi.android.BaseMviViewModel
import com.blackcatz.android.hnews.mvi.rx.RxLifeCycle
import com.blackcatz.android.hnews.ui.stories.domain.StoryRequest
import io.reactivex.Observable
import io.reactivex.functions.BiFunction
typealias StoriesBaseViewModel = BaseMviViewModel<StoriesIntent, StoriesViewState, StoriesAction>
class StoriesViewModel(
private val storiesActionProcessorHolder: StoriesActionProcessorHolder,
private val rxLifeCycle: RxLifeCycle
) : StoriesBaseViewModel() {
class Factory(
private val storiesActionProcessorHolder: StoriesActionProcessorHolder,
private val rxLifeCycle: RxLifeCycle
) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return StoriesViewModel(storiesActionProcessorHolder, rxLifeCycle) as T
}
}
override fun compose(): Observable<StoriesViewState> {
return intentsSubject
.compose(rxLifeCycle.async())
.map(this::actionFromIntents)
.compose(storiesActionProcessorHolder.actionProcessor)
.scan(StoriesViewState.idle(), reducer)
.distinctUntilChanged()
.replay(1)
.autoConnect()
}
override fun actionFromIntents(intents: StoriesIntent): StoriesAction {
return when (intents) {
is StoriesIntent.RefreshIntent -> StoriesAction.LoadStoriesAction(
StoryRequest(
story = intents.story,
forceUpdate = true
)
)
is StoriesIntent.LoadStories -> StoriesAction.LoadStoriesAction(intents.storyRequest)
}
}
private val reducer = BiFunction { previousState: StoriesViewState, result: StoriesResult ->
when (result) {
is StoriesResult.LoadStoriesResult -> when (result) {
is StoriesResult.LoadStoriesResult.Loading -> {
previousState.copy(isLoading = true)
}
is StoriesResult.LoadStoriesResult.Success -> {
val items = previousState.itemList + result.storyResponse.stories
val nextPage = result.storyResponse.page + 1
previousState.copy(
itemList = items,
nextPage = nextPage,
isLoading = false
)
}
is StoriesResult.LoadStoriesResult.Error -> {
previousState.copy(error = result.throwable, isLoading = false)
}
}
}
}
} | 1 | Kotlin | 1 | 1 | 04e68552bfc295ee18f028a8a77c13f55e842de4 | 2,785 | hnews | Apache License 2.0 |
geotabdrivesdk/src/main/java/com/geotab/mobile/sdk/MyGeotabConfig.kt | Geotab | 333,267,573 | false | null | package com.geotab.mobile.sdk
import androidx.annotation.Keep
@Keep
class MyGeotabConfig {
@Keep
companion object {
var serverAddress = "my3.geotab.com"
var allowThirdPartyCookies = false
}
}
| 1 | null | 2 | 2 | a71c2e0ff77e101000eb0477051f8a182a8d8304 | 222 | mobile-sdk-android | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/ses/CfnDedicatedIpPoolPropsDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.ses
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.ses.CfnDedicatedIpPoolProps
/**
* Properties for defining a `CfnDedicatedIpPool`.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.ses.*;
* CfnDedicatedIpPoolProps cfnDedicatedIpPoolProps = CfnDedicatedIpPoolProps.builder()
* .poolName("poolName")
* .scalingMode("scalingMode")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ses-dedicatedippool.html)
*/
@CdkDslMarker
public class CfnDedicatedIpPoolPropsDsl {
private val cdkBuilder: CfnDedicatedIpPoolProps.Builder = CfnDedicatedIpPoolProps.builder()
/** @param poolName The name of the dedicated IP pool that the IP address is associated with. */
public fun poolName(poolName: String) {
cdkBuilder.poolName(poolName)
}
/**
* @param scalingMode The type of scaling mode. The following options are available:
* * `STANDARD` - The customer controls which IPs are part of the dedicated IP pool.
* * `MANAGED` - The reputation and number of IPs are automatically managed by Amazon SES .
*
* The `STANDARD` option is selected by default if no value is specified.
*
* Updating *ScalingMode* doesn't require a replacement if you're updating its value from
* `STANDARD` to `MANAGED` . However, updating *ScalingMode* from `MANAGED` to `STANDARD` is not
* supported.
*/
public fun scalingMode(scalingMode: String) {
cdkBuilder.scalingMode(scalingMode)
}
public fun build(): CfnDedicatedIpPoolProps = cdkBuilder.build()
}
| 4 | null | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 2,060 | awscdk-dsl-kotlin | Apache License 2.0 |
idea/testData/wordSelection/MultiDeclaration/4.kt | JakeWharton | 99,388,807 | false | null | fun f() {
<selection>val (a<caret>, b) = 1 to 2</selection>
} | 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 65 | kotlin | Apache License 2.0 |
luakt-extension/src/main/kotlin/com/github/only52607/luakt/extension/LuaFunctionExtensions.kt | only52607 | 269,326,871 | false | {"Java": 993860, "Kotlin": 67377, "Lua": 2642} | @file:Suppress("UNUSED")
package com.github.only52607.luakt.extension
import org.luaj.vm2.LuaValue
import org.luaj.vm2.Varargs
import org.luaj.vm2.lib.*
fun VarArgFunction(block: (Varargs) -> Varargs) = object : VarArgFunction() {
override fun onInvoke(args: Varargs?): Varargs {
args ?: return NIL
return block(args)
}
}
fun ZeroArgFunction(
block: () -> LuaValue
) = object : ZeroArgFunction() {
override fun call(): LuaValue {
return block()
}
}
fun OneArgFunction(
block: (LuaValue) -> LuaValue
) = object : OneArgFunction() {
override fun call(arg: LuaValue?): LuaValue {
return block(arg!!)
}
}
fun TwoArgFunction(
block: (LuaValue, LuaValue) -> LuaValue
) = object : TwoArgFunction() {
override fun call(arg1: LuaValue?, arg2: LuaValue?): LuaValue {
return block(arg1!!, arg2!!)
}
}
fun ThreeArgFunction(
block: (LuaValue, LuaValue, LuaValue) -> LuaValue
) = object : ThreeArgFunction() {
override fun call(arg1: LuaValue?, arg2: LuaValue?, arg3: LuaValue?): LuaValue {
return block(arg1!!, arg2!!, arg3!!)
}
} | 0 | Java | 5 | 18 | 1ebf17bf9fc0b28c5ba292b4abe85451d9ad4848 | 1,128 | luakt | MIT License |
src/app/api/src/main/kotlin/yapp/be/apiapplication/shelter/service/shelter/VolunteerEventApplicationService.kt | YAPP-Github | 634,126,325 | false | null | package yapp.be.apiapplication.shelter.service.shelter
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import yapp.be.apiapplication.shelter.service.shelter.model.GetVolunteerEventsRequestDto
import yapp.be.apiapplication.shelter.service.shelter.model.GetVolunteerEventsResponseDto
import yapp.be.apiapplication.shelter.service.shelter.model.GetVolunteerSimpleEventResponseDto
import yapp.be.domain.port.inbound.GetVolunteerEventUseCase
@Service
class VolunteerEventApplicationService(
private val getVolunteerEventUseCase: GetVolunteerEventUseCase,
) {
@Transactional(readOnly = true)
fun getVolunteerEvents(
reqDto: GetVolunteerEventsRequestDto
): GetVolunteerEventsResponseDto {
val volunteerEvents = if (reqDto.volunteerId != null) {
getVolunteerEventUseCase.getMemberVolunteerEventsByYearAndMonth(
shelterId = reqDto.shelterId,
volunteerId = reqDto.volunteerId,
year = reqDto.year,
month = reqDto.month
)
} else {
getVolunteerEventUseCase.getNonMemberVolunteerEventsByYearAndMonth(
shelterId = reqDto.shelterId,
year = reqDto.year,
month = reqDto.month
)
}
return GetVolunteerEventsResponseDto(
events = volunteerEvents.map {
GetVolunteerSimpleEventResponseDto(
volunteerEventId = it.volunteerEventId,
title = it.title,
eventStatus = it.eventStatus,
myParticipationStatus = it.myParticipationStatus,
startAt = it.startAt,
endAt = it.endAt,
recruitNum = it.recruitNum,
participantNum = it.participantNum,
waitingNum = it.waitingNum
)
}
)
}
}
| 1 | Kotlin | 1 | 3 | f797516c508da438773590c8e749aa7b624ccb75 | 1,975 | 22nd-Web-Team-2-BE | Apache License 2.0 |
runtime/src/commonTest/kotlin/pbandk/json/IgnoreUnknownFieldsTest.kt | streem | 202,946,849 | false | {"Kotlin": 3635065, "Shell": 1992, "Go": 698} | package pbandk.json
import kotlinx.serialization.json.add
import kotlinx.serialization.json.buildJsonArray
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import pbandk.InvalidProtocolBufferException
import pbandk.testpb.ForeignEnum
import pbandk.testpb.TestAllTypesProto3
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class IgnoreUnknownFieldsTest {
@Test
fun testEnumWithUnknownValue() {
val json = buildJsonObject {
put("optionalForeignEnum", "XXX")
}.toString()
// Without [ignoreUnknownFieldsInInput], a known enum field with an unknown enum value should fail to decode.
assertFailsWith(InvalidProtocolBufferException::class) {
TestAllTypesProto3.decodeFromJsonString(json)
}
// With [ignoreUnknownFieldsInInput], the enum field should be ignored during decoding if it contains an unknown
// value.
val expected = TestAllTypesProto3()
val parsed = TestAllTypesProto3.decodeFromJsonString(
json, JsonConfig.DEFAULT.copy(ignoreUnknownFieldsInInput = true)
)
assertEquals(expected, parsed)
}
@Test
fun testEnumWithUnknownNumericValue() {
val json = buildJsonObject {
put("optionalForeignEnum", 1234)
}.toString()
val expected = TestAllTypesProto3(optionalForeignEnum = ForeignEnum.UNRECOGNIZED(1234))
// Without [ignoreUnknownFieldsInInput], a known enum field with an unknown numeric enum value should be parsed
// as an UNRECOGNIZED value.
assertEquals(expected, TestAllTypesProto3.decodeFromJsonString(json))
// With [ignoreUnknownFieldsInInput], the enum field should likewise be parsed as an UNRECOGNIZED value.
assertEquals(
expected,
TestAllTypesProto3.decodeFromJsonString(json, JsonConfig.DEFAULT.copy(ignoreUnknownFieldsInInput = true))
)
}
@Test
fun testRepeatedEnumWithUnknownValue() {
val json = buildJsonObject {
put("repeatedForeignEnum", buildJsonArray {
add("FOREIGN_FOO")
add("XXX")
add("FOREIGN_BAR")
})
}.toString()
// Without [ignoreUnknownFieldsInInput], a repeated enum field with some known and some unknown values should
// fail to decode.
assertFailsWith(InvalidProtocolBufferException::class) {
TestAllTypesProto3.decodeFromJsonString(json)
}
// With [ignoreUnknownFieldsInInput], the unknown values in a repeated enum should be skipped during decoding
// but the other values should be returned successfully.
val expected = TestAllTypesProto3(
repeatedForeignEnum = listOf(ForeignEnum.FOREIGN_FOO, ForeignEnum.FOREIGN_BAR)
)
val parsed = TestAllTypesProto3.decodeFromJsonString(
json, JsonConfig.DEFAULT.copy(ignoreUnknownFieldsInInput = true)
)
assertEquals(expected, parsed)
}
@Test
fun testMapEnumWithUnknownValue() {
val json = buildJsonObject {
put("mapStringForeignEnum", buildJsonObject {
put("a", "FOREIGN_FOO")
put("b", "XXX")
})
}.toString()
// Without [ignoreUnknownFieldsInInput], a map field with some known and some unknown enum values should fail
// to decode.
assertFailsWith(InvalidProtocolBufferException::class) {
TestAllTypesProto3.decodeFromJsonString(json)
}
// With [ignoreUnknownFieldsInInput], the unknown enum values in a map field should be skipped during decoding
// but the other values should be returned successfully.
val expected = TestAllTypesProto3(
mapStringForeignEnum = mapOf("a" to ForeignEnum.FOREIGN_FOO)
)
val parsed = TestAllTypesProto3.decodeFromJsonString(
json, JsonConfig.DEFAULT.copy(ignoreUnknownFieldsInInput = true)
)
assertEquals(expected, parsed)
}
} | 42 | Kotlin | 38 | 265 | 61a1e322ae04a8a10d62862aa85c430a9a1ba9c9 | 4,119 | pbandk | MIT License |
sample/src/main/java/com/spendesk/grapes/samples/home/fragments/CardsFragment.kt | Spendesk | 364,042,096 | false | null | package com.spendesk.grapes.samples.home.fragments
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import com.spendesk.grapes.DeepBlueBucketView
import com.spendesk.grapes.InformativeActionBucketView
import com.spendesk.grapes.messages.MessageInlineView
import com.spendesk.grapes.samples.R
import kotlinx.android.synthetic.main.fragment_home_cards.*
import kotlinx.android.synthetic.main.view_home_header.*
/**
* @author danyboucanova
* @since 1/6/21
*/
class CardsFragment : Fragment(R.layout.fragment_home_cards) {
companion object {
fun newInstance() = CardsFragment()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
homeGenericHeaderTitle.text = context?.getString(R.string.cards)
bindView()
}
private fun bindView() {
homeCardSectionOnTheWayDeepBlueBucketView.updateData(
DeepBlueBucketView.Configuration(
title = requireContext().getString(R.string.homePushSectionOnTheWayDeepBlueBucketViewTitle),
description = requireContext().getString(R.string.homePushSectionOnTheWayDeepBlueBucketViewDescription),
buttonText = requireContext().getString(R.string.homePushSectionOnTheWayDeepBlueBucketViewButtonText)
)
)
homeCardSectionRecardDeepBlueBucketView.updateData(
DeepBlueBucketView.Configuration(
title = requireContext().getString(R.string.homePushSectionRecardDeepBlueBucketViewTitle),
description = requireContext().getString(R.string.homePushSectionRecardDeepBlueBucketViewDescription),
buttonText = requireContext().getString(R.string.homePushSectionRecardDeepBlueBucketViewButtonText)
)
)
homeCardSectionPlasticCardNormalInformativeActionBucketView.updateData(
InformativeActionBucketView.Configuration(
title = requireContext().getString(R.string.homePushSectionPlasticCardNormalInformativeActionBucketViewTitle),
smallButtonText = requireContext().getString(R.string.homePushSectionPlasticCardNormalInformativeActionBucketViewSmallButtonText),
subtitleText = requireContext().getString(R.string.homePushSectionPlasticCardNormalInformativeActionBucketViewSubtitleText),
shouldShowChip = false,
messageContent = null
)
)
homeCardSectionPlasticCardWarningInformativeActionBucketView.updateData(
InformativeActionBucketView.Configuration(
title = requireContext().getString(R.string.homePushSectionPlasticCardWarningInformativeActionBucketViewTitle),
smallButtonText = requireContext().getString(R.string.homePushSectionPlasticCardWarningInformativeActionBucketViewSmallButtonText),
subtitleText = requireContext().getString(R.string.homePushSectionPlasticCardWarningInformativeActionBucketViewSubtitleText),
shouldShowChip = true,
messageContent = MessageInlineView.Style.WARNING
)
)
homeCardSectionPlasticCardAlertInformativeActionBucketView.updateData(
InformativeActionBucketView.Configuration(
title = requireContext().getString(R.string.homePushSectionPlasticCardAlertInformativeActionBucketViewTitle),
smallButtonText = requireContext().getString(R.string.homePushSectionPlasticCardAlertInformativeActionBucketViewSmallButtonText),
subtitleText = requireContext().getString(R.string.homePushSectionPlasticCardAlertInformativeActionBucketViewSubtitleText),
shouldShowChip = true,
messageContent = MessageInlineView.Style.ALERT
)
)
}
} | 0 | Kotlin | 1 | 1 | 7b60fac5ab278ed8c3688dc0ee50183e8d69e4c8 | 3,864 | grapes-android | Apache License 2.0 |
core/src/main/java/com/jn/kikukt/activity/RootTabActivity2.kt | JerrNeon | 196,114,074 | false | {"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 6, "Batchfile": 1, "Markdown": 1, "Proguard": 43, "INI": 1, "Kotlin": 253, "XML": 83, "Java": 2} | package com.jn.kikukt.activity
import android.os.Bundle
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.PagerAdapter
import androidx.viewpager.widget.ViewPager
import com.google.android.material.tabs.TabLayout
import com.jn.kikukt.R
import com.jn.kikukt.adapter.BaseFragmentPagerAdapter
import com.jn.kikukt.common.api.ITabLayoutView
/**
* Author:Stevie.Chen Time:2020/7/15
* Class Comment:TabLayout + ViewPager
*/
abstract class RootTabActivity2 : RootTbActivity(R.layout.common_tab_layout_viewpager),
ITabLayoutView {
abstract val fragments: MutableList<Fragment>
abstract val titles: MutableList<String>
open val mAdapter: PagerAdapter
get() = BaseFragmentPagerAdapter(supportFragmentManager, fragments, titles)
protected lateinit var mViewPager: ViewPager
protected lateinit var mTabLayout: TabLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initTabView()
setTabLayoutAttribute()
setOffscreenPageLimit()
}
override fun initTabView() {
mViewPager = findViewById(R.id.viewpager_RootTab)
mTabLayout = findViewById(R.id.tabLayout_RootTab)
mViewPager.adapter = mAdapter
titles.forEach { title ->
mTabLayout.addTab(mTabLayout.newTab().setText(title))
}
mTabLayout.setupWithViewPager(mViewPager)
}
override fun setTabLayoutAttribute() {
mTabLayout.run {
//indicator color
setSelectedTabIndicatorColor(
ContextCompat.getColor(
applicationContext,
tabIndicatorColorId
)
)
//text color
setTabTextColors(
ContextCompat.getColor(applicationContext, tabNormalTextColorId),
ContextCompat.getColor(applicationContext, tabSelectedTextColorId)
)
//TabIndicatorFullWidth
isTabIndicatorFullWidth = [email protected]
}
}
override fun setOffscreenPageLimit() {
fragments.let { mViewPager.offscreenPageLimit = it.size }
}
} | 0 | Kotlin | 1 | 1 | e0dec8176b914a4b7476aedbb44ba592f2769b31 | 2,239 | Kiku-kotlin | Apache License 2.0 |
core/src/driver/java/dev/forcecodes/truckme/core/domain/jobs/AssignedJobsMapper.kt | forceporquillo | 403,934,320 | false | {"Kotlin": 465111} | package dev.forcecodes.truckme.core.domain.jobs
import dev.forcecodes.truckme.core.data.ActiveJobItems
import dev.forcecodes.truckme.core.mapper.DomainMapperSingle
import dev.forcecodes.truckme.core.model.DeliveryInfo
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class AssignedJobsMapper @Inject constructor() :
DomainMapperSingle<DeliveryInfo, ActiveJobItems> {
override suspend fun invoke(from: DeliveryInfo): ActiveJobItems {
return from.run {
ActiveJobItems(
id = id,
title = title,
destination = destination?.address ?: destination?.title ?: "",
items = items
)
}
}
} | 0 | Kotlin | 1 | 3 | 54ac8235c4920abfd0a2cd5ded5db56cd7c392e3 | 655 | truck-me-android | Apache License 2.0 |
src/main/kotlin/org/uevola/jsonautovalidation/core/strategies/validators/RequestParamStrategy.kt | ugoevola | 646,607,242 | false | {"Kotlin": 74176} | package org.uevola.jsonautovalidation.core.strategies.validators
import com.fasterxml.jackson.core.JsonParseException
import jakarta.servlet.http.HttpServletRequest
import org.json.JSONObject
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Component
import org.uevola.jsonautovalidation.common.enums.HttpRequestPartEnum
import org.uevola.jsonautovalidation.common.utils.ExceptionUtil
import org.uevola.jsonautovalidation.common.utils.isIgnoredType
import java.lang.reflect.Parameter
@Component
class RequestParamStrategy : ValidatorStrategy, AbstractValidatorStrategy() {
override fun getOrdered() = Int.MAX_VALUE
override fun resolve(parameter: Parameter) = true
override fun validate(request: HttpServletRequest, parameter: Parameter) {
try {
val json = extractJsonRequestParamsFromRequest(request.parameterMap).toString()
if (parameter.type.isIgnoredType()) {
validate(parameter, json, HttpRequestPartEnum.REQUEST_PARAMS)
} else {
validate(parameter.type, json, HttpRequestPartEnum.REQUEST_PARAMS, getCustomMessage(parameter))
}
} catch (e: JsonParseException) {
throw ExceptionUtil.httpClientErrorException(
"Error in ${HttpRequestPartEnum.REQUEST_PARAMS}: ${e.message}",
HttpStatus.BAD_REQUEST
)
}
}
private fun extractJsonRequestParamsFromRequest(parameterMap: Map<String, Array<String>>): JSONObject {
val jsonObject = JSONObject()
parameterMap.forEach { (key, value) ->
if (value.isNotEmpty()) {
val finalValue = if (value.size > 1) value else value[0]
jsonObject.put(key, finalValue)
}
}
return jsonObject
}
} | 0 | Kotlin | 0 | 0 | edd264448997bd498f172df66542cf2381e67c53 | 1,829 | json-auto-validation | MIT License |
core/src/main/java/com/nabla/sdk/core/domain/entity/Attachment.kt | nabla | 478,468,099 | false | null | package com.nabla.sdk.core.domain.entity
import com.benasher44.uuid.Uuid
public data class Attachment(
val id: Uuid,
val url: Uri,
val mimeType: MimeType,
val thumbnailUrl: Uri,
)
| 0 | Kotlin | 1 | 16 | 83f1c42f21e826dd11b1330fb2d800a67720ea6c | 198 | nabla-android | MIT License |
feature-wallet-api/src/main/java/io/novafoundation/nova/feature_wallet_api/domain/validation/FeeChangeValidation.kt | novasamatech | 415,834,480 | false | {"Kotlin": 8137060, "Java": 14723, "JavaScript": 425} | package io.novafoundation.nova.feature_wallet_api.domain.validation
import io.novafoundation.nova.common.mixin.api.CustomDialogDisplayer.Payload
import io.novafoundation.nova.common.mixin.api.CustomDialogDisplayer.Payload.DialogAction
import io.novafoundation.nova.common.resources.ResourceManager
import io.novafoundation.nova.common.utils.hasTheSaveValueAs
import io.novafoundation.nova.common.validation.TransformedFailure
import io.novafoundation.nova.common.validation.Validation
import io.novafoundation.nova.common.validation.ValidationFlowActions
import io.novafoundation.nova.common.validation.ValidationStatus
import io.novafoundation.nova.common.validation.ValidationSystemBuilder
import io.novafoundation.nova.common.validation.isTrueOrError
import io.novafoundation.nova.feature_account_api.data.model.Fee
import io.novafoundation.nova.feature_wallet_api.R
import io.novafoundation.nova.feature_wallet_api.domain.model.amountFromPlanks
import io.novafoundation.nova.feature_wallet_api.presentation.formatters.formatTokenAmount
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.GenericFee
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.GenericFeeLoaderMixin
import io.novafoundation.nova.feature_wallet_api.presentation.mixin.fee.SimpleFee
import io.novafoundation.nova.feature_wallet_api.presentation.model.GenericDecimalFee
import io.novafoundation.nova.feature_wallet_api.presentation.model.networkFeeByRequestedAccount
import io.novafoundation.nova.feature_wallet_api.presentation.model.networkFeeByRequestedAccountOrZero
import io.novafoundation.nova.runtime.multiNetwork.chain.model.Chain
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import java.math.BigDecimal
private val FEE_RATIO_THRESHOLD = 1.5.toBigDecimal()
class FeeChangeValidation<P, E, F : GenericFee>(
private val calculateFee: suspend (P) -> GenericDecimalFee<F>,
private val currentFee: GenericFeeProducer<F, P>,
private val chainAsset: (P) -> Chain.Asset,
private val error: (FeeChangeDetectedFailure.Payload<F>) -> E
) : Validation<P, E> {
override suspend fun validate(value: P): ValidationStatus<E> {
val oldFee = currentFee(value)
val newFee = calculateFee(value)
val oldAmount = oldFee.networkFeeByRequestedAccountOrZero
val newAmount = newFee.networkFeeByRequestedAccount
val areFeesSame = oldAmount hasTheSaveValueAs newAmount
return areFeesSame isTrueOrError {
val payload = FeeChangeDetectedFailure.Payload(
needsUserAttention = newAmount / oldAmount > FEE_RATIO_THRESHOLD,
oldFee = oldAmount,
newFee = newFee,
chainAsset = chainAsset(value)
)
error(payload)
}
}
}
interface FeeChangeDetectedFailure<T : GenericFee> {
class Payload<T : GenericFee>(
val needsUserAttention: Boolean,
val oldFee: BigDecimal,
val newFee: GenericDecimalFee<T>,
val chainAsset: Chain.Asset,
)
val payload: Payload<T>
}
fun <P, E> ValidationSystemBuilder<P, E>.checkForSimpleFeeChanges(
calculateFee: suspend (P) -> Fee,
currentFee: FeeProducer<P>,
chainAsset: (P) -> Chain.Asset,
error: (FeeChangeDetectedFailure.Payload<SimpleFee>) -> E
) {
checkForFeeChanges(
calculateFee = { payload -> SimpleFee(calculateFee(payload)) },
currentFee = currentFee,
chainAsset = chainAsset,
error = error
)
}
fun <P, E, F : GenericFee> ValidationSystemBuilder<P, E>.checkForFeeChanges(
calculateFee: suspend (P) -> F,
currentFee: GenericFeeProducer<F, P>,
chainAsset: (P) -> Chain.Asset,
error: (FeeChangeDetectedFailure.Payload<F>) -> E
) = validate(
FeeChangeValidation(
calculateFee = { payload ->
val newFee = calculateFee(payload)
GenericDecimalFee(
genericFee = calculateFee(payload),
networkFeeDecimalAmount = chainAsset(payload).amountFromPlanks(newFee.networkFee.amount)
)
},
currentFee = currentFee,
error = error,
chainAsset = chainAsset
)
)
fun <F : GenericFee> CoroutineScope.handleFeeSpikeDetected(
error: FeeChangeDetectedFailure<F>,
resourceManager: ResourceManager,
feeLoaderMixin: GenericFeeLoaderMixin.Presentation<F>,
actions: ValidationFlowActions<*>
): TransformedFailure? = handleFeeSpikeDetected(
error = error,
resourceManager = resourceManager,
actions = actions,
setFee = { feeLoaderMixin.setFee(it.newFee.genericFee) }
)
fun <T : GenericFee> CoroutineScope.handleFeeSpikeDetected(
error: FeeChangeDetectedFailure<T>,
resourceManager: ResourceManager,
actions: ValidationFlowActions<*>,
setFee: suspend (error: FeeChangeDetectedFailure.Payload<T>) -> Unit,
): TransformedFailure? {
if (!error.payload.needsUserAttention) {
actions.resumeFlow()
return null
}
val chainAsset = error.payload.chainAsset
val oldFee = error.payload.oldFee.formatTokenAmount(chainAsset)
val newFee = error.payload.newFee.networkFeeByRequestedAccount.formatTokenAmount(chainAsset)
return TransformedFailure.Custom(
Payload(
title = resourceManager.getString(R.string.common_fee_changed_title),
message = resourceManager.getString(R.string.common_fee_changed_message, newFee, oldFee),
customStyle = R.style.AccentNegativeAlertDialogTheme_Reversed,
okAction = DialogAction(
title = resourceManager.getString(R.string.common_proceed),
action = {
launch {
setFee(error.payload)
actions.resumeFlow()
}
}
),
cancelAction = DialogAction(
title = resourceManager.getString(R.string.common_refresh_fee),
action = {
launch {
setFee(error.payload)
}
}
)
)
)
}
| 14 | Kotlin | 6 | 9 | 618357859a4b7af95391fc0991339b78aff1be82 | 6,153 | nova-wallet-android | Apache License 2.0 |
features/numbers-trivia/src/main/java/br/com/andretortolano/numbers_trivia/presentation/NumbersTriviaViewModelFactory.kt | andretortolano | 300,768,631 | false | null | package br.com.andretortolano.numbers_trivia.presentation
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import javax.inject.Inject
class NumbersTriviaViewModelFactory @Inject constructor(private val model: NumbersTriviaModel) :
ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(NumbersTriviaModel::class.java).newInstance(model)
}
fun getViewModel(owner: ViewModelStoreOwner) = ViewModelProvider(owner, this).get(NumbersTriviaViewModel::class.java)
} | 0 | Kotlin | 2 | 1 | 3bddd900279ec1c8ab31af4289f59355440edf96 | 632 | clean-architecture-sample | Apache License 2.0 |
client/src/main/kotlin/com/ecwid/upsource/rpc/users/UserInfoRequestDTO.kt | turchenkoalex | 266,583,029 | false | null | // Generated by the codegen. Please DO NOT EDIT!
// source: message.ftl
package com.ecwid.upsource.rpc.users
/**
* @param ids A list of user IDs to request the full user info for
*/
@Suppress("unused")
data class UserInfoRequestDTO(
/**
* A list of user IDs to request the full user info for (repeated)
*/
val ids: List<String> = emptyList()
)
| 0 | Kotlin | 0 | 3 | 0e2ce7aae14a98e1bbdcf6dcb23a3ae089cebaa4 | 354 | upsource-rpc | Apache License 2.0 |
src/jvmTest/kotlin/fr/acinq/bitcoin/CryptoTestsJvm.kt | AndreyBubnov | 404,589,021 | true | {"Kotlin": 673395, "Java": 1896} | /*
* Copyright 2020 ACINQ SAS
*
* 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 fr.acinq.bitcoin
import fr.acinq.secp256k1.Hex
import org.junit.Test
import kotlin.test.assertEquals
@ExperimentalStdlibApi
class CryptoTestsJvm {
@Test
fun `recover public keys from signatures (secp256k1 test)`() {
val stream = javaClass.getResourceAsStream("/recid.txt")
val iterator = stream.bufferedReader(charset("UTF-8")).lines().iterator()
var priv: PrivateKey? = null
var message: ByteVector? = null
var pub: PublicKey? = null
//var sig: ByteVector? = null
var recid: Int
while (iterator.hasNext()) {
val line = iterator.next()
val values = line.split(" = ")
val lhs = values[0]
val rhs = values[1]
when (lhs) {
"privkey" -> priv = PrivateKey(ByteVector(rhs).toByteArray())
"message" -> message = ByteVector(rhs)
"pubkey" -> pub = PublicKey(ByteVector(rhs))
//"sig" -> sig = ByteVector(rhs)
"recid" -> {
recid = rhs.toInt()
assert(priv!!.publicKey() == pub)
val sig1 = Crypto.sign(message!!.toByteArray(), priv)
val pub1 = Crypto.recoverPublicKey(sig1, message.toByteArray(), recid)
assert(pub1 == pub)
}
}
}
}
} | 0 | null | 0 | 0 | 9dcf89d04aa9b66bb6c8e446665bd529345fdfa1 | 1,978 | bitcoin-kmp | Apache License 2.0 |
app/src/main/java/com/borabor/threeinone/fragment/CountdownTimerFragment.kt | bbor98 | 402,649,783 | false | {"Kotlin": 75819} | package com.borabor.threeinone.fragment
import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.SeekBar
import androidx.fragment.app.Fragment
import com.borabor.threeinone.R
import com.borabor.threeinone.util.ButtonUtil.vibratePhone
import com.borabor.threeinone.util.PrefUtil
import kotlinx.android.synthetic.main.fragment_countdown_timer.*
import java.util.concurrent.TimeUnit
class CountdownTimerFragment : Fragment() {
enum class TimerState {
Stopped, Paused, Running
}
private var timer: CountDownTimer? = null
private var timerState = TimerState.Stopped
private var remainingTime = 0L
private var startTime = 0L
private var endTime = 0L
private var sbProgressList = hashMapOf<String, Int>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_countdown_timer, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fabStartCD.setOnClickListener {
vibratePhone(requireContext())
if (timerState == TimerState.Stopped) {
remainingTime = sbProgressList["hour"]!! * 3600000L +
sbProgressList["minute"]!! * 60000L +
sbProgressList["second"]!! * 1000L +
1000L
startTime = remainingTime
cl.startAnimation(AnimationUtils.loadAnimation(requireContext(), R.anim.slide_up))
}
startTimer()
}
fabPauseCD.setOnClickListener {
vibratePhone(requireContext())
pauseTimer()
}
fabStopCD.setOnClickListener {
vibratePhone(requireContext())
stopTimer()
cl.startAnimation(AnimationUtils.loadAnimation(requireContext(), R.anim.slide_down))
}
sbHour.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
tvHour.text = "$progress"
tvCountdownTimer.text = String.format("%02d:%02d:%02d", progress, sbProgressList["minute"], sbProgressList["second"])
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
sbProgressList["hour"] = seekBar!!.progress
}
})
sbMinute.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
tvMinute.text = "$progress"
tvCountdownTimer.text = String.format("%02d:%02d:%02d", sbProgressList["hour"], progress, sbProgressList["second"])
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
sbProgressList["minute"] = seekBar!!.progress
}
})
sbSecond.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
tvSecond.text = "$progress"
tvCountdownTimer.text = String.format("%02d:%02d:%02d", sbProgressList["hour"], sbProgressList["minute"], progress)
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
sbProgressList["second"] = seekBar!!.progress
}
})
}
override fun onStart() {
super.onStart()
remainingTime = PrefUtil.getRemainingTime(requireContext())
startTime = PrefUtil.getStartTimeCD(requireContext())
timerState = PrefUtil.getTimerStateCD(requireContext())
sbProgressList = PrefUtil.getSbProgressList(requireContext())
sbHour.progress = sbProgressList["hour"]!!
sbMinute.progress = sbProgressList["minute"]!!
sbSecond.progress = sbProgressList["second"]!!
tvHour.text = sbHour.progress.toString()
tvMinute.text = sbMinute.progress.toString()
tvSecond.text = sbSecond.progress.toString()
if (timerState == TimerState.Running) {
endTime = PrefUtil.getEndTime(requireContext())
remainingTime = endTime - System.currentTimeMillis()
if (remainingTime <= 0) {
remainingTime = 0
timerState = TimerState.Stopped
updateButtons()
} else startTimer()
} else if (timerState == TimerState.Paused) pauseTimer()
updateCountDownText()
}
override fun onStop() {
super.onStop()
PrefUtil.setRemainingTime(requireContext(), remainingTime)
PrefUtil.setStartTimeCD(requireContext(), startTime)
PrefUtil.setEndTime(requireContext(), endTime)
PrefUtil.setTimerStateCD(requireContext(), timerState)
PrefUtil.setSbProgressList(requireContext(), sbProgressList)
timer?.cancel()
}
private fun startTimer() {
endTime = System.currentTimeMillis() + remainingTime
timer = object : CountDownTimer(remainingTime, 1000) {
override fun onTick(millisUntilFinished: Long) {
remainingTime = millisUntilFinished
updateCountDownText()
}
override fun onFinish() {
stopTimer()
tvCountdownTimer.text = "00:00:00"
}
}.start()
timerState = TimerState.Running
updateButtons()
}
private fun pauseTimer() {
timer?.cancel()
timerState = TimerState.Paused
updateButtons()
}
private fun stopTimer() {
timer?.cancel()
remainingTime = startTime - 1000
timerState = TimerState.Stopped
updateCountDownText()
updateButtons()
}
fun updateCountDownText() {
val hms = String.format(
"%02d:%02d:%02d",
(TimeUnit.MILLISECONDS.toHours(remainingTime) - TimeUnit.DAYS.toHours(TimeUnit.MILLISECONDS.toDays(remainingTime))),
(TimeUnit.MILLISECONDS.toMinutes(remainingTime) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(remainingTime))),
(TimeUnit.MILLISECONDS.toSeconds(remainingTime) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(remainingTime)))
)
tvCountdownTimer.text = hms
}
private fun updateButtons() {
when (timerState) {
TimerState.Stopped -> {
fabStartCD.visibility = View.VISIBLE
fabStartCD.isEnabled = true
fabStartCD.animate().translationY(0f).translationX(0f).duration = 500
fabPauseCD.animate().translationY(0f).translationX(0f).duration = 500
val handlerPause = Handler()
handlerPause.postDelayed({
fabPauseCD.visibility = View.INVISIBLE
fabPauseCD.isEnabled = false
}, 500)
fabStopCD.animate().translationY(0f).translationX(0f).duration = 500
val handlerStop = Handler()
handlerStop.postDelayed({
fabStopCD.visibility = View.INVISIBLE
fabStopCD.isEnabled = false
}, 500)
cl.startAnimation(AnimationUtils.loadAnimation(requireContext(), R.anim.slide_down))
cl.visibility = View.VISIBLE
sbHour.isEnabled = true
sbMinute.isEnabled = true
sbSecond.isEnabled = true
}
TimerState.Paused -> {
fabStartCD.visibility = View.VISIBLE
fabStartCD.isEnabled = true
fabPauseCD.visibility = View.INVISIBLE
fabPauseCD.isEnabled = false
fabStopCD.visibility = View.VISIBLE
fabStopCD.isEnabled = true
fabStartCD.animate().translationY(-500f).translationX(165f).duration = 0
fabPauseCD.animate().translationY(-500f).translationX(165f).duration = 0
fabStopCD.animate().translationY(-500f).translationX(-165f).duration = 0
cl.visibility = View.INVISIBLE
sbHour.isEnabled = false
sbMinute.isEnabled = false
sbSecond.isEnabled = false
}
TimerState.Running -> {
fabStartCD.visibility = View.INVISIBLE
fabStartCD.isEnabled = false
fabStartCD.animate().translationY(-500f).translationX(165f).duration = 0
fabPauseCD.visibility = View.VISIBLE
fabPauseCD.isEnabled = true
fabPauseCD.animate().translationY(-500f).translationX(165f).duration = 500
fabStopCD.visibility = View.VISIBLE
fabStopCD.isEnabled = true
fabStopCD.animate().translationY(-500f).translationX(-165f).duration = 500
cl.visibility = View.INVISIBLE
sbHour.isEnabled = false
sbMinute.isEnabled = false
sbSecond.isEnabled = false
}
}
}
} | 0 | Kotlin | 4 | 5 | b53f08bc897f2d99a17c6096da15c90b00a422fe | 9,744 | three-in-one | MIT License |
app/src/main/kotlin/cz/covid19cz/erouska/net/api/KeyServerApi.kt | radeksimko | 283,801,413 | true | {"Kotlin": 167486, "Java": 1863, "Shell": 384} | package cz.covid19cz.erouska.net.api
import cz.covid19cz.erouska.net.model.ExposureRequest
import retrofit2.http.Body
import retrofit2.http.POST
interface KeyServerApi {
@POST
suspend fun reportExposure(@Body exposureRequest: ExposureRequest)
} | 0 | null | 0 | 1 | 93df27675ef0dfb8500b2af2d829cd18b8690f1f | 255 | erouska-android | MIT License |
app/src/main/java/com/example/mygyp/models/UserModel.kt | mobile-app-dev-1 | 747,752,346 | false | {"Kotlin": 40047} | package com.example.mygyp.models
import android.net.Uri
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
/**
* Represents a user model.
*
* @property id The unique identifier of the user.
* @property firstname The first name of the user.
* @property lastname The last name of the user.
* @property image The image URI of the user.
*/
@Parcelize
data class UserModel(
var id: Long = 0,
var firstname: String = "",
var lastname: String = "",
var image: Uri? = Uri.EMPTY,
) : Parcelable
/**
* Represents a location with latitude, longitude, and zoom level.
*
* @property lat The latitude coordinate of the location.
* @property lng The longitude coordinate of the location.
* @property zoom The zoom level of the location.
*/
@Parcelize
data class Location(
var lat: Double = 0.0,
var lng: Double = 0.0,
var zoom: Float = 0f,
) : Parcelable
/**
* Represents a day of the week.
*
* @property name The name of the day.
*/
data class Day(
val name: String,
)
/**
* Represents an hour of the day.
*
* @property hour The hour value.
*/
data class hour(
val hour: Int,
)
| 1 | Kotlin | 0 | 0 | 97ff4a50d23ce83c18d41c64cfb90377018e169b | 1,138 | mobileapp-KevinK60 | MIT License |
kool-physics/src/commonMain/kotlin/de/fabmax/kool/physics/joints/Joint.kt | kool-engine | 81,503,047 | false | {"Kotlin": 5929566, "C++": 3256, "CMake": 1870, "HTML": 1464, "JavaScript": 597} | package de.fabmax.kool.physics.joints
import de.fabmax.kool.math.PoseF
import de.fabmax.kool.physics.RigidActor
import de.fabmax.kool.util.Releasable
@Suppress("EXPECT_ACTUAL_CLASSIFIERS_ARE_IN_BETA_WARNING")
expect class JointHolder
interface Joint : Releasable {
val joint: JointHolder
val bodyA: RigidActor?
val bodyB: RigidActor
var isChildCollisionEnabled: Boolean
val frameA: PoseF
val frameB: PoseF
val isBroken: Boolean
var debugVisualize: Boolean
fun enableBreakage(breakForce: Float, breakTorque: Float)
fun disableBreakage() = enableBreakage(Float.MAX_VALUE, Float.MAX_VALUE)
} | 11 | Kotlin | 20 | 303 | 8d05acd3e72ff2fc115d0939bf021a5f421469a5 | 636 | kool | Apache License 2.0 |
src/android_app/app/src/main/java/com/mobilehealthsports/vaccinepass/ui/main/add_calendar_entry/CalendarEntryFragment.kt | AndreasRoither | 302,008,747 | false | null | package com.mobilehealthsports.vaccinepass.ui.main.add_calendar_entry
import android.app.DatePickerDialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.commit
import androidx.fragment.app.replace
import com.mobilehealthsports.vaccinepass.R
import com.mobilehealthsports.vaccinepass.databinding.FragmentAddCalendarEntryBinding
import com.mobilehealthsports.vaccinepass.ui.main.calendar.CalendarFragment
import com.mobilehealthsports.vaccinepass.util.livedata.NonNullMutableLiveData
import com.mobilehealthsports.vaccinepass.util.notification.AlarmScheduler
import org.koin.androidx.viewmodel.ext.android.stateViewModel
import java.time.LocalDate
import java.util.*
class CalendarEntryFragment : Fragment() {
private lateinit var binding: FragmentAddCalendarEntryBinding
private val viewModel: CalendarEntryViewModel by stateViewModel()
private var currentDate: String = ""
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
currentDate = it.getString(CalendarFragment.SELECTED_DATE, "")
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_add_calendar_entry, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentAddCalendarEntryBinding.bind(view)
binding.viewModel = viewModel
binding.lifecycleOwner = requireActivity()
viewModel.appointmentDate = NonNullMutableLiveData(LocalDate.parse(currentDate))
viewModel.errorText.value = getString(R.string.fragment_user_creation_error_required)
viewModel.errorTextValidity.value = getString(R.string.fragment_user_creation_error_invalid)
viewModel.cancelAdd.observe(viewLifecycleOwner, {
if (it) {
requireActivity().supportFragmentManager.commit {
replace<CalendarFragment>(R.id.fragment_container_view)
}
}
})
viewModel.addAppointment.observe(viewLifecycleOwner, {
if (it) {
requireActivity().supportFragmentManager.commit {
replace<CalendarFragment>(R.id.fragment_container_view)
}
}
})
viewModel.addReminder.observe(viewLifecycleOwner, {
if (it == null) return@observe
AlarmScheduler.scheduleAlarmForReminder(requireContext(), it)
})
binding.appointmentDate.setOnClickListener {
val c = Calendar.getInstance()
val dpd = DatePickerDialog(
requireContext(),
R.style.SpinnerDatePickerStyle,
{ _, year, month, dayOfMonth ->
viewModel.appointmentDate.value = LocalDate.of(year, month + 1, dayOfMonth);
},
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)
)
dpd.show()
}
binding.reminderDate.setOnClickListener {
val c = Calendar.getInstance()
val dpd = DatePickerDialog(
requireContext(),
R.style.SpinnerDatePickerStyle,
{ _, year, month, dayOfMonth ->
viewModel.reminderDate.value = LocalDate.of(year, month + 1, dayOfMonth);
},
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)
)
dpd.show()
}
}
companion object {
@JvmStatic
fun newInstance(date: String) =
CalendarEntryFragment().apply {
arguments = Bundle().apply {
putString(CalendarFragment.SELECTED_DATE, date)
}
}
}
} | 0 | Kotlin | 0 | 0 | 55e84ef5d88abcbfe925aa0e48510a2c9acb8ced | 4,161 | VaccinePass | MIT License |
app/src/main/java/com/renaisn/reader/ui/widget/text/MultilineTextView.kt | RenaisnNce | 598,532,496 | false | null | package io.legado.app.ui.widget.text
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
class MultilineTextView(context: Context, attrs: AttributeSet?) :
AppCompatTextView(context, attrs) {
override fun onDraw(canvas: Canvas?) {
calculateLines()
super.onDraw(canvas)
}
private fun calculateLines() {
val mHeight = measuredHeight
val lHeight = lineHeight
val lines = mHeight / lHeight
setLines(lines)
}
} | 1 | Kotlin | 1 | 4 | 4ac03e214e951f7f4f337d4da1f7e39fa715d1c0 | 570 | Renaisn_Android | MIT License |
src/main/kotlin/moe/gensoukyo/gui/pages/DecomposePage.kt | MineCraftGensoukyo | 402,519,776 | false | null | package moe.gensoukyo.gui.pages
import me.wuxie.wakeshow.wakeshow.api.WuxieAPI
import me.wuxie.wakeshow.wakeshow.ui.WInventoryScreen
import me.wuxie.wakeshow.wakeshow.ui.WxScreen
import me.wuxie.wakeshow.wakeshow.ui.component.WButton
import me.wuxie.wakeshow.wakeshow.ui.component.WSlot
import me.wuxie.wakeshow.wakeshow.ui.component.WTextList
import moe.gensoukyo.gui.config.MainConfig.conf
import moe.gensoukyo.gui.util.EquipmentDecompose
import org.bukkit.Material
import org.bukkit.inventory.ItemStack
import taboolib.common.platform.function.warning
class DecomposePage : Page {
private val BG_URL = "location:mcgproject:textures/gui/decompose_bg.png"
private val BTN_URL_1 = "location:mcgproject:textures/gui/decompose_btn_1.png"
private val BTN_URL_2 = "location:mcgproject:textures/gui/decompose_btn_2.png"
private val BTN_URL_3 = "location:mcgproject:textures/gui/decompose_btn_3.png"
private val decomposeGui =
WInventoryScreen("分解UI", BG_URL, -1, -1, 190, 190, 15, 110)
private val guiContainer = decomposeGui.getContainer()
private val equipmentSlot =
WSlot(guiContainer, "equipment", ItemStack(Material.AIR), 56, 39)
private val outputSlot =
WSlot(guiContainer, "output", ItemStack(Material.AIR), 118, 39)
private val decomposeButton =
WButton(guiContainer, "decompose", "",
BTN_URL_1, BTN_URL_2, BTN_URL_3, 76, 39)
private val equipText =
WTextList(guiContainer, "equipment_text", listOf(), 22, 44, 60, 0)
private val outputText =
WTextList(guiContainer, "output_text", listOf(), 142, 44, 60, 0)
private val titleText =
WTextList(guiContainer, "title_text", listOf("§1§l分 解"), 80, 4, 40, 20)
override fun getPage(): WxScreen {
equipmentSlot.isCanDrag = true
equipmentSlot.emptyTooltips = listOf("§f请放入装备")
guiContainer.add(equipmentSlot)
outputSlot.isCanDrag = true
guiContainer.add(outputSlot)
decomposeButton.tooltips = listOf("§f分解")
decomposeButton.w = 27
decomposeButton.h = 18
decomposeButton.setFunction { _, pl ->
try {
val equip = equipmentSlot.itemStack
val output = outputSlot.itemStack
val (success, product) = EquipmentDecompose.run(pl, equip, output)
if (success) {
outputSlot.itemStack = product
equipmentSlot.itemStack = ItemStack(Material.AIR)
DecomposePageTools.refresh(null, product, equipText, outputText)
WuxieAPI.updateGui(pl)
}
} catch (e: Exception) {
warning(e, e.stackTrace.first())
}
}
guiContainer.add(decomposeButton)
equipText.scale = 0.0
guiContainer.add(equipText)
outputText.scale = 0.0
guiContainer.add(outputText)
titleText.scale = 1.2
guiContainer.add(titleText)
return decomposeGui
}
}
| 1 | Kotlin | 0 | 1 | f5fa356457be5e23a2994124d28946cb7eca6410 | 3,022 | MCGUserGUI | MIT License |
src/main/kotlin/com/github/vacxe/googleplaycli/actions/model/DefaultModel.kt | Vacxe | 246,494,735 | false | null | package com.github.vacxe.googleplaycli.actions.model
class DefaultModel(val packageName: String) | 4 | Kotlin | 0 | 9 | af63a0578eabd3889663f11d1714e5935034db6a | 97 | google-play-cli-kt | Apache License 2.0 |
mobile-application/app/src/main/java/eu/sofie_iot/smaug/mobile/model/Rent.kt | SOFIE-project | 318,155,704 | false | {"Markdown": 5, "Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Proguard": 2, "XML": 67, "Kotlin": 47, "Java": 1, "HTML": 1, "INI": 1} | /*
* Copyright 2020 Ericsson AB
*
* 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 eu.sofie_iot.smaug.mobile.model
import androidx.room.*
import java.time.Instant
@Entity(tableName = "rents",
indices = arrayOf(
Index(value = ["locker_id"]),
Index(value = ["bid_id"])
),
foreignKeys = arrayOf(
ForeignKey(
entity = Locker::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("locker_id"),
onDelete = ForeignKey.CASCADE
),
ForeignKey(
entity = Bid::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("bid_id"),
onDelete = ForeignKey.CASCADE
)
))
data class Rent(
@PrimaryKey(autoGenerate = true) val id: Long = 0,
@ColumnInfo(name = "locker_id") val lockerId: Long,
// some rents may be "given", without bids associated with them
@ColumnInfo(name = "bid_id") val bidId: Long? = null,
@ColumnInfo(name = "start_time") val start: Instant,
@ColumnInfo(name = "end_time") val end: Instant
) {
fun within(time: Instant) =
start.isBefore(time) && end.isAfter(time)
} | 0 | Kotlin | 1 | 0 | c03161ab85ed5efceb79b2c10e7eef98baeeb2c2 | 1,702 | SMAUG-Renter | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.