path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/cn/tursom/RoomUtils.kt | tursom | 255,871,213 | false | null | package cn.tursom
import cn.tursom.core.fromJson
import cn.tursom.room.*
import cn.tursom.utils.AsyncHttpRequest
@Suppress("MemberVisibilityCanBePrivate")
object RoomUtils {
//const val roomInfoUrl = "https://api.live.bilibili.com/room/v1/Room/get_info"
const val roomInfoUrl = "http://api.live.bilibili.com/room/v1/Room/room_init"
suspend fun getRoomInfo(roomId: Int): RoomInfoData {
//val url = "https://api.live.bilibili.com/room/v1/Room/get_info?id=$roomId&from=room".println()
val response = AsyncHttpRequest.get(
roomInfoUrl,
param = mapOf(
"id" to roomId.toString(),
"from" to "room"
),
headers = getBiliLiveJsonAPIHeaders(roomId)
)
val roomInfoStr = response.body()!!.string()
val room = roomInfoStr.fromJson<RoomInfo>()
return room.data
}
const val liveUserInfoUrl = "https://api.live.bilibili.com/live_user/v1/UserInfo/get_anchor_in_room"
suspend fun getLiveUserInfo(roomId: Int): LiveUserData {
//val url = "https://api.live.bilibili.com/live_user/v1/UserInfo/get_anchor_in_room?roomid=$roomId"
//val liveUser = sendGet(url, getBiliLiveJsonAPIHeaders(roomId)).println().fromJson<LiveUser>()
val liveUser = AsyncHttpRequest.getStr(
liveUserInfoUrl,
param = mapOf(
"roomid" to roomId.toString()
),
headers = getBiliLiveJsonAPIHeaders(roomId)
).fromJson<LiveUser>()
return liveUser.data
}
const val liveInfoUrl = "https://api.live.bilibili.com/room/v1/Room/playUrl"
suspend fun getLiveInfo(roomId: Int, qn: Int): PlayUrlData {
//val url = "https://api.live.bilibili.com/room/v1/Room/playUrl?cid=$roomId&quality=$qn&platform=web"
val liveUser = AsyncHttpRequest.getStr(
liveInfoUrl,
param = mapOf(
"cid" to roomId.toString(),
"quality" to qn.toString(),
"platform" to "web"
),
headers = getBiliLiveJsonAPIHeaders(roomId)
).fromJson<PlayUrl>()
return liveUser.data
}
const val liveServer = "https://api.live.bilibili.com/room/v1/Danmu/getConf"
suspend fun getLiveServerConf(): WsServerConf {
return AsyncHttpRequest.getStr(liveServer).fromJson()
}
suspend fun getLiveServerConf(roomId: Int): WsServerConf {
return AsyncHttpRequest.getStr(
liveServer, mapOf(
"room_id" to roomId.toString(), "platform" to "pc", "player" to "web"
)
).fromJson()
}
/**
* 该Header配置用于直播 api 信息查询
*/
fun getBiliLiveJsonAPIHeaders(shortId: Int): HashMap<String, String> {
val headerMap = HashMap<String, String>()
headerMap["Origin"] = "https://live.bilibili.com"
headerMap["Referer"] = "https://live.bilibili.com/blanc/$shortId" // need addavId
headerMap["User-Agent"] =
"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36 SE 2.X MetaSr 1.0"
return headerMap
}
}
| 0 | Kotlin | 0 | 0 | e1fc79083536f8e4ec149d859d8e576bd9a71132 | 2,893 | BiliWS | MIT License |
sources/mobile/app/src/main/java/com/console/ratcord/domain/entity/debtAdjustment/DebtAdjustment.kt | Xelone28 | 766,079,514 | false | {"Kotlin": 273180, "C#": 198756, "JavaScript": 83774, "Python": 50479, "CSS": 12586, "Shell": 4593, "HTML": 1719, "Dockerfile": 1031} | package com.console.ratcord.domain.entity.debtAdjustment
import androidx.room.Entity
import androidx.room.PrimaryKey
import kotlinx.serialization.Serializable
@Serializable
@Entity
data class DebtAdjustment(
@PrimaryKey val id: Int,
val groupId : Int,
val userInCreditId: Int,
val userInDebtId: Int,
val adjustmentAmount: Float,
val adjustmentDate: String //issue here
) | 11 | Kotlin | 0 | 0 | 74dde31034cd01fda5b1733bebe4615df67026cf | 401 | 3PROJ | MIT License |
src/main/kotlin/com/twcrone/spacemines/data/GameService.kt | space-mines | 174,262,991 | false | {"Kotlin": 11055, "Groovy": 2005} | package com.twcrone.spacemines.data
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
open class GameService(
private val playerRepository: PlayerRepository,
private val gameRepository: GameRepository,
private val levelRepository: LevelRepository
) {
@Transactional
open fun findOrCreateGameFor(playerId: Long): PlayerEntity {
val player = playerRepository.findOne(playerId)
if (player.game == null) {
val firstLevel = levelRepository.findOne(1)
player.game = build(firstLevel)
playerRepository.save(player)
}
return player
}
private fun build(level: Level): GameEntity {
val game = GameEntity(level)
repeat(level.size) { x ->
repeat(level.size) { y ->
repeat(level.size) { z ->
game.pods.add(PodEntity(game = game, x = x, y = y, z = z))
}
}
}
return game
}
@Transactional
open fun get(id: Long): GameEntity {
val game = gameRepository.findOne(id)
game.pods
return game
}
@Transactional
open fun mark(id: Long, podId: Long): GameEntity {
val game = gameRepository.findOne(id)
val pod = game.pods.find { it.id == podId }
if (pod!!.radiation > -1) {
return game
}
pod.flagged = !pod.flagged
if (game.allMinesFlagged()) {
val levelId = game.level!!.id + 1
val level = levelRepository.findOne(levelId)
game.level = level ?: levelRepository.findOne(1)
reset(game)
}
return this.gameRepository.save(game)
}
@Transactional
open fun reveal(id: Long, podId: Long): GameEntity {
val game = gameRepository.findOne(id)
val pod = game.pods.find { it.id == podId }
if (pod!!.flagged) {
return game
}
val sector = game.level?.sectors?.find {
it.x == pod!!.x && it.y == pod.y && it.z == pod.z
}
if (sector!!.hasMine) {
game.pods.forEach {
it.flagged = false
it.radiation = -1
}
} else {
if (!pod.flagged) {
pod.radiation = sector.radiation
revealEmptySectors(pod, game)
}
}
return this.gameRepository.save(game)
}
private fun reset(game: GameEntity): GameEntity {
game.pods.clear()
val level = game.level
val size = level!!.size
repeat(size) { x ->
repeat(size) { y ->
repeat(size) { z ->
game.pods.add(PodEntity(game = game, x = x, y = y, z = z))
}
}
}
return game
}
private fun close(i1: Int, i2: Int): Boolean {
return i2 < i1 + 2 && i2 > i1 - 2
}
private fun findSectorFor(pod: PodEntity, mineField: Level) = mineField.sectors.find {
it.x == pod.x && it.y == pod.y && it.z == pod.z
}
private fun revealEmptySectors(pod: PodEntity, game: GameEntity) {
if (pod.radiation != 0) { return }
val pods = game.pods
pods.forEach {
if (it.radiation == -1) {
if (close(it.x, pod.x) && close(it.y, pod.y) && close(it.z, pod.z)) {
val sector = findSectorFor(it, game.level!!)
if (!pod.flagged) {
it.radiation = sector!!.radiation
revealEmptySectors(it, game)
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 9da5e3fea1ae200f2a551d0968bd963e83eebc91 | 3,694 | space-mines-api | MIT License |
common/src/commonMain/kotlin/dev/zwander/common/model/MainModel.kt | zacharee | 641,202,797 | false | {"Kotlin": 465345, "Swift": 10431, "Ruby": 2751, "Shell": 470} | package dev.zwander.common.model
import dev.zwander.common.model.adapters.*
import dev.zwander.common.util.TimestampedMutableStateFlow
import kotlinx.coroutines.flow.MutableStateFlow
object MainModel {
val currentMainData = TimestampedMutableStateFlow<MainData?>(null)
val currentClientData = TimestampedMutableStateFlow<ClientDeviceData?>(null)
val currentWifiData = TimestampedMutableStateFlow<WifiConfig?>(null)
val currentCellData = TimestampedMutableStateFlow<CellDataRoot?>(null)
val currentSimData = TimestampedMutableStateFlow<SimDataRoot?>(null)
val tempWifiState = MutableStateFlow<WifiConfig?>(null)
}
| 14 | Kotlin | 4 | 91 | 3d958ae0b2581815d4e496b0fef69186cc3a8c4f | 640 | ArcadyanKVD21Control | MIT License |
app/src/main/java/org/coepi/android/domain/TcnMatcher.kt | mellowgeek | 250,538,164 | true | {"Kotlin": 295633, "Java": 86847, "Shell": 964} | package org.coepi.android.domain
import kotlinx.coroutines.Dispatchers.Default
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.runBlocking
import org.coepi.android.extensions.toHex
import org.coepi.android.repo.reportsupdate.MatchedReport
import org.coepi.android.tcn.ReceivedTcn
import org.tcncoalition.tcnclient.crypto.SignedReport
interface TcnMatcher {
fun match(tcns: List<ReceivedTcn>, reports: List<SignedReport>): List<MatchedReport>
}
class TcnMatcherImpl : TcnMatcher {
override fun match(tcns: List<ReceivedTcn>, reports: List<SignedReport>): List<MatchedReport> =
if (tcns.isEmpty()) {
emptyList()
} else {
runBlocking {
matchSuspended(tcns, reports)
}
}
private suspend fun matchSuspended(tcns: List<ReceivedTcn>, reports: List<SignedReport>)
: List<MatchedReport> =
coroutineScope {
// Put TCNs in a map for quicker lookup
// NOTE: If there are repeated TCNs, only the last is used.
val tcnsMap: Map<String, ReceivedTcn> = tcns.associateBy { it.tcn.toHex() }
reports.distinct().map { report ->
async(Default) {
match(tcnsMap, report)
}
}.awaitAll().filterNotNull()
}
private fun match(tcns: Map<String, ReceivedTcn>, signedReport: SignedReport): MatchedReport? {
val reportTcns = signedReport.report.temporaryContactNumbers
.asSequence()
for (reportTcn in reportTcns) {
val matchingTcn: ReceivedTcn? = tcns[reportTcn.bytes.toHex()]
if (matchingTcn != null) {
return MatchedReport(signedReport, matchingTcn.timestamp)
}
}
return null
}
}
| 1 | Kotlin | 0 | 0 | 789ca9902f47423542c0428ba7d1752b87164f1e | 1,876 | app-android | MIT License |
wow-mongo/src/main/kotlin/me/ahoo/wow/mongo/Documents.kt | Ahoo-Wang | 628,167,080 | false | {"Kotlin": 2407170, "TypeScript": 50124, "Java": 37656, "HTML": 15900, "Lua": 3978, "JavaScript": 2514, "Dockerfile": 820, "SCSS": 609, "Less": 413} | /*
* Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)].
* 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 me.ahoo.wow.mongo
import com.fasterxml.jackson.databind.JavaType
import me.ahoo.wow.api.query.DynamicDocument
import me.ahoo.wow.api.query.MaterializedSnapshot
import me.ahoo.wow.api.query.SimpleDynamicDocument.Companion.toDynamicDocument
import me.ahoo.wow.eventsourcing.snapshot.Snapshot
import me.ahoo.wow.mongo.Documents.replacePrimaryKeyToAggregateId
import me.ahoo.wow.serialization.MessageRecords
import me.ahoo.wow.serialization.toObject
import org.bson.Document
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
object Documents {
const val ID_FIELD = "_id"
fun Document.replaceIdToPrimaryKey(): Document = replaceToPrimaryKey(MessageRecords.ID)
fun Document.replacePrimaryKeyToId(): Document = replacePrimaryKeyTo(MessageRecords.ID)
fun Document.replaceAggregateIdToPrimaryKey(): Document = replaceToPrimaryKey(MessageRecords.AGGREGATE_ID)
fun Document.replacePrimaryKeyToAggregateId(): Document = replacePrimaryKeyTo(MessageRecords.AGGREGATE_ID)
fun Document.replaceToPrimaryKey(key: String): Document {
val id = checkNotNull(getString(key))
append(ID_FIELD, id)
remove(key)
return this
}
fun Document.replacePrimaryKeyTo(key: String): Document {
val primaryKey = checkNotNull(getString(ID_FIELD))
append(key, primaryKey)
remove(ID_FIELD)
return this
}
}
fun <S : Any> Document.toSnapshot(): Snapshot<S> {
val snapshotJsonString = this.replacePrimaryKeyToAggregateId().toJson()
return snapshotJsonString.toObject()
}
fun <S : Any> Document.toSnapshotState(): S {
return toSnapshot<S>().state
}
fun Mono<Document>.toDynamicDocument(): Mono<DynamicDocument> {
return map {
it.replacePrimaryKeyToAggregateId().toDynamicDocument()
}
}
fun Flux<Document>.toDynamicDocument(): Flux<DynamicDocument> {
return map {
it.replacePrimaryKeyToAggregateId().toDynamicDocument()
}
}
fun <S : Any> Mono<Document>.toSnapshot(): Mono<Snapshot<S>> {
return map {
it.toSnapshot()
}
}
fun <S : Any> Mono<Document>.toSnapshotState(): Mono<S> {
return map {
it.toSnapshotState<S>()
}
}
fun <S : Any> Flux<Document>.toSnapshot(): Flux<Snapshot<S>> {
return map {
it.toSnapshot()
}
}
fun <S : Any> Flux<Document>.toSnapshotState(): Flux<S> {
return map {
it.toSnapshotState<S>()
}
}
fun <S : Any> Document.toMaterializedSnapshot(snapshotType: JavaType): MaterializedSnapshot<S> {
val snapshotJsonString = this.replacePrimaryKeyToAggregateId().toJson()
return snapshotJsonString.toObject(snapshotType)
}
fun <S : Any> Mono<Document>.toMaterializedSnapshot(snapshotType: JavaType): Mono<MaterializedSnapshot<S>> {
return map {
it.toMaterializedSnapshot(snapshotType)
}
}
fun <S : Any> Flux<Document>.toMaterializedSnapshot(snapshotType: JavaType): Flux<MaterializedSnapshot<S>> {
return map {
it.toMaterializedSnapshot(snapshotType)
}
}
| 3 | Kotlin | 22 | 167 | f9bf2e88ac483523692f8325f6c6a59bcb2259c2 | 3,653 | Wow | Apache License 2.0 |
wow-mongo/src/main/kotlin/me/ahoo/wow/mongo/Documents.kt | Ahoo-Wang | 628,167,080 | false | {"Kotlin": 2407170, "TypeScript": 50124, "Java": 37656, "HTML": 15900, "Lua": 3978, "JavaScript": 2514, "Dockerfile": 820, "SCSS": 609, "Less": 413} | /*
* Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)].
* 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 me.ahoo.wow.mongo
import com.fasterxml.jackson.databind.JavaType
import me.ahoo.wow.api.query.DynamicDocument
import me.ahoo.wow.api.query.MaterializedSnapshot
import me.ahoo.wow.api.query.SimpleDynamicDocument.Companion.toDynamicDocument
import me.ahoo.wow.eventsourcing.snapshot.Snapshot
import me.ahoo.wow.mongo.Documents.replacePrimaryKeyToAggregateId
import me.ahoo.wow.serialization.MessageRecords
import me.ahoo.wow.serialization.toObject
import org.bson.Document
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
object Documents {
const val ID_FIELD = "_id"
fun Document.replaceIdToPrimaryKey(): Document = replaceToPrimaryKey(MessageRecords.ID)
fun Document.replacePrimaryKeyToId(): Document = replacePrimaryKeyTo(MessageRecords.ID)
fun Document.replaceAggregateIdToPrimaryKey(): Document = replaceToPrimaryKey(MessageRecords.AGGREGATE_ID)
fun Document.replacePrimaryKeyToAggregateId(): Document = replacePrimaryKeyTo(MessageRecords.AGGREGATE_ID)
fun Document.replaceToPrimaryKey(key: String): Document {
val id = checkNotNull(getString(key))
append(ID_FIELD, id)
remove(key)
return this
}
fun Document.replacePrimaryKeyTo(key: String): Document {
val primaryKey = checkNotNull(getString(ID_FIELD))
append(key, primaryKey)
remove(ID_FIELD)
return this
}
}
fun <S : Any> Document.toSnapshot(): Snapshot<S> {
val snapshotJsonString = this.replacePrimaryKeyToAggregateId().toJson()
return snapshotJsonString.toObject()
}
fun <S : Any> Document.toSnapshotState(): S {
return toSnapshot<S>().state
}
fun Mono<Document>.toDynamicDocument(): Mono<DynamicDocument> {
return map {
it.replacePrimaryKeyToAggregateId().toDynamicDocument()
}
}
fun Flux<Document>.toDynamicDocument(): Flux<DynamicDocument> {
return map {
it.replacePrimaryKeyToAggregateId().toDynamicDocument()
}
}
fun <S : Any> Mono<Document>.toSnapshot(): Mono<Snapshot<S>> {
return map {
it.toSnapshot()
}
}
fun <S : Any> Mono<Document>.toSnapshotState(): Mono<S> {
return map {
it.toSnapshotState<S>()
}
}
fun <S : Any> Flux<Document>.toSnapshot(): Flux<Snapshot<S>> {
return map {
it.toSnapshot()
}
}
fun <S : Any> Flux<Document>.toSnapshotState(): Flux<S> {
return map {
it.toSnapshotState<S>()
}
}
fun <S : Any> Document.toMaterializedSnapshot(snapshotType: JavaType): MaterializedSnapshot<S> {
val snapshotJsonString = this.replacePrimaryKeyToAggregateId().toJson()
return snapshotJsonString.toObject(snapshotType)
}
fun <S : Any> Mono<Document>.toMaterializedSnapshot(snapshotType: JavaType): Mono<MaterializedSnapshot<S>> {
return map {
it.toMaterializedSnapshot(snapshotType)
}
}
fun <S : Any> Flux<Document>.toMaterializedSnapshot(snapshotType: JavaType): Flux<MaterializedSnapshot<S>> {
return map {
it.toMaterializedSnapshot(snapshotType)
}
}
| 3 | Kotlin | 22 | 167 | f9bf2e88ac483523692f8325f6c6a59bcb2259c2 | 3,653 | Wow | Apache License 2.0 |
forage-android/src/test/java/com/joinforage/forage/android/core/env/EnvConfigTest.kt | teamforage | 554,343,430 | false | {"Kotlin": 333963} | package com.joinforage.forage.android.core.env
import com.joinforage.forage.android.core.EnvConfig
import com.joinforage.forage.android.ui.ForageConfig
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class EnvConfigTest_fromSessionToken {
@Test
fun `when passed null returns Sandbox`() {
val result = EnvConfig.fromSessionToken(null)
assertThat(result).isEqualTo(EnvConfig.Sandbox)
}
@Test
fun `when passed string with no _ returns Sandbox`() {
val result = EnvConfig.fromSessionToken("certtoken1010101")
assertThat(result).isEqualTo(EnvConfig.Sandbox)
}
@Test
fun `when parsed parts are empty string returns Sandbox`() {
val result = EnvConfig.fromSessionToken("_")
assertThat(result).isEqualTo(EnvConfig.Sandbox)
}
@Test
fun `not case sensitive`() {
val result = EnvConfig.fromSessionToken("StAgInG_202020202")
assertThat(result).isEqualTo(EnvConfig.Staging)
}
@Test
fun `correctly parses DEV tokens`() {
val result = EnvConfig.fromSessionToken("dev_202020202")
assertThat(result).isEqualTo(EnvConfig.Dev)
}
@Test
fun `correctly parses STAGING tokens`() {
val result = EnvConfig.fromSessionToken("staging_202020202")
assertThat(result).isEqualTo(EnvConfig.Staging)
}
@Test
fun `correctly parses SANDBOX tokens`() {
val result = EnvConfig.fromSessionToken("sandbox_202020202")
assertThat(result).isEqualTo(EnvConfig.Sandbox)
}
@Test
fun `correctly parses CERT tokens`() {
val result = EnvConfig.fromSessionToken("cert_202020202")
assertThat(result).isEqualTo(EnvConfig.Cert)
}
@Test
fun `correctly parses PROD tokens`() {
val result = EnvConfig.fromSessionToken("prod_202020202")
assertThat(result).isEqualTo(EnvConfig.Prod)
}
}
class EnvConfigTest_fromForageConfig {
@Test
fun `when passed null returns Sandbox`() {
val result = EnvConfig.fromForageConfig(null)
assertThat(result).isEqualTo(EnvConfig.Sandbox)
}
@Test
fun `when passed valid session token, it works`() {
val result = EnvConfig.fromForageConfig(
ForageConfig(
merchantId = "",
sessionToken = "dev_2020202"
)
)
assertThat(result).isEqualTo(EnvConfig.Dev)
}
}
| 5 | Kotlin | 0 | 0 | 8f86a943326f989fd5e9cbdaffb1058821fe4acf | 2,433 | forage-android-sdk | MIT License |
forage-android/src/test/java/com/joinforage/forage/android/core/env/EnvConfigTest.kt | teamforage | 554,343,430 | false | {"Kotlin": 333963} | package com.joinforage.forage.android.core.env
import com.joinforage.forage.android.core.EnvConfig
import com.joinforage.forage.android.ui.ForageConfig
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class EnvConfigTest_fromSessionToken {
@Test
fun `when passed null returns Sandbox`() {
val result = EnvConfig.fromSessionToken(null)
assertThat(result).isEqualTo(EnvConfig.Sandbox)
}
@Test
fun `when passed string with no _ returns Sandbox`() {
val result = EnvConfig.fromSessionToken("certtoken1010101")
assertThat(result).isEqualTo(EnvConfig.Sandbox)
}
@Test
fun `when parsed parts are empty string returns Sandbox`() {
val result = EnvConfig.fromSessionToken("_")
assertThat(result).isEqualTo(EnvConfig.Sandbox)
}
@Test
fun `not case sensitive`() {
val result = EnvConfig.fromSessionToken("StAgInG_202020202")
assertThat(result).isEqualTo(EnvConfig.Staging)
}
@Test
fun `correctly parses DEV tokens`() {
val result = EnvConfig.fromSessionToken("dev_202020202")
assertThat(result).isEqualTo(EnvConfig.Dev)
}
@Test
fun `correctly parses STAGING tokens`() {
val result = EnvConfig.fromSessionToken("staging_202020202")
assertThat(result).isEqualTo(EnvConfig.Staging)
}
@Test
fun `correctly parses SANDBOX tokens`() {
val result = EnvConfig.fromSessionToken("sandbox_202020202")
assertThat(result).isEqualTo(EnvConfig.Sandbox)
}
@Test
fun `correctly parses CERT tokens`() {
val result = EnvConfig.fromSessionToken("cert_202020202")
assertThat(result).isEqualTo(EnvConfig.Cert)
}
@Test
fun `correctly parses PROD tokens`() {
val result = EnvConfig.fromSessionToken("prod_202020202")
assertThat(result).isEqualTo(EnvConfig.Prod)
}
}
class EnvConfigTest_fromForageConfig {
@Test
fun `when passed null returns Sandbox`() {
val result = EnvConfig.fromForageConfig(null)
assertThat(result).isEqualTo(EnvConfig.Sandbox)
}
@Test
fun `when passed valid session token, it works`() {
val result = EnvConfig.fromForageConfig(
ForageConfig(
merchantId = "",
sessionToken = "dev_2020202"
)
)
assertThat(result).isEqualTo(EnvConfig.Dev)
}
}
| 5 | Kotlin | 0 | 0 | 8f86a943326f989fd5e9cbdaffb1058821fe4acf | 2,433 | forage-android-sdk | MIT License |
Retos/Reto #3 - EL GENERADOR DE CONTRASEÑAS [Media]/kotlin/RO-MP.kt | mouredev | 581,049,695 | false | {"Python": 4194087, "JavaScript": 1590517, "Java": 1408944, "C#": 782329, "Kotlin": 533858, "TypeScript": 479964, "Rust": 357628, "Go": 322940, "PHP": 288620, "Swift": 278290, "C": 223896, "Jupyter Notebook": 221090, "C++": 175187, "Dart": 159755, "Ruby": 71132, "Perl": 52923, "VBScript": 49663, "HTML": 45912, "Raku": 44139, "Scala": 33508, "Haskell": 27994, "Shell": 27979, "R": 19771, "Lua": 16964, "COBOL": 15467, "PowerShell": 14611, "Common Lisp": 12839, "F#": 12816, "Pascal": 12673, "Assembly": 10368, "Elixir": 9033, "Visual Basic .NET": 7350, "Groovy": 7331, "PLpgSQL": 6742, "Clojure": 6227, "TSQL": 5744, "Zig": 5594, "Objective-C": 5413, "Apex": 4662, "ActionScript": 3778, "Batchfile": 3608, "OCaml": 3407, "Ada": 3349, "ABAP": 2631, "Carbon": 2611, "Erlang": 2460, "BASIC": 2340, "D": 2243, "Awk": 2203, "CoffeeScript": 2199, "Vim Script": 2158, "Brainfuck": 1550, "Prolog": 1394, "Crystal": 783, "Fortran": 778, "Solidity": 560, "Standard ML": 525, "Scheme": 457, "Vala": 454, "Limbo": 356, "xBase": 346, "Jasmin": 285, "Eiffel": 256, "GDScript": 252, "Witcher Script": 228, "Julia": 224, "MATLAB": 193, "Forth": 177, "Mercury": 175, "Befunge": 173, "Ballerina": 160, "Smalltalk": 130, "Modula-2": 129, "Rebol": 127, "Haxe": 112, "HolyC": 110, "OpenEdge ABL": 105, "AL": 102, "Fantom": 97, "Alloy": 93, "Cool": 93, "AppleScript": 85, "Ceylon": 81, "Idris": 80, "TeX": 72, "Dylan": 70, "Agda": 69, "Pony": 69, "Pawn": 65, "Elm": 61, "Red": 61, "Grace": 59, "Mathematica": 58, "Lasso": 57, "Genie": 42, "LOLCODE": 40, "Nim": 38, "V": 38, "Mojo": 37, "Chapel": 34, "Ioke": 32, "Racket": 28, "LiveScript": 25, "Self": 24, "Hy": 22, "Arc": 21, "Nit": 21, "Boo": 19, "Tcl": 17, "Turing": 17} | import kotlin.random.Random
fun main() {
// Params definition
val length = 16
val containCapitals = true
val containNumbers = true
val containSymbols = true
if (length in 8..16) {
val password = getPassword(length, containCapitals, containNumbers, containSymbols)
println(password)
} else{
println("Introduce a correct length")
}
}
fun getPassword(length: Int, containCapitals: Boolean, containNumbers: Boolean, containSymbols: Boolean): String {
val letters = listOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z")
val numbers = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "0")
val symbols = listOf("!", "#", "$", "%", "&", "/", "+", "^", "*", "~", "?")
// Lambda to get a random String from any List of letters, numbers or symbols
val nextCharacterFromList: (List<String>) -> String = { list ->
list[Random.nextInt(0,(list.size))]
}
// Define which lists will be used
val possibleLists = mutableListOf(letters)
if (containNumbers) possibleLists.add(numbers)
if (containSymbols) possibleLists.add(symbols)
var password = ""
repeat(length){
val randomListIndex = Random.nextInt(0,(possibleLists.size))
// Return random list from the selected lists
val list = possibleLists[randomListIndex]
var nextCharacter = nextCharacterFromList(list)
// Change just letter to upperCase with a random selection
if (randomListIndex == 0 && containCapitals){
if (Random.nextBoolean()) nextCharacter = nextCharacter.toUpperCase()
}
// Concatenate password
password = <PASSWORD>"
}
return password
}
| 1 | Python | 2974 | 5,192 | f8c44ac12756b14a32abf57cbf4e0cd06ad58088 | 1,790 | retos-programacion-2023 | Apache License 2.0 |
target/app/src/main/java/com/yunwoon/targetproject/IntroActivity.kt | uunwon | 392,897,841 | false | null | package com.yunwoon.targetproject
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.view.WindowManager
class IntroActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_intro)
val window = window
window.setFlags( // full screen setting
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN)
val handler = Handler()
handler.postDelayed( {
val intent = Intent( this, MainActivity::class.java)
startActivity(intent) },
3500) // 3.5초 후 종료
}
override fun onPause() {
super.onPause()
finish()
}
} | 0 | Kotlin | 0 | 1 | dfe90b9e428fcb324abaf8b0ee47dd4cb1f48350 | 861 | Target | Apache License 2.0 |
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress4010013.kt | qwewqa | 390,928,568 | false | null | package xyz.qwewqa.relive.simulator.core.presets.dress.generated
import xyz.qwewqa.relive.simulator.core.stage.actor.ActType
import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute
import xyz.qwewqa.relive.simulator.core.stage.actor.StatData
import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters
import xyz.qwewqa.relive.simulator.core.stage.dress.ActBlueprint
import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint
import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost
import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType
import xyz.qwewqa.relive.simulator.stage.character.Character
import xyz.qwewqa.relive.simulator.stage.character.DamageType
import xyz.qwewqa.relive.simulator.stage.character.Position
/*
import xyz.qwewqa.relive.simulator.core.presets.condition.*
import xyz.qwewqa.relive.simulator.core.presets.dress.generated.dress4010013
import xyz.qwewqa.relive.simulator.core.stage.Act
import xyz.qwewqa.relive.simulator.core.stage.actor.ActType
import xyz.qwewqa.relive.simulator.core.stage.actor.CountableBuff
import xyz.qwewqa.relive.simulator.core.stage.dress.DressCategory
import xyz.qwewqa.relive.simulator.core.stage.autoskill.new
import xyz.qwewqa.relive.simulator.core.stage.dress.blueprint
import xyz.qwewqa.relive.simulator.core.stage.buff.*
import xyz.qwewqa.relive.simulator.core.stage.passive.*
import xyz.qwewqa.relive.simulator.core.stage.stageeffect.*
val dress = dress4010013(
name = "諜報員 レディA",
acts = listOf(
ActType.Act1.blueprint("キラめきの刺突") {
Act {
/*
%attr%属性攻撃(威力%value%)
target: 前から1番目の敵役
hit_rate1: 100
values1: [93, 98, 102, 107, 112]
times1: 1
キラめき回復(%value%)
target: 自身
hit_rate2: 100
values2: [20, 20, 20, 20, 20]
times2: [0, 0, 0, 0, 0]
*/
}
},
ActType.Act2.blueprint("隠密の幻惑") {
Act {
/*
混乱
target: 敵役全体
hit_rate1: 75
values1: [0, 0, 0, 0, 0]
times1: [2, 2, 2, 2, 2]
*/
}
},
ActType.Act3.blueprint("突破の諜者") {
Act {
/*
%attr%属性攻撃(威力%value%)
target: 前から3体の敵役
hit_rate1: 100
values1: [84, 88, 92, 97, 101]
times1: 1
ACTパワーアップ(%value%)
target: 味方全体
hit_rate2: 100
values2: [10, 12, 14, 17, 20]
times2: [3, 3, 3, 3, 3]
クリティカル率アップ(%value%)
target: 味方全体
hit_rate3: 100
values3: [10, 12, 14, 17, 20]
times3: [3, 3, 3, 3, 3]
クリティカル威力アップ(%value%)
target: 味方全体
hit_rate4: 100
values4: [10, 12, 14, 17, 20]
times4: [3, 3, 3, 3, 3]
*/
}
},
ActType.ClimaxAct.blueprint("シークレット・ミッション") {
Act {
/*
プラス効果解除
target: 敵役全体
hit_rate1: 100
values1: [0, 0, 0, 0, 0]
times1: [0, 0, 0, 0, 0]
%attr%属性攻撃(威力%value%)
target: 敵役全体
hit_rate2: 100
values2: [117, 123, 128, 134, 140]
times2: 4
混乱
target: 敵役全体
hit_rate3: 100
values3: [0, 0, 0, 0, 0]
times3: [2, 2, 2, 2, 2]
暗闇
target: 敵役全体
hit_rate4: 100
values4: [0, 0, 0, 0, 0]
times4: [2, 2, 2, 2, 2]
*/
}
}
),
autoSkills = listOf(
listOf(
/*
auto skill 1:
毎ターンHP回復(%value%)
target: 味方全体
hit_rate: 100
value: 1000
time: 3
*/
),
listOf(
/*
auto skill 2:
クライマックスACT威力アップ(%value%)
target: 自身
values: [10, 11, 12, 13, 15]
*/
),
listOf(
/*
auto skill 3:
暗闇耐性アップ(%value%)
target: 自身
values: [100, 100, 100, 100, 200]
*/
),
),
unitSkill = null /* 立ち位置中の舞台少女のACTパワーアップ %opt1_value%%(MAX30%) クリティカル威力アップ %opt2_value%%(MAX30%) */,
multipleCA = false,
categories = setOf(),
)
*/
val dress4010013 = PartialDressBlueprint(
id = 4010013,
name = "諜報員 レディA",
baseRarity = 4,
cost = 12,
character = Character.Akira,
attribute = Attribute.Snow,
damageType = DamageType.Normal,
position = Position.Middle,
positionValue = 24051,
stats = StatData(
hp = 1156,
actPower = 188,
normalDefense = 108,
specialDefense = 71,
agility = 187,
dexterity = 5,
critical = 50,
accuracy = 0,
evasion = 0,
),
growthStats = StatData(
hp = 38090,
actPower = 3110,
normalDefense = 1780,
specialDefense = 1170,
agility = 3080,
),
actParameters = mapOf(
ActType.Act1 to ActBlueprint(
name = "キラめきの刺突",
type = ActType.Act1,
apCost = 2,
icon = 89,
parameters = listOf(
actParameters2,
actParameters3,
actParameters1,
actParameters1,
actParameters1,
),
),
ActType.Act2 to ActBlueprint(
name = "隠密の幻惑",
type = ActType.Act2,
apCost = 2,
icon = 59,
parameters = listOf(
actParameters198,
actParameters1,
actParameters1,
actParameters1,
actParameters1,
),
),
ActType.Act3 to ActBlueprint(
name = "突破の諜者",
type = ActType.Act3,
apCost = 3,
icon = 20,
parameters = listOf(
actParameters136,
actParameters42,
actParameters42,
actParameters42,
actParameters1,
),
),
ActType.ClimaxAct to ActBlueprint(
name = "シークレット・ミッション",
type = ActType.ClimaxAct,
apCost = 2,
icon = 59,
parameters = listOf(
actParameters30,
actParameters83,
actParameters14,
actParameters14,
actParameters1,
),
),
),
autoSkillRanks = listOf(1, 4, 9, null),
autoSkillPanels = listOf(0, 0, 5, 0),
rankPanels = growthBoard2,
friendshipPanels = friendshipPattern0,
remakeParameters = listOf(
StatData(
hp = 9000,
actPower = 300,
normalDefense = 360,
specialDefense = 150,
agility = 180,
),
StatData(
hp = 15000,
actPower = 500,
normalDefense = 600,
specialDefense = 250,
agility = 300,
),
StatData(
hp = 24000,
actPower = 800,
normalDefense = 960,
specialDefense = 400,
agility = 480,
),
StatData(
hp = 30000,
actPower = 1000,
normalDefense = 1200,
specialDefense = 500,
agility = 600,
),
),
)
| 0 | Kotlin | 11 | 7 | 70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74 | 7,250 | relight | MIT License |
src/main/kotlin/model/Config.kt | YektaDev | 394,141,724 | false | null | data class Config(
val theme: Theme,
val window: Window,
)
data class Theme(
val isDark: Boolean,
val color: Color,
)
data class Window(
val widthP: Int,
val heightP: Int,
val alwaysOnTop: Boolean,
)
data class Color(
val front: Long,
val back: Long,
val primary: Long,
val secondary: Long,
val success: Long,
val warning: Long,
val error: Long,
)
| 0 | Kotlin | 2 | 9 | 6c20dd71651479f07ba119f13e81d481a03bedb4 | 407 | Konsole | Apache License 2.0 |
app/src/main/java/com/anujandankit/foodrunner/activity/MainActivity.kt | appcreatorabhay | 710,860,531 | false | null | package com.anujandankit.foodrunner.activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.AsyncTask
import android.os.Bundle
import android.view.MenuItem
import android.widget.TextView
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.core.view.GravityCompat
import androidx.drawerlayout.widget.DrawerLayout
import androidx.room.Room
import com.anujandankit.foodrunner.R
import com.anujandankit.foodrunner.database.RestaurantDatabase
import com.anujandankit.foodrunner.fragment.*
import com.google.android.material.navigation.NavigationView
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var drawerLayout: DrawerLayout
private lateinit var navigationView: NavigationView
lateinit var sharedPref: SharedPreferences
private val PREFS_LOGIN_INSTANCE = "loginPref"
private val APPLICATION_ID = "com.anujandankit.foodrunner"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sharedPref =
this.getSharedPreferences(APPLICATION_ID, Context.MODE_PRIVATE)
if (sharedPref.getBoolean(PREFS_LOGIN_INSTANCE, false)) {
setContentView(R.layout.activity_main)
toolbarAndNavViewSetup()
openHomeFragment()
} else {
val intentToLoginActivity = Intent(this@MainActivity, LoginActivity::class.java)
startActivity(intentToLoginActivity)
finish()
}
}
private fun toolbarAndNavViewSetup() {
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
drawerLayout = findViewById(R.id.drawer_layout)
navigationView = findViewById(R.id.nav_view)
val actionBarDrawerToggle = ActionBarDrawerToggle(
this@MainActivity,
drawerLayout,
R.string.navigation_drawer_open,
R.string.navigation_drawer_close
)
drawerLayout.addDrawerListener(actionBarDrawerToggle)
actionBarDrawerToggle.syncState()
navigationView.setCheckedItem(R.id.action_home)
navigationView.setNavigationItemSelectedListener {
when (it.itemId) {
R.id.action_home -> {
when (supportFragmentManager.findFragmentById(R.id.nav_host_fragment)) {
!is HomeFragment -> {
openHomeFragment()
drawerLayout.closeDrawers()
}
else -> {
drawerLayout.closeDrawers()
}
}
}
R.id.action_favorites -> {
when (supportFragmentManager.findFragmentById(R.id.nav_host_fragment)) {
!is FavoritesFragment -> {
supportFragmentManager.beginTransaction()
.replace(
R.id.nav_host_fragment,
FavoritesFragment()
)
.commit()
supportActionBar?.title = "Favorite Restaurants"
drawerLayout.closeDrawers()
}
else -> {
drawerLayout.closeDrawers()
}
}
}
R.id.action_profile -> {
when (supportFragmentManager.findFragmentById(R.id.nav_host_fragment)) {
!is ProfileFragment -> {
supportFragmentManager.beginTransaction()
.replace(
R.id.nav_host_fragment,
ProfileFragment()
)
.commit()
supportActionBar?.title = "My Profile"
drawerLayout.closeDrawers()
}
else -> {
drawerLayout.closeDrawers()
}
}
}
R.id.action_order_history -> {
when (supportFragmentManager.findFragmentById(R.id.nav_host_fragment)) {
!is OrderHistoryFragment -> {
supportFragmentManager.beginTransaction()
.replace(
R.id.nav_host_fragment,
OrderHistoryFragment()
)
.commit()
supportActionBar?.title = "Order History"
drawerLayout.closeDrawers()
}
else -> {
drawerLayout.closeDrawers()
}
}
}
R.id.action_faq -> {
when (supportFragmentManager.findFragmentById(R.id.nav_host_fragment)) {
!is FAQsFragment -> {
supportFragmentManager.beginTransaction()
.replace(
R.id.nav_host_fragment,
FAQsFragment()
)
.commit()
supportActionBar?.title = "Frequently Asked Questions"
drawerLayout.closeDrawers()
}
else -> {
drawerLayout.closeDrawers()
}
}
}
R.id.action_logout -> {
drawerLayout.closeDrawers()
val dialog = AlertDialog.Builder(this@MainActivity)
dialog.setTitle("Confirmation")
dialog.setMessage("Are you sure that you want to log out?")
dialog.setPositiveButton("Yes, Log Out") { _, _ ->
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.clear()
editor.apply()
DeleteFavorites(this@MainActivity).execute()
val intentToLoginActivity =
Intent(this@MainActivity, LoginActivity::class.java)
startActivity(intentToLoginActivity)
finish()
}
dialog.setNegativeButton("Never Mind", null)
dialog.create().show()
}
}
return@setNavigationItemSelectedListener true
}
val userName = nav_view.getHeaderView(0).findViewById<TextView>(R.id.userName)
val userPhone = nav_view.getHeaderView(0).findViewById<TextView>(R.id.userPhone)
userName.text = sharedPref.getString("name", "null")
userPhone.text = "+91 ${sharedPref.getString("mobile_number", "null")}"
}
private fun openHomeFragment() {
supportFragmentManager.beginTransaction()
.replace(
R.id.nav_host_fragment,
HomeFragment()
).commit()
supportActionBar?.title = "All Restaurants"
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
drawerLayout.openDrawer(GravityCompat.START)
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
when (supportFragmentManager.findFragmentById(R.id.nav_host_fragment)) {
!is HomeFragment -> {
openHomeFragment()
drawerLayout.closeDrawers()
navigationView.setCheckedItem(R.id.action_home)
}
else -> super.onBackPressed()
}
}
class DeleteFavorites(val context: Context) :
AsyncTask<Void, Void, Void>() {
override fun doInBackground(vararg params: Void?): Void? {
val db = Room.databaseBuilder(context, RestaurantDatabase::class.java, "restaurants-db")
.build()
db.restaurantDao().deleteAllRestaurants()
db.close()
return null
}
}
}
| 0 | Kotlin | 0 | 0 | 814a03a46708ac5d7bc5c412bdf1c07c84981fc0 | 8,854 | foodrunner | Apache License 2.0 |
core/src/commonMain/kotlin/com.chrynan.graphkl/language/parser/usecase/definition/ParseFragmentDefinitionUseCase.kt | chRyNaN | 230,310,677 | false | null | package com.chrynan.graphkl.language.parser.usecase.definition
import com.chrynan.graphkl.language.node.FragmentDefinitionNode
class ParseFragmentDefinitionUseCase {
operator fun invoke(): FragmentDefinitionNode = TODO()
} | 0 | Kotlin | 0 | 2 | 2526cedddc0a5b5777dea0ec7fc67bc2cd16fe05 | 229 | graphkl | Apache License 2.0 |
wearos/src/main/java/com/prosabdev/wearos/MainActivity.kt | 4kpros | 555,755,264 | false | {"Kotlin": 948923, "Java": 1923} | package com.prosabdev.wearos
import android.app.Activity
import android.os.Bundle
import com.prosabdev.wearos.databinding.ActivityMainBinding
class MainActivity : Activity() {
private lateinit var mBinding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(mBinding.root)
}
} | 0 | Kotlin | 0 | 2 | c9363fa150d1cd34b0fac119c825bfe75e2f96e1 | 444 | FluidMusic | Apache License 2.0 |
library/modules/gdpr/src/main/java/com/michaelflisar/composedialogs/dialogs/gdpr/DialogGDPR.kt | MFlisar | 615,268,735 | false | {"Kotlin": 219223} | package com.michaelflisar.composedialogs.dialogs.ads
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import com.michaelflisar.composedialogs.core.Dialog
import com.michaelflisar.composedialogs.core.DialogButtons
import com.michaelflisar.composedialogs.core.DialogDefaults
import com.michaelflisar.composedialogs.core.DialogEvent
import com.michaelflisar.composedialogs.core.DialogState
import com.michaelflisar.composedialogs.core.DialogStyle
import com.michaelflisar.composedialogs.core.Options
@Composable
fun DialogAds(
state: DialogState,
// custom settings
// ...
title: (@Composable () -> Unit)? = null,
icon: (@Composable () -> Unit)? = null,
style: DialogStyle = DialogDefaults.styleDialog(),
buttons: DialogButtons = DialogDefaults.buttons(),
options: Options = Options(),
onEvent: (event: DialogEvent) -> Unit = {}
) {
Dialog(state, title, icon, style, buttons, options, onEvent = onEvent) {
Text(text = "TODO")
}
} | 2 | Kotlin | 2 | 30 | 544c0cea1200431846bf32d104e5164a819158a1 | 1,013 | ComposeDialogs | Apache License 2.0 |
app/src/main/java/com/perol/asdpl/pixivez/sql/entity/IllustEntity.kt | LuckXuemo | 221,128,046 | true | {"Java": 876786, "Kotlin": 597202} | package com.perol.asdpl.pixivez.sql.entity
import androidx.room.Entity
import androidx.room.PrimaryKey
| 0 | Java | 0 | 2 | 005805a34d977ad4b1bd09095211abd17768429c | 105 | Pix-EzViewer | MIT License |
core/src/rustyice/editor/annotations/ComponentProperty.kt | eyneill777 | 51,181,302 | false | {"Gradle": 5, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Kotlin": 66, "Java": 3, "JSON": 3, "Java Properties": 1, "XML": 1} | package rustyice.editor.annotations
/**
* @author gabek
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
annotation class ComponentProperty()
| 1 | null | 1 | 1 | 1e22436d0860f9950d2f2e4fed984e9623b9b0db | 174 | SpacePirates | MIT License |
src/main/kotlin/com/fwdekker/randomness/string/StringScheme.kt | FWDekker | 96,791,256 | false | null | package com.fwdekker.randomness.string
import com.fwdekker.randomness.Bundle
import com.fwdekker.randomness.CapitalizationMode
import com.fwdekker.randomness.Icons
import com.fwdekker.randomness.Scheme
import com.fwdekker.randomness.TypeIcon
import com.fwdekker.randomness.array.ArrayDecorator
import com.fwdekker.randomness.string.StringScheme.Companion.LOOK_ALIKE_CHARACTERS
import com.github.curiousoddman.rgxgen.RgxGen
import com.github.curiousoddman.rgxgen.parsing.dflt.RgxGenParseException
import com.intellij.ui.JBColor
import java.awt.Color
import kotlin.random.asJavaRandom
/**
* Contains settings for generating random strings.
*
* @property pattern The regex-like pattern according to which the string is generated.
* @property isRegex `true` if and only if [pattern] should be interpreted as a regex.
* @property isNonMatching `true` if and only if non-matching values should be generated if [isRegex] is `true`.
* @property capitalization The capitalization mode of the generated string.
* @property removeLookAlikeSymbols Whether the symbols in [LOOK_ALIKE_CHARACTERS] should be removed.
* @property arrayDecorator Settings that determine whether the output should be an array of values.
*/
data class StringScheme(
var pattern: String = DEFAULT_PATTERN,
var isRegex: Boolean = DEFAULT_IS_REGEX,
var isNonMatching: Boolean = DEFAULT_IS_NON_MATCHING,
var capitalization: CapitalizationMode = DEFAULT_CAPITALIZATION,
var removeLookAlikeSymbols: Boolean = DEFAULT_REMOVE_LOOK_ALIKE_SYMBOLS,
val arrayDecorator: ArrayDecorator = DEFAULT_ARRAY_DECORATOR,
) : Scheme() {
override val name = Bundle("string.title")
override val typeIcon = BASE_ICON
override val decorators get() = listOf(arrayDecorator)
/**
* Returns `true` if and only if this scheme does not use any regex functionality beyond escape characters.
*/
fun isSimple() =
doValidate() == null &&
generateStrings()[0] == if (isRegex) pattern.replace(Regex("\\\\(.)"), "$1") else pattern
/**
* Returns [count] strings of random alphanumerical characters.
*/
override fun generateUndecoratedStrings(count: Int): List<String> {
val rawStrings =
if (isRegex) {
val rgxGen = RgxGen(pattern)
List(count) {
if (this.isNonMatching) rgxGen.generateNotMatching(random.asJavaRandom())
else rgxGen.generate(random.asJavaRandom())
}
} else {
List(count) { pattern }
}
return rawStrings.map { rawString ->
val capitalizedString = capitalization.transform(rawString, random)
if (removeLookAlikeSymbols) capitalizedString.filterNot { it in LOOK_ALIKE_CHARACTERS }
else capitalizedString
}
}
override fun doValidate() =
when {
!isRegex -> arrayDecorator.doValidate()
pattern.takeLastWhile { it == '\\' }.length.mod(2) != 0 -> Bundle("string.error.trailing_backslash")
pattern == "{}" || pattern.contains(Regex("""[^\\]\{}""")) -> Bundle("string.error.empty_curly")
pattern == "[]" || pattern.contains(Regex("""[^\\]\[]""")) -> Bundle("string.error.empty_square")
else ->
@Suppress("detekt:TooGenericExceptionCaught") // Consequence of incomplete validation in RgxGen
try {
if (this.isNonMatching) RgxGen(pattern).generate()
else RgxGen(pattern).generateNotMatching()
arrayDecorator.doValidate()
} catch (exception: RgxGenParseException) {
exception.message
} catch (exception: Exception) {
"Uncaught RgxGen exception: ${exception.message}"
}
}
override fun deepCopy(retainUuid: Boolean) =
copy(arrayDecorator = arrayDecorator.deepCopy(retainUuid)).deepCopyTransient(retainUuid)
/**
* Holds constants.
*/
companion object {
/**
* Symbols that look like other symbols.
*
* To be precise, this string contains the symbols `0`, `1`, `l`, `I`, `O`, `|`, and `﹒`.
*/
const val LOOK_ALIKE_CHARACTERS = "01lLiIoO|﹒"
/**
* The base icon for strings.
*/
val BASE_ICON = TypeIcon(
Icons.SCHEME,
"abc",
listOf(JBColor(Color(244, 175, 61, 154), Color(244, 175, 61, 154)))
)
/**
* The default value of the [pattern] field.
*/
const val DEFAULT_PATTERN = "[a-zA-Z0-9]{7,11}"
/**
* The default value of the [isRegex] field.
*/
const val DEFAULT_IS_REGEX = true
/**
* The default value of the [isNonMatching] field.
*/
const val DEFAULT_IS_NON_MATCHING = false
/**
* The preset values for the [capitalization] field.
*/
val PRESET_CAPITALIZATION = listOf(
CapitalizationMode.RETAIN,
CapitalizationMode.LOWER,
CapitalizationMode.UPPER,
CapitalizationMode.RANDOM,
)
/**
* The default value of the [capitalization] field.
*/
val DEFAULT_CAPITALIZATION = CapitalizationMode.RETAIN
/**
* The default value of the [removeLookAlikeSymbols] field.
*/
const val DEFAULT_REMOVE_LOOK_ALIKE_SYMBOLS = false
/**
* The default value of the [arrayDecorator] field.
*/
val DEFAULT_ARRAY_DECORATOR get() = ArrayDecorator()
}
}
| 9 | null | 7 | 45 | 26475825f420720f2050cfbee4a738d615001009 | 5,691 | intellij-randomness | MIT License |
app/src/main/java/cn/cqautotest/sunnybeach/other/CrashHandler.kt | anjiemo | 378,095,612 | false | null | package cn.cqautotest.sunnybeach.other
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.os.Process
import cn.cqautotest.sunnybeach.ui.activity.CrashActivity
import cn.cqautotest.sunnybeach.ui.activity.RestartActivity
import kotlin.system.exitProcess
/**
* author : Android 轮子哥
* github : https://github.com/getActivity/AndroidProject-Kotlin
* time : 2020/02/03
* desc : Crash 处理类
*/
class CrashHandler private constructor(private val application: Application) :
Thread.UncaughtExceptionHandler {
companion object {
/** Crash 文件名 */
private const val CRASH_FILE_NAME: String = "crash_file"
/** Crash 时间记录 */
private const val KEY_CRASH_TIME: String = "key_crash_time"
/**
* 注册 Crash 监听
*/
fun register(application: Application) {
Thread.setDefaultUncaughtExceptionHandler(CrashHandler(application))
}
}
private val nextHandler: Thread.UncaughtExceptionHandler? = Thread.getDefaultUncaughtExceptionHandler()
init {
if ((javaClass.name == nextHandler?.javaClass?.name)) {
// 请不要重复注册 Crash 监听
throw IllegalStateException("are you ok?")
}
}
@Suppress("ApplySharedPref")
override fun uncaughtException(thread: Thread, throwable: Throwable) {
val sharedPreferences: SharedPreferences = application.getSharedPreferences(
CRASH_FILE_NAME, Context.MODE_PRIVATE
)
val currentCrashTime: Long = System.currentTimeMillis()
val lastCrashTime: Long = sharedPreferences.getLong(KEY_CRASH_TIME, 0)
// 记录当前崩溃的时间,以便下次崩溃时进行比对
sharedPreferences.edit().putLong(KEY_CRASH_TIME, currentCrashTime).commit()
// 致命异常标记:如果上次崩溃的时间距离当前崩溃小于 5 分钟,那么判定为致命异常
val deadlyCrash: Boolean = currentCrashTime - lastCrashTime < 1000 * 60 * 5
if (AppConfig.isDebug()) {
CrashActivity.start(application, throwable)
} else {
if (!deadlyCrash) {
// 如果不是致命的异常就自动重启应用
RestartActivity.start(application)
}
}
// 不去触发系统的崩溃处理(com.android.internal.os.RuntimeInit$KillApplicationHandler)
if (nextHandler != null && !nextHandler.javaClass.name
.startsWith("com.android.internal.os")
) {
nextHandler.uncaughtException(thread, throwable)
}
// 杀死进程(这个事应该是系统干的,但是它会多弹出一个崩溃对话框,所以需要我们自己手动杀死进程)
Process.killProcess(Process.myPid())
exitProcess(10)
}
} | 1 | null | 6 | 95 | a2402da1cb6af963c829a69d9783053f15d866b5 | 2,605 | SunnyBeach | Apache License 2.0 |
app/src/main/java/com/giffinder/app/presentation/details/adapter/GifListAdapter.kt | maxchn | 499,102,675 | false | null | package com.giffinder.app.presentation.details.adapter
import android.view.ViewGroup
import androidx.recyclerview.widget.AsyncListDiffer
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.giffinder.app.domain.entity.GifData
class GifListAdapter(
private val onItemBlock: (item: GifData) -> Unit
) : RecyclerView.Adapter<GifViewHolder>() {
private val diffItemCallback = object : DiffUtil.ItemCallback<GifData>() {
override fun areItemsTheSame(oldItem: GifData, newItem: GifData): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: GifData, newItem: GifData): Boolean {
return oldItem == newItem
}
}
private val differ = AsyncListDiffer(this, diffItemCallback)
private var items: List<GifData>
get() = differ.currentList
set(value) {
differ.submitList(value)
}
fun setNewItems(newItems: List<GifData>) {
items = newItems
}
fun deleteItem(item: GifData) {
setNewItems(items.filter { it.id != item.id })
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GifViewHolder {
return GifViewHolder.create(
parent = parent,
onItemBlock = onItemBlock
)
}
override fun onBindViewHolder(holder: GifViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount(): Int = items.size
}
| 0 | Kotlin | 0 | 0 | b8b84bac183a13cadd4797c74b2b750b1ff82b3a | 1,522 | GifFinder | MIT License |
data/src/main/java/bruhcollective/itaysonlab/jetisteam/MmkvKvDatabase.kt | iTaysonLab | 529,265,880 | false | {"Kotlin": 665372} | package bruhcollective.itaysonlab.jetisteam
import bruhcollective.itaysonlab.jetisteam.controllers.ConfigService
import bruhcollective.itaysonlab.ksteam.database.keyvalue.KeyValueDatabase
import okhttp3.internal.EMPTY_BYTE_ARRAY
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class MmkvKvDatabase @Inject constructor(
configService: ConfigService
) : KeyValueDatabase {
private val mmkv = configService.getAsMmkv(ConfigService.Instance.Main)
override fun getAllByteArrays(startingFrom: String): List<ByteArray> {
return mmkv.allKeys()?.filter { it.startsWith(startingFrom, ignoreCase = true) }
?.mapNotNull { mmkv.getBytes(it, EMPTY_BYTE_ARRAY) }.orEmpty()
}
override fun getByteArray(key: String): ByteArray {
return mmkv.getBytes(key, EMPTY_BYTE_ARRAY)
}
override fun getLong(key: String): Long {
return mmkv.getLong(key, 0L)
}
override fun putByteArray(key: String, value: ByteArray) {
mmkv.putBytes(key, value)
}
override fun putByteArrays(values: Map<String, ByteArray>) {
values.forEach { (key, array) ->
mmkv.putBytes(key, array)
}
}
override fun putLong(key: String, value: Long) {
mmkv.putLong(key, value)
}
} | 2 | Kotlin | 4 | 87 | 04fb50f721342bbec5efea17cf681fba37114993 | 1,283 | jetisteam | Apache License 2.0 |
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/BedSolid.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36756847} | package compose.icons.lineawesomeicons
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 compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.BedSolid: ImageVector
get() {
if (_bedSolid != null) {
return _bedSolid!!
}
_bedSolid = Builder(name = "BedSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp,
viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(6.0f, 6.0f)
curveTo(4.3555f, 6.0f, 3.0f, 7.3555f, 3.0f, 9.0f)
lineTo(3.0f, 15.7813f)
curveTo(2.3906f, 16.332f, 2.0f, 17.1211f, 2.0f, 18.0f)
lineTo(2.0f, 27.0f)
lineTo(7.0f, 27.0f)
lineTo(7.0f, 25.0f)
lineTo(25.0f, 25.0f)
lineTo(25.0f, 27.0f)
lineTo(30.0f, 27.0f)
lineTo(30.0f, 18.0f)
curveTo(30.0f, 17.1211f, 29.6094f, 16.332f, 29.0f, 15.7813f)
lineTo(29.0f, 9.0f)
curveTo(29.0f, 7.3555f, 27.6445f, 6.0f, 26.0f, 6.0f)
close()
moveTo(6.0f, 8.0f)
lineTo(26.0f, 8.0f)
curveTo(26.5547f, 8.0f, 27.0f, 8.4453f, 27.0f, 9.0f)
lineTo(27.0f, 15.0f)
lineTo(25.0f, 15.0f)
lineTo(25.0f, 14.0f)
curveTo(25.0f, 12.3555f, 23.6445f, 11.0f, 22.0f, 11.0f)
lineTo(18.0f, 11.0f)
curveTo(17.2344f, 11.0f, 16.5313f, 11.3008f, 16.0f, 11.7813f)
curveTo(15.4688f, 11.3008f, 14.7656f, 11.0f, 14.0f, 11.0f)
lineTo(10.0f, 11.0f)
curveTo(8.3555f, 11.0f, 7.0f, 12.3555f, 7.0f, 14.0f)
lineTo(7.0f, 15.0f)
lineTo(5.0f, 15.0f)
lineTo(5.0f, 9.0f)
curveTo(5.0f, 8.4453f, 5.4453f, 8.0f, 6.0f, 8.0f)
close()
moveTo(10.0f, 13.0f)
lineTo(14.0f, 13.0f)
curveTo(14.5547f, 13.0f, 15.0f, 13.4453f, 15.0f, 14.0f)
lineTo(15.0f, 15.0f)
lineTo(9.0f, 15.0f)
lineTo(9.0f, 14.0f)
curveTo(9.0f, 13.4453f, 9.4453f, 13.0f, 10.0f, 13.0f)
close()
moveTo(18.0f, 13.0f)
lineTo(22.0f, 13.0f)
curveTo(22.5547f, 13.0f, 23.0f, 13.4453f, 23.0f, 14.0f)
lineTo(23.0f, 15.0f)
lineTo(17.0f, 15.0f)
lineTo(17.0f, 14.0f)
curveTo(17.0f, 13.4453f, 17.4453f, 13.0f, 18.0f, 13.0f)
close()
moveTo(5.0f, 17.0f)
lineTo(27.0f, 17.0f)
curveTo(27.5547f, 17.0f, 28.0f, 17.4453f, 28.0f, 18.0f)
lineTo(28.0f, 25.0f)
lineTo(27.0f, 25.0f)
lineTo(27.0f, 23.0f)
lineTo(5.0f, 23.0f)
lineTo(5.0f, 25.0f)
lineTo(4.0f, 25.0f)
lineTo(4.0f, 18.0f)
curveTo(4.0f, 17.4453f, 4.4453f, 17.0f, 5.0f, 17.0f)
close()
}
}
.build()
return _bedSolid!!
}
private var _bedSolid: ImageVector? = null
| 15 | Kotlin | 20 | 460 | 651badc4ace0137c5541f859f61ffa91e5242b83 | 3,895 | compose-icons | MIT License |
app/src/main/java/org/vitrivr/vitrivrapp/di/AppComponent.kt | iammvaibhav | 134,688,773 | false | {"Kotlin": 290803, "JavaScript": 26575} | package org.vitrivr.vitrivrapp.di
import dagger.Component
import org.vitrivr.vitrivrapp.App
import org.vitrivr.vitrivrapp.data.helper.SharedPreferenceHelper
import org.vitrivr.vitrivrapp.data.repository.QueryResultsRepository
import org.vitrivr.vitrivrapp.features.addmedia.AddMediaActivity
import org.vitrivr.vitrivrapp.features.query.QueryViewModel
import org.vitrivr.vitrivrapp.features.resultdetails.AllSegmentsAdapter
import org.vitrivr.vitrivrapp.features.resultdetails.ImageResultDetailActivity
import org.vitrivr.vitrivrapp.features.resultdetails.Model3DResultDetailActivity
import org.vitrivr.vitrivrapp.features.resultdetails.VideoResultDetailActivity
import org.vitrivr.vitrivrapp.features.results.ResultsViewModel
import org.vitrivr.vitrivrapp.features.results.SwapAdapter
import org.vitrivr.vitrivrapp.features.results.ViewDetailsAdapter
import org.vitrivr.vitrivrapp.features.results.ViewSmallAdapter
import org.vitrivr.vitrivrapp.features.settings.SettingsViewModel
import org.vitrivr.vitrivrapp.utils.PathUtils
import javax.inject.Singleton
@Singleton
@Component(modules = [AppModule::class])
interface AppComponent {
fun inject(app: App)
fun inject(sharedPreferenceHelper: SharedPreferenceHelper)
fun inject(viewModel: QueryViewModel)
fun inject(viewModel: SettingsViewModel)
fun inject(resultsViewModel: ResultsViewModel)
fun inject(queryResultsRepository: QueryResultsRepository)
fun inject(pathUtils: PathUtils)
fun inject(viewSmallAdapter: ViewSmallAdapter)
fun inject(viewDetailsAdapter: ViewDetailsAdapter)
fun inject(imageResultDetailActivity: ImageResultDetailActivity)
fun inject(allSegmentsAdapter: AllSegmentsAdapter)
fun inject(videoResultDetailActivity: VideoResultDetailActivity)
fun inject(model3DResultDetailActivity: Model3DResultDetailActivity)
fun inject(addMediaActivity: AddMediaActivity)
fun inject(swapAdapter: SwapAdapter)
} | 0 | Kotlin | 1 | 3 | 81ee1d7ff3d1237c3d5739da5c6607b5b2b0906d | 1,929 | vitrivr-App | MIT License |
ui/settings/src/main/kotlin/app/surgo/ui/settings/advanced/AdvancedAction.kt | tsukiymk | 382,220,719 | false | {"Kotlin": 889558, "Shell": 553, "CMake": 252, "C++": 166} | package app.surgo.ui.settings.advanced
internal sealed interface AdvancedAction {
object OpenManageSource : AdvancedAction
}
| 0 | Kotlin | 0 | 0 | 99038e0621ecc17e47965c3b352391c6a780f26c | 130 | surgo | Apache License 2.0 |
executor/type/src/commonMain/kotlin/io/github/charlietap/chasm/executor/type/matching/NumberTypeMatcher.kt | CharlieTap | 743,980,037 | false | {"Kotlin": 1682566, "WebAssembly": 75112} | package io.github.charlietap.chasm.executor.type.matching
import io.github.charlietap.chasm.ast.type.NumberType
@Suppress("UNUSED_PARAMETER")
fun NumberTypeMatcher(
type1: NumberType,
type2: NumberType,
context: TypeMatcherContext,
): Boolean = type1 == type2
| 2 | Kotlin | 2 | 43 | addbd2285ab2c9a7f0c12bb0d9fd246241f59513 | 274 | chasm | Apache License 2.0 |
libnavigation-core/src/main/java/com/mapbox/navigation/core/lifecycle/RequireMapboxNavigation.kt | mapbox | 87,455,763 | false | {"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624} | @file:JvmName("RequireMapboxNavigation")
package com.mapbox.navigation.core.lifecycle
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.mapbox.navigation.core.MapboxNavigation
import com.mapbox.navigation.core.lifecycle.MapboxNavigationApp.lifecycleOwner
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* Extension function to make it simple to create the [RequireMapboxNavigationDelegate].
* Below are a couple examples of how you may use the delegate.
*
* Default can be used when [MapboxNavigationApp] is setup elsewhere.
* ```
* val mapboxNavigation by requireMapboxNavigation()
* ```
*
* Initialize the [MapboxNavigationApp] when you are ready to use it
* ```
* val mapboxNavigation by requireMapboxNavigation {
* MapboxNavigationApp.setup(..)
* }
* ```
*
* Register subscriptions and setup MapboxNavigationApp
* ```
* private val mapboxNavigation by requireMapboxNavigation(
* onResumedObserver = object : MapboxNavigationObserver {
* override fun onAttached(mapboxNavigation: MapboxNavigation) {
* mapboxNavigation.registerLocationObserver(locationObserver)
* mapboxNavigation.registerRoutesObserver(routesObserver)
* }
* override fun onDetached(mapboxNavigation: MapboxNavigation) {
* mapboxNavigation.unregisterLocationObserver(locationObserver)
* mapboxNavigation.unregisterRoutesObserver(routesObserver)
* }
* }
* ) {
* MapboxNavigationApp.setup(
* NavigationOptions.Builder(this)
* .accessToken(accessToken)
* .build()
* )
* }
* ```
*
* @see [RequireMapboxNavigationDelegate] for more details.
*/
fun LifecycleOwner.requireMapboxNavigation(
onCreatedObserver: MapboxNavigationObserver? = null,
onStartedObserver: MapboxNavigationObserver? = null,
onResumedObserver: MapboxNavigationObserver? = null,
onInitialize: (() -> Unit)? = null,
): ReadOnlyProperty<Any, MapboxNavigation> = RequireMapboxNavigationDelegate(
lifecycleOwner = this,
onCreatedObserver = onCreatedObserver,
onStartedObserver = onStartedObserver,
onResumedObserver = onResumedObserver,
onInitialize = onInitialize,
)
/**
* Attaches a [LifecycleOwner] to [MapboxNavigationApp] and provides access to [MapboxNavigation].
*
* You can choose to call [MapboxNavigationApp.setup] in the [onInitialize]. You can also setup in
* the onCreate calls, or any call that happens before this delegate is accessed. The delegate will
* crash if accessed when the app is not setup or an attached lifecycle has not been created.
*
* You can use the observers parameter to setup any subscriptions. This is important because the
* [MapboxNavigation] instance can be re-created with [MapboxNavigationApp.disable], or if all
* [MapboxNavigationApp.attach] lifecycles are destroyed.
*
* @param lifecycleOwner: LifecycleOwner
* @param onCreatedObserver registered to the [Lifecycle.State.CREATED] lifecycle
* @param onStartedObserver registered to the [Lifecycle.State.STARTED] lifecycle
* @param onResumedObserver registered to the [Lifecycle.State.RESUMED] lifecycle
* @param onInitialize called when the [lifecycleOwner] is [Lifecycle.State.CREATED]
*/
internal class RequireMapboxNavigationDelegate(
lifecycleOwner: LifecycleOwner,
private val onCreatedObserver: MapboxNavigationObserver? = null,
private val onStartedObserver: MapboxNavigationObserver? = null,
private val onResumedObserver: MapboxNavigationObserver? = null,
private val onInitialize: (() -> Unit)? = null,
) : ReadOnlyProperty<Any, MapboxNavigation> {
private val lifecycleObserver = object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
onInitialize?.invoke()
onCreatedObserver?.let { MapboxNavigationApp.registerObserver(it) }
}
override fun onDestroy(owner: LifecycleOwner) {
onCreatedObserver?.let { MapboxNavigationApp.unregisterObserver(it) }
}
override fun onStart(owner: LifecycleOwner) {
onStartedObserver?.let { MapboxNavigationApp.registerObserver(it) }
}
override fun onStop(owner: LifecycleOwner) {
onStartedObserver?.let { MapboxNavigationApp.unregisterObserver(it) }
}
override fun onResume(owner: LifecycleOwner) {
onResumedObserver?.let { MapboxNavigationApp.registerObserver(it) }
}
override fun onPause(owner: LifecycleOwner) {
onResumedObserver?.let { MapboxNavigationApp.unregisterObserver(it) }
}
}
init {
MapboxNavigationApp.attach(lifecycleOwner)
lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
}
/**
* Returns an instance of [MapboxNavigation]. If [MapboxNavigationApp.isSetup] is false after
* all observers and initializers, this property getter will crash.
*
* @param thisRef - the [LifecycleOwner] that needs access to [MapboxNavigation].
* @param property - ignored
*/
override fun getValue(thisRef: Any, property: KProperty<*>): MapboxNavigation {
val mapboxNavigation = MapboxNavigationApp.current()
checkNotNull(mapboxNavigation) {
"MapboxNavigation cannot be null. Ensure that MapboxNavigationApp is setup and an" +
" attached lifecycle is at least CREATED."
}
return mapboxNavigation
}
}
| 508 | Kotlin | 319 | 621 | ad73c6011348cb9b24b92a369024ca06f48845ab | 5,523 | mapbox-navigation-android | Apache License 2.0 |
android/src/main/kotlin/com/oztechan/ccc/android/ui/adremove/AdRemoveBottomSheet.kt | CurrencyConverterCalculator | 102,633,334 | false | null | /*
* Copyright (c) 2021 <NAME>. All rights reserved.
*/
package com.github.mustafaozhan.ccc.android.ui.adremove
import android.os.Bundle
import android.view.View
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import co.touchlab.kermit.Logger
import com.github.mustafaozhan.ad.AdManager
import com.github.mustafaozhan.basemob.bottomsheet.BaseVBBottomSheetDialogFragment
import com.github.mustafaozhan.billing.BillingEffect
import com.github.mustafaozhan.billing.BillingManager
import com.github.mustafaozhan.ccc.android.util.showDialog
import com.github.mustafaozhan.ccc.android.util.showLoading
import com.github.mustafaozhan.ccc.android.util.showSnack
import com.github.mustafaozhan.ccc.android.util.toOldPurchaseList
import com.github.mustafaozhan.ccc.android.util.toRemoveAdDataList
import com.github.mustafaozhan.ccc.client.model.RemoveAdType
import com.github.mustafaozhan.ccc.client.viewmodel.adremove.AdRemoveEffect
import com.github.mustafaozhan.ccc.client.viewmodel.adremove.AdRemoveViewModel
import com.mustafaozhan.github.analytics.AnalyticsManager
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import mustafaozhan.github.com.mycurrencies.R
import mustafaozhan.github.com.mycurrencies.databinding.BottomSheetAdRemoveBinding
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
@Suppress("TooManyFunctions")
class AdRemoveBottomSheet : BaseVBBottomSheetDialogFragment<BottomSheetAdRemoveBinding>() {
private val analyticsManager: AnalyticsManager by inject()
private val adManager: AdManager by inject()
private val billingManager: BillingManager by inject()
private val adRemoveViewModel: AdRemoveViewModel by viewModel()
private val removeAdsAdapter: RemoveAdsAdapter by lazy {
RemoveAdsAdapter(adRemoveViewModel.event)
}
override fun getViewBinding() = BottomSheetAdRemoveBinding.inflate(layoutInflater)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Logger.i { "AdRemoveBottomSheet onViewCreated" }
billingManager.startConnection(
viewLifecycleOwner.lifecycleScope,
RemoveAdType.getPurchaseIds()
)
initViews()
observeStates()
observeEffects()
observeBillingEffects()
}
override fun onDestroyView() {
Logger.i { "AdRemoveBottomSheet onDestroyView" }
billingManager.endConnection()
binding.recyclerViewRemoveAds.adapter = null
super.onDestroyView()
}
override fun onResume() {
super.onResume()
analyticsManager.trackScreen(this::class.simpleName.toString())
}
private fun initViews() {
binding.recyclerViewRemoveAds.adapter = removeAdsAdapter
}
private fun observeStates() = adRemoveViewModel.state
.flowWithLifecycle(lifecycle)
.onEach {
with(it) {
binding.loadingView.showLoading(loading)
removeAdsAdapter.submitList(adRemoveTypes)
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
private fun observeEffects() = adRemoveViewModel.effect
.flowWithLifecycle(lifecycle)
.onEach { viewEffect ->
Logger.i { "AdRemoveBottomSheet observeEffects ${viewEffect::class.simpleName}" }
when (viewEffect) {
is AdRemoveEffect.LaunchRemoveAdFlow -> {
if (viewEffect.removeAdType == RemoveAdType.VIDEO) {
showDialog(
activity = requireActivity(),
title = R.string.txt_remove_ads,
message = R.string.txt_remove_ads_text,
positiveButton = R.string.txt_watch
) {
adRemoveViewModel.showLoadingView(true)
showRewardedAd()
}
} else {
billingManager.launchBillingFlow(
requireActivity(),
viewEffect.removeAdType.data.id
)
}
}
is AdRemoveEffect.AdsRemoved -> {
if (viewEffect.removeAdType == RemoveAdType.VIDEO ||
viewEffect.isRestorePurchase
) {
restartActivity()
} else {
billingManager.acknowledgePurchase()
}
}
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
private fun observeBillingEffects() = billingManager.effect
.flowWithLifecycle(lifecycle)
.onEach { viewEffect ->
Logger.i { "AdRemoveBottomSheet observeBillingEffects ${viewEffect::class.simpleName}" }
when (viewEffect) {
BillingEffect.SuccessfulPurchase -> restartActivity()
is BillingEffect.RestorePurchase -> adRemoveViewModel.restorePurchase(
viewEffect.purchaseHistoryRecordList.toOldPurchaseList()
)
is BillingEffect.AddPurchaseMethods -> adRemoveViewModel.addPurchaseMethods(
viewEffect.purchaseMethodList.toRemoveAdDataList()
)
is BillingEffect.UpdateAddFreeDate -> adRemoveViewModel.updateAddFreeDate(
RemoveAdType.getById(viewEffect.id)
)
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
private fun showRewardedAd() {
adManager.showRewardedAd(
activity = requireActivity(),
adId = getString(R.string.android_rewarded_ad_unit_id),
onAdFailedToLoad = {
adRemoveViewModel.showLoadingView(false)
view?.let { showSnack(it, R.string.error_text_unknown) }
},
onAdLoaded = {
adRemoveViewModel.showLoadingView(false)
},
onReward = {
adRemoveViewModel.updateAddFreeDate(RemoveAdType.VIDEO)
}
)
}
private fun restartActivity() = activity?.run {
finish()
startActivity(intent)
}
}
| 25 | null | 22 | 193 | 375828be4dcca3c99d0b0d084fa125cff1ad9895 | 6,358 | CCC | Apache License 2.0 |
android/src/main/kotlin/com/oztechan/ccc/android/ui/adremove/AdRemoveBottomSheet.kt | CurrencyConverterCalculator | 102,633,334 | false | null | /*
* Copyright (c) 2021 Mustafa Ozhan. All rights reserved.
*/
package com.github.mustafaozhan.ccc.android.ui.adremove
import android.os.Bundle
import android.view.View
import androidx.lifecycle.flowWithLifecycle
import androidx.lifecycle.lifecycleScope
import co.touchlab.kermit.Logger
import com.github.mustafaozhan.ad.AdManager
import com.github.mustafaozhan.basemob.bottomsheet.BaseVBBottomSheetDialogFragment
import com.github.mustafaozhan.billing.BillingEffect
import com.github.mustafaozhan.billing.BillingManager
import com.github.mustafaozhan.ccc.android.util.showDialog
import com.github.mustafaozhan.ccc.android.util.showLoading
import com.github.mustafaozhan.ccc.android.util.showSnack
import com.github.mustafaozhan.ccc.android.util.toOldPurchaseList
import com.github.mustafaozhan.ccc.android.util.toRemoveAdDataList
import com.github.mustafaozhan.ccc.client.model.RemoveAdType
import com.github.mustafaozhan.ccc.client.viewmodel.adremove.AdRemoveEffect
import com.github.mustafaozhan.ccc.client.viewmodel.adremove.AdRemoveViewModel
import com.mustafaozhan.github.analytics.AnalyticsManager
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import mustafaozhan.github.com.mycurrencies.R
import mustafaozhan.github.com.mycurrencies.databinding.BottomSheetAdRemoveBinding
import org.koin.android.ext.android.inject
import org.koin.androidx.viewmodel.ext.android.viewModel
@Suppress("TooManyFunctions")
class AdRemoveBottomSheet : BaseVBBottomSheetDialogFragment<BottomSheetAdRemoveBinding>() {
private val analyticsManager: AnalyticsManager by inject()
private val adManager: AdManager by inject()
private val billingManager: BillingManager by inject()
private val adRemoveViewModel: AdRemoveViewModel by viewModel()
private val removeAdsAdapter: RemoveAdsAdapter by lazy {
RemoveAdsAdapter(adRemoveViewModel.event)
}
override fun getViewBinding() = BottomSheetAdRemoveBinding.inflate(layoutInflater)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Logger.i { "AdRemoveBottomSheet onViewCreated" }
billingManager.startConnection(
viewLifecycleOwner.lifecycleScope,
RemoveAdType.getPurchaseIds()
)
initViews()
observeStates()
observeEffects()
observeBillingEffects()
}
override fun onDestroyView() {
Logger.i { "AdRemoveBottomSheet onDestroyView" }
billingManager.endConnection()
binding.recyclerViewRemoveAds.adapter = null
super.onDestroyView()
}
override fun onResume() {
super.onResume()
analyticsManager.trackScreen(this::class.simpleName.toString())
}
private fun initViews() {
binding.recyclerViewRemoveAds.adapter = removeAdsAdapter
}
private fun observeStates() = adRemoveViewModel.state
.flowWithLifecycle(lifecycle)
.onEach {
with(it) {
binding.loadingView.showLoading(loading)
removeAdsAdapter.submitList(adRemoveTypes)
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
private fun observeEffects() = adRemoveViewModel.effect
.flowWithLifecycle(lifecycle)
.onEach { viewEffect ->
Logger.i { "AdRemoveBottomSheet observeEffects ${viewEffect::class.simpleName}" }
when (viewEffect) {
is AdRemoveEffect.LaunchRemoveAdFlow -> {
if (viewEffect.removeAdType == RemoveAdType.VIDEO) {
showDialog(
activity = requireActivity(),
title = R.string.txt_remove_ads,
message = R.string.txt_remove_ads_text,
positiveButton = R.string.txt_watch
) {
adRemoveViewModel.showLoadingView(true)
showRewardedAd()
}
} else {
billingManager.launchBillingFlow(
requireActivity(),
viewEffect.removeAdType.data.id
)
}
}
is AdRemoveEffect.AdsRemoved -> {
if (viewEffect.removeAdType == RemoveAdType.VIDEO ||
viewEffect.isRestorePurchase
) {
restartActivity()
} else {
billingManager.acknowledgePurchase()
}
}
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
private fun observeBillingEffects() = billingManager.effect
.flowWithLifecycle(lifecycle)
.onEach { viewEffect ->
Logger.i { "AdRemoveBottomSheet observeBillingEffects ${viewEffect::class.simpleName}" }
when (viewEffect) {
BillingEffect.SuccessfulPurchase -> restartActivity()
is BillingEffect.RestorePurchase -> adRemoveViewModel.restorePurchase(
viewEffect.purchaseHistoryRecordList.toOldPurchaseList()
)
is BillingEffect.AddPurchaseMethods -> adRemoveViewModel.addPurchaseMethods(
viewEffect.purchaseMethodList.toRemoveAdDataList()
)
is BillingEffect.UpdateAddFreeDate -> adRemoveViewModel.updateAddFreeDate(
RemoveAdType.getById(viewEffect.id)
)
}
}.launchIn(viewLifecycleOwner.lifecycleScope)
private fun showRewardedAd() {
adManager.showRewardedAd(
activity = requireActivity(),
adId = getString(R.string.android_rewarded_ad_unit_id),
onAdFailedToLoad = {
adRemoveViewModel.showLoadingView(false)
view?.let { showSnack(it, R.string.error_text_unknown) }
},
onAdLoaded = {
adRemoveViewModel.showLoadingView(false)
},
onReward = {
adRemoveViewModel.updateAddFreeDate(RemoveAdType.VIDEO)
}
)
}
private fun restartActivity() = activity?.run {
finish()
startActivity(intent)
}
}
| 25 | null | 22 | 193 | 375828be4dcca3c99d0b0d084fa125cff1ad9895 | 6,365 | CCC | Apache License 2.0 |
app/src/main/java/com/sshex/multistack/navigation/BarAction.kt | ShadyRover | 214,213,910 | false | null | package com.sshex.multistack.navigation
data class BarAction(val graphId:Int, val selectFromUser:Boolean) | 0 | Kotlin | 0 | 0 | 5e1acd0d272c8fcb0bc529b4f39541f452febf8b | 106 | Navigation-Multistack-Component | Apache License 2.0 |
app/src/main/java/com/sshex/multistack/navigation/BarAction.kt | ShadyRover | 214,213,910 | false | null | package com.sshex.multistack.navigation
data class BarAction(val graphId:Int, val selectFromUser:Boolean) | 0 | Kotlin | 0 | 0 | 5e1acd0d272c8fcb0bc529b4f39541f452febf8b | 106 | Navigation-Multistack-Component | Apache License 2.0 |
app/src/main/java/com/example/notesapp/activities/AddNoteActivity.kt | Thre4dripper | 461,553,628 | false | {"Kotlin": 54718} | package com.example.notesapp.activities
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.example.notesapp.R
import com.example.notesapp.databinding.ActivityAddNoteBinding
import com.example.notesapp.viewModels.HomeViewModel
class AddNoteActivity : AppCompatActivity() {
companion object {
const val SEND_BACK_TITLE_KEY = "com.example.notesapp.activities.sendTitleBack"
const val SEND_BACK_BODY_KEY = "com.example.notesapp.activities.sendBodyBack"
const val SEND_BACK_INDEX_KEY = "com.example.notesapp.activities.sendIndexBack"
const val SEND_BACK_COLOR_KEY = "com.example.notesapp.activities.sendColorBack"
/*
* 0 for just adding note to display list
* 1 for archive new adding note
* 2 for archiving pre made note
*/
const val SEND_BACK_NOTE_OPERATION_KEY = "com.example.notesapp.activities.sendTypeBack"
}
private lateinit var binding: ActivityAddNoteBinding
private var cardIndex = -1
private var color = -1
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_add_note)
getNote()
binding.noteBackButton.setOnClickListener { sendDataBack(0) }
}
/**============================================ METHOD FOR GETTING FROM INTENT ===========================================**/
private fun getNote() {
//for new note this intent will be empty
val data = intent
val noteTitle = data.getStringExtra(HomeViewModel.NOTE_TITLE_KEY)
val noteBody = data.getStringExtra(HomeViewModel.NOTE_BODY_KEY)
val noteIndex = data.getIntExtra(HomeViewModel.NOTE_INDEX_KEY, -1)
val noteType = data.getIntExtra(HomeViewModel.NOTE_TYPE_KEY, -1)
val noteColor = data.getIntExtra(HomeViewModel.NOTE_COLOR_KEY, -1)
//and text will be empty for empty intent
binding.noteHeaderTextView.setText(noteTitle)
binding.noteBodyTextView.setText(noteBody)
binding.noteArchiveButton.setImageResource(
if (noteType == 0) R.drawable.ic_archive_note
else R.drawable.ic_unarchive_note
)
//setting click listener based on note type
binding.noteArchiveButton.setOnClickListener {
if (noteType == 0) sendDataBack(1)
else sendDataBack(2)
}
cardIndex = noteIndex
color = noteColor
}
/**================================== METHOD FOR SENDING DATA BACK TO HOME ACTIVITY ==================================**/
private fun sendDataBack(operation: Int) {
val title = binding.noteHeaderTextView.text.toString()
val body = binding.noteBodyTextView.text.toString()
val data = Intent()
data.putExtra(SEND_BACK_TITLE_KEY, title)
data.putExtra(SEND_BACK_BODY_KEY, body)
//sending which operation should be done to note
data.putExtra(SEND_BACK_NOTE_OPERATION_KEY, operation)
if (cardIndex != -1)
data.putExtra(SEND_BACK_INDEX_KEY, cardIndex)
data.putExtra(SEND_BACK_COLOR_KEY, color)
setResult(Activity.RESULT_OK, data)
super.onBackPressed()
}
/**======================================================= ON BACK PRESSED =======================================================**/
override fun onBackPressed() {
sendDataBack(0)
}
} | 0 | Kotlin | 0 | 0 | bb95d03c8c217932a39214ad4d5b97ad37794faa | 3,593 | NotesApp-AndroidApp | MIT License |
app/src/main/java/com/fahim/example_employee_app/di/anotation/ChildFragmentScoped.kt | fahim44 | 217,901,596 | false | null | package com.selva.example_employee_app.di.anotation
import kotlin.annotation.Retention
import kotlin.annotation.Target
import kotlin.annotation.AnnotationRetention
import javax.inject.Scope
/**
* The ChildFragmentScoped custom scoping annotation specifies that the lifespan of a dependency be
* the same as that of a child Fragment. This is used to annotate dependencies that behave like a
* singleton within the lifespan of a child Fragment
*/
@Scope
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.TYPE, AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class ActivityScoped | 0 | null | 1 | 2 | 003de32135692f8006313f59c8d01dba0c4f63ce | 612 | Example-Employee-App | MIT License |
libadwaita-bindings/src/nativeMain/kotlin/bindings.adw/Application.kt | vbsteven | 582,302,322 | false | null | package bindings.adw
import bindings.gobject.asTypedPointer
import internal.BuiltinTypeInfo
import kotlinx.cinterop.CPointer
import kotlinx.cinterop.sizeOf
import native.adwaita.ADW_TYPE_APPLICATION
import native.adwaita.AdwApplication
import native.adwaita.AdwApplicationClass
import native.adwaita.adw_application_new
import native.gio.GApplicationFlags
import native.gio.G_APPLICATION_FLAGS_NONE
import bindings.gtk.Application as GtkApplication
open class Application : GtkApplication {
val adwApplicationPointer get() = gApplicationPointer.asTypedPointer<AdwApplication>()
constructor(pointer: CPointer<*>) : super(pointer)
constructor(applicationId: String, flags: GApplicationFlags = G_APPLICATION_FLAGS_NONE) : this(
adw_application_new(applicationId, flags)!!
)
companion object {
val Type = BuiltinTypeInfo(
ADW_TYPE_APPLICATION,
sizeOf<AdwApplicationClass>(),
sizeOf<AdwApplication>(),
::Application
)
}
}
| 0 | Kotlin | 0 | 24 | af5f6c9d32498b6e791a92503dfb45ebfd1af6c3 | 1,019 | gtk-kotlin-native | MIT License |
keel-web/src/main/kotlin/com/netflix/spinnaker/keel/rest/ExportController.kt | spinnaker | 107,462,081 | false | null | package com.netflix.spinnaker.keel.rest
import com.netflix.spinnaker.keel.api.Exportable
import com.netflix.spinnaker.keel.api.ResourceKind
import com.netflix.spinnaker.keel.api.ResourceKind.Companion.parseKind
import com.netflix.spinnaker.keel.api.plugins.ResourceHandler
import com.netflix.spinnaker.keel.api.plugins.supporting
import com.netflix.spinnaker.keel.clouddriver.CloudDriverCache
import com.netflix.spinnaker.keel.core.api.SubmittedResource
import com.netflix.spinnaker.keel.core.parseMoniker
import com.netflix.spinnaker.keel.logging.TracingSupport.Companion.withTracingContext
import com.netflix.spinnaker.keel.yaml.APPLICATION_YAML_VALUE
import kotlinx.coroutines.runBlocking
import org.apache.maven.artifact.versioning.DefaultArtifactVersion
import org.slf4j.LoggerFactory
import org.springframework.http.MediaType.APPLICATION_JSON_VALUE
import org.springframework.util.comparator.NullSafeComparator
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping(path = ["/export"])
class ExportController(
private val handlers: List<ResourceHandler<*, *>>,
private val cloudDriverCache: CloudDriverCache
) {
private val log by lazy { LoggerFactory.getLogger(javaClass) }
/**
* Assist for mapping between Deck and Clouddriver cloudProvider names
* and Keel's plugin namespace.
*/
private val cloudProviderOverrides = mapOf(
"aws" to "ec2"
)
private val typeToKind = mapOf(
"classicloadbalancer" to "classic-load-balancer",
"classicloadbalancers" to "classic-load-balancer",
"applicationloadbalancer" to "application-load-balancer",
"applicationloadbalancers" to "application-load-balancer",
"securitygroup" to "security-group",
"securitygroups" to "security-group",
"cluster" to "cluster",
"clustersx" to "cluster"
)
/**
* This route is location-less; given a resource name that can be monikered,
* type, and account, all locations configured for the account are scanned for
* matching resources that can be combined into a multi-region spec.
*
* Types are derived from Clouddriver's naming convention. It is assumed that
* converting these to kebab case (i.e. securityGroups -> security-groups) will
* match either the singular or plural of a [ResourceHandler]'s
* [ResourceHandler.supportedKind].
*/
@GetMapping(
path = ["/{cloudProvider}/{account}/{type}/{name}"],
produces = [APPLICATION_JSON_VALUE, APPLICATION_YAML_VALUE]
)
fun get(
@PathVariable("cloudProvider") cloudProvider: String,
@PathVariable("account") account: String,
@PathVariable("type") type: String,
@PathVariable("name") name: String,
@RequestHeader("X-SPINNAKER-USER") user: String
): SubmittedResource<*> {
val kind = parseKind(cloudProvider, type)
val handler = handlers.supporting(kind)
val exportable = Exportable(
cloudProvider = kind.group,
account = account,
user = user,
moniker = parseMoniker(name),
regions = (
cloudDriverCache
.credentialBy(account)
.attributes["regions"] as List<Map<String, Any>>
)
.map { it["name"] as String }
.toSet(),
kind = kind
)
return runBlocking {
withTracingContext(exportable) {
log.info("Exporting resource ${exportable.toResourceId()}")
SubmittedResource(
kind = kind,
spec = handler.export(exportable)
)
}
}
}
fun parseKind(cloudProvider: String, type: String) =
type.toLowerCase().let { t1 ->
val group = cloudProviderOverrides[cloudProvider] ?: cloudProvider
var version: String? = null
val normalizedType = if (versionSuffix.containsMatchIn(t1)) {
version = versionSuffix.find(t1)!!.groups[1]?.value
t1.replace(versionSuffix, "")
} else {
t1
}.let { t2 ->
typeToKind.getOrDefault(t2, t2)
}
if (version == null) {
version = handlers
.supporting(group, normalizedType)
.map { h -> h.supportedKind.kind.version }
.sortedWith(versionComparator)
.last()
}
(version != null) || error("Unable to find version for group $group, $normalizedType")
"$group/$normalizedType@v$version"
}.let(ResourceKind.Companion::parseKind)
companion object {
val versionSuffix = """@v(\d+)$""".toRegex()
private val versionPrefix = """^v""".toRegex()
val versionComparator: Comparator<String> = NullSafeComparator<String>(
Comparator<String> { s1, s2 ->
DefaultArtifactVersion(s1?.replace(versionPrefix, "")).compareTo(
DefaultArtifactVersion(s2?.replace(versionPrefix, ""))
)
},
true // null is considered lower
)
}
}
| 3 | null | 144 | 99 | 6115964c42e863cfd269616a836145b883f165f3 | 5,023 | keel | Apache License 2.0 |
src/main/kotlin/com/pasmodev/training/app/service/RegisterBookAppService.kt | pasmontesinos | 167,554,439 | false | null | /*
* Copyright 2019 Pascual Montesinos - https://www.linkedin.com/in/pasmontesinos
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pasmodev.training.app.service
import com.pasmodev.training.app.configuration.Endpoints
import com.pasmodev.training.app.dto.BookDto
import com.pasmodev.training.app.dto.mapper.BookDtoToBookMapper
import com.pasmodev.training.app.exception.NullPropertyException
import com.pasmodev.training.domain.exception.BookAlreadyExistsException
import com.pasmodev.training.domain.model.Book
import com.pasmodev.training.domain.usecase.RegisterBookUsecase
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RestController
import java.io.IOException
import javax.servlet.http.HttpServletResponse
@RestController
class RegisterBookAppService {
@Autowired
lateinit var registerBook: RegisterBookUsecase
@Autowired
lateinit var bookDtoToBookMapper: BookDtoToBookMapper
@PostMapping(Endpoints.BOOKS)
fun register(@RequestBody bookDto: BookDto): BookDto {
return toDto(registerBook(toModel(bookDto)))
}
private fun toDto(book: Book): BookDto {
return bookDtoToBookMapper.reverseMap(book)
}
@Throws(NullPropertyException::class)
private fun toModel(bookDto: BookDto): Book {
return bookDtoToBookMapper.map(bookDto)
}
@ExceptionHandler(NullPropertyException::class)
@Throws(IOException::class)
internal fun handleNullPropertyException(e: NullPropertyException, response: HttpServletResponse) {
response.sendError(HttpStatus.BAD_REQUEST.value(), "${e.javaClass.simpleName}~: ${e.localizedMessage}")
}
@ExceptionHandler(BookAlreadyExistsException::class)
@Throws(IOException::class)
internal fun handleBookAlreadyExistsException(e: BookAlreadyExistsException, response: HttpServletResponse) {
response.sendError(HttpStatus.BAD_REQUEST.value(), "${e.javaClass.simpleName}~: ${e.localizedMessage}")
}
} | 0 | Kotlin | 0 | 2 | 46a7dbf97d0f3372b0f470ce6c7d827b367b84ba | 2,750 | pmd-spring-boot-kotlin-training | Apache License 2.0 |
src/test/kotlin/g0701_0800/s0773_sliding_puzzle/SolutionTest.kt | javadev | 190,711,550 | false | {"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994} | package g0701_0800.s0773_sliding_puzzle
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun slidingPuzzle() {
assertThat(Solution().slidingPuzzle(arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 0, 5))), equalTo(1))
}
@Test
fun slidingPuzzle2() {
assertThat(Solution().slidingPuzzle(arrayOf(intArrayOf(1, 2, 3), intArrayOf(5, 4, 0))), equalTo(-1))
}
@Test
fun slidingPuzzle3() {
assertThat(Solution().slidingPuzzle(arrayOf(intArrayOf(4, 1, 2), intArrayOf(5, 0, 3))), equalTo(5))
}
}
| 0 | Kotlin | 20 | 43 | 62708bc4d70ca2bfb6942e4bbfb4c64641e598e8 | 649 | LeetCode-in-Kotlin | MIT License |
src/test/kotlin/g0701_0800/s0773_sliding_puzzle/SolutionTest.kt | javadev | 190,711,550 | false | {"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994} | package g0701_0800.s0773_sliding_puzzle
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun slidingPuzzle() {
assertThat(Solution().slidingPuzzle(arrayOf(intArrayOf(1, 2, 3), intArrayOf(4, 0, 5))), equalTo(1))
}
@Test
fun slidingPuzzle2() {
assertThat(Solution().slidingPuzzle(arrayOf(intArrayOf(1, 2, 3), intArrayOf(5, 4, 0))), equalTo(-1))
}
@Test
fun slidingPuzzle3() {
assertThat(Solution().slidingPuzzle(arrayOf(intArrayOf(4, 1, 2), intArrayOf(5, 0, 3))), equalTo(5))
}
}
| 0 | Kotlin | 20 | 43 | 62708bc4d70ca2bfb6942e4bbfb4c64641e598e8 | 649 | LeetCode-in-Kotlin | MIT License |
app/src/main/java/com/weatherxm/data/datasource/RewardsDataSource.kt | WeatherXM | 728,657,649 | false | {"Kotlin": 1128981} | package com.weatherxm.data.datasource
import arrow.core.Either
import com.weatherxm.data.BoostRewardResponse
import com.weatherxm.data.Failure
import com.weatherxm.data.RewardDetails
import com.weatherxm.data.Rewards
import com.weatherxm.data.RewardsTimeline
import com.weatherxm.data.WalletRewards
import com.weatherxm.data.map
import com.weatherxm.data.network.ApiService
interface RewardsDataSource {
@Suppress("LongParameterList")
suspend fun getRewardsTimeline(
deviceId: String,
page: Int?,
pageSize: Int? = null,
timezone: String? = null,
fromDate: String? = null,
toDate: String? = null
): Either<Failure, RewardsTimeline>
suspend fun getRewards(deviceId: String): Either<Failure, Rewards>
suspend fun getRewardDetails(deviceId: String, date: String): Either<Failure, RewardDetails>
suspend fun getBoostReward(
deviceId: String,
boostCode: String
): Either<Failure, BoostRewardResponse>
suspend fun getWalletRewards(walletAddress: String): Either<Failure, WalletRewards>
}
class RewardsDataSourceImpl(private val apiService: ApiService) : RewardsDataSource {
override suspend fun getRewardsTimeline(
deviceId: String,
page: Int?,
pageSize: Int?,
timezone: String?,
fromDate: String?,
toDate: String?
): Either<Failure, RewardsTimeline> {
return apiService.getRewardsTimeline(
deviceId,
page,
pageSize,
timezone,
fromDate,
toDate
).map()
}
override suspend fun getRewards(deviceId: String): Either<Failure, Rewards> {
return apiService.getRewards(deviceId).map()
}
override suspend fun getRewardDetails(
deviceId: String,
date: String
): Either<Failure, RewardDetails> {
return apiService.getRewardDetails(deviceId, date).map()
}
override suspend fun getBoostReward(
deviceId: String,
boostCode: String
): Either<Failure, BoostRewardResponse> {
return apiService.getRewardBoost(deviceId, boostCode).map()
}
override suspend fun getWalletRewards(walletAddress: String): Either<Failure, WalletRewards> {
return apiService.getWalletRewards(walletAddress).map()
}
}
| 4 | Kotlin | 2 | 9 | eeb403f6da5f4e54e126e71edacf90c102bb0748 | 2,326 | wxm-android | Apache License 2.0 |
lib/src/main/java/de/inovex/blog/aidldemo/chatbot/lib/BotManager.kt | inovex | 645,052,604 | false | null | package de.inovex.blog.aidldemo.chatbot.lib
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import timber.log.Timber
/**
* Connection manager which handles the binding of the bound BotService, checks for availability
* and reduces callback complexity for the consumer side. A basic connection looks like this:
*/
object BotManager {
private var serviceConnection: ServiceConnection? = null
fun connect(context: Context, callback: BotServiceCallback) {
try {
check(serviceConnection == null) { "service is already connected" }
Timber.i("connecting to BotService")
serviceConnection = BotServiceConnection(callback)
val intent = Intent().apply {
component = ComponentName(
"de.inovex.blog.aidldemo.chatbot.service",
"de.inovex.blog.aidldemo.chatbot.service.BotService"
)
}
val serviceBound = context.bindService(
intent,
serviceConnection!!,
Context.BIND_AUTO_CREATE
)
check(serviceBound) { "Service was not found" }
} catch (e: SecurityException) {
callback.onConnectionFailed(e)
Timber.w(e, "could not connect to BotService")
serviceConnection = null
} catch (e: IllegalStateException) {
callback.onConnectionFailed(e)
Timber.w(e, e.message)
}
}
fun disconnect(context: Context) {
if (serviceConnection != null) {
context.unbindService(serviceConnection!!)
serviceConnection = null
} else {
Timber.w("not yet connected to BotService")
}
}
interface BotServiceCallback {
fun onConnected(service: IBotService)
fun onConnectionLost()
fun onConnectionFailed(e: Exception)
}
internal class BotServiceConnection(
private val callback: BotServiceCallback
) : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder) {
Timber.i("connected to BotService")
callback.onConnected(IBotService.Stub.asInterface(service))
}
override fun onServiceDisconnected(name: ComponentName?) {
Timber.i("disconnected from BotService")
callback.onConnectionLost()
}
override fun onNullBinding(name: ComponentName?) {
Timber.i("received null binding from BotService")
callback.onConnectionFailed(NullPointerException("received null binding from BotService"))
}
override fun onBindingDied(name: ComponentName?) {
Timber.i("connection died from BotService")
callback.onConnectionLost()
}
}
}
| 0 | Kotlin | 0 | 0 | c8b84373ccd5ec0953ec88365a32267b170e8729 | 2,929 | blog-android-service-kotlin-api-demo | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/servicecatalog/CfnResourceUpdateConstraintPropsDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 63959868} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.servicecatalog
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.servicecatalog.CfnResourceUpdateConstraintProps
/**
* Properties for defining a `CfnResourceUpdateConstraint`.
*
* 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.servicecatalog.*;
* CfnResourceUpdateConstraintProps cfnResourceUpdateConstraintProps =
* CfnResourceUpdateConstraintProps.builder()
* .portfolioId("portfolioId")
* .productId("productId")
* .tagUpdateOnProvisionedProduct("tagUpdateOnProvisionedProduct")
* // the properties below are optional
* .acceptLanguage("acceptLanguage")
* .description("description")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-resourceupdateconstraint.html)
*/
@CdkDslMarker
public class CfnResourceUpdateConstraintPropsDsl {
private val cdkBuilder: CfnResourceUpdateConstraintProps.Builder =
CfnResourceUpdateConstraintProps.builder()
/**
* @param acceptLanguage The language code.
* * `jp` - Japanese
* * `zh` - Chinese
*/
public fun acceptLanguage(acceptLanguage: String) {
cdkBuilder.acceptLanguage(acceptLanguage)
}
/** @param description The description of the constraint. */
public fun description(description: String) {
cdkBuilder.description(description)
}
/** @param portfolioId The portfolio identifier. */
public fun portfolioId(portfolioId: String) {
cdkBuilder.portfolioId(portfolioId)
}
/** @param productId The product identifier. */
public fun productId(productId: String) {
cdkBuilder.productId(productId)
}
/**
* @param tagUpdateOnProvisionedProduct If set to `ALLOWED` , lets users change tags in a
* [CloudFormationProvisionedProduct](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-cloudformationprovisionedproduct.html)
* resource. If set to `NOT_ALLOWED` , prevents users from changing tags in a
* [CloudFormationProvisionedProduct](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-servicecatalog-cloudformationprovisionedproduct.html)
* resource.
*/
public fun tagUpdateOnProvisionedProduct(tagUpdateOnProvisionedProduct: String) {
cdkBuilder.tagUpdateOnProvisionedProduct(tagUpdateOnProvisionedProduct)
}
public fun build(): CfnResourceUpdateConstraintProps = cdkBuilder.build()
}
| 3 | Kotlin | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 2,924 | awscdk-dsl-kotlin | Apache License 2.0 |
finch-java-core/src/test/kotlin/com/tryfinch/api/models/HrisIndividualRetrieveManyParamsTest.kt | Finch-API | 581,317,330 | false | {"Kotlin": 2738814, "Shell": 3626, "Java": 925, "Dockerfile": 366} | package com.tryfinch.api.models
import com.tryfinch.api.models.*
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class HrisIndividualRetrieveManyParamsTest {
@Test
fun createHrisIndividualRetrieveManyParams() {
HrisIndividualRetrieveManyParams.builder()
.options(
HrisIndividualRetrieveManyParams.Options.builder().include(listOf("string")).build()
)
.requests(
listOf(
HrisIndividualRetrieveManyParams.Request.builder()
.individualId("string")
.build()
)
)
.build()
}
@Test
fun getBody() {
val params =
HrisIndividualRetrieveManyParams.builder()
.options(
HrisIndividualRetrieveManyParams.Options.builder()
.include(listOf("string"))
.build()
)
.requests(
listOf(
HrisIndividualRetrieveManyParams.Request.builder()
.individualId("string")
.build()
)
)
.build()
val body = params.getBody()
assertThat(body).isNotNull
assertThat(body.options())
.isEqualTo(
HrisIndividualRetrieveManyParams.Options.builder().include(listOf("string")).build()
)
assertThat(body.requests())
.isEqualTo(
listOf(
HrisIndividualRetrieveManyParams.Request.builder()
.individualId("string")
.build()
)
)
}
@Test
fun getBodyWithoutOptionalFields() {
val params = HrisIndividualRetrieveManyParams.builder().build()
val body = params.getBody()
assertThat(body).isNotNull
}
}
| 2 | Kotlin | 1 | 5 | 2c6a4101439a510053c378c50c216f14e9d77154 | 2,016 | finch-api-java | Apache License 2.0 |
sample/shared/src/commonMain/kotlin/com/rickclephas/kmp/nativecoroutines/sample/tests/CompilerIntegrationTests.kt | rickclephas | 374,341,212 | false | null | package com.rickclephas.kmp.nativecoroutines.sample.tests
import com.rickclephas.kmp.nativecoroutines.NativeCoroutines
import com.rickclephas.kmp.nativecoroutines.NativeCoroutinesIgnore
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
class CompilerIntegrationTests<V>: IntegrationTests() {
@NativeCoroutines
suspend fun returnGenericClassValue(value: V): V {
return value
}
@NativeCoroutines
suspend fun returnDefaultValue(value: Int = 1): Int {
return value
}
@NativeCoroutines
suspend fun <T> returnGenericValue(value: T): T {
return value
}
fun returnAppendable(value: String): Appendable = StringBuilder(value)
@NativeCoroutines
suspend fun <T: Appendable> returnConstrainedGenericValue(value: T): T {
return value
}
@NativeCoroutines
suspend fun <T> returnGenericValues(values: List<T>): List<T> {
return values
}
@NativeCoroutines
suspend fun <T> returnGenericVarargValues(vararg values: T): Array<out T> {
return values
}
@NativeCoroutines
suspend fun <T> List<T>.returnGenericValueFromExtension(value: T): T {
return value
}
@NativeCoroutines
fun <T> returnGenericFlow(value: T): Flow<T> = flow {
emit(value)
}
@NativeCoroutinesIgnore
suspend fun returnIgnoredValue(value: Int): Int {
return value
}
}
| 15 | null | 28 | 654 | 768283b9db3e38b91d482e6615001843d712acf3 | 1,430 | KMP-NativeCoroutines | MIT License |
app/src/main/java/com/example/androiddevchallenge/screens/HomeScreen.kt | nguyenHanhNguyen | 347,578,812 | false | null | package com.example.androiddevchallenge.screens
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.example.androiddevchallenge.ui.theme.MyTheme
@Composable
fun HomeScreen() {
}
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun LightPreviewHome() {
MyTheme {
HomeScreen()
}
}
@Preview("Dark Theme", widthDp = 360, heightDp = 640)
@Composable
fun DarkPreviewHome() {
MyTheme(darkTheme = true) {
HomeScreen()
}
} | 0 | Kotlin | 0 | 0 | 3d6d94f0eb5b5848bd14eb11c052947dc50f1437 | 521 | week3_compose | Apache License 2.0 |
NavigationCodelab/app/src/main/java/com/example/compose/rally/RallyNavHost.kt | PaulinaSadowska | 448,604,363 | true | {"Kotlin": 598770, "Shell": 2341} | package com.example.compose.rally
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.navigation.NavHostController
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.navArgument
import androidx.navigation.navDeepLink
import com.example.compose.rally.data.UserData
import com.example.compose.rally.ui.accounts.AccountsBody
import com.example.compose.rally.ui.accounts.SingleAccountBody
import com.example.compose.rally.ui.bills.BillsBody
import com.example.compose.rally.ui.overview.OverviewBody
@Composable
fun RallyNavHost(
navController: NavHostController,
modifier: Modifier = Modifier
) {
NavHost(
navController = navController,
startDestination = RallyScreen.Overview.name,
modifier = modifier) {
composable(RallyScreen.Overview.name) {
OverviewBody(
onClickSeeAllAccounts = { navController.navigate(RallyScreen.Accounts.name) },
onClickSeeAllBills = { navController.navigate(RallyScreen.Bills.name) },
onAccountClick = { accountName ->
navController.navigateToSingleAccount(accountName)
}
)
}
composable(RallyScreen.Accounts.name) {
AccountsBody(
accounts = UserData.accounts,
onAccountClick = { accountName ->
navController.navigateToSingleAccount(accountName)
})
}
composable(RallyScreen.Bills.name) {
BillsBody(bills = UserData.bills)
}
val accountsName = RallyScreen.Accounts.name
composable(
route = "$accountsName/{name}",
arguments = listOf(navArgument("name") {
type = NavType.StringType
}),
deepLinks = listOf(navDeepLink { uriPattern = "rally://$accountsName/{name}" })
) { entry ->
val accountName = entry.arguments?.getString("name")
val account = UserData.getAccount(accountName)
SingleAccountBody(account = account)
}
}
}
private fun NavHostController.navigateToSingleAccount(accountName: String) {
navigate("${RallyScreen.Accounts.name}/$accountName")
} | 0 | Kotlin | 0 | 0 | b3a4236be829a47bb025364e467df4d61f775113 | 2,420 | android-compose-codelabs | Apache License 2.0 |
instantsearch/src/androidMain/kotlin/com/algolia/instantsearch/android/filter/facet/dynamic/DynamicFacetModel.kt | algolia | 55,971,521 | false | null | package com.algolia.instantsearch.helper.android.filter.facet.dynamic
import com.algolia.search.model.Attribute
import com.algolia.search.model.search.Facet
/**
* Facet view model to be rendered.
*/
public sealed class DynamicFacetModel {
/**
* Attribute view to be rendered.
*/
public data class Header(val attribute: Attribute) : DynamicFacetModel()
/**
* Facet value view to be rendered.
*/
public data class Item(val attribute: Attribute, val facet: Facet, val selected: Boolean) : DynamicFacetModel()
}
| 5 | null | 30 | 156 | eaf37a61303a8b9c5688a596e8aeab29dfbba398 | 550 | instantsearch-android | Apache License 2.0 |
app/src/main/java/com/muhammetkdr/weatherapp/data/repository/city/CityRepositoryImpl.kt | mskdr | 592,702,997 | false | null | package com.muhammetkdr.weatherapp.data.repository.city
import com.muhammetkdr.weatherapp.common.extensions.mapResource
import com.muhammetkdr.weatherapp.common.utils.Resource
import com.muhammetkdr.weatherapp.data.dto.city.CitiesResponse
import com.muhammetkdr.weatherapp.data.listmapper.ListMapper
import com.muhammetkdr.weatherapp.data.remote.city.CityRemoteDataSource
import com.muhammetkdr.weatherapp.di.Dispatcher
import com.muhammetkdr.weatherapp.di.DispatcherType
import com.muhammetkdr.weatherapp.domain.entity.cities.CitiesEntity
import com.muhammetkdr.weatherapp.domain.repository.city.CityRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
class CityRepositoryImpl @Inject constructor(
private val cityRemoteDataSource: CityRemoteDataSource,
private val cityListMapper: ListMapper<CitiesResponse, CitiesEntity>,
@Dispatcher(DispatcherType.Io) private val ioDispatcher: CoroutineContext
) : CityRepository {
override fun getAllCities(): Flow<Resource<List<CitiesEntity>>> =
cityRemoteDataSource.getCityResponse().map {
it.mapResource { cityListMapper.map(this) }
}.flowOn(ioDispatcher)
}
| 0 | null | 0 | 5 | d0bcd4634234fa6ebdede7e5c7cdec521a669927 | 1,275 | WeatherApp | MIT License |
kafka-connect-upload-source/src/main/java/org/radarbase/connect/upload/converter/oxford/CameraDataFileProcessor.kt | RADAR-base | 179,307,077 | false | null | package org.radarbase.connect.upload.converter.oxford
import org.radarbase.connect.upload.api.ContentsDTO
import org.radarbase.connect.upload.api.RecordDTO
import org.radarbase.connect.upload.converter.ConverterFactory
import org.radarbase.connect.upload.converter.FileProcessor
import org.radarbase.connect.upload.converter.FileProcessorFactory
import org.radarbase.connect.upload.converter.TimeFieldParser
import org.radarbase.connect.upload.converter.TopicData
import org.radarcns.connector.upload.oxford.OxfordCameraAxes
import org.radarcns.connector.upload.oxford.OxfordCameraData
import org.radarcns.connector.upload.oxford.OxfordCameraRgb
import java.io.InputStream
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
class CameraDataFileProcessor : FileProcessorFactory {
override fun matches(contents: ContentsDTO) = contents.fileName.endsWith("image_table.txt")
override fun createProcessor(record: RecordDTO): FileProcessor = CameraFileProcessor()
private class CameraFileProcessor : FileProcessor {
override fun processData(
context: ConverterFactory.ContentsContext,
inputStream: InputStream,
produce: (TopicData) -> Unit,
) {
val lines = inputStream.bufferedReader().use { it.readLines() }
require(lines.size >= 2) { "Image table too short" }
val header = lines[1]
.drop(1)
.split(",")
.map { it.trim() }
lines
.asSequence()
.drop(2)
.map { line ->
TopicData(
TOPIC,
line.toOxfordCameraRecord(header, context.timeReceived),
)
}
.forEach(produce)
}
fun String.toOxfordCameraRecord(
header: List<String>,
timeReceived: Double,
) = split(",")
.asSequence()
.mapIndexed { idx, field -> header[idx] to field.trim() }
.toMap()
.toOxfordCameraRecord(timeReceived)
fun Map<String, String>.toOxfordCameraRecord(
timeReceived: Double,
) = OxfordCameraData(
TIME_PARSER.time(this),
timeReceived,
getValue("id"),
getValue("p") == "1",
OxfordCameraAxes(
getValue("accx").toFloat(),
getValue("accy").toFloat(),
getValue("accz").toFloat(),
),
OxfordCameraAxes(
getValue("magx").toFloat(),
getValue("magy").toFloat(),
getValue("magz").toFloat(),
),
OxfordCameraAxes(
getValue("xor").toFloat(),
getValue("yor").toFloat(),
getValue("zor").toFloat(),
),
getValue("tem").toFloat(),
OxfordCameraRgb(
getValue("red").toInt() / RGB_RANGE,
getValue("green").toInt() / RGB_RANGE,
getValue("blue").toInt() / RGB_RANGE,
),
getValue("lum").toInt() / LUMINANCE_RANGE,
getValue("exp").toInt(),
getValue("gain").toFloat(),
OxfordCameraRgb(
getValue("rbal").toFloat(),
getValue("gbal").toFloat(),
getValue("bbal").toFloat(),
),
)
}
companion object {
private val TIME_PARSER = TimeFieldParser.DateFormatParser(
DateTimeFormatterBuilder()
// date/time
.append(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
// offset (hhmm - "+0000" when it's zero)
.appendOffset("+HHMM", "+0000")
// create formatter
.toFormatter(),
"dt",
)
private const val TOPIC = "connect_upload_oxford_camera_data"
private const val RGB_RANGE: Float = 255f
private const val LUMINANCE_RANGE: Float = RGB_RANGE * RGB_RANGE * RGB_RANGE
}
}
| 27 | Kotlin | 1 | 1 | 8ab51c5f80a69ab25a164a284dcfc7c2a798cea5 | 4,121 | radar-upload-source-connector | Apache License 2.0 |
common/common-ui/src/main/java/com/duckduckgo/common/ui/view/button/RadioButton.kt | duckduckgo | 78,869,127 | false | null | /*
* Copyright (c) 2022 DuckDuckGo
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.duckduckgo.mobile.android.ui.view.button
import android.content.Context
import android.util.AttributeSet
import com.duckduckgo.mobile.android.R
import com.google.android.material.button.MaterialButton
class ButtonSecondaryLarge @JvmOverloads constructor(
ctx: Context,
attrs: AttributeSet,
defStyleAttr: Int = R.attr.secondaryButtonLargeStyle
) : MaterialButton(
ctx,
attrs,
defStyleAttr
)
| 67 | null | 901 | 3,823 | 6415f0f087a11a51c0a0f15faad5cce9c790417c | 1,027 | Android | Apache License 2.0 |
src/main/kotlin/kr/sixtyfive/Dropbox.kt | snowphone | 370,909,635 | false | null | package kr.sixtyfive
import com.google.gson.GsonBuilder
import org.codehaus.httpcache4j.uri.URIEncoder
import org.slf4j.LoggerFactory
import java.awt.Desktop
import java.io.BufferedInputStream
import java.io.ByteArrayInputStream
import java.io.FileWriter
import java.io.InputStream
import java.net.URI
import java.net.URLDecoder
import java.net.http.HttpResponse.BodyHandlers
import java.nio.charset.StandardCharsets.UTF_8
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletableFuture.*
import java.util.concurrent.TimeUnit
class Dropbox {
private val gson = GsonBuilder().disableHtmlEscaping().create()
private val logger = LoggerFactory.getLogger(this::class.java)
private val client = Http()
private val baseHeader: Map<String, String>
get() = mapOf(
"Authorization" to "Bearer $token",
"Content-Type" to "application/octet-stream",
)
private val token: String
val user: String?
constructor(key: String, secret: String, savePath: String? = null) {
this.token = issueToken(key, secret)
savePath?.let(::FileWriter)
?.use { it.write(this.token) }
this.user = fetchUser(token)
}
constructor(token: String) {
this.token = token
this.user = fetchUser(this.token)
}
private fun fetchUser(token: String): String? {
return "https://api.dropboxapi.com/2/users/get_current_account"
.let { client.postAsync(it, headers = mapOf("Authorization" to "Bearer $token")) }
.get()
.body()
.let { URLDecoder.decode(it, UTF_8) }
.let { gson.fromJson(it, Map::class.java) }.get("name")
?.let { (it as Map<*, *>).get("display_name") }
?.let { it as String }
}
private fun issueToken(key: String, secret: String): String {
val requestUrl = "https://www.dropbox.com/oauth2/authorize?client_id=$key&response_type=code"
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(URI(requestUrl))
logger.info("Log in from your browser and copy TOKEN to console")
} else {
logger.info("Go to '$requestUrl' and enter the access code")
}
val accessCode = readLine()!!.trim()
val params = mapOf(
"code" to accessCode,
"grant_type" to "authorization_code",
"client_id" to key,
"client_secret" to secret,
)
val token = client.postAsync("https://api.dropboxapi.com/oauth2/token", params = params)
.get()
.body()!!
.let { gson.fromJson(it, Map::class.java) }
.get("access_token") as String
logger.info("Issued token: $token")
return token
}
fun authenticate(): Boolean = fetchUser(token) != null
fun download(fileName: String): CompletableFuture<Pair<InputStream, Response?>> {
val url = "https://content.dropboxapi.com/2/files/download"
val params = mapOf("arg" to gson.toJson(mapOf("path" to "/$fileName")))
return client.postAsync(url, headers = baseHeader, params = params, handler = BodyHandlers.ofInputStream())
.thenApply {
val metadata = it.headers().firstValue("Dropbox-API-Result")
.orElse(null)
?.let { i -> gson.fromJson(i, Response::class.java) }
it.body() to metadata
}
}
fun delete(fileName: String): CompletableFuture<Boolean> {
val url = "https://api.dropboxapi.com/2/files/delete_v2"
val hdr = mapOf(
"Authorization" to "Bearer $token",
"Content-type" to "application/json"
)
val data = gson.toJson(mapOf("path" to "/$fileName")).toByteArray().inputStream()
return client.postAsync(url, headers = hdr, data = data, handler = BodyHandlers.ofInputStream())
.thenApply {
logger.info(it.body().readAllBytes().decodeToString())
it.statusCode() in 200 until 300
}
}
fun upload(data: InputStream, fileName: String): CompletableFuture<Response?> {
val buffer = data.readAllBytes()
return upload(buffer, fileName)
}
private fun upload(buffer: ByteArray, fileName: String): CompletableFuture<Response?> {
val url = "https://content.dropboxapi.com/2/files/upload"
// Since http header cannot handle non-ascii characters correctly, any
// characters whose codepoint is bigger than 0x7F should have been escaped.
// But, both of kotlinx-serialization and Gson do not support this kind
// of http-header-safe-serialization, I chose to use an alternative: `arg` URL parameter.
val params = mapOf(
"arg" to gson.toJson(
mapOf(
"path" to "/$fileName",
"mode" to "overwrite",
)
)
)
return client.postAsync(url, headers = baseHeader, params = params, data = buffer.inputStream())
.thenCompose {
when (it.statusCode()) {
in 200 until 300 -> URLDecoder.decode(it.body(), UTF_8)
.let { b -> gson.fromJson(b, Response::class.java) }
.let { resp -> completedFuture(resp) }
429 -> { // Error: too-many-write-operations
logger.debug("429 error raised. Retry")
upload(buffer, fileName)
}
else -> {
logger.warn("Error occurred while uploading. Status code: ${it.statusCode()}, reason: ${it.body()}")
completedFuture(null)
}
}
}
}
}
| 0 | Kotlin | 0 | 1 | 27b2fd58bbe72727f7f9ebe0afd77ed1c2bcecb1 | 5,004 | async-dropbox | MIT License |
src/main/java/com/mallowigi/search/parsers/NetColorParser.kt | AtomMaterialUI | 215,215,096 | false | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2015-2022 <NAME>Mallowigi" Boukhobza
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
*
*/
package com.mallowigi.search.parsers
import com.mallowigi.colors.ColorData
import java.awt.Color
import java.util.*
/** Parses colors in the form `Color.FromArgb(a,b,c)` */
class NetColorParser : ColorParser {
override fun parseColor(text: String?): Color? = parseConstructor(text!!)
private fun parseConstructor(text: String): Color? {
val colorData = ColorData()
colorData.run {
init(text)
if (startParen == -1 || endParen == -1) return null
// tokenize the string into "alpha,red,green,blue"
val tokenizer = StringTokenizer(text.substring(startParen + 1, endParen), ",")
val params = tokenizer.countTokens()
getNextNumber(tokenizer).also { parseAlpha(it) }
if (params >= 2) getNextNumber(tokenizer).also { parseRed(it) }
if (params >= 3) getNextNumber(tokenizer).also { parseGreen(it) }
if (params == 4) getNextNumber(tokenizer).also { parseBlue(it) }
return when {
isFloat -> Color(floatRed, floatGreen, floatBlue, floatAlpha)
else -> when (params) {
1 -> Color(intRed)
2 -> Color(intRed, alpha)
else -> Color(intRed, intGreen, intBlue, intAlpha)
}
}
}
}
}
| 8 | null | 25 | 41 | 0fc0f5c0d8c1f3f25952f6b690797aba409cc37d | 2,380 | color-highlighter | MIT License |
time/src/main/kotlin/ca/allanwang/discord/bot/time/TimeApi.kt | AllanWang | 293,650,128 | false | null | package ca.allanwang.discord.bot.time
import ca.allanwang.discord.bot.base.ColorPalette
import ca.allanwang.discord.bot.firebase.*
import com.google.common.flogger.FluentLogger
import com.google.firebase.database.DatabaseReference
import dev.kord.common.Color
import dev.kord.common.entity.Snowflake
import dev.kord.core.entity.ReactionEmoji
import dev.kord.x.emoji.Emojis
import dev.kord.x.emoji.toReaction
import java.time.LocalDate
import java.time.LocalTime
import java.time.ZoneId
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class TimeApi @Inject constructor(
@FirebaseRootRef rootRef: DatabaseReference,
colorPalette: ColorPalette
) {
companion object {
private const val TIME = "time"
private val logger = FluentLogger.forEnclosingClass()
/**
* A time regex should match values of the format
* 8am, 9pm, 8:00, 8:00 am
*
* To avoid matching tags, time values should not be surrounded by alphanumeric characters.
*/
val timeRegex = Regex("(?:^|[^a-zA-Z0-9])(1[0-2]|0?[1-9])(?::([0-5][0-9]))?\\s*([AaPp][Mm])?(?:$|[^a-zA-Z0-9])")
}
private val ref = rootRef.child(TIME)
val dateTimeFormatterNoAmPm: DateTimeFormatter = DateTimeFormatter.ofPattern("h:mm")
val dateTimeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern("h:mm a")
val reactionEmoji: ReactionEmoji = Emojis.clock3.toReaction()
val reactionThresholdTime: Long = 5 * 60 * 1000
val embedColor: Color = colorPalette.lightBlue
suspend fun getTime(group: Snowflake, id: Snowflake): TimeZone? =
ref.child(group).child(id).single<String>()?.let { TimeZone.getTimeZone(it) }
suspend fun saveTime(group: Snowflake, id: Snowflake, value: TimeZone): Boolean =
ref.child(group).child(id).setValue(value.id)
suspend fun groupTimes(group: Snowflake): List<TimeZone> {
return ref.child(group)
.singleSnapshot().children
.asSequence()
.mapNotNull { it.getValueOrNull<String>() }
.distinct()
.mapNotNull { TimeZone.getTimeZone(it) }
.distinctBy { it.rawOffset }
.sortedBy { it.rawOffset }
.toList()
}
data class TimeEntry(val hour: Int, val minute: Int, val pm: Boolean?) {
override fun toString(): String = buildString {
append(hour)
append(':')
append(minute.toString().padStart(2, '0'))
if (pm != null) {
append(' ')
append(if (pm) "PM" else "AM")
}
}
val hour24: Int
get() = when {
hour == 12 -> if (pm == false) 0 else 12
pm == true -> hour + 12
else -> hour
}
/**
* Convert to zoned date time. If date is not set, it will be the closest zoned date time in the future.
*/
fun toZonedDateTime(zoneId: ZoneId, localDate: LocalDate? = null): ZonedDateTime {
val localTime = LocalTime.of(hour24, minute)
val _localDate: LocalDate = when {
localDate != null -> localDate
LocalTime.now(zoneId) > localTime -> LocalDate.now(zoneId).plusDays(1)
else -> LocalDate.now(zoneId)
}
return ZonedDateTime.of(_localDate, localTime, zoneId)
}
}
private fun MatchResult.toTimeEntry(): TimeEntry? {
// Disallow general numbers as timestamps
if (groupValues[2].isEmpty() && groupValues[3].isEmpty()) return null
val hour = groupValues[1].toInt()
val minute = groupValues[2].toIntOrNull() ?: 0
val pm = when (groupValues[3].toLowerCase(Locale.US)) {
"am" -> false
"pm" -> true
else -> null
}
return TimeEntry(hour, minute, pm)
}
fun findTimes(message: CharSequence): List<TimeEntry> =
timeRegex
.findAll(message)
.mapNotNull { it.toTimeEntry() }
.distinct()
.toList()
}
| 6 | Kotlin | 2 | 2 | d0715af30a1dc8cb883a79fbc7fcbca5ed482805 | 4,192 | Discord-Bot | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Hippo.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.Hippo: ImageVector
get() {
if (_hippo != null) {
return _hippo!!
}
_hippo = Builder(name = "Hippo", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(15.25f, 14.0f)
horizontalLineToRelative(4.5f)
curveToRelative(2.343f, 0.0f, 4.25f, -1.915f, 4.25f, -4.269f)
curveToRelative(0.0f, -1.258f, -0.552f, -2.43f, -1.5f, -3.233f)
verticalLineToRelative(-0.499f)
curveToRelative(0.0f, -1.125f, -0.373f, -2.164f, -1.003f, -3.0f)
horizontalLineToRelative(0.003f)
curveToRelative(0.828f, 0.0f, 1.5f, -0.672f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
verticalLineToRelative(0.171f)
curveToRelative(-0.736f, -0.427f, -1.59f, -0.671f, -2.5f, -0.671f)
reflectiveCurveToRelative(-1.764f, 0.245f, -2.5f, 0.671f)
verticalLineToRelative(-0.171f)
curveToRelative(0.0f, -0.828f, -0.672f, -1.5f, -1.5f, -1.5f)
reflectiveCurveToRelative(-1.5f, 0.672f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
horizontalLineToRelative(0.003f)
curveToRelative(-0.438f, 0.582f, -0.752f, 1.261f, -0.902f, 2.0f)
horizontalLineToRelative(-3.601f)
curveTo(4.589f, 5.0f, 1.0f, 8.589f, 1.0f, 13.0f)
curveToRelative(0.0f, 0.833f, 0.131f, 1.65f, 0.379f, 2.425f)
lineToRelative(-1.236f, 2.06f)
curveToRelative(-0.284f, 0.474f, -0.131f, 1.088f, 0.343f, 1.372f)
curveToRelative(0.161f, 0.097f, 0.338f, 0.143f, 0.514f, 0.143f)
curveToRelative(0.34f, 0.0f, 0.671f, -0.173f, 0.858f, -0.485f)
lineToRelative(0.574f, -0.956f)
curveToRelative(0.435f, 0.627f, 0.962f, 1.194f, 1.569f, 1.681f)
verticalLineToRelative(1.761f)
curveToRelative(0.0f, 1.654f, 1.346f, 3.0f, 3.0f, 3.0f)
reflectiveCurveToRelative(3.0f, -1.346f, 3.0f, -3.0f)
horizontalLineToRelative(3.0f)
curveToRelative(0.0f, 1.654f, 1.346f, 3.0f, 3.0f, 3.0f)
reflectiveCurveToRelative(3.0f, -1.346f, 3.0f, -3.0f)
verticalLineToRelative(-1.76f)
curveToRelative(0.597f, -0.478f, 1.121f, -1.037f, 1.561f, -1.667f)
curveToRelative(0.317f, -0.453f, 0.207f, -1.076f, -0.246f, -1.393f)
curveToRelative(-0.453f, -0.316f, -1.076f, -0.206f, -1.393f, 0.246f)
curveToRelative(-0.408f, 0.583f, -0.911f, 1.085f, -1.495f, 1.493f)
curveToRelative(-0.268f, 0.187f, -0.428f, 0.493f, -0.428f, 0.82f)
verticalLineToRelative(2.26f)
curveToRelative(0.0f, 0.551f, -0.449f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.449f, -1.0f, -1.0f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f)
horizontalLineToRelative(-5.0f)
curveToRelative(-0.552f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 0.551f, -0.449f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.449f, -1.0f, -1.0f)
verticalLineToRelative(-2.25f)
curveToRelative(0.0f, -0.647f, -0.423f, -0.826f, -0.427f, -0.829f)
curveToRelative(-0.931f, -0.65f, -1.644f, -1.539f, -2.082f, -2.551f)
curveToRelative(-0.021f, -0.157f, -0.079f, -0.309f, -0.17f, -0.441f)
curveToRelative(-0.21f, -0.614f, -0.321f, -1.265f, -0.321f, -1.929f)
curveToRelative(0.0f, -3.309f, 2.691f, -6.0f, 6.0f, -6.0f)
horizontalLineToRelative(2.999f)
curveToRelative(-0.638f, 0.755f, -0.999f, 1.715f, -0.999f, 2.731f)
curveToRelative(0.0f, 2.354f, 1.907f, 4.269f, 4.25f, 4.269f)
close()
moveTo(17.5f, 3.0f)
curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f)
verticalLineToRelative(1.0f)
curveToRelative(0.0f, 0.34f, 0.173f, 0.657f, 0.459f, 0.841f)
curveToRelative(0.651f, 0.418f, 1.041f, 1.125f, 1.041f, 1.89f)
curveToRelative(0.0f, 0.785f, -0.397f, 1.478f, -1.0f, 1.885f)
verticalLineToRelative(-0.617f)
curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f)
reflectiveCurveToRelative(-1.0f, 0.448f, -1.0f, 1.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(-3.0f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f)
reflectiveCurveToRelative(-1.0f, 0.448f, -1.0f, 1.0f)
verticalLineToRelative(0.617f)
curveToRelative(-0.603f, -0.407f, -1.0f, -1.1f, -1.0f, -1.885f)
curveToRelative(0.0f, -0.765f, 0.389f, -1.472f, 1.041f, -1.89f)
curveToRelative(0.286f, -0.184f, 0.459f, -0.501f, 0.459f, -0.841f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f)
close()
}
}
.build()
return _hippo!!
}
private var _hippo: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 6,504 | icons | MIT License |
lightweightlibrary/src/main/java/com/tradingview/lightweightcharts/api/delegates/SeriesApiDelegate.kt | grietzercs | 306,704,587 | true | {"Kotlin": 112058, "JavaScript": 21903, "HTML": 142} | package com.tradingview.lightweightcharts.api.delegates
import com.google.gson.reflect.TypeToken
import com.tradingview.lightweightcharts.Logger
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Func.APPLY_OPTIONS
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Func.COORDINATE_TO_PRICE
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Func.CREATE_PRICE_LINE
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Func.PRICE_FORMATTER
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Func.PRICE_TO_COORDINATE
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Func.REMOVE_PRICE_LINE
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Func.SET_MARKERS
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Func.SET_SERIES
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Func.UPDATE
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Params.BAR
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Params.COORDINATE
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Params.DATA
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Params.LINE_ID
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Params.OPTIONS
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Params.PRICE
import com.tradingview.lightweightcharts.api.interfaces.SeriesApi.Params.SERIES_ID
import com.tradingview.lightweightcharts.api.options.models.PriceLineOptions
import com.tradingview.lightweightcharts.api.options.models.SeriesOptionsCommon
import com.tradingview.lightweightcharts.api.serializer.Serializer
import com.tradingview.lightweightcharts.api.series.common.*
import com.tradingview.lightweightcharts.api.series.models.SeriesMarker
import com.tradingview.lightweightcharts.runtime.controller.WebMessageController
class SeriesApiDelegate<T: SeriesData, O : SeriesOptionsCommon>(
override val uuid: String,
private val controller: WebMessageController,
private val optionsSerializer: Serializer<out O>
): SeriesApi<T> {
override fun setData(data: List<T>) {
controller.callFunction(
SET_SERIES,
mapOf(
SERIES_ID to uuid,
DATA to data
)
)
}
override fun priceFormatter(): PriceFormatter {
val uuid = controller.callFunction(
PRICE_FORMATTER,
mapOf(SERIES_ID to uuid)
)
return PriceFormatterDelegate(
uuid,
controller
)
}
override fun priceToCoordinate(price: Float, completion: (Float?) -> Unit) {
controller.callFunction<Double>(
PRICE_TO_COORDINATE,
mapOf(
SERIES_ID to uuid,
PRICE to price
),
callback = { completion(it?.toFloat()) }
)
}
override fun coordinateToPrice(coordinate: Float, completion: (Float?) -> Unit) {
controller.callFunction(
COORDINATE_TO_PRICE,
mapOf(
SERIES_ID to uuid,
COORDINATE to coordinate
),
callback = completion
)
}
override fun applyOptions(options: SeriesOptionsCommon) {
controller.callFunction(
APPLY_OPTIONS,
mapOf(
SERIES_ID to uuid,
OPTIONS to options
)
)
}
override fun options(completion: (SeriesOptionsCommon?) -> Unit) {
val collectionType = object : TypeToken<T>() {}.type
Logger.printD("type $collectionType")
controller.callFunction(
OPTIONS,
mapOf(SERIES_ID to uuid),
callback = completion,
serializer = optionsSerializer
)
}
override fun setMarkers(data: List<SeriesMarker>) {
controller.callFunction(
SET_MARKERS,
mapOf(
SERIES_ID to uuid,
DATA to data
)
)
}
override fun createPriceLine(options: PriceLineOptions): PriceLine {
val uuid = controller.callFunction(
CREATE_PRICE_LINE,
mapOf(
SERIES_ID to uuid,
OPTIONS to options
)
)
return PriceLineDelegate(
uuid,
controller
)
}
override fun removePriceLine(line: PriceLine) {
controller.callFunction(
REMOVE_PRICE_LINE,
mapOf(
SERIES_ID to uuid,
LINE_ID to line.uuid
)
)
}
override fun update(bar: T) {
controller.callFunction(
UPDATE,
mapOf(
SERIES_ID to uuid,
BAR to bar
)
)
}
}
| 0 | null | 0 | 0 | 3dc7289f1860d8ed7374884ebbcfaf9a712b8174 | 4,954 | lightweight-charts-android | Apache License 2.0 |
compiler/testData/ir/box/closureConversion/closureConversion4.kt | JakeWharton | 99,388,807 | false | null | fun String.foo(): String {
fun bar(y: String) = this + y
return bar("K")
}
fun box() = "O".foo() | 179 | null | 5640 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 105 | kotlin | Apache License 2.0 |
app/src/androidTest/java/com/skydoves/themovies/db/DbTest.kt | paolorotolo | 163,106,329 | true | {"Kotlin": 173848} | package com.skydoves.themovies.db
import androidx.room.Room
import androidx.test.InstrumentationRegistry
import androidx.test.runner.AndroidJUnit4
import com.skydoves.themovies.room.AppDatabase
import org.junit.After
import org.junit.Before
import org.junit.runner.RunWith
/**
* Developed by skydoves on 2018-08-10.
* Copyright (c) 2018 skydoves rights reserved.
*/
@RunWith(AndroidJUnit4::class)
abstract class DbTest {
lateinit var db: AppDatabase
@Before
fun initDB() {
db = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(),
AppDatabase::class.java).build()
}
@After
fun closeDB() {
db.close()
}
}
| 0 | Kotlin | 0 | 2 | f784a842ba15feaeb1e958e0267f550160554a5d | 686 | TheMovies | MIT License |
src/main/kotlin/com/epam/brn/auth/model/UserAccountCredentials.kt | Brain-up | 216,092,521 | false | {"Kotlin": 1057933, "Handlebars": 512629, "TypeScript": 401203, "JavaScript": 168755, "HTML": 45401, "CSS": 30742, "SCSS": 27412, "RAML": 22982, "Makefile": 545, "Shell": 405, "Dockerfile": 185} | package com.epam.brn.auth.model
import com.google.firebase.auth.FirebaseToken
data class UserAccountCredentials(
private val decodedToken: FirebaseToken?,
private val idToken: String?
)
| 114 | Kotlin | 26 | 61 | 310cfcae2b9780740554396271444388258ce8da | 196 | brn | Creative Commons Zero v1.0 Universal |
src/main/kotlin/day04/Solution.kt | kcchoate | 683,597,644 | false | {"Kotlin": 25162} | package day04
import day04.models.BingoGame
import java.io.File
class Solution {
val input = File("src/main/kotlin/day04/input.txt").readText()
fun solve(): Int {
val game = BingoGame(input)
val lastNumber = game.play()
val winner = game.getWinner().get()
return winner.getScore(lastNumber)
}
}
| 0 | Kotlin | 0 | 1 | 3e7c24bc69a4de168ce0bdff855323c803b9a9a8 | 343 | advent-of-kotlin | MIT License |
js/js.translator/testData/box/inlineMultiModule/kt16160.kt | JakeWharton | 99,388,807 | false | null | // EXPECTED_REACHABLE_NODES: 1011
// MODULE: main(module2)
// FILE: main.kt
// CHECK_CONTAINS_NO_CALLS: box except=foo;bar;toString
import A.test
fun box(): String {
if (A.test() != 3) return "A.test()" + A.test()
if (B.test() != 6) return "B.test()" + B.test()
if (B().foo() != 4) return "B().foo()" + B().foo()
if (test() != 3) return "[A.]test()" + test()
if (test2() != 3) return "test2()" + test2()
if (A.test2() != 3) return "A.test2()" + A.test2()
if (B.test2() != 2) return "B.test2()" + B.test2()
if (B.C.test() != 4) return "B.C.test()" + B.C.test()
if (D().foo2() != 4) return "D().foo2()" + D().foo2()
if (D.test() != 4) return "D.test()" + D.test()
return "OK"
}
// MODULE: module2
// FILE: module2.kt
import A.foo
import B.Companion.bar
object A {
fun foo() = 1
inline fun test() = foo() + this.foo() + A.foo()
}
open class B {
companion object {
fun bar() = 2
inline fun test() = bar() + this.bar() + B.bar()
}
class C {
companion object {
inline fun test() = bar() + B.bar()
}
}
inline fun foo() = bar() + B.bar()
}
class D: B() {
inline fun foo2() = bar() + B.bar()
companion object {
inline fun test() = bar() + B.bar()
}
}
inline fun test2() = foo() + bar()
inline fun A.test2() = foo() + B.bar()
inline fun B.Companion.test2() = bar() | 184 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,402 | kotlin | Apache License 2.0 |
compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/transformers/irToJs/JsNameLinkingNamer.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.ir.backend.js.transformers.irToJs
import org.jetbrains.kotlin.ir.backend.js.JsIrBackendContext
import org.jetbrains.kotlin.ir.backend.js.export.isExported
import org.jetbrains.kotlin.ir.backend.js.utils.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.symbols.IrClassSymbol
import org.jetbrains.kotlin.ir.types.IrSimpleType
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.js.backend.ast.*
import org.jetbrains.kotlin.utils.DFS
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
class JsNameLinkingNamer(
private val context: JsIrBackendContext,
private val minimizedMemberNames: Boolean,
private val isEsModules: Boolean
) : IrNamerBase() {
val nameMap = mutableMapOf<IrDeclaration, JsName>()
private fun IrDeclarationWithName.getName(): JsName {
return nameMap.getOrPut(this) {
val name = (this as? IrClass)?.let { context.localClassNames[this] } ?: let {
this.nameIfPropertyAccessor() ?: getJsNameOrKotlinName().asString()
}
JsName(sanitizeName(name), true)
}
}
val importedModules = mutableListOf<JsImportedModule>()
val imports = mutableMapOf<IrDeclaration, JsStatement>()
override fun getNameForStaticDeclaration(declaration: IrDeclarationWithName): JsName {
if (declaration.isEffectivelyExternal()) {
val jsModule: String? = declaration.getJsModule()
val maybeParentFile: IrFile? = declaration.parent as? IrFile
val fileJsModule: String? = maybeParentFile?.getJsModule()
val jsQualifier: List<JsName>? = maybeParentFile?.getJsQualifier()?.split('.')?.map { JsName(it, false) }
return when {
jsModule != null -> declaration.generateImportForDeclarationWithJsModule(jsModule)
fileJsModule != null -> declaration.generateImportForDeclarationInFileWithJsModule(fileJsModule, jsQualifier)
else -> declaration.generateRegularQualifiedImport(jsQualifier)
}
}
return declaration.getName()
}
override fun getNameForMemberFunction(function: IrSimpleFunction): JsName {
require(function.dispatchReceiverParameter != null)
val signature = jsFunctionSignature(function, context)
if (context.keeper.shouldKeep(function)) {
context.minimizedNameGenerator.keepName(signature)
}
val result = if (minimizedMemberNames && !function.hasStableJsName(context)) {
function.parentAsClass.fieldData()
context.minimizedNameGenerator.nameBySignature(signature)
} else {
signature
}
return result.toJsName()
}
override fun getNameForMemberField(field: IrField): JsName {
require(!field.isStatic)
// TODO this looks funny. Rethink.
return JsName(field.parentAsClass.fieldData()[field]!!, false)
}
private fun IrDeclarationWithName.generateImportForDeclarationWithJsModule(jsModule: String): JsName {
val nameString = if (isJsNonModule()) {
getJsNameOrKotlinName().asString()
} else {
val parent = fqNameWhenAvailable!!.parent()
parent.child(getJsNameOrKotlinName()).asString()
}
val name = JsName(sanitizeName(nameString), true)
val nameRef = name.makeRef()
if (isEsModules) {
val importSubject = when {
this is IrClass && isObject -> JsImport.Target.All(nameRef)
else -> JsImport.Target.Default(nameRef)
}
imports[this] = JsImport(jsModule, importSubject)
nameMap[this] = name
} else {
importedModules += JsImportedModule(jsModule, name, nameRef)
}
return name
}
private fun IrDeclarationWithName.generateImportForDeclarationInFileWithJsModule(
fileJsModule: String,
jsQualifier: List<JsName>?
): JsName {
if (this in nameMap) return getName()
val declarationStableName = getJsNameOrKotlinName().identifier
if (isEsModules) {
val importedName = jsQualifier?.firstOrNull() ?: declarationStableName.toJsName(temporary = false)
val importStatement = JsImport(fileJsModule, JsImport.Element(importedName))
imports[this] = when (val qualifiedReference = jsQualifier?.makeRef()) {
null -> importStatement
else -> JsCompositeBlock(
listOf(
importStatement,
jsElementAccess(declarationStableName, qualifiedReference).putIntoVariableWitName(
declarationStableName.toJsName()
)
)
)
}
} else {
val moduleName = JsName(sanitizeName("\$module\$$fileJsModule"), true)
importedModules += JsImportedModule(fileJsModule, moduleName, null)
val qualifiedReference =
if (jsQualifier == null) moduleName.makeRef() else (listOf(moduleName) + jsQualifier).makeRef()
imports[this] =
jsElementAccess(declarationStableName, qualifiedReference).putIntoVariableWitName(declarationStableName.toJsName())
}
return getName()
}
private fun IrDeclarationWithName.generateRegularQualifiedImport(jsQualifier: List<JsName>?): JsName {
val name = getJsNameOrKotlinName().identifier
if (jsQualifier != null) {
imports[this] = jsElementAccess(name, jsQualifier.makeRef()).putIntoVariableWitName(name.toJsName())
return getName()
}
return name.toJsName(temporary = false)
}
private fun IrClass.fieldData(): Map<IrField, String> {
return context.fieldDataCache.getOrPut(this) {
val nameCnt = hashMapOf<String, Int>()
val allClasses = DFS.topologicalOrder(listOf(this)) { node ->
node.superTypes.mapNotNull {
it.safeAs<IrSimpleType>()?.classifier.safeAs<IrClassSymbol>()?.owner
}
}
val result = hashMapOf<IrField, String>()
if (minimizedMemberNames) {
allClasses.reversed().forEach {
it.declarations.forEach { declaration ->
when {
declaration is IrFunction && declaration.dispatchReceiverParameter != null -> {
val property = (declaration as? IrSimpleFunction)?.correspondingPropertySymbol?.owner
if (property?.isExported(context) == true || property?.isEffectivelyExternal() == true) {
context.minimizedNameGenerator.reserveName(property.getJsNameOrKotlinName().identifier)
}
if (declaration.hasStableJsName(context)) {
val signature = jsFunctionSignature(declaration, context)
context.minimizedNameGenerator.reserveName(signature)
}
}
declaration is IrProperty -> {
if (declaration.isExported(context)) {
context.minimizedNameGenerator.reserveName(declaration.getJsNameOrKotlinName().identifier)
}
}
}
}
}
}
allClasses.reversed().forEach {
it.declarations.forEach {
when {
it is IrField -> {
val correspondingProperty = it.correspondingPropertySymbol?.owner
val hasStableName = correspondingProperty != null &&
correspondingProperty.visibility.isPublicAPI &&
(correspondingProperty.isExported(context) || correspondingProperty.getJsName() != null) &&
correspondingProperty.isSimpleProperty
val safeName = when {
hasStableName -> (correspondingProperty ?: it).getJsNameOrKotlinName().identifier
minimizedMemberNames && !context.keeper.shouldKeep(it) -> context.minimizedNameGenerator.generateNextName()
else -> it.safeName()
}
val resultName = if (!hasStableName) {
val suffix = nameCnt.getOrDefault(safeName, 0) + 1
nameCnt[safeName] = suffix
safeName + "_$suffix"
} else safeName
result[it] = resultName
}
it is IrFunction && it.dispatchReceiverParameter != null -> {
nameCnt[jsFunctionSignature(it, context)] = 1 // avoid clashes with member functions
}
}
}
}
result
}
}
}
private fun IrField.safeName(): String {
return sanitizeName(name.asString()).let {
if (it.lastOrNull()!!.isDigit()) it + "_" else it // Avoid name clashes
}
}
private fun List<JsName>.makeRef(): JsNameRef {
var result = this[0].makeRef()
for (i in 1 until this.size) {
result = JsNameRef(this[i], result)
}
return result
}
| 182 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 9,939 | kotlin | Apache License 2.0 |
B4F-SDK-Android/src/main/java/com/batura/b4fLibrary/rest/models/Unlink.kt | Brand4Fans | 488,617,670 | false | {"Kotlin": 123340} | /**
* Third Party B4F Service
* No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
*
* OpenAPI spec version: v1
*
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package com.batura.b4fLibrary.rest.models
import com.squareup.moshi.Json
/**
*
* @param code Smarttag nfc's code
*/
data class Unlink (
/* Smarttag nfc's code */
@field:Json(name = "code")val code: kotlin.String? = null
) {
} | 0 | Kotlin | 0 | 0 | 3a531d1fe86dfefb9f14391a82fd978a619b9108 | 585 | B4F-SDK-Android | Apache License 2.0 |
src/main/kotlin/nebula/plugin/resolutionrules/gradleInterop.kt | jotel | 78,635,695 | true | {"Groovy": 117755, "Kotlin": 27631, "Shell": 1197} | package nebula.plugin.resolutionrules
import groovy.lang.Closure
import org.gradle.api.Action
inline fun <T> T.groovyClosure(crossinline call: () -> Unit) = object : Closure<Unit>(this) {
@Suppress("unused")
fun doCall() {
call()
}
}
inline fun <U> Any.action(crossinline call: U.() -> Unit) = Action<U> { call(it) }
| 0 | Groovy | 0 | 0 | 67a93773d9e6fc9f92d5b82d1b408e0bca9192a0 | 340 | gradle-resolution-rules-plugin | Apache License 2.0 |
app/src/main/kotlin/de/bahnhoefe/deutschlands/bahnhofsfotos/model/Country.kt | androidoma | 66,291,451 | false | {"Gradle Kotlin DSL": 3, "YAML": 5, "Java Properties": 2, "Shell": 1, "Text": 94, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "TOML": 1, "Proguard": 1, "JSON": 7, "Kotlin": 88, "XML": 183} | package de.bahnhoefe.deutschlands.bahnhofsfotos.model
import java.io.Serializable
import java.util.Objects
data class Country @JvmOverloads constructor(
val code: String,
val name: String,
val email: String? = null,
val timetableUrlTemplate: String? = null,
val overrideLicense: String? = null,
val providerApps: List<ProviderApp> = listOf()
) : Serializable, Comparable<Country> {
fun hasTimetableUrlTemplate(): Boolean {
return !timetableUrlTemplate.isNullOrEmpty()
}
val compatibleProviderApps: List<ProviderApp>
get() = getCompatibleProviderApps(providerApps)
override fun toString(): String {
return name
}
override fun compareTo(other: Country): Int {
return name.compareTo(other.name)
}
override fun equals(other: Any?): Boolean {
if (other === this) return true
if (other !is Country) return false
return Objects.equals(code, other.code)
}
override fun hashCode(): Int {
return code.hashCode()
}
}
fun getCountryByCode(countries: Collection<Country>, countryCode: String?) = countries
.firstOrNull { country: Country -> country.code == countryCode }
| 9 | Kotlin | 13 | 29 | 339bdb6ab7571c85e82d23bb0832acee75d89de2 | 1,203 | RSAndroidApp | MIT License |
feature-account-impl/src/main/java/io/novafoundation/nova/feature_account_impl/presentation/paritySigner/connect/finish/FinishImportParitySignerViewModel.kt | novasamatech | 415,834,480 | false | {"Kotlin": 7662683, "Java": 14723, "JavaScript": 425} | package io.novafoundation.nova.feature_account_impl.presentation.paritySigner.connect.finish
import io.novafoundation.nova.common.resources.ResourceManager
import io.novafoundation.nova.feature_account_api.domain.interfaces.AccountInteractor
import io.novafoundation.nova.feature_account_api.presenatation.account.createName.CreateWalletNameViewModel
import io.novafoundation.nova.feature_account_impl.domain.paritySigner.connect.finish.FinishImportParitySignerInteractor
import io.novafoundation.nova.feature_account_impl.presentation.AccountRouter
import io.novafoundation.nova.feature_account_impl.presentation.paritySigner.connect.ParitySignerAccountPayload
import kotlinx.coroutines.launch
class FinishImportParitySignerViewModel(
private val router: AccountRouter,
private val resourceManager: ResourceManager,
private val payload: ParitySignerAccountPayload,
private val accountInteractor: AccountInteractor,
private val interactor: FinishImportParitySignerInteractor
) : CreateWalletNameViewModel(router, resourceManager) {
override fun proceed(name: String) {
launch {
interactor.createWallet(name, payload.accountId, payload.variant)
.onSuccess { continueBasedOnCodeStatus() }
.onFailure(::showError)
}
}
private suspend fun continueBasedOnCodeStatus() {
if (accountInteractor.isCodeSet()) {
router.openMain()
} else {
router.openCreatePincode()
}
}
}
| 5 | Kotlin | 9 | 9 | 651db6927cdc6ff89448c83d451c84bda937e9fc | 1,510 | nova-wallet-android | Apache License 2.0 |
processor/src/main/kotlin/com/dbflow5/processor/definition/IndexGroupsDefinition.kt | agrosner | 24,161,015 | false | null | package com.dbflow5.processor.definition
import com.grosner.kpoet.S
import com.grosner.kpoet.`=`
import com.grosner.kpoet.field
import com.grosner.kpoet.final
import com.grosner.kpoet.public
import com.grosner.kpoet.static
import com.dbflow5.annotation.IndexGroup
import com.dbflow5.processor.definition.column.ColumnDefinition
import com.squareup.javapoet.ParameterizedTypeName
import java.util.concurrent.atomic.AtomicInteger
/**
* Description:
*/
class IndexGroupsDefinition(private val tableDefinition: TableDefinition, indexGroup: IndexGroup) {
val indexName = indexGroup.name
val indexNumber = indexGroup.number
val isUnique = indexGroup.unique
val columnDefinitionList: MutableList<ColumnDefinition> = arrayListOf()
val fieldSpec
get() = field(ParameterizedTypeName.get(com.dbflow5.processor.ClassNames.INDEX_PROPERTY, tableDefinition.elementClassName),
"index_$indexName") {
addModifiers(public, static, final)
`=` {
add("new \$T<>(${indexName.S}, $isUnique, \$T.class",
com.dbflow5.processor.ClassNames.INDEX_PROPERTY, tableDefinition.elementTypeName)
if (columnDefinitionList.isNotEmpty()) {
add(",")
}
val index = AtomicInteger(0)
columnDefinitionList.forEach { it.appendIndexInitializer(this, index) }
add(")")
}
}.build()!!
}
| 38 | null | 613 | 4,865 | e1b6211dac6ddc0aa0c1c9a76a116478ccf92b86 | 1,476 | DBFlow | MIT License |
data/traktauth/src/iosMain/kotlin/app/tivi/data/traktauth/IosAuthStore.kt | chrisbanes | 100,624,553 | false | null | // Copyright 2023, Christopher Banes and the Tivi project contributors
// SPDX-License-Identifier: Apache-2.0
package app.tivi.data.traktauth
import app.tivi.app.ApplicationInfo
import app.tivi.data.traktauth.store.AuthStore
import app.tivi.util.AppCoroutineDispatchers
import com.russhwolf.settings.ExperimentalSettingsApi
import com.russhwolf.settings.ExperimentalSettingsImplementation
import com.russhwolf.settings.KeychainSettings
import com.russhwolf.settings.set
import kotlinx.cinterop.ExperimentalForeignApi
import kotlinx.coroutines.withContext
import me.tatarka.inject.annotations.Inject
import platform.Foundation.CFBridgingRetain
import platform.Security.kSecAttrAccessible
import platform.Security.kSecAttrAccessibleAfterFirstUnlock
import platform.Security.kSecAttrService
@OptIn(
ExperimentalSettingsImplementation::class,
ExperimentalForeignApi::class,
ExperimentalSettingsApi::class,
)
@Inject
class IosAuthStore(
private val applicationInfo: ApplicationInfo,
private val dispatchers: AppCoroutineDispatchers,
) : AuthStore {
private val keyChainSettings by lazy {
KeychainSettings(
kSecAttrService to CFBridgingRetain("${applicationInfo.packageName}.auth"),
kSecAttrAccessible to kSecAttrAccessibleAfterFirstUnlock,
)
}
override suspend fun get(): AuthState? = withContext(dispatchers.io) {
val accessToken = keyChainSettings.getStringOrNull(KEY_ACCESS_TOKEN)
val refreshToken = keyChainSettings.getStringOrNull(KEY_REFRESH_TOKEN)
if (accessToken != null && refreshToken != null) {
SimpleAuthState(accessToken, refreshToken)
} else {
null
}
}
override suspend fun save(state: AuthState) = withContext(dispatchers.io) {
keyChainSettings[KEY_ACCESS_TOKEN] = state.accessToken
keyChainSettings[KEY_REFRESH_TOKEN] = state.refreshToken
}
override suspend fun clear() = withContext(dispatchers.io) {
keyChainSettings.remove(KEY_ACCESS_TOKEN)
keyChainSettings.remove(KEY_REFRESH_TOKEN)
}
}
private const val KEY_ACCESS_TOKEN = "access_token"
private const val KEY_REFRESH_TOKEN = "refresh_token"
| 23 | null | 876 | 6,626 | e261ffbded01c1439b93c550cd6e714c13bb9192 | 2,109 | tivi | Apache License 2.0 |
knee-gradle-plugin/src/main/kotlin/tasks/UnpackageCodegenSources.kt | deepmedia | 552,404,398 | false | {"Kotlin": 544280} | package tasks
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.ProjectLayout
import org.gradle.api.model.ObjectFactory
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputDirectory
import javax.inject.Inject
open class UnpackageCodegenSources @Inject constructor(objects: ObjectFactory, layout: ProjectLayout) : Copy() {
@get:InputFiles
val codegenFiles: ConfigurableFileCollection = objects.fileCollection()
@get:OutputDirectory
val outputDir: DirectoryProperty = objects.directoryProperty()
.convention(layout.buildDirectory.dir("codegen"))
init {
from(codegenFiles)
into(outputDir)
exclude { it.name == "META-INF" }
}
} | 5 | Kotlin | 2 | 76 | 033fe352320a38b882381929fecb7b1811e00ebb | 813 | Knee | Apache License 2.0 |
compiler/testData/codegen/bytecodeText/callableReference/boundFieldReferenceInInline.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // IGNORE_BACKEND_FIR: JVM_IR
// FILE: JClass.java
public class JClass {
public int field;
}
// FILE: main.kt
fun box(): String {
return if (call(10, JClass()::field) == 5) "OK" else "fail"
}
inline fun call(p: Int, s: () -> Int): Int {
return s()
}
// 1 NEW JClass
// 1 NEW | 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 290 | kotlin | Apache License 2.0 |
platform/vcs-api/src/com/intellij/openapi/vcs/ui/cloneDialog/VcsCloneDialogExtension.kt | ingokegel | 284,920,751 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.ui.cloneDialog
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.Nls
import javax.swing.Icon
/**
* Extension point that provide an ability to add integration with specific cloud repository hosting/service (e.g "GitHub", "BitBucket", etc)
*/
@ApiStatus.OverrideOnly
@JvmDefaultWithCompatibility
interface VcsCloneDialogExtension {
companion object {
val EP_NAME: ExtensionPointName<VcsCloneDialogExtension> =
ExtensionPointName.create<VcsCloneDialogExtension>("com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtension")
}
/**
* Visible name of extension (e.g. "Repository URL", "GitHub", etc)
*/
@Nls fun getName(): String
/**
* Visible icon of extension
*/
fun getIcon(): Icon
/**
* Additional status lines, which may contain some info and actions related to authorized accounts, internal errors, etc
*/
fun getAdditionalStatusLines(): List<VcsCloneDialogExtensionStatusLine> = emptyList()
/**
* Optional tooltip for extension item
*/
@Nls fun getTooltip(): String? = null
@Deprecated(message = "Implement createMainComponent(Project, ModalityState)")
fun createMainComponent(project: Project): VcsCloneDialogExtensionComponent {
throw AssertionError("Shouldn't be called, implement createMainComponent(Project, ModalityState)")
}
/**
* Builds [VcsCloneDialogExtensionComponent] that would be displayed on center of get-from-vcs dialog when extension is selected.
* Will be called lazily and once on first choosing of extension.
*/
fun createMainComponent(project: Project, modalityState: ModalityState): VcsCloneDialogExtensionComponent {
return createMainComponent(project)
}
} | 214 | null | 4829 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 2,015 | intellij-community | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/SolarPanelSun.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.SolarPanelSun: ImageVector
get() {
if (_solarPanelSun != null) {
return _solarPanelSun!!
}
_solarPanelSun = Builder(name = "SolarPanelSun", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(13.0f, 22.0f)
horizontalLineToRelative(5.0f)
verticalLineToRelative(2.0f)
lineTo(6.0f, 24.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(5.0f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(-2.283f)
lineToRelative(0.286f, -4.0f)
horizontalLineToRelative(6.031f)
lineToRelative(0.286f, 4.0f)
horizontalLineToRelative(-2.319f)
verticalLineToRelative(2.0f)
close()
moveTo(9.146f, 14.0f)
horizontalLineToRelative(5.745f)
lineToRelative(-0.286f, -4.0f)
horizontalLineToRelative(-5.174f)
lineToRelative(-0.286f, 4.0f)
close()
moveTo(16.61f, 10.0f)
lineToRelative(0.286f, 4.0f)
horizontalLineToRelative(5.636f)
lineToRelative(-0.468f, -1.768f)
curveToRelative(-0.349f, -1.314f, -1.541f, -2.232f, -2.9f, -2.232f)
horizontalLineToRelative(-2.554f)
close()
moveTo(17.324f, 20.0f)
horizontalLineToRelative(6.795f)
lineToRelative(-1.059f, -4.0f)
horizontalLineToRelative(-6.023f)
lineToRelative(0.286f, 4.0f)
close()
moveTo(7.426f, 10.0f)
horizontalLineToRelative(-2.589f)
curveToRelative(-1.359f, 0.0f, -2.552f, 0.918f, -2.9f, 2.232f)
lineToRelative(-0.468f, 1.768f)
horizontalLineToRelative(5.672f)
lineToRelative(0.286f, -4.0f)
close()
moveTo(6.998f, 16.0f)
lineTo(0.939f, 16.0f)
lineTo(-0.12f, 20.0f)
horizontalLineToRelative(6.831f)
lineToRelative(0.286f, -4.0f)
close()
moveTo(19.501f, 6.0f)
horizontalLineToRelative(-2.601f)
curveToRelative(-0.192f, -0.94f, -0.658f, -1.775f, -1.298f, -2.443f)
lineToRelative(1.662f, -2.399f)
lineTo(15.619f, 0.019f)
lineToRelative(-1.661f, 2.398f)
curveToRelative(-0.604f, -0.259f, -1.261f, -0.416f, -1.958f, -0.416f)
reflectiveCurveToRelative(-1.354f, 0.157f, -1.958f, 0.416f)
lineTo(8.398f, 0.043f)
lineToRelative(-1.645f, 1.139f)
lineToRelative(1.645f, 2.375f)
curveToRelative(-0.64f, 0.669f, -1.106f, 1.503f, -1.298f, 2.443f)
horizontalLineToRelative(-2.601f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(15.0f)
verticalLineToRelative(-2.0f)
close()
}
}
.build()
return _solarPanelSun!!
}
private var _solarPanelSun: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 4,178 | icons | MIT License |
app-data/src/main/java/me/dmba/teamworkboards/data/model/source/remote/model/ProjectsResponse.kt | dmba | 141,046,741 | false | {"Kotlin": 86040} | package me.dmba.teamworkboards.data.model.source.remote.model
import com.google.gson.annotations.SerializedName
/**
* Created by dmba on 7/17/18.
*/
data class ProjectsResponse(
@SerializedName("STATUS") val status: String,
@SerializedName("projects") val projects: List<Project>
)
data class Project(
@SerializedName("replyByEmailEnabled") val replyByEmailEnabled: Boolean,
@SerializedName("starred") val starred: Boolean,
@SerializedName("show-announcement") val showAnnouncement: Boolean,
@SerializedName("harvest-timers-enabled") val harvestTimersEnabled: Boolean,
@SerializedName("status") val status: String,
@SerializedName("subStatus") val subStatus: String,
@SerializedName("defaultPrivacy") val defaultPrivacy: String,
@SerializedName("created-on") val createdOn: String,
@SerializedName("category") val category: Category,
@SerializedName("filesAutoNewVersion") val filesAutoNewVersion: Boolean,
@SerializedName("overview-start-page") val overviewStartPage: String,
@SerializedName("tags") val tags: List<Any>,
@SerializedName("logo") val logo: String,
@SerializedName("startDate") val startDate: String,
@SerializedName("id") val id: String,
@SerializedName("last-changed-on") val lastChangedOn: String,
@SerializedName("endDate") val endDate: String,
@SerializedName("defaults") val defaults: Defaults,
@SerializedName("company") val company: Company,
@SerializedName("tasks-start-page") val tasksStartPage: String,
@SerializedName("name") val name: String,
@SerializedName("privacyEnabled") val privacyEnabled: Boolean,
@SerializedName("description") val description: String,
@SerializedName("announcement") val announcement: String,
@SerializedName("isProjectAdmin") val isProjectAdmin: Boolean,
@SerializedName("start-page") val startPage: String,
@SerializedName("notifyeveryone") val notifyeveryone: Boolean,
@SerializedName("announcementHTML") val announcementHTML: String
)
data class Category(
@SerializedName("name") val name: String,
@SerializedName("id") val id: String,
@SerializedName("color") val color: String
)
data class Xero(
@SerializedName("countrycode") val countrycode: String,
@SerializedName("enabled") val enabled: Boolean,
@SerializedName("connected") val connected: String,
@SerializedName("organisation") val organisation: String,
@SerializedName("basecurrency") val basecurrency: String
)
data class Defaults(
@SerializedName("privacy") val privacy: String
)
| 3 | Kotlin | 0 | 0 | a3d31225ebad80ae15158ca18ca0780b81c5726f | 2,567 | teamwork-boards | Apache License 2.0 |
app/src/main/java/com/coofee/dep/demo/MainActivity.kt | coofee | 217,515,717 | false | null | package com.coofee.dep.demo
import android.os.AsyncTask
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.coofee.dep.TaskManager
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
invokeConditionPermissionLocation.setOnClickListener {
AppServiceManager.invokeCondition(CONDITION_PERMISSION_LOCATION)
}
invokeConditionLaunchAd.setOnClickListener {
AppServiceManager.invokeCondition(CONDITION_LAUNCH_AD_SHOW)
}
invokeConditionLaunchShow.setOnClickListener {
AppServiceManager.invokeCondition(CONDITION_LAUNCH_SHOW)
}
invokeConditionDatabase.setOnClickListener {
AppServiceManager.invokeCondition(CONDITION_DATABASE)
}
AsyncTask.THREAD_POOL_EXECUTOR.execute {
val task8Service = AppServiceManager.getService<Task8>("task_8")
val result = task8Service?.methodTask8()
println("Dep.MainActivity; get task_8 service ${Thread.currentThread()} task8Service?.methodTask8()=$result")
}
val task8Service = AppServiceManager.getService<Task8>("task_8", TaskManager.MODE_ASYNC)
println("Dep.MainActivity; get task_8 service from ${Thread.currentThread()}; task8Service=$task8Service")
}
}
| 1 | null | 1 | 1 | a791455c34734ece5a3ac1beb810ad3cda2e4d2b | 1,493 | Dep | Apache License 2.0 |
src/main/kotlin/com/github/gabrielshanahan/phpkt/expressions/assignables/Assignable.kt | gabrielshanahan | 226,652,392 | false | null | package com.github.gabrielshanahan.phpkt.expressions.assignables
import com.github.gabrielshanahan.phpkt.Expression
import java.util.*
/**
* The base class for PHP assignables with the name [name].
*
* There are basically two types of assignables - [simple variables][SimpleVariable] (e.g. $a) or
* [variables which are indexed as an array][IndexedVariable] (e.g. `$a["b"][]`). It would be natural to model the
* indexed version as deriving from the simple version, however we run into problems when defining
* [com.github.gabrielshanahan.phpkt.statements.constructs.looping.ForEach], where it is required that the $key and
* $value are only simple variables. For this reason, we have to model the situation with two classes that inherit from
* a common superclass - [Assignable].
*
* Because PHP is messed up, any byte sequence constitutes a valid PHP name using the ${} syntax. We consider this to
* be black magic and do not support it, instead permitting only names consisting of alphanumeric characters or
* underscores, with the additional condition that the first character cannot be a number.
*
* When an invalid name is passed, an exception is thrown.
*
* @param name The name of the variable.
*/
abstract class Assignable(private val name: String) : Expression() {
/**
* Performs checks on the variable name. The first letter must be either a letter or an underscore, the rest must be
* alphanumeric or an underscore.
*
* TODO: Refactor into "name" component that would be used by function as well
*/
init {
if (!name.first().isLetter() && name.first() != '_') {
throw InvalidVariableName("Variable names must start with a letter or underscore, but got $name.")
}
if (!name.all { it.isLetterOrDigit() || it == '_' }) {
throw InvalidVariableName("Variable names can only contain letters, digits, or underscores, but got $name.")
}
}
override fun toPhpStr(): String = "\$$name"
override fun equals(other: Any?): Boolean = other is Assignable && other.name == name
override fun hashCode(): Int = Objects.hash(name)
/**
* Thrown when an invalid variable name is passed to Variable constructor.
*
* @param msg The exception message.
*/
class InvalidVariableName(msg: String) : Throwable(msg)
}
| 0 | Kotlin | 0 | 0 | 132f9ef6a517646f1ea1272af8a3066c4c147785 | 2,356 | PhpKt | MIT License |
src/main/kotlin/no/nav/api/sporreundersokelse/SpørreundersøkelseDTO.kt | navikt | 644,356,194 | false | {"Kotlin": 131314, "Dockerfile": 214} | package no.nav.api.sporreundersokelse
import kotlinx.serialization.Serializable
import java.util.UUID
import no.nav.domene.sporreundersokelse.SpørsmålOgSvaralternativer
import no.nav.util.UUIDSerializer
@Serializable
data class SpørsmålOgSvaralternativerDTO (
@Serializable(with = UUIDSerializer::class)
val id: UUID,
val spørsmål: String,
val svaralternativer: List<SvaralternativDTO>
) {
companion object {
fun toDto(spørsmålOgSvaralternativer: List<SpørsmålOgSvaralternativer>) =
spørsmålOgSvaralternativer.map { it.toDto() }
}
}
@Serializable
data class SvaralternativDTO (
@Serializable(with = UUIDSerializer::class)
val id: UUID,
val tekst: String
)
| 0 | Kotlin | 0 | 0 | a93704c4741562406ed5e429c77b2bd6a7c8a316 | 715 | fia-arbeidsgiver | MIT License |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/logs/destinations/LambdaDestination.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 149148378} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.logs.destinations
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.services.logs.ILogGroup
import io.cloudshiftdev.awscdk.services.logs.ILogSubscriptionDestination
import io.cloudshiftdev.awscdk.services.logs.LogSubscriptionDestinationConfig
import io.cloudshiftdev.constructs.Construct
import kotlin.Boolean
import kotlin.Unit
import io.cloudshiftdev.awscdk.services.lambda.IFunction as CloudshiftdevAwscdkServicesLambdaIFunction
import software.amazon.awscdk.services.lambda.IFunction as AmazonAwscdkServicesLambdaIFunction
/**
* Use a Lambda Function as the destination for a log subscription.
*
* Example:
*
* ```
* import io.cloudshiftdev.awscdk.services.logs.destinations.*;
* Function fn;
* LogGroup logGroup;
* SubscriptionFilter.Builder.create(this, "Subscription")
* .logGroup(logGroup)
* .destination(new LambdaDestination(fn))
* .filterPattern(FilterPattern.allTerms("ERROR", "MainThread"))
* .filterName("ErrorInMainThread")
* .build();
* ```
*/
public open class LambdaDestination(
cdkObject: software.amazon.awscdk.services.logs.destinations.LambdaDestination,
) : CdkObject(cdkObject), ILogSubscriptionDestination {
public constructor(fn: CloudshiftdevAwscdkServicesLambdaIFunction) :
this(software.amazon.awscdk.services.logs.destinations.LambdaDestination(fn.let(CloudshiftdevAwscdkServicesLambdaIFunction::unwrap))
)
public constructor(fn: CloudshiftdevAwscdkServicesLambdaIFunction,
options: LambdaDestinationOptions) :
this(software.amazon.awscdk.services.logs.destinations.LambdaDestination(fn.let(CloudshiftdevAwscdkServicesLambdaIFunction::unwrap),
options.let(LambdaDestinationOptions::unwrap))
)
public constructor(fn: CloudshiftdevAwscdkServicesLambdaIFunction,
options: LambdaDestinationOptions.Builder.() -> Unit) : this(fn,
LambdaDestinationOptions(options)
)
/**
* Return the properties required to send subscription events to this destination.
*
* If necessary, the destination can use the properties of the SubscriptionFilter
* object itself to configure its permissions to allow the subscription to write
* to it.
*
* The destination may reconfigure its own permissions in response to this
* function call.
*
* @param scope
* @param logGroup
*/
public override fun bind(scope: Construct, logGroup: ILogGroup): LogSubscriptionDestinationConfig
= unwrap(this).bind(scope.let(Construct::unwrap),
logGroup.let(ILogGroup::unwrap)).let(LogSubscriptionDestinationConfig::wrap)
/**
* A fluent builder for [io.cloudshiftdev.awscdk.services.logs.destinations.LambdaDestination].
*/
@CdkDslMarker
public interface Builder {
/**
* Whether or not to add Lambda Permissions.
*
* Default: true
*
* @param addPermissions Whether or not to add Lambda Permissions.
*/
public fun addPermissions(addPermissions: Boolean)
}
private class BuilderImpl(
fn: AmazonAwscdkServicesLambdaIFunction,
) : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.logs.destinations.LambdaDestination.Builder =
software.amazon.awscdk.services.logs.destinations.LambdaDestination.Builder.create(fn)
/**
* Whether or not to add Lambda Permissions.
*
* Default: true
*
* @param addPermissions Whether or not to add Lambda Permissions.
*/
override fun addPermissions(addPermissions: Boolean) {
cdkBuilder.addPermissions(addPermissions)
}
public fun build(): software.amazon.awscdk.services.logs.destinations.LambdaDestination =
cdkBuilder.build()
}
public companion object {
public operator fun invoke(fn: CloudshiftdevAwscdkServicesLambdaIFunction,
block: Builder.() -> Unit = {}): LambdaDestination {
val builderImpl = BuilderImpl(CloudshiftdevAwscdkServicesLambdaIFunction.unwrap(fn))
return LambdaDestination(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.logs.destinations.LambdaDestination):
LambdaDestination = LambdaDestination(cdkObject)
internal fun unwrap(wrapped: LambdaDestination):
software.amazon.awscdk.services.logs.destinations.LambdaDestination = wrapped.cdkObject as
software.amazon.awscdk.services.logs.destinations.LambdaDestination
}
}
| 1 | Kotlin | 0 | 4 | ddf2bfd2275b50bb86a667c4298dd92f59d7e342 | 4,662 | kotlin-cdk-wrapper | Apache License 2.0 |
shared/src/main/kotlin/me/rasztabiga/thesis/shared/adapter/in/rest/api/WithdrawBalanceRequest.kt | BartlomiejRasztabiga | 604,846,079 | false | {"Kotlin": 368953, "TypeScript": 109077, "Python": 10389, "Dockerfile": 1695, "Shell": 662, "JavaScript": 618, "CSS": 59} | package me.rasztabiga.thesis.shared.adapter.`in`.rest.api
import java.math.BigDecimal
data class WithdrawBalanceRequest(
val amount: BigDecimal,
val targetBankAccount: String
)
| 31 | Kotlin | 0 | 2 | c8c84b606788fd5100bd816c0ca1e033d8ab00c2 | 187 | thesis | MIT License |
app/src/main/java/com/ayni/heroesatwork/models/Game.kt | aynigames | 107,723,388 | false | null | package com.ayni.heroesatwork.models
import java.util.*
class Game() {
private var gameId: Int = 0
var organizationId: Int = 0
var gameTemplateId: Int = 0
lateinit var name: String
private lateinit var status: String
var gameMasterId: Int = 0
var gameVisibility: Int = 0
lateinit var createdOn: Date
lateinit var startedOn: Date
lateinit var endedOn: Date
private lateinit var players: List<Player>
private var settings = mutableListOf<Setting>()
lateinit var leaderBoard: LeaderBoard
constructor(gameId: Int, name: String, status: String, players: List<Player>, settings: MutableList<Setting>, leaderBoard: LeaderBoard): this() {
this.gameId = gameId
this.name = name
this.status = status
this.players = players
this.settings = settings
this.leaderBoard = leaderBoard
}
fun getSetting(key: String): Setting? {
return settings.find { setting -> setting.key == key }
}
fun getPlayer(memberId: Int): Player? {
return leaderBoard.players.find { player -> player.memberId == memberId }
}
fun getTopPlayer(): Player? {
return leaderBoard.players.maxBy { player -> player.playerScore }
}
fun putSetting(key: String, value: String) {
var setting = settings.find { s -> s.key == key }
if (setting == null) {
settings.add(Setting(key, value))
}
else {
setting.value = value
}
}
fun getMaxScore() : Float? {
return leaderBoard.players.map { p -> p.playerScore }.max()
}
} | 0 | Kotlin | 0 | 0 | fe6408a16212403ff837096ed4c8be948efdae19 | 1,615 | heroes-at-work-android | MIT License |
buildSrc/src/main/kotlin/DependencyGradle.kt | frogobox | 463,901,878 | false | {"Kotlin": 168173, "Java": 77640} | /*
* Created by faisalamir on 19/09/21
* FrogoRecyclerView
* -----------------------------------------
* Name : Muhammad Faisal Amir
* E-mail : [email protected]
* Github : github.com/amirisback
* -----------------------------------------
* Copyright (C) 2021 FrogoBox Inc.
* All rights reserved
*
*/
object DependencyGradle {
// dependencies version
const val KOTLIN_VERSION = Version.JetBrains.kotlin
const val COMPOSE_MULTIPLATFORM_VERSION = Version.Androidx.composeMultiPlatform
const val COMPOSE_VERSION = Version.Androidx.composeCompiler
const val FROGO_PATH_CORE_UI = ":frogocoreui"
const val FROGO_PATH_UI = ":frogoui"
const val FrogoRecyclerView = "com.github.amirisback:frogo-recycler-view:4.3.3"
} | 0 | Kotlin | 3 | 22 | ca169e252ea5f9ec03333aaa35541d691e244e13 | 765 | frogo-ui | Apache License 2.0 |
app/src/main/java/me/wsj/fengyun/view/TempChart.kt | wsjAliYun | 283,814,909 | false | null | package me.wsj.fengyun.view
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.util.Pair
import android.view.View
import me.wsj.fengyun.R
import me.wsj.fengyun.bean.Daily
import per.wsj.commonlib.utils.DisplayUtil
/**
* create by shiju.wang
*/
class TempChart @JvmOverloads constructor(
context: Context?,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
private var topBottom = 0
private var minTemp = 0
private var maxTemp = 0
private var lowTemp = 0
private var highTemp = 0
private var mHalfWidth = 0f
private var mHeight = 0f
private var mLowPaint: Paint
private var mHighPaint: Paint
private var mTextPaint: Paint
private var textHeight = 0
private var lowText = ""
private var highText = ""
private var lowTextWidth = 0
private var highTextWidth = 0
private var usableHeight = 0
private var tempDiff = 0
private var density = 0f
private var pntRadius = 0f
// 前一天数�?
private var mPrev: Daily? = null
// 后一天数�?
private var mNext: Daily? = null
init {
topBottom = DisplayUtil.dp2px(8f)
mTextPaint = Paint(Paint.ANTI_ALIAS_FLAG)
mTextPaint.textSize = DisplayUtil.sp2px(context, 12f).toFloat()
mTextPaint.color = resources.getColor(R.color.color_666)
textHeight = (mTextPaint.fontMetrics.bottom - mTextPaint.fontMetrics.top).toInt()
val lineWidth = DisplayUtil.dp2px(2f)
mLowPaint = Paint(Paint.ANTI_ALIAS_FLAG)
mLowPaint.strokeWidth = lineWidth.toFloat()
// 设置线帽,方式折线陡峭时线中间出现裂�?
mLowPaint.strokeCap = Paint.Cap.SQUARE
mLowPaint.color = Color.parseColor("#00A368")
mHighPaint = Paint(Paint.ANTI_ALIAS_FLAG)
mHighPaint.strokeWidth = lineWidth.toFloat()
mHighPaint.strokeCap = Paint.Cap.SQUARE
mHighPaint.color = Color.parseColor("#FF7200")
pntRadius = DisplayUtil.dp2px(3f).toFloat()
}
fun setData(minTemp: Int, maxTemp: Int, prev: Daily?, current: Daily, next: Daily?) {
// LogUtil.e("min: " + minTemp + " max:" + maxTemp + " prev:" + prev + " curr: " + current + " next: " + next);
this.minTemp = minTemp
this.maxTemp = maxTemp
lowTemp = current.tempMin.toInt()
highTemp = current.tempMax.toInt()
mPrev = prev
mNext = next
lowText = "$lowTemp°C"
highText = "$highTemp°C"
lowTextWidth = mTextPaint.measureText(lowText).toInt()
highTextWidth = mTextPaint.measureText(highText).toInt()
tempDiff = maxTemp - minTemp
if (usableHeight != 0) {
density = usableHeight / tempDiff.toFloat()
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
mHalfWidth = measuredWidth / 2f
mHeight = measuredHeight.toFloat()
usableHeight = (mHeight - topBottom * 2 - textHeight * 2).toInt()
density = usableHeight / tempDiff.toFloat()
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
canvas.translate(mHalfWidth, 0f)
val topY = ((maxTemp - highTemp) * density + topBottom + textHeight).toInt()
val bottomY = ((maxTemp - lowTemp) * density + topBottom + textHeight).toInt()
canvas.drawCircle(0f, topY.toFloat(), pntRadius, mHighPaint)
canvas.drawCircle(0f, bottomY.toFloat(), pntRadius, mLowPaint)
canvas.drawText(
highText,
(-lowTextWidth / 2).toFloat(),
topY - mTextPaint.fontMetrics.bottom * 2,
mTextPaint
)
canvas.drawText(
lowText,
(-lowTextWidth / 2).toFloat(),
(bottomY + textHeight).toFloat(),
mTextPaint
)
// 绘制当前点给前一天数据的连线
if (mPrev != null) {
val prev = getEnds(mPrev!!)
canvas.drawLine(-mHalfWidth, (prev.first + topY) / 2f, 0f, topY.toFloat(), mHighPaint)
canvas.drawLine(
-mHalfWidth,
(prev.second + bottomY) / 2f,
0f,
bottomY.toFloat(),
mLowPaint
)
}
// 绘制当前点给后一天数据的连线
if (mNext != null) {
val next = getEnds(mNext!!)
canvas.drawLine(0f, topY.toFloat(), mHalfWidth, (next.first + topY) / 2f, mHighPaint)
canvas.drawLine(
0f,
bottomY.toFloat(),
mHalfWidth,
(next.second + bottomY) / 2f,
mLowPaint
)
}
}
private fun getEnds(daily: Daily): Pair<Int, Int> {
val topY = ((maxTemp - daily.tempMax.toInt()) * density + topBottom + textHeight).toInt()
val bottomY = ((maxTemp - daily.tempMin.toInt()) * density + topBottom + textHeight).toInt()
return Pair(topY, bottomY)
}
} | 3 | Java | 74 | 514 | da4cba77a13cf10878c388bc67d96f9bc8a4230d | 5,063 | kms | Apache License 2.0 |
plugins/source-sections/source-sections-compiler/src/org/jetbrains/kotlin/sourceSections/FilteredSectionsVirtualFile.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.sourceSections
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileSystem
import com.intellij.testFramework.LightVirtualFile
import org.jetbrains.kotlin.lexer.KotlinLexer
import org.jetbrains.kotlin.lexer.KtTokens
import java.io.ByteArrayInputStream
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.Charset
class FilteredSectionsVirtualFile(val delegate: VirtualFile, val sectionIds: Collection<String>) : VirtualFile() {
override fun refresh(asynchronous: Boolean, recursive: Boolean, postRunnable: Runnable?) {
delegate.refresh(asynchronous, recursive, postRunnable)
}
override fun getLength(): Long = delegate.length
override fun getFileSystem(): VirtualFileSystem = delegate.fileSystem
override fun getPath(): String = delegate.path
override fun isDirectory(): Boolean = delegate.isDirectory
override fun getTimeStamp(): Long = delegate.timeStamp
override fun getName(): String = delegate.name
override fun contentsToByteArray(): ByteArray = filterByteContents(sectionIds, delegate.contentsToByteArray(), delegate.charset)
override fun getInputStream(): InputStream = ByteArrayInputStream(contentsToByteArray())
override fun isValid(): Boolean =delegate.isValid
override fun getParent(): VirtualFile = delegate.parent
override fun getChildren(): Array<VirtualFile> = delegate.children
override fun isWritable(): Boolean = delegate.isWritable
override fun getOutputStream(requestor: Any?, newModificationStamp: Long, newTimeStamp: Long): OutputStream =
delegate.getOutputStream(requestor, newModificationStamp, newTimeStamp)
}
class FilteredSectionsLightVirtualFile(val delegate: LightVirtualFile, val sectionIds: Collection<String>) : LightVirtualFile(delegate.name, delegate.fileType, delegate.content, delegate.charset, delegate.modificationStamp) {
override fun getContent(): CharSequence = filterStringBuilderContents(StringBuilder(delegate.content), sectionIds)
override fun contentsToByteArray(): ByteArray = filterByteContents(sectionIds, delegate.contentsToByteArray(), delegate.charset)
}
private fun filterByteContents(sectionIds: Collection<String>, bytes: ByteArray, charset: Charset): ByteArray {
val content = StringBuilder(charset.decode(ByteBuffer.wrap(bytes)))
filterStringBuilderContents(content, sectionIds)
val buffer = charset.encode(CharBuffer.wrap(content))
return if (buffer.limit() == buffer.capacity()) buffer.array()
else {
val res = ByteArray(buffer.limit())
buffer.get(res)
res
}
}
private fun filterStringBuilderContents(content: StringBuilder, sectionIds: Collection<String>): StringBuilder {
var curPos = 0
val sectionsIter = FilteredSectionsTokensRangeIterator(content, sectionIds)
for (range in sectionsIter) {
for (i in curPos..range.start - 1) {
if (content[i] != '\n') {
content.setCharAt(i, ' ')
}
}
curPos = range.end
}
for (i in curPos..content.length - 1) {
if (content[i] != '\n') {
content.setCharAt(i, ' ')
}
}
return content
}
private class TokenRange(val start: Int, val end: Int)
private class FilteredSectionsTokensRangeIterator(script: CharSequence, val sectionIds: Collection<String>) : Iterator<TokenRange> {
private val lexer = KotlinLexer().apply {
start(script)
}
private var currentRange: TokenRange? = advanceToNextFilteredSection()
fun advanceToNextFilteredSection(): TokenRange? {
fun KotlinLexer.skipWhiteSpaceAndComments() {
while (tokenType in KtTokens.WHITE_SPACE_OR_COMMENT_BIT_SET) {
advance()
}
}
var depth = 0
var sectionStartPos = 0
var inside = false
with(lexer) {
loop@ while (tokenType != null) {
if (!inside && depth == 0 && tokenType == KtTokens.IDENTIFIER && tokenText in sectionIds) {
sectionStartPos = currentPosition.offset
advance()
skipWhiteSpaceAndComments()
inside = (tokenType == KtTokens.LBRACE)
}
when (tokenType) {
KtTokens.LBRACE -> depth += 1
KtTokens.RBRACE -> depth -= 1
}
if (inside && depth == 0) {
advance()
break@loop
}
advance()
}
}
return if (lexer.tokenType == null && !inside) null
else TokenRange(sectionStartPos, lexer.currentPosition.offset)
}
override fun hasNext(): Boolean = currentRange != null
override fun next(): TokenRange {
val ret = currentRange
currentRange = advanceToNextFilteredSection()
return ret!!
}
}
| 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 5,641 | kotlin | Apache License 2.0 |
src/main/kotlin/com/ecwid/apiclient/v3/impl/CouponsApiClientImpl.kt | Ecwid | 160,232,759 | false | null | package com.ecwid.apiclient.v3.impl
import com.ecwid.apiclient.v3.ApiClientHelper
import com.ecwid.apiclient.v3.CouponsApiClient
import com.ecwid.apiclient.v3.dto.coupon.request.*
import com.ecwid.apiclient.v3.dto.coupon.result.*
import com.ecwid.apiclient.v3.responsefields.AS_SEQUENCE_SEARCH_RESULT_REQUIRED_FIELDS
internal data class CouponsApiClientImpl(
private val apiClientHelper: ApiClientHelper
) : CouponsApiClient {
override fun searchCoupons(request: CouponSearchRequest) =
apiClientHelper.makeObjectResultRequest<CouponSearchResult>(request)
override fun searchCouponsAsSequence(request: CouponSearchRequest) = sequence {
var offsetRequest = request.copy(
responseFields = request.responseFields + AS_SEQUENCE_SEARCH_RESULT_REQUIRED_FIELDS
)
do {
val searchResult = searchCoupons(offsetRequest)
yieldAll(searchResult.items)
offsetRequest = offsetRequest.copy(offset = offsetRequest.offset + searchResult.count)
} while (searchResult.count >= searchResult.limit)
}
override fun getCouponDetails(request: CouponDetailsRequest) =
apiClientHelper.makeObjectResultRequest<FetchedCoupon>(request)
override fun createCoupon(request: CouponCreateRequest) =
apiClientHelper.makeObjectResultRequest<CouponCreateResult>(request)
override fun updateCoupon(request: CouponUpdateRequest) =
apiClientHelper.makeObjectResultRequest<CouponUpdateResult>(request)
override fun deleteCoupon(request: CouponDeleteRequest) =
apiClientHelper.makeObjectResultRequest<CouponDeleteResult>(request)
}
| 6 | null | 8 | 9 | d1a470002ba7bee6f2edc25d0038aeb085c91352 | 1,532 | ecwid-java-api-client | Apache License 2.0 |
components/bridge/impl/src/main/java/com/flipperdevices/bridge/impl/manager/delegates/FlipperConnectionInformationApiImpl.kt | Flipper-Zero | 288,258,832 | false | null | package com.flipperdevices.bridge.impl.manager.delegates
import com.flipperdevices.bridge.api.manager.delegates.FlipperConnectionInformationApi
import com.flipperdevices.bridge.impl.manager.UnsafeBleManager
import kotlinx.coroutines.flow.StateFlow
import no.nordicsemi.android.ble.ktx.state.ConnectionState
import no.nordicsemi.android.ble.ktx.stateAsFlow
class FlipperConnectionInformationApiImpl(
private val bleManager: UnsafeBleManager
) : FlipperConnectionInformationApi {
override fun isDeviceConnected(): Boolean {
return bleManager.isConnected
}
override fun getConnectionStateFlow(): StateFlow<ConnectionState> {
return bleManager.stateAsFlow()
}
override fun getConnectedDeviceName(): String? {
return bleManager.bluetoothDevice?.name
}
}
| 3 | null | 28 | 254 | 5e33771c3e317c9f826ccd0a6352d9c131fbccca | 805 | Flipper-Android-App | MIT License |
secdra-data/src/main/kotlin/com/junjie/secdradata/database/collect/dao/PixivPictureDAO.kt | fuzeongit | 154,359,683 | false | null | package com.junjie.secdradata.database.collect.dao
import com.junjie.secdradata.constant.TransferState
import com.junjie.secdradata.database.collect.entity.PixivPicture
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import java.util.*
@Repository
interface PixivPictureDAO : JpaRepository<PixivPicture, String> {
fun findAllByPixivId(pixivId: String): List<PixivPicture>
fun findAllByState(state: TransferState): List<PixivPicture>
fun findOneByPictureId(pictureId: String): Optional<PixivPicture>
} | 1 | Kotlin | 4 | 11 | f75c32e5fb834d456a3182f71aee08029a1629d3 | 578 | secdra | MIT License |
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/types/qualifiers/UsualClassTypeQualifierBuilder.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.fir.types.qualifiers
import org.jetbrains.kotlin.analysis.api.fir.KtSymbolByFirBuilder
import org.jetbrains.kotlin.analysis.api.types.KtClassTypeQualifier
import org.jetbrains.kotlin.analysis.low.level.api.fir.api.tryCollectDesignation
import org.jetbrains.kotlin.analysis.low.level.api.fir.util.errorWithFirSpecificEntries
import org.jetbrains.kotlin.fir.utils.exceptions.withFirEntry
import org.jetbrains.kotlin.utils.exceptions.checkWithAttachment
import org.jetbrains.kotlin.fir.containingClassForLocal
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.declarations.utils.isInner
import org.jetbrains.kotlin.fir.declarations.utils.isLocal
import org.jetbrains.kotlin.fir.renderWithType
import org.jetbrains.kotlin.fir.resolve.toFirRegularClass
import org.jetbrains.kotlin.fir.resolve.toSymbol
import org.jetbrains.kotlin.fir.symbols.impl.FirRegularClassSymbol
import org.jetbrains.kotlin.fir.symbols.impl.LookupTagInternals
import org.jetbrains.kotlin.fir.types.impl.ConeClassLikeTypeImpl
import org.jetbrains.kotlin.utils.exceptions.errorWithAttachment
import org.jetbrains.kotlin.utils.exceptions.withPsiEntry
internal object UsualClassTypeQualifierBuilder {
fun buildQualifiers(
coneType: ConeClassLikeTypeImpl,
builder: KtSymbolByFirBuilder
): List<KtClassTypeQualifier.KtResolvedClassTypeQualifier> {
val classSymbolToRender = coneType.lookupTag.toSymbol(builder.rootSession)
?: errorWithFirSpecificEntries("ConeClassLikeTypeImpl is not resolved to symbol for on-error type", coneType = coneType) {
withEntry("useSiteSession", builder.rootSession) { it.toString() }
}
if (classSymbolToRender !is FirRegularClassSymbol) {
return listOf(
KtClassTypeQualifier.KtResolvedClassTypeQualifier(
builder.classifierBuilder.buildClassifierSymbol(classSymbolToRender),
coneType.typeArguments.map { builder.typeBuilder.buildTypeProjection(it) },
builder.token
)
)
}
val designation = classSymbolToRender.fir.let {
val nonLocalDesignation = it.tryCollectDesignation()
nonLocalDesignation?.toSequence(includeTarget = true)?.toList()
?: collectDesignationPathForLocal(it)
}
var typeParametersLeft = coneType.typeArguments.size
fun needToRenderTypeParameters(index: Int): Boolean {
if (typeParametersLeft <= 0) return false
return index == designation.lastIndex ||
(designation[index] as? FirRegularClass)?.isInner == true ||
(designation[index + 1] as? FirRegularClass)?.isInner == true
}
val result = mutableListOf<KtClassTypeQualifier.KtResolvedClassTypeQualifier>()
designation.forEachIndexed { index, currentClass ->
check(currentClass is FirRegularClass)
val typeParameters = if (needToRenderTypeParameters(index)) {
val typeParametersCount = currentClass.typeParameters.count { it is FirTypeParameter }
val begin = typeParametersLeft - typeParametersCount
val end = typeParametersLeft
check(begin >= 0)
typeParametersLeft -= typeParametersCount
coneType.typeArguments.slice(begin until end).map { builder.typeBuilder.buildTypeProjection(it) }
} else emptyList()
result += KtClassTypeQualifier.KtResolvedClassTypeQualifier(
builder.classifierBuilder.buildClassifierSymbol(currentClass.symbol),
typeParameters,
builder.token
)
}
return result
}
private fun FirRegularClass.collectForLocal(): List<FirClassLikeDeclaration> {
require(isLocal)
var containingClassLookUp = containingClassForLocal()
val designation = mutableListOf<FirClassLikeDeclaration>(this)
@OptIn(LookupTagInternals::class)
while (containingClassLookUp != null && containingClassLookUp.classId.isLocal) {
val currentClass = containingClassLookUp.toFirRegularClass(moduleData.session) ?: break
designation.add(currentClass)
containingClassLookUp = currentClass.containingClassForLocal()
}
return designation.asReversed()
}
private fun collectDesignationPathForLocal(declaration: FirClassLikeDeclaration): List<FirDeclaration> {
checkWithAttachment(
declaration.isLocal,
message = { "${declaration::class} is not local" }
) {
withFirEntry("firDeclaration", declaration)
}
return when (declaration) {
is FirAnonymousObject -> listOf(declaration)
is FirRegularClass -> declaration.collectForLocal()
is FirTypeAlias -> listOf(declaration) // TODO: handle type aliases
else -> errorWithAttachment("Invalid declaration ${declaration::class}") {
withFirEntry("declaration", declaration)
}
}
}
} | 182 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 5,392 | kotlin | Apache License 2.0 |
src/main/kotlin/com/security/jwt/api/domain/Role.kt | frankdaza | 263,793,361 | false | null | package com.security.jwt.api.domain
import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id
import javax.persistence.Column
import javax.persistence.OneToMany
@Entity
data class Role(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long,
@Column(unique = true)
val name: String,
@OneToMany
val accountRole: List<AccountRole>
)
| 0 | Kotlin | 0 | 0 | 64cac13e003fd8b34f88c39a56b16a9a66b18871 | 457 | jwt-security-spring-api | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/hazarbelge/themoviedb/app/TheMovieDBApp.kt | hazarbelge | 302,702,214 | false | {"Kotlin": 76299} | package com.hazarbelge.themoviedb.app
import android.app.Application
import androidx.appcompat.app.AppCompatDelegate
import com.hazarbelge.themoviedb.ui.main.dependency_injection.mainModule
import com.hazarbelge.themoviedb.ui.launcher.dependency_injection.launcherModule
import com.hazarbelge.themoviedb.network.dependency_injection.networkModule
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
import org.koin.core.logger.Level
class TheMovieDBApp : Application() {
override fun onCreate() {
super.onCreate()
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
startKoin {
androidContext(this@TheMovieDBApp)
androidLogger(Level.ERROR)
modules(networkModule + launcherModule + mainModule)
}
}
} | 0 | Kotlin | 0 | 3 | 065a431b8f1c807d5a8a57521e670746d7e856e8 | 880 | kotlin_the_moviedb | MIT License |
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/food/BreadFill.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.remix.remix.food
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.FoodGroup
public val FoodGroup.BreadFill: ImageVector
get() {
if (_breadFill != null) {
return _breadFill!!
}
_breadFill = Builder(name = "BreadFill", 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(1.0f, 7.0f)
curveTo(1.0f, 4.791f, 2.791f, 3.0f, 5.0f, 3.0f)
horizontalLineTo(7.0f)
curveTo(4.791f, 3.0f, 3.0f, 4.791f, 3.0f, 7.0f)
curveTo(3.0f, 8.482f, 3.805f, 9.773f, 5.0f, 10.465f)
verticalLineTo(19.0f)
curveTo(5.0f, 20.657f, 6.343f, 22.0f, 8.0f, 22.0f)
horizontalLineTo(6.0f)
curveTo(4.343f, 22.0f, 3.0f, 20.657f, 3.0f, 19.0f)
verticalLineTo(10.465f)
curveTo(1.805f, 9.773f, 1.0f, 8.482f, 1.0f, 7.0f)
close()
moveTo(8.0f, 22.0f)
verticalLineTo(20.0f)
curveTo(7.448f, 20.0f, 7.0f, 19.552f, 7.0f, 19.0f)
verticalLineTo(9.122f)
lineTo(6.333f, 8.886f)
curveTo(5.555f, 8.611f, 5.0f, 7.869f, 5.0f, 7.0f)
curveTo(5.0f, 5.895f, 5.895f, 5.0f, 7.0f, 5.0f)
verticalLineTo(3.0f)
horizontalLineTo(19.0f)
curveTo(21.209f, 3.0f, 23.0f, 4.791f, 23.0f, 7.0f)
curveTo(23.0f, 8.482f, 22.195f, 9.773f, 21.0f, 10.465f)
verticalLineTo(19.0f)
curveTo(21.0f, 20.657f, 19.657f, 22.0f, 18.0f, 22.0f)
horizontalLineTo(8.0f)
close()
}
}
.build()
return _breadFill!!
}
private var _breadFill: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 2,608 | compose-icon-collections | MIT License |
kotlin-electron/src/jsMain/generated/electron/utility/VisibleOnAllWorkspacesOptions.kt | JetBrains | 93,250,841 | false | {"Kotlin": 12635434, "JavaScript": 423801} | // Generated by Karakum - do not modify it manually!
package electron.utility
typealias VisibleOnAllWorkspacesOptions = electron.core.VisibleOnAllWorkspacesOptions
| 38 | Kotlin | 162 | 1,347 | 997ed3902482883db4a9657585426f6ca167d556 | 166 | kotlin-wrappers | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnTemplateContributionAnalysisDefaultPropertyDsl.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.Any
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.quicksight.CfnAnalysis
/**
* The contribution analysis visual display for a line, pie, or bar chart.
*
* 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.*;
* ContributionAnalysisDefaultProperty contributionAnalysisDefaultProperty =
* ContributionAnalysisDefaultProperty.builder()
* .contributorDimensions(List.of(ColumnIdentifierProperty.builder()
* .columnName("columnName")
* .dataSetIdentifier("dataSetIdentifier")
* .build()))
* .measureFieldId("measureFieldId")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-analysis-contributionanalysisdefault.html)
*/
@CdkDslMarker
public class CfnAnalysisContributionAnalysisDefaultPropertyDsl {
private val cdkBuilder: CfnAnalysis.ContributionAnalysisDefaultProperty.Builder =
CfnAnalysis.ContributionAnalysisDefaultProperty.builder()
private val _contributorDimensions: MutableList<Any> = mutableListOf()
/**
* @param contributorDimensions The dimensions columns that are used in the contribution
* analysis, usually a list of `ColumnIdentifiers` .
*/
public fun contributorDimensions(vararg contributorDimensions: Any) {
_contributorDimensions.addAll(listOf(*contributorDimensions))
}
/**
* @param contributorDimensions The dimensions columns that are used in the contribution
* analysis, usually a list of `ColumnIdentifiers` .
*/
public fun contributorDimensions(contributorDimensions: Collection<Any>) {
_contributorDimensions.addAll(contributorDimensions)
}
/**
* @param contributorDimensions The dimensions columns that are used in the contribution
* analysis, usually a list of `ColumnIdentifiers` .
*/
public fun contributorDimensions(contributorDimensions: IResolvable) {
cdkBuilder.contributorDimensions(contributorDimensions)
}
/** @param measureFieldId The measure field that is used in the contribution analysis. */
public fun measureFieldId(measureFieldId: String) {
cdkBuilder.measureFieldId(measureFieldId)
}
public fun build(): CfnAnalysis.ContributionAnalysisDefaultProperty {
if (_contributorDimensions.isNotEmpty())
cdkBuilder.contributorDimensions(_contributorDimensions)
return cdkBuilder.build()
}
}
| 4 | null | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 3,006 | awscdk-dsl-kotlin | Apache License 2.0 |
plugins/editorconfig/src/org/editorconfig/language/services/impl/EditorConfigFileHierarchyServiceImpl.kt | ingokegel | 284,920,751 | false | null | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.services.impl
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.registry.RegistryValue
import com.intellij.openapi.util.registry.RegistryValueListener
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.psi.PsiManager
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import com.intellij.reference.SoftReference
import com.intellij.util.concurrency.SequentialTaskExecutor
import com.intellij.util.containers.FixedHashMap
import com.intellij.util.ui.update.MergingUpdateQueue
import com.intellij.util.ui.update.Update
import org.editorconfig.EditorConfigRegistry
import org.editorconfig.language.filetype.EditorConfigFileConstants
import org.editorconfig.language.psi.EditorConfigPsiFile
import org.editorconfig.language.psi.reference.EditorConfigVirtualFileDescriptor
import org.editorconfig.language.services.EditorConfigFileHierarchyService
import org.editorconfig.language.services.EditorConfigServiceLoaded
import org.editorconfig.language.services.EditorConfigServiceLoading
import org.editorconfig.language.services.EditorConfigServiceResult
import org.editorconfig.language.util.EditorConfigPsiTreeUtil
import org.editorconfig.language.util.matches
import java.lang.ref.Reference
class EditorConfigFileHierarchyServiceImpl(
private val manager: PsiManager,
private val application: Application,
private val project: Project
) : EditorConfigFileHierarchyService(), BulkFileListener, RegistryValueListener {
private val taskExecutor = SequentialTaskExecutor.createSequentialApplicationPoolExecutor("editorconfig.notification.vfs.update.executor")
private val updateQueue = MergingUpdateQueue("EditorConfigFileHierarchy UpdateQueue", 500, true, null, project)
@Volatile
private var cacheDropsCount = 0
private val cacheLocker = Any()
private val affectingFilesCache = FixedHashMap<VirtualFile, Reference<List<EditorConfigPsiFile>>>(CacheSize)
init {
DumbService.getInstance(project).runWhenSmart {
application.messageBus.connect(project).subscribe(VirtualFileManager.VFS_CHANGES, this)
}
Registry.get(EditorConfigRegistry.EDITORCONFIG_STOP_AT_PROJECT_ROOT_KEY).addListener(this, project)
}
private fun updateHandlers(project: Project) {
updateQueue.queue(Update.create("editorconfig hierarchy update") {
CodeStyleSettingsManager.getInstance(project).fireCodeStyleSettingsChanged(null)
})
}
// method of BulkFileListener
override fun after(events: List<VFileEvent>) {
val editorConfigs = events
.asSequence()
.filter { it.path.endsWith(EditorConfigFileConstants.FILE_NAME) }
.mapNotNull(VFileEvent::getFile)
.filter { it.name == EditorConfigFileConstants.FILE_NAME }
.toList()
if (editorConfigs.isNotEmpty()) {
synchronized(cacheLocker) {
cacheDropsCount += 1
affectingFilesCache.clear()
}
updateHandlers(project)
}
}
override fun beforeValueChanged(value: RegistryValue) {}
override fun afterValueChanged(value: RegistryValue) {
synchronized(cacheLocker) {
cacheDropsCount += 1
affectingFilesCache.clear()
}
}
override fun getParentEditorConfigFiles(virtualFile: VirtualFile): EditorConfigServiceResult {
val cachedResult = SoftReference.dereference(synchronized(cacheLocker) {
affectingFilesCache[virtualFile]
})
if (cachedResult != null) return EditorConfigServiceLoaded(cachedResult)
startBackgroundTask(virtualFile)
return EditorConfigServiceLoading
}
private fun startBackgroundTask(virtualFile: VirtualFile) {
val expectedCacheDropsCount = cacheDropsCount
ReadAction
.nonBlocking<List<EditorConfigPsiFile>?> { findApplicableFiles(virtualFile) }
.expireWith(project)
.finishOnUiThread(ModalityState.any()) ui@{ affectingFiles ->
if (affectingFiles == null) return@ui
synchronized(cacheLocker) {
if (expectedCacheDropsCount != cacheDropsCount) return@ui
affectingFilesCache[virtualFile] = SoftReference(affectingFiles)
}
}.submit(taskExecutor)
}
/**
* *null* means that operation was aborted due to cache drop
*/
private fun findApplicableFiles(virtualFile: VirtualFile): List<EditorConfigPsiFile>? {
Log.assertTrue(!application.isDispatchThread)
application.assertReadAccessAllowed()
val expectedCacheDropsCount = cacheDropsCount
val parentFiles = if (!EditorConfigRegistry.shouldStopAtProjectRoot()) findParentPsiFiles(virtualFile)
else EditorConfigPsiTreeUtil.findAllParentsFiles(manager.findFile(virtualFile) ?: return null)
return parentFiles?.filter { parent ->
parent.sections.any { section ->
if (expectedCacheDropsCount != cacheDropsCount) return null
ProgressIndicatorProvider.checkCanceled()
val header = section.header
if (header.isValidGlob) header matches virtualFile
else false
}
}
}
/**
* Searches for files manually, i.e. without using indices.
* *null* means that operation was aborted due to cache drop.
* Current file *is* included.
* Honors root declarations.
*/
private fun findParentPsiFiles(file: VirtualFile): List<EditorConfigPsiFile>? {
Log.assertTrue(!application.isDispatchThread)
application.assertReadAccessAllowed()
val expectedCacheDropsCount = cacheDropsCount
val parents =
findParentFiles(file)
?.asSequence()
?.sortedBy(EditorConfigVirtualFileDescriptor(file)::distanceToParent)
?.mapNotNull {
manager.findFile(it) as? EditorConfigPsiFile
} ?: return null
val firstRoot = parents.indexOfFirst(EditorConfigPsiFile::hasValidRootDeclaration)
if (cacheDropsCount != expectedCacheDropsCount) return null
ProgressManager.checkCanceled()
return if (firstRoot < 0) parents.toList()
else parents.take(firstRoot + 1).toList()
}
/**
* *null* means that operation was aborted due to cache drop.
* Current file *is* included
*/
private fun findParentFiles(file: VirtualFile): List<VirtualFile>? {
Log.assertTrue(!application.isDispatchThread)
application.assertReadAccessAllowed()
val fileName = EditorConfigFileConstants.FILE_NAME
val expectedCacheDropsCount = cacheDropsCount
val result = mutableListOf<VirtualFile>()
var currentFolder: VirtualFile? = file.parent
while (currentFolder != null) {
if (cacheDropsCount != expectedCacheDropsCount) return null
ProgressManager.checkCanceled()
val child = currentFolder.findChild(fileName)
if (child != null && !child.isDirectory) {
result.add(child)
}
currentFolder = currentFolder.parent
}
return result
}
private companion object {
private val Log = logger<EditorConfigFileHierarchyService>()
private const val CacheSize = 10
}
}
| 214 | null | 4829 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 7,607 | intellij-community | Apache License 2.0 |
core/src/main/java/com/bruno13palhano/core/data/database/DriverFactory.kt | bruno13palhano | 670,001,130 | false | {"Kotlin": 1380539} | package com.bruno13palhano.core.data.database
import android.content.Context
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.android.AndroidSqliteDriver
import com.bruno13palhano.cache.ShopDatabase
internal class DriverFactory(private val context: Context) {
fun createDriver(): SqlDriver {
return AndroidSqliteDriver(ShopDatabase.Schema, context, "shopDatabase.db")
}
} | 0 | Kotlin | 0 | 2 | 437aa6b904d89fd0ece9eb33ccbd24ea1875ad2d | 414 | shop-dani-management | MIT License |
src/commonMain/kotlin/data/items/BrutalGladiatorsWyrmhideGloves.kt | marisa-ashkandi | 332,658,265 | false | null | package `data`.items
import `data`.Constants
import `data`.buffs.Buffs
import `data`.itemsets.ItemSets
import `data`.model.Item
import `data`.model.ItemSet
import `data`.model.Socket
import `data`.model.SocketBonus
import character.Buff
import character.Stats
import kotlin.Array
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.String
import kotlin.collections.List
import kotlin.js.JsExport
@JsExport
public class BrutalGladiatorsKodohideGloves : Item() {
public override var isAutoGenerated: Boolean = true
public override var id: Int = 35022
public override var name: String = "Brutal Gladiator's Kodohide Gloves"
public override var itemLevel: Int = 159
public override var quality: Int = 4
public override var icon: String = "inv_gauntlets_25.jpg"
public override var inventorySlot: Int = 10
public override var itemSet: ItemSet? = ItemSets.byId(685)
public override var itemClass: Constants.ItemClass? = Constants.ItemClass.ARMOR
public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.LEATHER
public override var allowableClasses: Array<Constants.AllowableClass>? = arrayOf(
Constants.AllowableClass.DRUID
)
public override var minDmg: Double = 0.0
public override var maxDmg: Double = 0.0
public override var speed: Double = 0.0
public override var stats: Stats = Stats(
stamina = 49,
intellect = 39,
armor = 354,
resilienceRating = 21.0
)
public override var sockets: Array<Socket> = arrayOf()
public override var socketBonus: SocketBonus? = null
public override val buffs: List<Buff> by lazy {
listOfNotNull(
Buffs.byIdOrName(33820, "Increase Healing 88", this),
Buffs.byIdOrName(33830, "Cyclone Cast Time Decrease", this),
Buffs.byIdOrName(21632, "Increased Mana Regen", this)
)}
}
| 21 | Kotlin | 11 | 25 | 9cb6a0e51a650b5d04c63883cb9bf3f64057ce73 | 1,885 | tbcsim | MIT License |
src/main/kotlin/com/faendir/zachtronics/bot/repository/SolutionRepository.kt | F43nd1r | 290,065,466 | false | null | /*
* Copyright (c) 2021
*
* 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.faendir.zachtronics.bot.repository
import com.faendir.zachtronics.bot.model.Category
import com.faendir.zachtronics.bot.model.Puzzle
import com.faendir.zachtronics.bot.model.Record
import com.faendir.zachtronics.bot.model.Submission
import com.faendir.zachtronics.bot.validation.ValidationResult
interface SolutionRepository<C : Category, P : Puzzle<C>, S : Submission<C, P>, R: Record<C>> {
fun submit(submission: S) : SubmitResult<R, C>
fun submitAll(validationResults: Collection<ValidationResult<S>>): List<SubmitResult<R, C>> {
throw NotImplementedError()
}
fun find(puzzle: P, category: C) : R? =
findCategoryHolders(puzzle, false).firstOrNull { it.categories.contains(category) }?.record
fun findCategoryHolders(puzzle: P, includeFrontier: Boolean) : List<CategoryRecord<R, C>>
}
sealed class SubmitResult<R: Record<C>, C: Category> {
data class Success<R: Record<C>, C: Category>(val message: String?, val record: R?, val beatenRecords: Collection<CategoryRecord<R?, C>>) : SubmitResult<R, C>()
data class Updated<R: Record<C>, C: Category>(val record: R?, val oldRecord: CategoryRecord<R, C>) : SubmitResult<R, C>()
class AlreadyPresent<R: Record<C>, C: Category> : SubmitResult<R, C>()
data class NothingBeaten<R: Record<C>, C: Category>(val records: Collection<CategoryRecord<R, C>>) : SubmitResult<R, C>()
data class Failure<R: Record<C>, C: Category>(val message: String): SubmitResult<R, C>()
}
data class CategoryRecord<R: Record<C>?, C: Category>(val record: R, val categories: Set<C>) | 7 | Java | 6 | 4 | f10fb507c64cfd9af5c3c5f655336ad0610facec | 2,165 | zachtronics-leaderboard-bot | Apache License 2.0 |
pcbridge-spigot/test/com/projectcitybuild/features/bans/SanitizerTest.kt | projectcitybuild | 42,997,941 | false | null | package com.projectcitybuild.features.bans
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
class SanitizerTest {
@Test
fun `sanitize ip should strip slashes and ports`() {
arrayOf(
"127.0.0.1",
"/127.0.0.1",
"/127.0.0.1:12345",
).forEach {
val sanitized = Sanitizer().sanitizedIP(it)
assertEquals("127.0.0.1", sanitized)
}
}
} | 5 | Kotlin | 0 | 3 | 36a7197d870aa24a9b9ea65567a35fa38f86a31d | 464 | PCBridge | MIT License |
src/main/kotlin/dev/retrotv/random/RandomByteGenerator.kt | retrotv-maven-repo | 708,020,248 | false | {"Kotlin": 16154, "Java": 429} | package dev.retrotv.random
import java.util.Random
class ByteGenerator(private val random: Random): RandomGenerator<ByteArray> {
private lateinit var randomData: ByteArray
override fun generate(len: Int) {
randomData = ByteArray(len)
random.nextBytes(randomData)
}
override fun getValue(): ByteArray {
return randomData
}
} | 0 | Kotlin | 0 | 0 | e5e5730bb776732e39fe6141aa66ff85886ab58a | 371 | random-value | MIT License |
libraries/stdlib/unsigned/src/kotlin/UShort.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
// Auto-generated file. DO NOT EDIT!
package kotlin
import kotlin.experimental.*
@Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS")
@SinceKotlin("1.3")
@ExperimentalUnsignedTypes
public inline class UShort @PublishedApi internal constructor(@PublishedApi internal val data: Short) : Comparable<UShort> {
companion object {
/**
* A constant holding the minimum value an instance of UShort can have.
*/
public const val MIN_VALUE: UShort = UShort(0)
/**
* A constant holding the maximum value an instance of UShort can have.
*/
public const val MAX_VALUE: UShort = UShort(-1)
/**
* The number of bytes used to represent an instance of UShort in a binary form.
*/
public const val SIZE_BYTES: Int = 2
/**
* The number of bits used to represent an instance of UShort in a binary form.
*/
public const val SIZE_BITS: Int = 16
}
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
@kotlin.internal.InlineOnly
public inline operator fun compareTo(other: UByte): Int = this.toInt().compareTo(other.toInt())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
@kotlin.internal.InlineOnly
@Suppress("OVERRIDE_BY_INLINE")
public override inline operator fun compareTo(other: UShort): Int = this.toInt().compareTo(other.toInt())
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
@kotlin.internal.InlineOnly
public inline operator fun compareTo(other: UInt): Int = this.toUInt().compareTo(other)
/**
* Compares this value with the specified value for order.
* Returns zero if this value is equal to the specified other value, a negative number if it's less than other,
* or a positive number if it's greater than other.
*/
@kotlin.internal.InlineOnly
public inline operator fun compareTo(other: ULong): Int = this.toULong().compareTo(other)
/** Adds the other value to this value. */
@kotlin.internal.InlineOnly
public inline operator fun plus(other: UByte): UInt = this.toUInt().plus(other.toUInt())
/** Adds the other value to this value. */
@kotlin.internal.InlineOnly
public inline operator fun plus(other: UShort): UInt = this.toUInt().plus(other.toUInt())
/** Adds the other value to this value. */
@kotlin.internal.InlineOnly
public inline operator fun plus(other: UInt): UInt = this.toUInt().plus(other)
/** Adds the other value to this value. */
@kotlin.internal.InlineOnly
public inline operator fun plus(other: ULong): ULong = this.toULong().plus(other)
/** Subtracts the other value from this value. */
@kotlin.internal.InlineOnly
public inline operator fun minus(other: UByte): UInt = this.toUInt().minus(other.toUInt())
/** Subtracts the other value from this value. */
@kotlin.internal.InlineOnly
public inline operator fun minus(other: UShort): UInt = this.toUInt().minus(other.toUInt())
/** Subtracts the other value from this value. */
@kotlin.internal.InlineOnly
public inline operator fun minus(other: UInt): UInt = this.toUInt().minus(other)
/** Subtracts the other value from this value. */
@kotlin.internal.InlineOnly
public inline operator fun minus(other: ULong): ULong = this.toULong().minus(other)
/** Multiplies this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun times(other: UByte): UInt = this.toUInt().times(other.toUInt())
/** Multiplies this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun times(other: UShort): UInt = this.toUInt().times(other.toUInt())
/** Multiplies this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun times(other: UInt): UInt = this.toUInt().times(other)
/** Multiplies this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun times(other: ULong): ULong = this.toULong().times(other)
/** Divides this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun div(other: UByte): UInt = this.toUInt().div(other.toUInt())
/** Divides this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun div(other: UShort): UInt = this.toUInt().div(other.toUInt())
/** Divides this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun div(other: UInt): UInt = this.toUInt().div(other)
/** Divides this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun div(other: ULong): ULong = this.toULong().div(other)
/** Calculates the remainder of dividing this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun rem(other: UByte): UInt = this.toUInt().rem(other.toUInt())
/** Calculates the remainder of dividing this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun rem(other: UShort): UInt = this.toUInt().rem(other.toUInt())
/** Calculates the remainder of dividing this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun rem(other: UInt): UInt = this.toUInt().rem(other)
/** Calculates the remainder of dividing this value by the other value. */
@kotlin.internal.InlineOnly
public inline operator fun rem(other: ULong): ULong = this.toULong().rem(other)
/** Increments this value. */
@kotlin.internal.InlineOnly
public inline operator fun inc(): UShort = UShort(data.inc())
/** Decrements this value. */
@kotlin.internal.InlineOnly
public inline operator fun dec(): UShort = UShort(data.dec())
/** Creates a range from this value to the specified [other] value. */
@kotlin.internal.InlineOnly
public inline operator fun rangeTo(other: UShort): UIntRange = UIntRange(this.toUInt(), other.toUInt())
/** Performs a bitwise AND operation between the two values. */
@kotlin.internal.InlineOnly
public inline infix fun and(other: UShort): UShort = UShort(this.data and other.data)
/** Performs a bitwise OR operation between the two values. */
@kotlin.internal.InlineOnly
public inline infix fun or(other: UShort): UShort = UShort(this.data or other.data)
/** Performs a bitwise XOR operation between the two values. */
@kotlin.internal.InlineOnly
public inline infix fun xor(other: UShort): UShort = UShort(this.data xor other.data)
/** Inverts the bits in this value. */
@kotlin.internal.InlineOnly
public inline fun inv(): UShort = UShort(data.inv())
/**
* Converts this [UShort] value to [Byte].
*
* If this value is less than or equals to [Byte.MAX_VALUE], the resulting `Byte` value represents
* the same numerical value as this `UShort`.
*
* The resulting `Byte` value is represented by the least significant 8 bits of this `UShort` value.
* Note that the resulting `Byte` value may be negative.
*/
@kotlin.internal.InlineOnly
public inline fun toByte(): Byte = data.toByte()
/**
* Converts this [UShort] value to [Short].
*
* If this value is less than or equals to [Short.MAX_VALUE], the resulting `Short` value represents
* the same numerical value as this `UShort`. Otherwise the result is negative.
*
* The resulting `Short` value has the same binary representation as this `UShort` value.
*/
@kotlin.internal.InlineOnly
public inline fun toShort(): Short = data
/**
* Converts this [UShort] value to [Int].
*
* The resulting `Int` value represents the same numerical value as this `UShort`.
*
* The least significant 16 bits of the resulting `Int` value are the same as the bits of this `UShort` value,
* whereas the most significant 16 bits are filled with zeros.
*/
@kotlin.internal.InlineOnly
public inline fun toInt(): Int = data.toInt() and 0xFFFF
/**
* Converts this [UShort] value to [Long].
*
* The resulting `Long` value represents the same numerical value as this `UShort`.
*
* The least significant 16 bits of the resulting `Long` value are the same as the bits of this `UShort` value,
* whereas the most significant 48 bits are filled with zeros.
*/
@kotlin.internal.InlineOnly
public inline fun toLong(): Long = data.toLong() and 0xFFFF
/**
* Converts this [UShort] value to [UByte].
*
* If this value is less than or equals to [UByte.MAX_VALUE], the resulting `UByte` value represents
* the same numerical value as this `UShort`.
*
* The resulting `UByte` value is represented by the least significant 8 bits of this `UShort` value.
*/
@kotlin.internal.InlineOnly
public inline fun toUByte(): UByte = data.toUByte()
/** Returns this value. */
@kotlin.internal.InlineOnly
public inline fun toUShort(): UShort = this
/**
* Converts this [UShort] value to [UInt].
*
* The resulting `UInt` value represents the same numerical value as this `UShort`.
*
* The least significant 16 bits of the resulting `UInt` value are the same as the bits of this `UShort` value,
* whereas the most significant 16 bits are filled with zeros.
*/
@kotlin.internal.InlineOnly
public inline fun toUInt(): UInt = UInt(data.toInt() and 0xFFFF)
/**
* Converts this [UShort] value to [ULong].
*
* The resulting `ULong` value represents the same numerical value as this `UShort`.
*
* The least significant 16 bits of the resulting `ULong` value are the same as the bits of this `UShort` value,
* whereas the most significant 48 bits are filled with zeros.
*/
@kotlin.internal.InlineOnly
public inline fun toULong(): ULong = ULong(data.toLong() and 0xFFFF)
/**
* Converts this [UShort] value to [Float].
*
* The resulting `Float` value represents the same numerical value as this `UShort`.
*/
@kotlin.internal.InlineOnly
public inline fun toFloat(): Float = this.toInt().toFloat()
/**
* Converts this [UShort] value to [Double].
*
* The resulting `Double` value represents the same numerical value as this `UShort`.
*/
@kotlin.internal.InlineOnly
public inline fun toDouble(): Double = this.toInt().toDouble()
public override fun toString(): String = toInt().toString()
}
/**
* Converts this [Byte] value to [UShort].
*
* If this value is positive, the resulting `UShort` value represents the same numerical value as this `Byte`.
*
* The least significant 8 bits of the resulting `UShort` value are the same as the bits of this `Byte` value,
* whereas the most significant 8 bits are filled with the sign bit of this value.
*/
@SinceKotlin("1.3")
@ExperimentalUnsignedTypes
@kotlin.internal.InlineOnly
public inline fun Byte.toUShort(): UShort = UShort(this.toShort())
/**
* Converts this [Short] value to [UShort].
*
* If this value is positive, the resulting `UShort` value represents the same numerical value as this `Short`.
*
* The resulting `UShort` value has the same binary representation as this `Short` value.
*/
@SinceKotlin("1.3")
@ExperimentalUnsignedTypes
@kotlin.internal.InlineOnly
public inline fun Short.toUShort(): UShort = UShort(this)
/**
* Converts this [Int] value to [UShort].
*
* If this value is positive and less than or equals to [UShort.MAX_VALUE], the resulting `UShort` value represents
* the same numerical value as this `Int`.
*
* The resulting `UShort` value is represented by the least significant 16 bits of this `Int` value.
*/
@SinceKotlin("1.3")
@ExperimentalUnsignedTypes
@kotlin.internal.InlineOnly
public inline fun Int.toUShort(): UShort = UShort(this.toShort())
/**
* Converts this [Long] value to [UShort].
*
* If this value is positive and less than or equals to [UShort.MAX_VALUE], the resulting `UShort` value represents
* the same numerical value as this `Long`.
*
* The resulting `UShort` value is represented by the least significant 16 bits of this `Long` value.
*/
@SinceKotlin("1.3")
@ExperimentalUnsignedTypes
@kotlin.internal.InlineOnly
public inline fun Long.toUShort(): UShort = UShort(this.toShort())
| 181 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 13,148 | kotlin | Apache License 2.0 |
main/java/com/android/genshinImpact/CharacterListFragment.kt | Edwin0430 | 698,105,616 | false | {"Kotlin": 38943} | package com.android.genshinImpact
import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.ImageView
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.text.SimpleDateFormat
import java.util.*
import android.view.LayoutInflater
import android.view.ViewGroup
private const val TAG = "CharacterListFragment"
class CharacterListFragment : Fragment() {
/**
* Required for hosting activities
*/
interface Callbacks {
fun onCharacterSelected(characterId: UUID)
}
private var callbacks: Callbacks? = null
private lateinit var characterRecyclerView: RecyclerView
private var adapter: CharacterAdapter? = CharacterAdapter(emptyList())
private val characterListViewModel: CharacterListViewModel by lazy {
ViewModelProviders.of(this).get(CharacterListViewModel::class.java)
}
override fun onAttach(context: Context) {
super.onAttach(context)
callbacks = context as Callbacks?
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_character_list, container, false)
characterRecyclerView = view.findViewById(R.id.character_recycler_view)
characterRecyclerView.layoutManager = LinearLayoutManager(context)
characterRecyclerView.adapter = adapter
return view
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
characterListViewModel.characterListLiveData.observe(
viewLifecycleOwner,
Observer { characters ->
characters?.let {
Log.i(TAG, "Got characters: ${characters.size}")
updateUI(characters)
}
}
)
}
private fun updateUI(characters: List<Character>) {
val nonNullCharacters = characters.filterNotNull()
adapter?.characters = nonNullCharacters
adapter?.notifyDataSetChanged()
}
override fun onDetach() {
super.onDetach()
callbacks = null
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.fragment_character_list, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.new_character -> {
val character = Character()
characterListViewModel.addCharacter(character)
callbacks?.onCharacterSelected(character.id)
true
}
else -> return super.onOptionsItemSelected(item)
}
}
private inner class CharacterHolder(view: View) : RecyclerView.ViewHolder(view), View.OnClickListener {
private lateinit var character: Character
private val titleTextView: TextView = itemView.findViewById(R.id.character_title)
private val dateTextView: TextView = itemView.findViewById(R.id.character_date)
private val timeTextView: TextView = itemView.findViewById(R.id.character_time)
private val pyroImageView: ImageView = itemView.findViewById(R.id.character_pyro)
private val hydroImageView: ImageView = itemView.findViewById(R.id.character_hydro)
private val electroImageView: ImageView = itemView.findViewById(R.id.character_electro)
private val geoImageView: ImageView = itemView.findViewById(R.id.character_geo)
private val anemoImageView: ImageView = itemView.findViewById(R.id.character_anemo)
private val cryoImageView: ImageView = itemView.findViewById(R.id.character_cryo)
private val dendroImageView: ImageView = itemView.findViewById(R.id.character_dendro)
init {
itemView.setOnClickListener(this)
}
fun bind(character: Character?, elementType: ElementType?) {
// Check if the character is null, if so, hide the views and return
if (character == null) {
titleTextView.visibility = View.GONE
dateTextView.visibility = View.GONE
timeTextView.visibility = View.GONE
pyroImageView.visibility = View.GONE
hydroImageView.visibility = View.GONE
electroImageView.visibility = View.GONE
geoImageView.visibility = View.GONE
anemoImageView.visibility = View.GONE
cryoImageView.visibility = View.GONE
dendroImageView.visibility = View.GONE
return
}
// Update UI based on the element type
titleTextView.text = character.title
dateTextView.text = formatDateToString(character.date)
timeTextView.text = formatTimeToString(character.time)
// Show the views and set the corresponding image for the element type
titleTextView.visibility = View.VISIBLE
dateTextView.visibility = View.VISIBLE
timeTextView.visibility = View.VISIBLE
pyroImageView.visibility = View.GONE
hydroImageView.visibility = View.GONE
electroImageView.visibility = View.GONE
geoImageView.visibility = View.GONE
anemoImageView.visibility = View.GONE
cryoImageView.visibility = View.GONE
dendroImageView.visibility = View.GONE
if (elementType != null) {
when (elementType) {
ElementType.PYRO -> pyroImageView.visibility = View.VISIBLE
ElementType.HYDRO -> hydroImageView.visibility = View.VISIBLE
ElementType.ELECTRO -> electroImageView.visibility = View.VISIBLE
ElementType.GEO -> geoImageView.visibility = View.VISIBLE
ElementType.ANEMO -> anemoImageView.visibility = View.VISIBLE
ElementType.CRYO -> cryoImageView.visibility = View.VISIBLE
ElementType.DENDRO -> dendroImageView.visibility = View.VISIBLE
}
}
// Assign the character passed to the property
this.character = character
}
override fun onClick(v: View?) {
// Check if the character property is initialized before accessing it
if (::character.isInitialized) {
callbacks?.onCharacterSelected(character.id)
} else {
Log.e(TAG, "Character property is not initialized.")
}
}
}
private enum class ElementType {
PYRO, HYDRO, ELECTRO, GEO, ANEMO, CRYO, DENDRO
}
private inner class CharacterAdapter(var characters: List<Character>) :
RecyclerView.Adapter<CharacterHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CharacterHolder {
val view = layoutInflater.inflate(R.layout.list_item_character, parent, false)
return CharacterHolder(view)
}
override fun getItemCount() = characters.size
override fun onBindViewHolder(holder: CharacterHolder, position: Int) {
val character = characters[position]
val elementType = when {
character.isPyro -> ElementType.PYRO
character.isHydro -> ElementType.HYDRO
character.isElectro -> ElementType.ELECTRO
character.isGeo -> ElementType.GEO
character.isAnemo -> ElementType.ANEMO
character.isCryo -> ElementType.CRYO
character.isDendro -> ElementType.DENDRO
else -> null
}
holder.bind(character, elementType)
}
}
companion object {
fun newInstance(): CharacterListFragment {
return CharacterListFragment()
}
}
private fun formatDateToString(date: Date): String {
val format = SimpleDateFormat("EEE-yyyy-MM-dd", Locale.getDefault())
return format.format(date)
}
private fun formatTimeToString(time: Date): String {
val format = SimpleDateFormat("hh:mm a", Locale.getDefault())
return format.format(time)
}
}
| 0 | Kotlin | 0 | 0 | 49bd3706a3f60711bfde20980a1d85f27c6d0ba2 | 8,728 | GenshinCharacter-note-app | Apache License 2.0 |
data/src/main/java/com/wasin/data/model/user/SignupRequest.kt | wa-sin-sang-dam | 828,217,645 | false | {"Kotlin": 301042} | package com.wasin.data.model.user
import kotlinx.serialization.Serializable
@Serializable
data class SignupRequest(
val role: String = "",
val username: String = "",
val email: String = "",
val password: String = "",
val password2: String = "",
)
| 2 | Kotlin | 0 | 0 | 28a58078ff866f6f9baa460714217884fdbea3ab | 269 | wasin-android | MIT License |
compiler/frontend/src/org/jetbrains/kotlin/resolve/calls/tower/PSICallResolver.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2000-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.resolve.calls.tower
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.contracts.EffectSystem
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.extensions.internal.CandidateInterceptor
import org.jetbrains.kotlin.incremental.components.LookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.BindingContext.NEW_INFERENCE_CATCH_EXCEPTION_PARAMETER
import org.jetbrains.kotlin.resolve.calls.ArgumentTypeResolver
import org.jetbrains.kotlin.resolve.calls.CallTransformer
import org.jetbrains.kotlin.resolve.calls.KotlinCallResolver
import org.jetbrains.kotlin.resolve.calls.callResolverUtil.isBinaryRemOperator
import org.jetbrains.kotlin.resolve.calls.callUtil.*
import org.jetbrains.kotlin.resolve.calls.components.CallableReferenceResolver
import org.jetbrains.kotlin.resolve.calls.components.InferenceSession
import org.jetbrains.kotlin.resolve.calls.components.PostponedArgumentsAnalyzer
import org.jetbrains.kotlin.resolve.calls.context.BasicCallResolutionContext
import org.jetbrains.kotlin.resolve.calls.context.ContextDependency
import org.jetbrains.kotlin.resolve.calls.inference.buildResultingSubstitutor
import org.jetbrains.kotlin.resolve.calls.inference.components.KotlinConstraintSystemCompleter
import org.jetbrains.kotlin.resolve.calls.model.*
import org.jetbrains.kotlin.resolve.calls.results.*
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.resolve.calls.tasks.DynamicCallableDescriptors
import org.jetbrains.kotlin.resolve.calls.tasks.ResolutionCandidate
import org.jetbrains.kotlin.resolve.calls.tasks.TracingStrategy
import org.jetbrains.kotlin.resolve.calls.util.CallMaker
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.deprecation.DeprecationResolver
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.receivers.*
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.expressions.*
import org.jetbrains.kotlin.types.model.TypeSystemInferenceExtensionContext
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
import java.util.*
class PSICallResolver(
private val typeResolver: TypeResolver,
private val expressionTypingServices: ExpressionTypingServices,
private val doubleColonExpressionResolver: DoubleColonExpressionResolver,
private val languageVersionSettings: LanguageVersionSettings,
private val dynamicCallableDescriptors: DynamicCallableDescriptors,
private val syntheticScopes: SyntheticScopes,
private val callComponents: KotlinCallComponents,
private val kotlinToResolvedCallTransformer: KotlinToResolvedCallTransformer,
private val kotlinCallResolver: KotlinCallResolver,
private val typeApproximator: TypeApproximator,
private val argumentTypeResolver: ArgumentTypeResolver,
private val effectSystem: EffectSystem,
private val constantExpressionEvaluator: ConstantExpressionEvaluator,
private val dataFlowValueFactory: DataFlowValueFactory,
private val postponedArgumentsAnalyzer: PostponedArgumentsAnalyzer,
private val kotlinConstraintSystemCompleter: KotlinConstraintSystemCompleter,
private val deprecationResolver: DeprecationResolver,
private val moduleDescriptor: ModuleDescriptor,
private val callableReferenceResolver: CallableReferenceResolver,
private val candidateInterceptor: CandidateInterceptor,
private val missingSupertypesResolver: MissingSupertypesResolver
) {
private val givenCandidatesName = Name.special("<given candidates>")
val defaultResolutionKinds = setOf(
NewResolutionOldInference.ResolutionKind.Function,
NewResolutionOldInference.ResolutionKind.Variable,
NewResolutionOldInference.ResolutionKind.Invoke
)
fun <D : CallableDescriptor> runResolutionAndInference(
context: BasicCallResolutionContext,
name: Name,
resolutionKind: NewResolutionOldInference.ResolutionKind,
tracingStrategy: TracingStrategy
): OverloadResolutionResults<D> {
val isBinaryRemOperator = isBinaryRemOperator(context.call)
val refinedName = refineNameForRemOperator(isBinaryRemOperator, name)
val kotlinCallKind = resolutionKind.toKotlinCallKind()
val kotlinCall = toKotlinCall(context, kotlinCallKind, context.call, refinedName, tracingStrategy)
val scopeTower = ASTScopeTower(context)
val resolutionCallbacks = createResolutionCallbacks(context)
val expectedType = calculateExpectedType(context)
var result =
kotlinCallResolver.resolveCall(scopeTower, resolutionCallbacks, kotlinCall, expectedType, context.collectAllCandidates) {
FactoryProviderForInvoke(context, scopeTower, kotlinCall)
}
val shouldUseOperatorRem = languageVersionSettings.supportsFeature(LanguageFeature.OperatorRem)
if (isBinaryRemOperator && shouldUseOperatorRem && (result.isEmpty() || result.areAllInapplicable())) {
result = resolveToDeprecatedMod(name, context, kotlinCallKind, tracingStrategy, scopeTower, resolutionCallbacks, expectedType)
}
if (result.isEmpty() && reportAdditionalDiagnosticIfNoCandidates(context, scopeTower, kotlinCallKind, kotlinCall)) {
return OverloadResolutionResultsImpl.nameNotFound()
}
val overloadResolutionResults = convertToOverloadResolutionResults<D>(context, result, tracingStrategy)
return overloadResolutionResults.also {
clearCacheForApproximationResults()
}
}
// actually, `D` is at least FunctionDescriptor, but right now because of CallResolver it isn't possible change upper bound for `D`
fun <D : CallableDescriptor> runResolutionAndInferenceForGivenCandidates(
context: BasicCallResolutionContext,
resolutionCandidates: Collection<ResolutionCandidate<D>>,
tracingStrategy: TracingStrategy
): OverloadResolutionResults<D> {
val dispatchReceiver = resolutionCandidates.firstNotNullResult { it.dispatchReceiver }
val kotlinCall =
toKotlinCall(context, KotlinCallKind.FUNCTION, context.call, givenCandidatesName, tracingStrategy, dispatchReceiver)
val scopeTower = ASTScopeTower(context)
val resolutionCallbacks = createResolutionCallbacks(context)
val givenCandidates = resolutionCandidates.map {
GivenCandidate(
it.descriptor as FunctionDescriptor,
it.dispatchReceiver?.let { context.transformToReceiverWithSmartCastInfo(it) },
it.knownTypeParametersResultingSubstitutor
)
}
val result = kotlinCallResolver.resolveGivenCandidates(
scopeTower, resolutionCallbacks, kotlinCall, calculateExpectedType(context), givenCandidates, context.collectAllCandidates
)
val overloadResolutionResults = convertToOverloadResolutionResults<D>(context, result, tracingStrategy)
return overloadResolutionResults.also {
clearCacheForApproximationResults()
}
}
private fun clearCacheForApproximationResults() {
// Mostly, we approximate captured or some other internal types that don't live longer than resolve for a call,
// so it's quite useless to preserve cache for longer time
typeApproximator.clearCache()
}
private fun resolveToDeprecatedMod(
remOperatorName: Name,
context: BasicCallResolutionContext,
kotlinCallKind: KotlinCallKind,
tracingStrategy: TracingStrategy,
scopeTower: ImplicitScopeTower,
resolutionCallbacks: KotlinResolutionCallbacksImpl,
expectedType: UnwrappedType?
): CallResolutionResult {
val deprecatedName = OperatorConventions.REM_TO_MOD_OPERATION_NAMES[remOperatorName]!!
val callWithDeprecatedName = toKotlinCall(context, kotlinCallKind, context.call, deprecatedName, tracingStrategy)
return kotlinCallResolver.resolveCall(
scopeTower, resolutionCallbacks, callWithDeprecatedName, expectedType, context.collectAllCandidates
) {
FactoryProviderForInvoke(context, scopeTower, callWithDeprecatedName)
}
}
private fun refineNameForRemOperator(isBinaryRemOperator: Boolean, name: Name): Name {
val shouldUseOperatorRem = languageVersionSettings.supportsFeature(LanguageFeature.OperatorRem)
return if (isBinaryRemOperator && !shouldUseOperatorRem) OperatorConventions.REM_TO_MOD_OPERATION_NAMES[name]!! else name
}
private fun createResolutionCallbacks(context: BasicCallResolutionContext) =
createResolutionCallbacks(context.trace, context.inferenceSession, context)
fun createResolutionCallbacks(trace: BindingTrace, inferenceSession: InferenceSession, context: BasicCallResolutionContext?) =
KotlinResolutionCallbacksImpl(
trace, expressionTypingServices, typeApproximator,
argumentTypeResolver, languageVersionSettings, kotlinToResolvedCallTransformer,
dataFlowValueFactory, inferenceSession, constantExpressionEvaluator, typeResolver,
this, postponedArgumentsAnalyzer, kotlinConstraintSystemCompleter, callComponents,
doubleColonExpressionResolver, deprecationResolver, moduleDescriptor, context, missingSupertypesResolver
)
private fun calculateExpectedType(context: BasicCallResolutionContext): UnwrappedType? {
val expectedType = context.expectedType.unwrap()
return if (context.contextDependency == ContextDependency.DEPENDENT) {
assert(TypeUtils.noExpectedType(expectedType)) {
"Should have no expected type, got: $expectedType"
}
null
} else {
if (expectedType.isError) TypeUtils.NO_EXPECTED_TYPE else expectedType
}
}
fun <D : CallableDescriptor> convertToOverloadResolutionResults(
context: BasicCallResolutionContext,
result: CallResolutionResult,
tracingStrategy: TracingStrategy
): OverloadResolutionResults<D> {
if (result is AllCandidatesResolutionResult) {
val resolvedCalls = result.allCandidates.map { (candidate, diagnostics) ->
val system = candidate.getSystem()
val resultingSubstitutor =
system.asReadOnlyStorage().buildResultingSubstitutor(system as TypeSystemInferenceExtensionContext)
kotlinToResolvedCallTransformer.transformToResolvedCall<D>(
candidate.resolvedCall, null, resultingSubstitutor, diagnostics
)
}
return AllCandidates(resolvedCalls)
}
val trace = context.trace
handleErrorResolutionResult<D>(context, trace, result, tracingStrategy)?.let { errorResult ->
context.inferenceSession.addErrorCallInfo(PSIErrorCallInfo(result, errorResult))
return errorResult
}
val resolvedCall = kotlinToResolvedCallTransformer.transformAndReport<D>(result, context, tracingStrategy)
// NB. Be careful with moving this invocation, as effect system expects resolution results to be written in trace
// (see EffectSystem for details)
resolvedCall.recordEffects(trace)
return SingleOverloadResolutionResult(resolvedCall)
}
private fun <D : CallableDescriptor> handleErrorResolutionResult(
context: BasicCallResolutionContext,
trace: BindingTrace,
result: CallResolutionResult,
tracingStrategy: TracingStrategy
): OverloadResolutionResults<D>? {
val diagnostics = result.diagnostics
diagnostics.firstIsInstanceOrNull<NoneCandidatesCallDiagnostic>()?.let {
kotlinToResolvedCallTransformer.transformAndReport<D>(result, context, tracingStrategy)
tracingStrategy.unresolvedReference(trace)
return OverloadResolutionResultsImpl.nameNotFound()
}
diagnostics.firstIsInstanceOrNull<ManyCandidatesCallDiagnostic>()?.let {
kotlinToResolvedCallTransformer.transformAndReport<D>(result, context, tracingStrategy)
return transformManyCandidatesAndRecordTrace(it, tracingStrategy, trace, context)
}
if (getResultApplicability(diagnostics) == ResolutionCandidateApplicability.INAPPLICABLE_WRONG_RECEIVER) {
val singleCandidate = result.resultCallAtom() ?: error("Should be not null for result: $result")
val resolvedCall = kotlinToResolvedCallTransformer.onlyTransform<D>(singleCandidate, diagnostics).also {
tracingStrategy.unresolvedReferenceWrongReceiver(trace, listOf(it))
}
return SingleOverloadResolutionResult(resolvedCall)
}
return null
}
private fun <D : CallableDescriptor> transformManyCandidatesAndRecordTrace(
diagnostic: ManyCandidatesCallDiagnostic,
tracingStrategy: TracingStrategy,
trace: BindingTrace,
context: BasicCallResolutionContext
): ManyCandidates<D> {
val resolvedCalls = diagnostic.candidates.map {
kotlinToResolvedCallTransformer.onlyTransform<D>(
it.resolvedCall, it.diagnosticsFromResolutionParts + it.getSystem().diagnostics
)
}
if (diagnostic.candidates.areAllFailed()) {
if (diagnostic.candidates.areAllFailedWithInapplicableWrongReceiver()) {
tracingStrategy.unresolvedReferenceWrongReceiver(trace, resolvedCalls)
} else {
tracingStrategy.noneApplicable(trace, resolvedCalls)
tracingStrategy.recordAmbiguity(trace, resolvedCalls)
}
} else {
tracingStrategy.recordAmbiguity(trace, resolvedCalls)
if (!context.call.hasUnresolvedArguments(context)) {
if (resolvedCalls.allIncomplete) {
tracingStrategy.cannotCompleteResolve(trace, resolvedCalls)
} else {
tracingStrategy.ambiguity(trace, resolvedCalls)
}
}
}
return ManyCandidates(resolvedCalls)
}
private val List<ResolvedCall<*>>.allIncomplete: Boolean get() = all { it.status == ResolutionStatus.INCOMPLETE_TYPE_INFERENCE }
private fun ResolvedCall<*>.recordEffects(trace: BindingTrace) {
val moduleDescriptor = DescriptorUtils.getContainingModule(this.resultingDescriptor?.containingDeclaration ?: return)
recordLambdasInvocations(trace, moduleDescriptor)
recordResultInfo(trace, moduleDescriptor)
}
private fun ResolvedCall<*>.recordResultInfo(trace: BindingTrace, moduleDescriptor: ModuleDescriptor) {
if (this !is NewResolvedCallImpl) return
val resultDFIfromES = effectSystem.getDataFlowInfoForFinishedCall(this, trace, moduleDescriptor)
this.updateResultingDataFlowInfo(resultDFIfromES)
}
private fun ResolvedCall<*>.recordLambdasInvocations(trace: BindingTrace, moduleDescriptor: ModuleDescriptor) {
effectSystem.recordDefiniteInvocations(this, trace, moduleDescriptor)
}
private fun CallResolutionResult.isEmpty(): Boolean =
diagnostics.firstIsInstanceOrNull<NoneCandidatesCallDiagnostic>() != null
private fun Collection<KotlinResolutionCandidate>.areAllFailed() =
all {
!it.resultingApplicability.isSuccess
}
private fun Collection<KotlinResolutionCandidate>.areAllFailedWithInapplicableWrongReceiver() =
all {
it.resultingApplicability == ResolutionCandidateApplicability.INAPPLICABLE_WRONG_RECEIVER
}
private fun CallResolutionResult.areAllInapplicable(): Boolean {
val manyCandidates = diagnostics.firstIsInstanceOrNull<ManyCandidatesCallDiagnostic>()?.candidates
if (manyCandidates != null) {
return manyCandidates.areAllFailed()
}
val applicability = getResultApplicability(diagnostics)
return applicability == ResolutionCandidateApplicability.INAPPLICABLE ||
applicability == ResolutionCandidateApplicability.INAPPLICABLE_WRONG_RECEIVER ||
applicability == ResolutionCandidateApplicability.HIDDEN
}
// true if we found something
private fun reportAdditionalDiagnosticIfNoCandidates(
context: BasicCallResolutionContext,
scopeTower: ImplicitScopeTower,
kind: KotlinCallKind,
kotlinCall: KotlinCall
): Boolean {
val reference = context.call.calleeExpression as? KtReferenceExpression ?: return false
val errorCandidates = when (kind) {
KotlinCallKind.FUNCTION ->
collectErrorCandidatesForFunction(scopeTower, kotlinCall.name, kotlinCall.explicitReceiver?.receiver)
KotlinCallKind.VARIABLE ->
collectErrorCandidatesForVariable(scopeTower, kotlinCall.name, kotlinCall.explicitReceiver?.receiver)
else -> emptyList()
}
for (candidate in errorCandidates) {
if (candidate is ErrorCandidate.Classifier) {
context.trace.record(BindingContext.REFERENCE_TARGET, reference, candidate.descriptor)
context.trace.report(
Errors.RESOLUTION_TO_CLASSIFIER.on(
reference,
candidate.descriptor,
candidate.kind,
candidate.errorMessage
)
)
return true
}
}
return false
}
private inner class ASTScopeTower(
val context: BasicCallResolutionContext
) : ImplicitScopeTower {
// todo may be for invoke for case variable + invoke we should create separate dynamicScope(by newCall for invoke)
override val dynamicScope: MemberScope =
dynamicCallableDescriptors.createDynamicDescriptorScope(context.call, context.scope.ownerDescriptor)
// same for location
override val location: LookupLocation = context.call.createLookupLocation()
override val syntheticScopes: SyntheticScopes get() = [email protected]
override val isDebuggerContext: Boolean get() = context.isDebuggerContext
override val isNewInferenceEnabled: Boolean get() = context.languageVersionSettings.supportsFeature(LanguageFeature.NewInference)
override val lexicalScope: LexicalScope get() = context.scope
override val typeApproximator: TypeApproximator get() = [email protected]
private val cache = HashMap<ReceiverParameterDescriptor, ReceiverValueWithSmartCastInfo>()
override fun getImplicitReceiver(scope: LexicalScope): ReceiverValueWithSmartCastInfo? {
val implicitReceiver = scope.implicitReceiver ?: return null
return cache.getOrPut(implicitReceiver) {
context.transformToReceiverWithSmartCastInfo(implicitReceiver.value)
}
}
override fun interceptCandidates(
resolutionScope: ResolutionScope,
name: Name,
initialResults: Collection<FunctionDescriptor>,
location: LookupLocation
): Collection<FunctionDescriptor> {
return candidateInterceptor.interceptCandidates(initialResults, this, context, resolutionScope, null, name, location)
}
}
private inner class FactoryProviderForInvoke(
val context: BasicCallResolutionContext,
val scopeTower: ImplicitScopeTower,
val kotlinCall: PSIKotlinCallImpl
) : CandidateFactoryProviderForInvoke<KotlinResolutionCandidate> {
init {
assert(kotlinCall.dispatchReceiverForInvokeExtension == null) { kotlinCall }
}
override fun transformCandidate(
variable: KotlinResolutionCandidate,
invoke: KotlinResolutionCandidate
) = invoke
override fun factoryForVariable(stripExplicitReceiver: Boolean): CandidateFactory<KotlinResolutionCandidate> {
val explicitReceiver = if (stripExplicitReceiver) null else kotlinCall.explicitReceiver
val variableCall = PSIKotlinCallForVariable(kotlinCall, explicitReceiver, kotlinCall.name)
return SimpleCandidateFactory(
callComponents, scopeTower, variableCall, createResolutionCallbacks(context), callableReferenceResolver
)
}
override fun factoryForInvoke(variable: KotlinResolutionCandidate, useExplicitReceiver: Boolean):
Pair<ReceiverValueWithSmartCastInfo, CandidateFactory<KotlinResolutionCandidate>>? {
if (isRecursiveVariableResolution(variable)) return null
assert(variable.isSuccessful) {
"Variable call should be successful: $variable " +
"Descriptor: ${variable.resolvedCall.candidateDescriptor}"
}
val variableCallArgument = createReceiverCallArgument(variable)
val explicitReceiver = kotlinCall.explicitReceiver
val callForInvoke = if (useExplicitReceiver && explicitReceiver != null) {
PSIKotlinCallForInvoke(kotlinCall, variable, explicitReceiver, variableCallArgument)
} else {
PSIKotlinCallForInvoke(kotlinCall, variable, variableCallArgument, null)
}
return variableCallArgument.receiver to SimpleCandidateFactory(
callComponents, scopeTower, callForInvoke, createResolutionCallbacks(context), callableReferenceResolver
)
}
// todo: create special check that there is no invoke on variable
private fun isRecursiveVariableResolution(variable: KotlinResolutionCandidate): Boolean {
val variableType = variable.resolvedCall.candidateDescriptor.returnType
return variableType is DeferredType && variableType.isComputing
}
// todo: review
private fun createReceiverCallArgument(variable: KotlinResolutionCandidate): SimpleKotlinCallArgument {
variable.forceResolution()
val variableReceiver = createReceiverValueWithSmartCastInfo(variable)
if (variableReceiver.possibleTypes.isNotEmpty()) {
return ReceiverExpressionKotlinCallArgument(
createReceiverValueWithSmartCastInfo(variable),
isForImplicitInvoke = true
)
}
val psiKotlinCall = variable.resolvedCall.atom.psiKotlinCall
val variableResult = PartialCallResolutionResult(variable.resolvedCall, listOf(), variable.getSystem().asReadOnlyStorage())
return SubKotlinCallArgumentImpl(
CallMaker.makeExternalValueArgument((variableReceiver.receiverValue as ExpressionReceiver).expression),
psiKotlinCall.resultDataFlowInfo, psiKotlinCall.resultDataFlowInfo, variableReceiver,
variableResult
)
}
// todo: decrease hacks count
private fun createReceiverValueWithSmartCastInfo(variable: KotlinResolutionCandidate): ReceiverValueWithSmartCastInfo {
val callForVariable = variable.resolvedCall.atom as PSIKotlinCallForVariable
val calleeExpression = callForVariable.baseCall.psiCall.calleeExpression as? KtReferenceExpression
?: error("Unexpected call : ${callForVariable.baseCall.psiCall}")
val temporaryTrace = TemporaryBindingTrace.create(context.trace, "Context for resolve candidate")
val type = variable.resolvedCall.freshReturnType!!
val variableReceiver = ExpressionReceiver.create(calleeExpression, type, temporaryTrace.bindingContext)
temporaryTrace.record(BindingContext.REFERENCE_TARGET, calleeExpression, variable.resolvedCall.candidateDescriptor)
val dataFlowValue =
dataFlowValueFactory.createDataFlowValue(variableReceiver, temporaryTrace.bindingContext, context.scope.ownerDescriptor)
return ReceiverValueWithSmartCastInfo(
variableReceiver,
context.dataFlowInfo.getCollectedTypes(dataFlowValue, context.languageVersionSettings),
dataFlowValue.isStable
).prepareReceiverRegardingCaptureTypes()
}
}
private fun NewResolutionOldInference.ResolutionKind.toKotlinCallKind(): KotlinCallKind =
when (this) {
is NewResolutionOldInference.ResolutionKind.Function -> KotlinCallKind.FUNCTION
is NewResolutionOldInference.ResolutionKind.Variable -> KotlinCallKind.VARIABLE
is NewResolutionOldInference.ResolutionKind.Invoke -> KotlinCallKind.INVOKE
is NewResolutionOldInference.ResolutionKind.CallableReference -> KotlinCallKind.UNSUPPORTED
is NewResolutionOldInference.ResolutionKind.GivenCandidates -> KotlinCallKind.UNSUPPORTED
}
private fun toKotlinCall(
context: BasicCallResolutionContext,
kotlinCallKind: KotlinCallKind,
oldCall: Call,
name: Name,
tracingStrategy: TracingStrategy,
forcedExplicitReceiver: Receiver? = null
): PSIKotlinCallImpl {
val resolvedExplicitReceiver = resolveReceiver(
context, forcedExplicitReceiver ?: oldCall.explicitReceiver, oldCall.isSafeCall(), isForImplicitInvoke = false
)
val dispatchReceiverForInvoke = resolveDispatchReceiverForInvoke(context, kotlinCallKind, oldCall)
val resolvedTypeArguments = resolveTypeArguments(context, oldCall.typeArguments)
val lambdasOutsideParenthesis = oldCall.functionLiteralArguments.size
val extraArgumentsNumber = if (oldCall.callType == Call.CallType.ARRAY_SET_METHOD) 1 else lambdasOutsideParenthesis
val allValueArguments = oldCall.valueArguments
val argumentsInParenthesis = if (extraArgumentsNumber == 0) allValueArguments else allValueArguments.dropLast(extraArgumentsNumber)
val externalLambdaArguments = oldCall.functionLiteralArguments
val resolvedArgumentsInParenthesis = resolveArgumentsInParenthesis(context, argumentsInParenthesis)
val externalArgument = if (oldCall.callType == Call.CallType.ARRAY_SET_METHOD) {
assert(externalLambdaArguments.isEmpty()) {
"Unexpected lambda parameters for call $oldCall"
}
allValueArguments.last()
} else {
if (externalLambdaArguments.size > 1) {
for (i in externalLambdaArguments.indices) {
if (i == 0) continue
val lambdaExpression = externalLambdaArguments[i].getLambdaExpression() ?: continue
if (lambdaExpression.isTrailingLambdaOnNewLIne) {
context.trace.report(Errors.UNEXPECTED_TRAILING_LAMBDA_ON_A_NEW_LINE.on(lambdaExpression))
}
context.trace.report(Errors.MANY_LAMBDA_EXPRESSION_ARGUMENTS.on(lambdaExpression))
}
}
externalLambdaArguments.firstOrNull()
}
val dataFlowInfoAfterArgumentsInParenthesis =
if (externalArgument != null && resolvedArgumentsInParenthesis.isNotEmpty())
resolvedArgumentsInParenthesis.last().psiCallArgument.dataFlowInfoAfterThisArgument
else
context.dataFlowInfoForArguments.resultInfo
val resolvedExternalArgument = externalArgument?.let { resolveValueArgument(context, dataFlowInfoAfterArgumentsInParenthesis, it) }
val resultDataFlowInfo = resolvedExternalArgument?.dataFlowInfoAfterThisArgument ?: dataFlowInfoAfterArgumentsInParenthesis
resolvedArgumentsInParenthesis.forEach { it.setResultDataFlowInfoIfRelevant(resultDataFlowInfo) }
resolvedExternalArgument?.setResultDataFlowInfoIfRelevant(resultDataFlowInfo)
val isForImplicitInvoke = oldCall is CallTransformer.CallForImplicitInvoke
return PSIKotlinCallImpl(
kotlinCallKind, oldCall, tracingStrategy, resolvedExplicitReceiver, dispatchReceiverForInvoke, name,
resolvedTypeArguments, resolvedArgumentsInParenthesis, resolvedExternalArgument, context.dataFlowInfo, resultDataFlowInfo,
context.dataFlowInfoForArguments, isForImplicitInvoke
)
}
private fun resolveDispatchReceiverForInvoke(
context: BasicCallResolutionContext,
kotlinCallKind: KotlinCallKind,
oldCall: Call
): ReceiverKotlinCallArgument? {
if (kotlinCallKind != KotlinCallKind.INVOKE) return null
require(oldCall is CallTransformer.CallForImplicitInvoke) { "Call should be CallForImplicitInvoke, but it is: $oldCall" }
return resolveReceiver(context, oldCall.dispatchReceiver, isSafeCall = false, isForImplicitInvoke = true)
}
private fun resolveReceiver(
context: BasicCallResolutionContext,
oldReceiver: Receiver?,
isSafeCall: Boolean,
isForImplicitInvoke: Boolean
): ReceiverKotlinCallArgument? {
return when (oldReceiver) {
null -> null
is QualifierReceiver -> QualifierReceiverKotlinCallArgument(oldReceiver) // todo report warning if isSafeCall
is ReceiverValue -> {
if (oldReceiver is ExpressionReceiver) {
val ktExpression = KtPsiUtil.getLastElementDeparenthesized(oldReceiver.expression, context.statementFilter)
val bindingContext = context.trace.bindingContext
val call =
bindingContext[BindingContext.DELEGATE_EXPRESSION_TO_PROVIDE_DELEGATE_CALL, ktExpression]
?: ktExpression?.getCall(bindingContext)
val partiallyResolvedCall = call?.let { bindingContext.get(BindingContext.ONLY_RESOLVED_CALL, it)?.result }
if (partiallyResolvedCall != null) {
val receiver = ReceiverValueWithSmartCastInfo(oldReceiver, emptySet(), isStable = true)
return SubKotlinCallArgumentImpl(
CallMaker.makeExternalValueArgument(oldReceiver.expression),
context.dataFlowInfo, context.dataFlowInfo, receiver, partiallyResolvedCall
)
}
}
ReceiverExpressionKotlinCallArgument(
context.transformToReceiverWithSmartCastInfo(oldReceiver),
isSafeCall,
isForImplicitInvoke
)
}
else -> error("Incorrect receiver: $oldReceiver")
}
}
private fun resolveTypeArguments(context: BasicCallResolutionContext, typeArguments: List<KtTypeProjection>): List<TypeArgument> =
typeArguments.map { projection ->
if (projection.projectionKind != KtProjectionKind.NONE) {
context.trace.report(Errors.PROJECTION_ON_NON_CLASS_TYPE_ARGUMENT.on(projection))
}
ModifierCheckerCore.check(projection, context.trace, null, languageVersionSettings)
resolveType(context, projection.typeReference, typeResolver)?.let { SimpleTypeArgumentImpl(projection.typeReference!!, it) }
?: TypeArgumentPlaceholder
}
private fun resolveArgumentsInParenthesis(
context: BasicCallResolutionContext,
arguments: List<ValueArgument>
): List<KotlinCallArgument> {
val dataFlowInfoForArguments = context.dataFlowInfoForArguments
return arguments.map { argument ->
resolveValueArgument(context, dataFlowInfoForArguments.getInfo(argument), argument).also { resolvedArgument ->
dataFlowInfoForArguments.updateInfo(argument, resolvedArgument.dataFlowInfoAfterThisArgument)
}
}
}
private fun resolveValueArgument(
outerCallContext: BasicCallResolutionContext,
startDataFlowInfo: DataFlowInfo,
valueArgument: ValueArgument
): PSIKotlinCallArgument {
val builtIns = outerCallContext.scope.ownerDescriptor.builtIns
fun createParseErrorElement() = ParseErrorKotlinCallArgument(valueArgument, startDataFlowInfo, builtIns)
val argumentExpression = valueArgument.getArgumentExpression() ?: return createParseErrorElement()
val ktExpression = KtPsiUtil.deparenthesize(argumentExpression) ?: createParseErrorElement()
val argumentName = valueArgument.getArgumentName()?.asName
processFunctionalExpression(
outerCallContext, argumentExpression, startDataFlowInfo,
valueArgument, argumentName, builtIns, typeResolver
)?.let {
return it
}
if (ktExpression is KtCollectionLiteralExpression) {
return CollectionLiteralKotlinCallArgumentImpl(
valueArgument, argumentName, startDataFlowInfo, startDataFlowInfo, ktExpression, outerCallContext
)
}
val context = outerCallContext.replaceContextDependency(ContextDependency.DEPENDENT)
.replaceExpectedType(TypeUtils.NO_EXPECTED_TYPE).replaceDataFlowInfo(startDataFlowInfo)
.expandContextForCatchClause(ktExpression)
if (ktExpression is KtCallableReferenceExpression) {
checkNoSpread(outerCallContext, valueArgument)
val expressionTypingContext = ExpressionTypingContext.newContext(context)
val lhsResult = if (ktExpression.isEmptyLHS) null else doubleColonExpressionResolver.resolveDoubleColonLHS(
ktExpression,
expressionTypingContext
)
val newDataFlowInfo = (lhsResult as? DoubleColonLHS.Expression)?.dataFlowInfo ?: startDataFlowInfo
val name = ktExpression.callableReference.getReferencedNameAsName()
val lhsNewResult = when (lhsResult) {
null -> LHSResult.Empty
is DoubleColonLHS.Expression -> {
if (lhsResult.isObjectQualifier) {
val classifier = lhsResult.type.constructor.declarationDescriptor
val calleeExpression = ktExpression.receiverExpression?.getCalleeExpressionIfAny()
if (calleeExpression is KtSimpleNameExpression && classifier is ClassDescriptor) {
LHSResult.Object(ClassQualifier(calleeExpression, classifier))
} else {
LHSResult.Error
}
} else {
val fakeArgument = FakeValueArgumentForLeftCallableReference(ktExpression)
val kotlinCallArgument = createSimplePSICallArgument(context, fakeArgument, lhsResult.typeInfo)
kotlinCallArgument?.let { LHSResult.Expression(it as SimpleKotlinCallArgument) } ?: LHSResult.Error
}
}
is DoubleColonLHS.Type -> {
val qualifiedExpression = ktExpression.receiverExpression!!.let { it.referenceExpression() ?: it }
val qualifier = expressionTypingContext.trace.get(BindingContext.QUALIFIER, qualifiedExpression)
LHSResult.Type(qualifier, lhsResult.type.unwrap())
}
}
return CallableReferenceKotlinCallArgumentImpl(
ASTScopeTower(context), valueArgument, startDataFlowInfo, newDataFlowInfo,
ktExpression, argumentName, lhsNewResult, name
)
}
// argumentExpression instead of ktExpression is hack -- type info should be stored also for parenthesized expression
val typeInfo = expressionTypingServices.getTypeInfo(argumentExpression, context)
return createSimplePSICallArgument(context, valueArgument, typeInfo) ?: createParseErrorElement()
}
private fun BasicCallResolutionContext.expandContextForCatchClause(ktExpression: Any): BasicCallResolutionContext {
if (ktExpression !is KtExpression) return this
val variableDescriptorHolder = trace.bindingContext[NEW_INFERENCE_CATCH_EXCEPTION_PARAMETER, ktExpression] ?: return this
val variableDescriptor = variableDescriptorHolder.get() ?: return this
variableDescriptorHolder.set(null)
val redeclarationChecker = expressionTypingServices.createLocalRedeclarationChecker(trace)
val catchScope = with(scope) {
LexicalWritableScope(this, ownerDescriptor, false, redeclarationChecker, LexicalScopeKind.CATCH)
}
catchScope.addVariableDescriptor(variableDescriptor)
return replaceScope(catchScope)
}
}
| 7 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 37,590 | kotlin | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.