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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
notifications/src/main/java/io/karte/android/notifications/internal/track/ReachedTracker.kt | plaidev | 208,185,127 | false | null | //
// Copyright 2020 PLAID, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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 io.karte.android.notifications.internal.track
import io.karte.android.core.logger.Logger
import io.karte.android.notifications.internal.MessageIgnoredEvent
import io.karte.android.notifications.internal.wrapper.MessageWrapper
import io.karte.android.tracking.Tracker
import io.karte.android.tracking.Values
private const val LOG_TAG = "Karte.Notifications.IgnoreTracker"
internal object IgnoreTracker : MessageTracker {
override fun sendIfNeeded(wrapper: MessageWrapper?) {
Logger.d(LOG_TAG, "sendIfNeeded")
if (wrapper?.isValid != true) return
try {
when {
wrapper.isTargetPush -> trackTargetPush(
wrapper.campaignId,
wrapper.shortenId,
wrapper.eventValues
)
}
wrapper.clean()
} catch (e: Exception) {
Logger.e(LOG_TAG, "Failed to handle push notification _message_ignored.", e)
}
}
private fun trackTargetPush(
campaignId: String?,
shortenId: String?,
eventValues: Values
) {
if (campaignId == null || shortenId == null || eventValues.isEmpty()) return
Logger.i(
LOG_TAG,
"Deleted karte notification. campaignId: $campaignId, shortenId: $shortenId"
)
Tracker.track(MessageIgnoredEvent(campaignId, shortenId, eventValues))
}
}
| 3 | null | 4 | 5 | ad6959aa506ce2d85888bd9d6e452387898ab899 | 2,026 | karte-android-sdk | Apache License 2.0 |
src/main/kotlin/engine/utils/CommandList.kt | CozmicGames | 560,807,673 | false | {"Kotlin": 612419} | package engine.utils
import com.cozmicgames.utils.Disposable
import com.cozmicgames.utils.collections.Pool
open class CommandList<T : Any>(private val pool: Pool<T>) : Disposable {
constructor(supplier: () -> T, reset: (T) -> Unit = {}) : this(Pool(supplier = supplier, reset = reset))
private val commands = arrayListOf<T>()
private val processingCommands = arrayListOf<T>()
fun get() = pool.obtain()
fun add(command: T) {
commands += command
}
fun process(block: (T) -> Unit) {
processingCommands.clear()
processingCommands.addAll(commands)
commands.clear()
processingCommands.forEach {
block(it)
pool.free(it)
}
}
override fun dispose() {
pool.dispose()
}
}
operator fun <T : Any> CommandList<T>.plusAssign(command: T) = add(command) | 0 | Kotlin | 0 | 0 | d85d016431fb0490dcb6b125be5fd285e409bfc4 | 864 | GameOff2022 | MIT License |
src/main/kotlin/com/nearsoft/ipapiklient/models/IpInfo.kt | epool | 139,361,941 | false | {"Kotlin": 9993} | package com.nearsoft.ipapiklient.models
/**
* In case we don't have data on a specific field, the returned value will be, depending on the field type:
* String: empty ("")
* Double: 0.0
* Boolean: false
*/
data class IpInfo(
/**
* AS number and name, separated by space e.g. AS15169 Google Inc.
*/
val `as`: String,
/**
* City e.g. Mountain View
*/
val city: String,
/**
* Country e.g. United States
*/
val country: String,
/**
* Country short e.g. US
*/
val countryCode: String,
/**
* ISP name e.g. Google
*/
val isp: String,
/**
* Latitude e.g. 37.4192
*/
val lat: Double,
/**
* Longitude e.g. -122.0574
*/
val lon: Double,
/**
* Mobile (cellular) connection e.g. true
*/
val mobile: Boolean,
/**
* Organization name e.g. Google
*/
val org: String,
/**
* Proxy (anonymous) e.g. true
*/
val proxy: Boolean,
/**
* IP used for the query e.g. 172.16.17.32
*/
val query: String,
/**
* Region/state short e.g. CA or 10
*/
val region: String,
/**
* Region/state e.g. California
*/
val regionName: String,
/**
* Reverse DNS of the IP e.g. wi-in-f94.1e100.net
*/
val reverse: String,
/**
* Always success e.g. success
*/
val status: String,
/**
* City timezone e.g. America/Los_Angeles
*/
val timezone: String,
/**
* Zip code e.g. 94043
*/
val zip: String
) | 0 | Kotlin | 0 | 1 | 5c073c0046bdc2a36d0f2e4303bca7792329b194 | 1,834 | ip-api-klient | Apache License 2.0 |
modules/arch-lifecycle/src/androidMain/kotlin/splitties/arch/lifecycle/ViewModel.kt | LouisCAD | 65,558,914 | false | {"Gradle Kotlin DSL": 70, "Shell": 3, "Text": 4, "Markdown": 56, "Java Properties": 2, "Ignore List": 67, "Batchfile": 2, "Git Attributes": 1, "EditorConfig": 1, "YAML": 6, "XML": 72, "Kotlin": 299, "INI": 1, "Proguard": 5, "Java": 1, "CSS": 1, "AsciiDoc": 1} | /*
* Copyright 2019-2021 <NAME>. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.arch.lifecycle
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
inline fun <reified VM : ViewModel> FragmentActivity.viewModels(
noinline factory: () -> VM
): Lazy<VM> = viewModels { TypeSafeViewModelFactory(factory) }
inline fun <reified VM : ViewModel> Fragment.activityViewModels(
noinline factory: () -> VM
): Lazy<VM> = activityViewModels { TypeSafeViewModelFactory(factory) }
inline fun <reified VM : ViewModel> Fragment.viewModels(
noinline factory: () -> VM
): Lazy<VM> = viewModels { TypeSafeViewModelFactory(factory) }
@PublishedApi
internal class TypeSafeViewModelFactory<VM : ViewModel>(
private val factory: () -> VM
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>) = factory() as T
}
| 53 | Kotlin | 160 | 2,476 | 1ed56ba2779f31dbf909509c955fce7b9768e208 | 1,155 | Splitties | Apache License 2.0 |
modulecheck-parsing/android/src/main/kotlin/modulecheck/parsing/android/AndroidManifestParser.kt | RBusarow | 316,627,145 | false | null | /*
* Copyright (C) 2021-2023 Rick Busarow
* 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 modulecheck.parsing.android
import groovy.util.Node
import java.io.File
class AndroidLayoutParser {
fun parseViews(file: File): Set<String> {
val node = SafeXmlParser().parse(file) ?: return emptySet()
return node.breadthFirst()
.filterIsInstance<Node>()
.mapNotNull { it.name() as? String }
.toSet()
}
fun parseResources(file: File): Set<String> {
val node = SafeXmlParser().parse(file) ?: return emptySet()
return node.breadthFirst()
.filterIsInstance<Node>()
.mapNotNull { it.attributes() }
.flatMap { it.values.mapNotNull { value -> value } }
.filterIsInstance<String>()
.toSet()
}
}
| 8 | null | 7 | 95 | 24e7c7667490630d30cf8b59cd504cd863cd1fba | 1,278 | ModuleCheck | Apache License 2.0 |
android-uitests/testData/iosched/mobile/src/main/java/com/google/samples/apps/iosched/ui/map/LoadGeoJsonFeaturesUseCase.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright 2018 Google LLC
*
* 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.sree.oneapp.ui.map
import android.content.Context
import android.text.TextUtils
import com.google.android.gms.maps.GoogleMap
import com.google.maps.android.data.geojson.GeoJsonFeature
import com.google.maps.android.data.geojson.GeoJsonLayer
import com.sree.oneapp.shared.domain.UseCase
import javax.inject.Inject
/** Parameters for this use case. */
typealias LoadGeoJsonParams = Pair<GoogleMap, Int>
/** Data loaded by this use case. */
data class GeoJsonData(
val geoJsonLayer: GeoJsonLayer,
val featureMap: Map<String, GeoJsonFeature>
)
/** Use case that loads a GeoJsonLayer and its features. */
class LoadGeoJsonFeaturesUseCase @Inject constructor(
private val context: Context
) : UseCase<LoadGeoJsonParams, GeoJsonData>() {
override fun execute(parameters: LoadGeoJsonParams): GeoJsonData {
val layer = GeoJsonLayer(parameters.first, parameters.second, context)
processGeoJsonLayer(layer, context)
layer.isLayerOnMap
return GeoJsonData(layer, buildFeatureMap(layer))
}
private fun buildFeatureMap(layer: GeoJsonLayer): Map<String, GeoJsonFeature> {
val featureMap: MutableMap<String, GeoJsonFeature> = mutableMapOf()
layer.features.forEach {
val id = it.getProperty("id")
if (!TextUtils.isEmpty(id)) {
// Marker can map to multiple room IDs
for (part in id.split(",")) {
featureMap[part] = it
}
}
}
return featureMap
}
}
| 77 | null | 6259 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 2,138 | android | Apache License 2.0 |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/covidcertificate/common/certificate/CwaCovidCertificate.kt | corona-warn-app | 268,027,139 | false | null | package de.rki.coronawarnapp.covidcertificate.common.certificate
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import de.rki.coronawarnapp.covidcertificate.common.certificate.CwaCovidCertificate.State.Blocked
import de.rki.coronawarnapp.covidcertificate.common.certificate.CwaCovidCertificate.State.ExpiringSoon
import de.rki.coronawarnapp.covidcertificate.common.certificate.CwaCovidCertificate.State.Invalid
import de.rki.coronawarnapp.covidcertificate.common.certificate.CwaCovidCertificate.State.Revoked
import de.rki.coronawarnapp.covidcertificate.common.repository.CertificateContainerId
import de.rki.coronawarnapp.covidcertificate.test.core.TestCertificate
import de.rki.coronawarnapp.covidcertificate.test.core.storage.isScreenedTestCert
import de.rki.coronawarnapp.reyclebin.common.Recyclable
import de.rki.coronawarnapp.util.qrcode.coil.CoilQrCode
import de.rki.coronawarnapp.util.serialization.SerializationModule
import de.rki.coronawarnapp.util.serialization.adapter.RuntimeTypeAdapterFactory
import org.joda.time.Instant
/**
* For use with the UI
*/
interface CwaCovidCertificate : Recyclable {
// Header
val headerIssuer: String
val headerIssuedAt: Instant
val headerExpiresAt: Instant
val qrCodeToDisplay: CoilQrCode
val firstName: String?
val lastName: String
val fullName: String
val fullNameFormatted: String
val fullNameStandardizedFormatted: String
val dateOfBirthFormatted: String
val personIdentifier: CertificatePersonIdentifier
val certificateIssuer: String
val certificateCountry: String
val qrCodeHash: String
/**
* `ci` field
*/
val uniqueCertificateIdentifier: String
/**
* The ID of the container holding this certificate in the CWA.
*/
val containerId: CertificateContainerId
val rawCertificate: DccV1.MetaData
val dccData: DccData<out DccV1.MetaData>
val notifiedExpiresSoonAt: Instant?
val notifiedExpiredAt: Instant?
val notifiedInvalidAt: Instant?
val notifiedBlockedAt: Instant?
val notifiedRevokedAt: Instant?
val lastSeenStateChange: State?
val lastSeenStateChangeAt: Instant?
/**
* Indicates that certificate has updates regarding its status such as:
* Expiring_Soon, Expired, Invalid, Blocked, Revoked or certificate is newly registered in the App
* @see [isNew]
*/
val hasNotificationBadge: Boolean
/**
* Certificate is newly scanned or retrieved from server in case of TC
*/
val isNew: Boolean
/**
* The current state of the certificate, see [State]
*/
val state: State
val isDisplayValid
get() = when (this) {
is TestCertificate -> !isScreenedTestCert(state)
else -> state is State.Valid || state is ExpiringSoon
}
val isNotScreened get() = state !in setOf(Blocked, Revoked)
/**
* Requires RuntimeAdapterFactory, see [SerializationModule]
*/
@Keep
sealed class State(val type: String) {
data class Valid(
@SerializedName("expiresAt") val expiresAt: Instant,
) : State("Valid")
data class ExpiringSoon(
@SerializedName("expiresAt") val expiresAt: Instant,
) : State("ExpiringSoon")
data class Expired(
@SerializedName("expiredAt") val expiredAt: Instant,
) : State("Expired")
data class Invalid(
@SerializedName("isInvalidSignature") val isInvalidSignature: Boolean = true
) : State("Invalid") {
companion object {
const val URL_INVALID_SIGNATURE_DE = "https://www.coronawarn.app/de/faq/#hc_signature_invalid"
const val URL_INVALID_SIGNATURE_EN = "https://www.coronawarn.app/en/faq/#hc_signature_invalid"
}
}
object Blocked : State("Blocked")
object Recycled : State("Recycled")
object Revoked : State("Revoked")
companion object {
val typeAdapter: RuntimeTypeAdapterFactory<State> = RuntimeTypeAdapterFactory
.of(State::class.java, "type", true)
.registerSubtype(Valid::class.java, "Valid")
.registerSubtype(ExpiringSoon::class.java, "ExpiringSoon")
.registerSubtype(Expired::class.java, "Expired")
.registerSubtype(Invalid::class.java, "Invalid")
.registerSubtype(Blocked::class.java, "Blocked")
.registerSubtype(Revoked::class.java, "Revoked")
}
override fun equals(other: Any?): Boolean {
if (this is Blocked && other is Blocked) return true
if (this is Revoked && other is Revoked) return true
if (this is Recycled && other is Recycled) return true
return super.equals(other)
}
override fun hashCode(): Int {
return type.hashCode()
}
}
}
| 35 | null | 516 | 2,495 | d3833a212bd4c84e38a1fad23b282836d70ab8d5 | 4,948 | cwa-app-android | Apache License 2.0 |
armthing/src/main/kotlin/crackers/kobots/app/Stuff.kt | EAGrahamJr | 564,081,499 | false | null | /*
* Copyright 2022-2023 by E. A. Graham, Jr.
*
* 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 crackers.kobots.app
import com.diozero.util.SleepUtil
import crackers.kobots.devices.expander.CRICKITHat
import java.time.Duration
import java.util.concurrent.Executors
import java.util.concurrent.Future
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.math.abs
// shared devices
internal val crickitHat by lazy { CRICKITHat() }
// TODO this might be useful as a generic app convention?
// threads and execution control
internal val executor = Executors.newCachedThreadPool()
internal val runFlag = AtomicBoolean(true)
/**
* Run a [block] and ensure it takes up **at least** [millis] time. This is basically to keep various parts from
* overloading the various buses.
*/
internal fun <R> executeWithMinTime(millis: Long, block: () -> R): R {
val startAt = System.currentTimeMillis()
val response = block()
val runtime = System.currentTimeMillis() - startAt
if (runtime < millis) {
SleepUtil.busySleep(Duration.ofMillis(millis - runtime).toNanos())
}
return response
}
/**
* Run an execution loop until the run-flag says stop
*/
internal fun checkRun(ms: Long, block: () -> Unit): Future<*> = executor.submit {
while (runFlag.get()) executeWithMinTime(ms) { block() }
}
fun Float.almostEquals(another: Float, wibble: Float): Boolean = abs(this - another) < wibble
| 0 | Kotlin | 0 | 1 | 1c1ded437032058e3a660d5137d75a1ce4c18186 | 1,945 | kobots | Apache License 2.0 |
gto-support-snowplow/src/main/kotlin/org/ccci/gto/android/common/snowplow/events/EventSynchronizer.kt | CruGlobal | 30,609,844 | false | null | package org.ccci.gto.android.common.snowplow.events
import androidx.annotation.VisibleForTesting
import com.snowplowanalytics.snowplow.event.Event
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
internal object EventSynchronizer {
@VisibleForTesting
internal val semaphore = Semaphore(1, true)
private val currentEvent = AtomicReference<Event?>()
@VisibleForTesting
internal var lockTimeout = 2000L
fun lockFor(event: Event) {
while (true) {
val curr = currentEvent.get()
if (semaphore.tryAcquire(lockTimeout, TimeUnit.MILLISECONDS)) {
if (currentEvent.compareAndSet(null, event)) break
semaphore.release()
} else if (curr != null && currentEvent.compareAndSet(curr, event)) {
break
}
}
}
fun unlockFor(event: Event) {
if (currentEvent.compareAndSet(event, null)) semaphore.release()
}
}
| 9 | null | 2 | 8 | 529634f181da6f2c1394d07ed05594caf178706c | 1,027 | android-gto-support | MIT License |
src/main/kotlin/org/teamvoided/voidlib/pow/registry/EnergyRegistries.kt | TeamVoided | 570,651,037 | false | null | package org.teamvoided.voidlib.pow.registry
import net.fabricmc.fabric.api.event.registry.FabricRegistryBuilder
import net.minecraft.registry.Registry
import org.teamvoided.voidlib.id
import org.teamvoided.voidlib.pow.energy.EnergyUnit
object EnergyRegistries {
val UNIT: Registry<EnergyUnit> =
FabricRegistryBuilder.createSimple(EnergyUnit::class.java, id("energy_unit_reg"))
.buildAndRegister()
} | 0 | Kotlin | 0 | 1 | 130c6c83f8c332fabfb942158f1e77ed6c5da882 | 424 | VoidLib | MIT License |
core/src/commonMain/kotlin/com/ramitsuri/notificationjournal/core/model/DayGroup.kt | ramitsuri | 667,037,607 | false | {"Kotlin": 274675, "Shell": 8329, "Python": 3405, "HTML": 1499, "JavaScript": 1016} | package com.ramitsuri.notificationjournal.core.model
import kotlinx.datetime.LocalDate
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class DayGroup(
@SerialName("date")
val date: LocalDate,
@SerialName("tag_groups")
val tagGroups: List<TagGroup>
)
| 0 | Kotlin | 0 | 0 | 40d69baae3f526432f9c3b03f5cec7eb0173c85b | 322 | notification-journal | MIT License |
adoptium-updater-parent/adoptium-api-v3-updater/src/test/kotlin/net/adoptium/api/GraphQLGitHubReleaseClientTest.kt | adoptium | 349,432,712 | false | null | package net.adoptium.api
import io.aexp.nodes.graphql.GraphQLRequestEntity
import io.aexp.nodes.graphql.GraphQLResponseEntity
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.runBlocking
import net.adoptium.api.v3.AdoptRepositoryImpl
import net.adoptium.api.v3.dataSources.github.graphql.clients.GraphQLGitHubReleaseClient
import net.adoptium.api.v3.dataSources.github.graphql.clients.GraphQLGitHubRepositoryClient
import net.adoptium.api.v3.dataSources.github.graphql.clients.GraphQLGitHubSummaryClient
import net.adoptium.api.v3.dataSources.github.graphql.clients.GraphQLRequest
import net.adoptium.api.v3.dataSources.github.graphql.models.GHAsset
import net.adoptium.api.v3.dataSources.github.graphql.models.GHAssets
import net.adoptium.api.v3.dataSources.github.graphql.models.GHRelease
import net.adoptium.api.v3.dataSources.github.graphql.models.GHReleaseResult
import net.adoptium.api.v3.dataSources.github.graphql.models.GHReleases
import net.adoptium.api.v3.dataSources.github.graphql.models.GHRepository
import net.adoptium.api.v3.dataSources.github.graphql.models.PageInfo
import net.adoptium.api.v3.dataSources.github.graphql.models.QueryData
import net.adoptium.api.v3.dataSources.github.graphql.models.QuerySummaryData
import net.adoptium.api.v3.dataSources.github.graphql.models.RateLimit
import net.adoptium.api.v3.dataSources.github.graphql.models.summary.GHAssetsSummary
import net.adoptium.api.v3.dataSources.github.graphql.models.summary.GHReleaseSummary
import net.adoptium.api.v3.dataSources.github.graphql.models.summary.GHReleasesSummary
import net.adoptium.api.v3.dataSources.github.graphql.models.summary.GHRepositorySummary
import net.adoptium.api.v3.dataSources.models.GitHubId
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class GraphQLGitHubReleaseClientTest : BaseTest() {
companion object {
val source = GHAssets(
listOf(
GHAsset(
"OpenJDK8U-jre_x64_linux_hotspot-1.tar.gz",
1L,
"",
1L,
"2013-02-27T19:35:32Z"
),
GHAsset(
"OpenJDK8U-jre_x64_linux_hotspot-1.tar.gz.json",
1L,
"1",
1L,
"2013-02-27T19:35:32Z"
)
),
PageInfo(false, ""),
2
)
val response = GHRelease(
id = GitHubId("1"),
name = "jdk9u-2018-09-27-08-50",
isPrerelease = true,
publishedAt = "2013-02-27T19:35:32Z",
updatedAt = "2013-02-27T19:35:32Z",
releaseAssets = source,
resourcePath = "8",
url = "https://github.com/AdoptOpenJDK/openjdk9-binaries/releases/download/jdk9u-2018-09-27-08-50/OpenJDK9U-jre_aarch64_linux_hotspot_2018-09-27-08-50.tar.gz"
)
val repo = GHRepository(GHReleases(listOf(response), PageInfo(false, null)))
}
@Test
fun `GraphQLGitHubReleaseClient client returns correct release`() {
runBlocking {
val client = GraphQLGitHubReleaseClient(
object : GraphQLRequest {
override fun <F> query(query: GraphQLRequestEntity, clazz: Class<F>): GraphQLResponseEntity<F> {
val builder = mockk<GraphQLResponseEntity<F>>()
assert(query.toString().contains("a-github-id"))
every { builder.response } returns GHReleaseResult(response, RateLimit(0, 5000)) as F
return builder
}
},
mockkHttpClient()
)
val release = client.getReleaseById(GitHubId("a-github-id"))
assertEquals(response, release)
}
}
@Test
fun `GraphQLGitHubRepositoryClient client returns correct repository`() {
runBlocking {
val client = GraphQLGitHubRepositoryClient(
object : GraphQLRequest {
override fun <F> query(query: GraphQLRequestEntity, clazz: Class<F>): GraphQLResponseEntity<F> {
val builder = mockk<GraphQLResponseEntity<F>>()
assert(query.toString().contains("a-repo-name"))
every { builder.response } returns QueryData(repo, RateLimit(0, 5000)) as F
every { builder.errors } returns null
return builder
}
},
mockkHttpClient()
)
val repo = client.getRepository(AdoptRepositoryImpl.ADOPT_ORG, "a-repo-name")
assertEquals(Companion.repo, repo)
}
}
@Test
fun `GraphQLGitHubSummaryClient client returns correct repository`() {
runBlocking {
val summary = QuerySummaryData(
GHRepositorySummary(
GHReleasesSummary(
listOf(
GHReleaseSummary(
GitHubId("foo"),
"a",
"b",
"c",
GHAssetsSummary(0)
)
),
PageInfo(false, null)
)
),
RateLimit(0, 5000)
)
val client = GraphQLGitHubSummaryClient(
object : GraphQLRequest {
override fun <F> query(query: GraphQLRequestEntity, clazz: Class<F>): GraphQLResponseEntity<F> {
val builder = mockk<GraphQLResponseEntity<F>>()
assert(query.toString().contains("a-repo-name"))
every { builder.response } returns summary as F
every { builder.errors } returns null
return builder
}
},
mockkHttpClient()
)
val repo = client.getRepositorySummary(AdoptRepositoryImpl.ADOPT_ORG, "a-repo-name")
assertEquals(summary.repository, repo)
}
}
@Test
fun `requests second page`() {
runBlocking {
val client = GraphQLGitHubRepositoryClient(
object : GraphQLRequest {
override fun <F> query(query: GraphQLRequestEntity, clazz: Class<F>): GraphQLResponseEntity<F> {
val builder = mockk<GraphQLResponseEntity<F>>()
assert(query.toString().contains("a-repo-name"))
val pageInfo = if (query.variables["cursorPointer"] != null) {
PageInfo(false, null)
} else {
PageInfo(true, "next-page-id")
}
val repo = GHRepository(GHReleases(listOf(response), pageInfo))
every { builder.response } returns QueryData(repo, RateLimit(0, 5000)) as F
every { builder.errors } returns null
return builder
}
},
mockkHttpClient()
)
val repo = client.getRepository(AdoptRepositoryImpl.ADOPT_ORG, "a-repo-name")
assertEquals(2, repo.releases.releases.size)
}
}
}
| 19 | null | 34 | 9 | ddb39b5f7a71236694fc9df44e1bf3a888ba1fbc | 7,511 | api.adoptium.net | Apache License 2.0 |
instance-keeper/src/commonMain/kotlin/com/arkivanov/essenty/instancekeeper/InstanceKeeperDispatcher.kt | arkivanov | 385,374,863 | false | null | package com.arkivanov.essenty.instancekeeper
import kotlin.js.JsName
/**
* Represents a destroyable [InstanceKeeper].
*/
interface InstanceKeeperDispatcher : InstanceKeeper {
/**
* Destroys all existing instances. Instances are not cleared, so that they can be
* accessed later. Any new instances will be immediately destroyed.
*/
fun destroy()
}
/**
* Creates a default implementation of [InstanceKeeperDispatcher].
*/
@JsName("instanceKeeperDispatcher")
@Suppress("FunctionName")
fun InstanceKeeperDispatcher(): InstanceKeeperDispatcher = DefaultInstanceKeeperDispatcher()
| 1 | null | 15 | 499 | bc67da4c3b069cf4b89d7b8b0a75869c9b704981 | 606 | Essenty | Apache License 2.0 |
app/src/main/java/com/ecodemo/silk/DecodeFile.kt | moieo | 433,604,739 | false | {"C": 1243474, "C++": 211104, "Assembly": 165771, "Kotlin": 52711, "CMake": 2381, "HTML": 2072, "Java": 1552} | package com.ecodemo.silk;
import java.io.File
import android.net.Uri
import kotlin.Suppress
import android.os.Build
import android.Manifest
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import java.util.LinkedList
import java.lang.Runnable
import java.lang.Character
import android.os.Message
import java.util.Collections
import android.view.Menu
import android.app.Activity
import android.widget.Toast
import java.util.regex.Pattern
import android.content.Intent
import android.view.MenuItem
import android.app.AlertDialog
import android.os.Environment
import android.content.Context
import android.provider.Settings
import android.app.ProgressDialog
import java.util.concurrent.TimeUnit
import java.util.concurrent.Executors
import android.content.DialogInterface
import androidx.core.app.ActivityCompat
import java.util.concurrent.ExecutorService
import android.content.pm.PackageManager
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import androidx.documentfile.provider.DocumentFile
import com.ecodemo.silk.databinding.DecodeFileBinding
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.DividerItemDecoration
class DecodeFile: Activity() {
private lateinit var binding: DecodeFileBinding
private var list = mutableListOf<File>()
private var adapter: DecodeAdapter? = null
@Suppress("DEPRECATION")
private val sd_path: File = Environment.getExternalStorageDirectory()
@Suppress("UNUSED", "DEPRECATION")
private var handler: Handler = Handler {
if(it.what == 0) {
list.add(it.obj as File)
adapter?.notifyDataSetChanged()
false
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
}
binding = DecodeFileBinding.inflate(layoutInflater)
actionBar?.setDisplayHomeAsUpEnabled(true)
setContentView(binding.root)
adapter = DecodeAdapter(this, list)
var decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
binding.recycle.addItemDecoration(decoration)
var layoutManager = LinearLayoutManager(this)
layoutManager.setRecycleChildrenOnDetach(true)
binding.recycle.layoutManager = layoutManager
binding.recycle.adapter = adapter
binding.recycle.setHasFixedSize(true)
binding.recycle.setItemViewCacheSize(60)
binding.recycle.setDrawingCacheEnabled(true)
var files = File(sd_path, "Silk解码器/解码")
if(!files.exists()) {
files.mkdirs()
}
if(files.listFiles().size == 0) {
binding.tisp.text = "啥也没有"
binding.tisp.visibility = View.VISIBLE
return;
}
for(file in files.listFiles()) {
if(file.isFile){
var msg = Message()
msg.what = 0
msg.obj = file
handler.sendMessage(msg)
}
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when(item.getItemId()) {
android.R.id.home -> {
finish()
}
}
return false
}
} | 0 | C | 0 | 14 | 01be4f32a2c8c58be8c22e354a0e12de2dee0e2c | 3,475 | Silk-Decoder | MIT License |
src/test/kotlin/no/nav/personbruker/minesaker/api/saf/journalposter/objectmothers/AvsenderMottakerObjectMother.kt | joakibj | 458,172,377 | true | {"Kotlin": 170883, "Shell": 265, "Dockerfile": 250} | package no.nav.personbruker.minesaker.api.saf.journalposter.objectmothers
import no.nav.dokument.saf.selvbetjening.generated.dto.HentJournalposter
object AvsenderMottakerObjectMother {
fun giveMePerson(
ident: String = "123",
idType: HentJournalposter.AvsenderMottakerIdType = HentJournalposter.AvsenderMottakerIdType.FNR
) =
HentJournalposter.AvsenderMottaker(ident, idType)
fun giveMeOrganisasjon(
ident: String = "987654",
idType: HentJournalposter.AvsenderMottakerIdType = HentJournalposter.AvsenderMottakerIdType.ORGNR
) =
HentJournalposter.AvsenderMottaker(ident, idType)
}
| 0 | null | 0 | 0 | 51dd522799ecbd53207a55a44c8378ecdb819547 | 649 | mine-saker-api | MIT License |
glyphbutton/src/main/kotlin/org/librecode/glyphbutton/util/GlyphFont.kt | Librecode | 627,137,506 | false | null | package org.librecode.glyphbutton.util
import android.content.Context
import android.graphics.Typeface
import androidx.core.content.res.ResourcesCompat
import org.librecode.glyphbutton.R
object GlyphFont {
private var ICONS_FONT: Typeface? = null
fun getTypeface(context: Context): Typeface? {
if(ICONS_FONT == null) {
ICONS_FONT = ResourcesCompat.getFont(context, R.font.material_icons)
}
return ICONS_FONT
}
}
| 0 | Kotlin | 0 | 0 | 9058e3146f09c9f021230f9b522c5fdc98ef8c69 | 464 | MaterialGlyphButton | Apache License 2.0 |
compiler/src/main/kotlin/se/ansman/kotshi/Errors.kt | ansman | 95,685,398 | false | null | package se.ansman.kotshi
object Errors {
const val sealedClassMustBePolymorphic = "Sealed classes must be annotated with @Polymorphic"
const val nestedSealedClassMustBePolymorphic = "Children of a sealed class must be annotated with @Polymorphic"
const val defaultSealedValueIsGeneric = "The default value of a sealed class cannot be generic"
const val javaClassNotSupported = "Only Kotlin types are supported"
const val unsupportedSerializableType = "@JsonSerializable can only be applied to enums, objects, sealed classes and data classes"
const val privateClass = "Classes annotated with @JsonSerializable must public or internal"
const val privateDataClassConstructor = "The constructor must be public or internal to use @JsonSerializable on a data class"
const val polymorphicClassMustHaveJsonSerializable = "Classes annotated with @Polymorphic must also be annotated with @JsonSerializable"
const val polymorphicSubclassMustHaveJsonSerializable = "Sealed class subclasses must be annotated with @JsonSerializable"
const val polymorphicSubclassMustHavePolymorphicLabel = "Sealed class subclasses must be annotated with @PolymorphicLabel unless they are sealed classes or are annotated with @JsonDefaultValue"
const val dataClassCannotBeInner = "@JsonSerializable can't be applied to inner classes"
const val dataClassCannotBeLocal = "@JsonSerializable can't be applied to local classes"
const val noSealedSubclasses = "Sealed class has no implementations"
const val multipleJsonDefaultValueInEnum = "Only one enum entry can be annotated with @JsonDefaultValue"
const val multipleJsonDefaultValueInSealedClass = "Only one sealed subclass can be annotated with @JsonDefaultValue"
const val jsonDefaultValueAppliedToInvalidType = "@JsonDefaultValue can only be applied to enum entries, data classes and objects"
const val nestedSealedClassHasPolymorphicLabel = "Children of a sealed class with the same label key must not be annotated with @PolymorphicLabel"
const val nestedSealedClassMissingPolymorphicLabel = "Children of a sealed class with a different label key must be annotated with @PolymorphicLabel"
const val unsupportedFactoryType = "@KotshiJsonAdapterFactory can only be applied to objects, interfaces and abstract classes"
const val invalidRegisterAdapterType = "Only objects and non abstract classes can be annotated with @RegisterJsonAdapter"
const val invalidRegisterAdapterVisibility = "Types annotated @RegisterJsonAdapter must be public or internal"
const val abstractFactoriesAreDeprecated = "Having abstract factories is deprecated and will be removed in the future. Please migrate to use objects with delegation to the generated factory."
const val registeredAdapterWithoutFactory = "Found classes annotated with @RegisterJsonAdapter but no factory annotated with @KotshiJsonAdapterFactory"
const val nonDataObject = "JsonSerializable objects must be data objects. This warning will become an error in the future."
fun privateDataClassProperty(propertyName: String) = "Property $propertyName must be public or internal"
fun transientDataClassPropertyWithoutDefaultValue(propertyName: String) = "Transient property $propertyName must declare a default value"
fun ignoredDataClassPropertyWithoutDefaultValue(propertyName: String) = "Ignored property $propertyName must declare a default value"
fun nonIgnoredDataClassPropertyMustNotBeTransient(propertyName: String) = "Property $propertyName cannot have ignore = false and @Transient"
fun sealedSubclassMustNotHaveGeneric(typeVariableName: String) = "Could not determine type of type variable $typeVariableName. This can happen when sealed subclasses have type variables that are not present in all superclasses."
fun multipleFactories(names: List<String>) = "Multiple classes found with annotations @KotshiJsonAdapterFactory: ${names.sorted().joinToString()}"
fun invalidGeneratedAnnotation(name: String): String =
"Invalid value $name for option ${Options.generatedAnnotation}. Possible values are ${Options.possibleGeneratedAnnotations.keys.joinToString()}"
} | 5 | null | 42 | 759 | 9611441b4dcb400d1b219fa0692454a80f9c1ed3 | 4,167 | kotshi | Apache License 2.0 |
app/src/main/java/com/kleinreveche/playground/features/cafeteria/ui/CheckoutScreen.kt | KleinReveche | 537,970,451 | false | {"Kotlin": 293106} | package com.kleinreveche.playground.features.cafeteria.ui
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.kleinreveche.playground.R
import com.kleinreveche.playground.features.cafeteria.datasource.DataSource
import com.kleinreveche.playground.features.cafeteria.model.MenuItem
import com.kleinreveche.playground.features.cafeteria.model.OrderUiState
@Composable
fun CheckoutScreen(
orderUiState: OrderUiState,
onNextButtonClicked: () -> Unit,
onCancelButtonClicked: () -> Unit,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.padding(16.dp)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
Text(
text = stringResource(R.string.order_summary),
fontWeight = FontWeight.Bold
)
ItemSummary(item = orderUiState.entree)
ItemSummary(item = orderUiState.sideDish)
ItemSummary(item = orderUiState.accompaniment)
Divider(thickness = 1.dp, modifier = Modifier.padding(bottom = 8.dp))
OrderSubCost(
resourceId = R.string.subtotal,
price = orderUiState.itemTotalPrice.formatPrice(),
Modifier.align(Alignment.End)
)
OrderSubCost(
resourceId = R.string.tax,
price = orderUiState.orderTax.formatPrice(),
Modifier.align(Alignment.End)
)
Text(
text = stringResource(R.string.total, orderUiState.orderTotalPrice.formatPrice()),
modifier = Modifier.align(Alignment.End),
fontWeight = FontWeight.Bold
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp)
){
OutlinedButton(modifier = Modifier.weight(1f), onClick = onCancelButtonClicked) {
Text(stringResource(R.string.cancel).uppercase())
}
Button(
modifier = Modifier.weight(1f),
onClick = onNextButtonClicked
) {
Text(stringResource(R.string.submit).uppercase())
}
}
}
}
@Composable
fun ItemSummary(
item: MenuItem?,
modifier: Modifier = Modifier
) {
Row(
modifier = modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween
) {
Text(item?.name ?: "")
Text(item?.getFormattedPrice() ?: "")
}
}
@Composable
fun OrderSubCost(
@StringRes resourceId: Int,
price: String,
modifier: Modifier = Modifier
) {
Text(
text = stringResource(resourceId, price),
modifier = modifier
)
}
@Preview
@Composable
fun CheckoutScreenPreview() {
CheckoutScreen(
orderUiState = OrderUiState(
entree = DataSource.entreeMenuItems[0],
sideDish = DataSource.sideDishMenuItems[0],
accompaniment = DataSource.accompanimentMenuItems[0],
itemTotalPrice = 15.00,
orderTax = 1.00,
orderTotalPrice = 16.00
),
onNextButtonClicked = {},
onCancelButtonClicked = {}
)
}
| 0 | Kotlin | 0 | 0 | 062c3257ef1a434ed5b11ec947104908467e9f7f | 3,836 | Playground | Apache License 2.0 |
app/src/main/java/liou/rayyuan/ebooksearchtaiwan/view/ListDraggingViewHolderHelper.kt | YuanLiou | 111,275,765 | false | {"Kotlin": 284264, "Shell": 1384} | package liou.rayyuan.ebooksearchtaiwan.view
interface ListDraggingViewHolderHelper {
fun onListItemSelected()
fun onListItemCleared()
} | 1 | Kotlin | 4 | 40 | d767ad0d5b778b14fc68809e265bec5633b2aaed | 144 | TaiwanEbookSearch | MIT License |
buildSrc/src/main/java/com/paulrybitskyi/gamedge/plugins/GamedgeRemoteApiPlugin.kt | mars885 | 289,036,871 | false | {"Kotlin": 1318694, "Shell": 593} | package com.paulrybitskyi.gamedge.plugins
import com.android.build.api.dsl.LibraryExtension
import com.paulrybitskyi.gamedge.extensions.addBundle
import com.paulrybitskyi.gamedge.extensions.libs
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
class GamedgeRemoteApiPlugin : Plugin<Project> {
override fun apply(project: Project) = with(project) {
setupPlugins()
configurePlugins()
addDependencies()
}
private fun Project.setupPlugins(): Unit = with(plugins) {
apply(libs.plugins.androidLibrary.get().pluginId)
apply(libs.plugins.gamedgeAndroid.get().pluginId)
apply(libs.plugins.gamedgeDaggerHilt.get().pluginId)
apply(libs.plugins.gamedgeKotlinxSerialization.get().pluginId)
}
private fun Project.configurePlugins() {
configure<LibraryExtension> {
buildFeatures {
buildConfig = true
}
}
}
private fun Project.addDependencies(): Unit = with(dependencies) {
add("api", project(localModules.commonApi))
add("implementation", project(localModules.core))
add("implementation", libs.retrofit.get())
add("testImplementation", project(localModules.commonTesting))
addBundle("testImplementation", libs.bundles.testing.get())
addBundle("androidTestImplementation", libs.bundles.testingAndroid.get())
add("androidTestImplementation", libs.mockWebServer.get())
}
}
| 4 | Kotlin | 63 | 659 | 69b3ada08cb877af9b775c6a4f3d9eb1c3470d9c | 1,513 | gamedge | Apache License 2.0 |
core/designsystem/src/main/java/com/hankki/core/designsystem/component/button/HankkiButton.kt | Team-Hankki | 816,081,730 | false | {"Kotlin": 587452} | package com.hankki.core.designsystem.component.button
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.hankki.core.common.extension.bounceClick
import com.hankki.core.common.extension.noRippleClickable
import com.hankki.core.designsystem.theme.HankkijogboTheme
import com.hankki.core.designsystem.theme.Red400
import com.hankki.core.designsystem.theme.Red500
import com.hankki.core.designsystem.theme.White
@Composable
fun HankkiButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
textStyle: TextStyle = TextStyle.Default,
) {
Box(
contentAlignment = Alignment.Center,
modifier = modifier
.run {
if (enabled) bounceClick(
radius = 16f,
onClick = onClick
)
else this
}
.clip(RoundedCornerShape(16.dp))
.background(if (enabled) Red500 else Red400)
.padding(vertical = 15.dp, horizontal = 22.dp)
) {
Text(
text = text,
style = textStyle,
color = White
)
}
}
@Composable
fun HankkiTextButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
backgroundColor: Color? = null,
textStyle: TextStyle = TextStyle.Default,
) {
Box(
contentAlignment = Alignment.Center,
modifier = modifier
.run {
if (enabled) noRippleClickable(onClick = onClick)
else this
}
.clip(RoundedCornerShape(16.dp))
.background(backgroundColor ?: Color.Transparent)
.padding(vertical = 15.dp, horizontal = 22.dp)
) {
Text(
text = text,
style = textStyle,
color = Red500
)
}
}
@Composable
fun HankkiMediumButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
textStyle: TextStyle = TextStyle.Default,
backgroundColor: Color = if (enabled) Red500 else Red400,
) {
Box(
contentAlignment = Alignment.Center,
modifier = modifier
.run {
if (enabled) bounceClick(
radius = 16f,
onClick = onClick
)
else this
}
.clip(RoundedCornerShape(16.dp))
.background(backgroundColor)
.padding(vertical = 15.dp, horizontal = 36.dp)
) {
Text(
text = text,
style = textStyle,
color = White
)
}
}
@Composable
fun HankkiExpandedButton(
text: String,
onClick: () -> Unit,
modifier: Modifier = Modifier,
enabled: Boolean = true,
textStyle: TextStyle = TextStyle.Default,
textColor: Color = White,
backgroundColor: Color = if (enabled) Red500 else Red400,
) {
Box(
contentAlignment = Alignment.Center,
modifier = modifier
.run {
if (enabled) bounceClick(
onClick = onClick
)
else this
}
.background(backgroundColor)
.padding(vertical = 15.dp)
) {
Text(
text = text,
style = textStyle,
color = textColor
)
}
}
@Preview
@Composable
fun HankkiButtonPreview() {
HankkijogboTheme {
Column {
HankkiButton(text = "로그아웃", onClick = {})
HankkiTextButton(text = "돌아가기", onClick = {})
HankkiMediumButton(text = "확인", onClick = {})
HankkiExpandedButton(modifier = Modifier.fillMaxWidth(), text = "적용", onClick = {})
}
}
}
| 9 | Kotlin | 0 | 43 | e83ea4cf5cfd0b23d71da164090c29ba0e253b18 | 4,409 | hankki-android | Apache License 2.0 |
src/i_introduction/_6_Data_Classes/DataClasses.kt | joethorngren | 91,930,087 | false | {"XML": 8, "Gradle": 1, "Ignore List": 1, "Text": 1, "Markdown": 1, "Kotlin": 112, "Java": 11} | package i_introduction._6_Data_Classes
import util.TODO
import util.doc6
fun todoTask6(): Nothing = TODO(
"""
Convert 'JavaCode6.Person' class to Kotlin.
Then add a modifier `data` to the resulting class.
This annotation means the compiler will generate a bunch of useful methods in this class: `equals`/`hashCode`, `toString` and some others.
The `task6` function should return a list of persons.
""",
documentation = doc6(),
references = { JavaCode6.Person("Alice", 29) }
)
data class Person(val name: String, val age: Int)
fun task6(): List<Person> {
return listOf(Person(name = "Alice", age = 29), Person(name = "Bob", age = 31))
}
| 1 | null | 1 | 1 | 08e08ef7570cbb995c90fada73505d72033119fe | 693 | kotlin-koans | MIT License |
shared/src/commonMain/kotlin/likco.likfit/ui/GenderSelection.kt | LikDan | 653,590,458 | false | null | package likco.likfit.ui
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Button
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.Icon
import androidx.compose.material.ListItem
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Info
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalUriHandler
import androidx.compose.ui.unit.dp
import likco.likfit.i18n.Languages
import likco.likfit.i18n.Strings
import likco.likfit.models.Gender
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun GenderSelection(i18n: Languages, back: () -> Unit, select: (Gender) -> Unit) = Column {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth()
) {
Button(onClick = back) {
Icon(Icons.Default.ArrowBack, "back")
}
val urlHandler = LocalUriHandler.current
Button(onClick = { urlHandler.openUri(Gender.URL) }) {
Icon(Icons.Default.Info, "source")
Spacer(modifier = Modifier.width(8.dp))
Text(i18n(Strings.GENDERS_SOURCE))
}
}
Text(i18n(Strings.GENDER_NOT_FOUND))
LazyColumn {
items(Gender.values()) {
ListItem(
modifier = Modifier
.fillMaxWidth()
.clickable { select(it) }
) {
Text(i18n(it.toString()))
}
}
}
}
| 0 | Kotlin | 0 | 0 | ab39c86e6380b8e7a5ad6975b986ef7f25660efd | 2,055 | LikFit | Apache License 2.0 |
app/src/main/java/com/cornerjob/marvelheroes/data/model/mapper/MarvelHeroMapper.kt | Rigogp2610 | 340,006,060 | false | null | package com.cornerjob.marvelheroes.data.model.mapper
import com.cornerjob.marvelheroes.data.model.MarvelHeroResponse
import com.cornerjob.marvelheroes.domain.model.MarvelHeroEntity
class MarvelHeroMapper : Mapper<MarvelHeroResponse, MarvelHeroEntity> {
override fun transform(input: MarvelHeroResponse): MarvelHeroEntity =
MarvelHeroEntity(
name = input.name,
photoUrl = input.thumbnail.path + "." + input.thumbnail.extension,
description = input.description
)
override fun transformList(inputList: List<MarvelHeroResponse>): List<MarvelHeroEntity> =
inputList.map { transform(it) }
} | 0 | Kotlin | 0 | 0 | ed265b89c642996663a6ddb52d669f3e00fdc96a | 693 | marvel | MIT License |
idea/tests/testData/inspectionsLocal/redundantSetter/lowerVisibility2.kt | JetBrains | 278,369,660 | false | null | // PROBLEM: none
class Test {
internal var x = 1
private <caret>set
} | 0 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 81 | intellij-kotlin | Apache License 2.0 |
eclipse-pde-partial-idea/src/main/kotlin/cn/varsa/idea/pde/partial/plugin/dom/completion/MenuContributionURICompletionContributor.kt | JaneWardSandy | 361,593,873 | false | null | package cn.varsa.idea.pde.partial.plugin.dom.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.*
import com.intellij.openapi.editor.*
import com.intellij.patterns.*
import com.intellij.psi.*
import com.intellij.psi.xml.*
import com.intellij.util.*
class MenuContributionURICompletionContributor : CompletionContributor() {
init {
extend(
CompletionType.BASIC,
PlatformPatterns.psiElement(XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN)
.withSuperParent(2, PlatformPatterns.psiElement(PsiElement::class.java).withName("locationURI"))
.withSuperParent(3, PlatformPatterns.psiElement(XmlTag::class.java).withName("menuContribution")),
SchemeProvider()
)
}
}
private val addResultWithCaret = { value: String, result: CompletionResultSet, caret: String ->
result.addElement(LookupElementBuilder.create(value).withCaseSensitivity(false).withInsertHandler { context, _ ->
context.setAddCompletionChar(false)
EditorModificationUtil.insertStringAtCaret(context.editor, caret)
context.commitDocument()
})
}
class SchemeProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(
parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet
) {
arrayOf("menu", "popup", "toolbar").forEach { addResultWithCaret(it, result, ":") }
}
}
| 3 | Kotlin | 6 | 9 | 5c8192b92d5b0d3eba9e7a6218d180a0996aea49 | 1,469 | eclipse-pde-partial-idea | Apache License 2.0 |
diktat-rules/src/test/kotlin/org/cqfn/diktat/ruleset/chapter3/EmptyBlockWarnTest.kt | petertrr | 284,037,259 | false | null | package org.cqfn.diktat.ruleset.chapter3
import com.pinterest.ktlint.core.LintError
import org.cqfn.diktat.common.config.rules.RulesConfig
import org.cqfn.diktat.ruleset.constants.Warnings.EMPTY_BLOCK_STRUCTURE_ERROR
import org.cqfn.diktat.ruleset.rules.DIKTAT_RULE_SET_ID
import org.cqfn.diktat.ruleset.rules.EmptyBlock
import org.cqfn.diktat.util.lintMethod
import org.junit.jupiter.api.Test
class EmptyBlockWarnTest {
private val ruleId = "$DIKTAT_RULE_SET_ID:empty-block-structure"
private val rulesConfigListIgnoreEmptyBlock: List<RulesConfig> = listOf(
RulesConfig(EMPTY_BLOCK_STRUCTURE_ERROR.name, true,
mapOf("styleEmptyBlockWithNewline" to "False"))
)
private val rulesConfigListEmptyBlockExist: List<RulesConfig> = listOf(
RulesConfig(EMPTY_BLOCK_STRUCTURE_ERROR.name, true,
mapOf("allowEmptyBlocks" to "True"))
)
@Test
fun `check if expression with empty else block`() {
lintMethod(EmptyBlock(),
"""
|fun foo() {
| if (x < -5) {
| goo()
| }
| else {
| }
|}
""".trimMargin(),
LintError(5,10,ruleId,"${EMPTY_BLOCK_STRUCTURE_ERROR.warnText()} empty blocks are forbidden unless it is function with override keyword", true)
)
}
@Test
fun `check if expression with empty else block with config`() {
lintMethod(EmptyBlock(),
"""
|fun foo() {
| if (x < -5) {
| goo()
| }
| else {}
|}
""".trimMargin(),
LintError(5,10,ruleId,"${EMPTY_BLOCK_STRUCTURE_ERROR.warnText()} empty blocks are forbidden unless it is function with override keyword", true),
rulesConfigList = rulesConfigListIgnoreEmptyBlock
)
}
@Test
fun `check fun expression with empty block and override annotation`() {
lintMethod(EmptyBlock(),
"""
|override fun foo() {
|}
""".trimMargin()
)
}
@Test
fun `check if expression with empty else block but with permission to use empty block`() {
lintMethod(EmptyBlock(),
"""
|fun foo() {
| if (x < -5) {
| goo()
| }
| else {
| }
|}
""".trimMargin(),
rulesConfigList = rulesConfigListEmptyBlockExist
)
}
}
| 2 | null | 0 | 1 | 45231eddab4e968db6f19a6ad82ae96f14223385 | 2,801 | diktat-backup | MIT License |
android/MyApplication/app/src/main/java/cn/magicalsheep/myapplication/SimpleDialog.kt | MagicalSheep | 570,933,605 | false | {"Kotlin": 287381, "Java": 145241, "C": 78070, "Rust": 41263, "HTML": 17978, "CSS": 6500, "Batchfile": 3923, "CMake": 777} | package cn.magicalsheep.myapplication
import android.app.AlertDialog
import android.app.Dialog
import android.os.Bundle
import androidx.fragment.app.DialogFragment
class SimpleDialog : DialogFragment() {
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return activity?.let {
val builder = AlertDialog.Builder(it)
builder.setMessage(R.string.simple_dialog)
.setNeutralButton(R.string.close) { _, _ -> }
builder.create()
} ?: throw IllegalStateException("Activity cannot be null")
}
} | 0 | Kotlin | 6 | 44 | a550ba111bfbc715ae4bb1bff15eed757bb749bb | 580 | lab | MIT License |
native/swift/sir/tree-generator/src/org/jetbrains/kotlin/sir/tree/generator/Main.kt | JetBrains | 3,432,266 | false | {"Kotlin": 78150544, "Java": 6691623, "Swift": 4062767, "C": 2609482, "C++": 1967564, "Objective-C++": 169966, "JavaScript": 135932, "Python": 48711, "Shell": 34712, "TypeScript": 22800, "Lex": 18369, "Groovy": 17400, "Objective-C": 15578, "Batchfile": 11746, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "LLVM": 395, "Scala": 80} | /*
* Copyright 2010-2023 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.sir.tree.generator
import org.jetbrains.kotlin.generators.tree.printer.generateTree
import org.jetbrains.kotlin.sir.tree.generator.model.Element
import org.jetbrains.kotlin.sir.tree.generator.printer.*
import org.jetbrains.kotlin.utils.bind
import java.io.File
internal const val BASE_PACKAGE = "org.jetbrains.kotlin.sir"
typealias Model = org.jetbrains.kotlin.generators.tree.Model<Element>
fun main(args: Array<String>) {
val generationPath = args.firstOrNull()?.let { File(it) }
?: File("./native/swift/sir/gen/").canonicalFile
val model = SwiftIrTree.build()
generateTree(
generationPath,
"native/swift/sir/tree-generator/Readme.md",
model,
pureAbstractElementType,
::ElementPrinter,
emptyList(),
ImplementationConfigurator,
BuilderConfigurator(model.elements),
::ImplementationPrinter,
::BuilderPrinter,
)
}
| 179 | Kotlin | 5771 | 47,508 | 5fa326aec313d6e9bb0b461664c38d445eac72e9 | 1,161 | kotlin | Apache License 2.0 |
src/main/kotlin/dev/mythicdrops/gradle/conventions/MythicDropsJavaPlatformPlugin.kt | MythicDrops | 391,648,860 | false | null | package dev.mythicdrops.gradle.conventions
import org.gradle.api.Project
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.withType
/**
* Plugin that configures Maven publications for Java Platforms.
*/
open class MythicDropsJavaPlatformPlugin : DependentPlugin("Java", "java-platform") {
override fun configureProject(target: Project) {
target.pluginManager.withPlugin("maven-publish") {
target.extensions.getByType<PublishingExtension>().publications.withType<MavenPublication> {
from(target.components.getByName("javaPlatform"))
}
}
}
}
| 6 | Kotlin | 0 | 0 | ee9677a65e4f1ebdbfa1c5e8ec4d574b33d1a989 | 729 | mythicdrops-gradle-plugin | MIT License |
app/src/main/java/jp/juggler/subwaytooter/util/NotificationHelper.kt | geckour | 194,987,270 | true | {"Kotlin": 2079900, "Java": 2066023, "Perl": 55985} | package jp.juggler.subwaytooter.util
import android.annotation.TargetApi
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import jp.juggler.subwaytooter.R
import jp.juggler.subwaytooter.table.SavedAccount
import jp.juggler.util.LogCategory
object NotificationHelper {
private val log = LogCategory("NotificationHelper")
@TargetApi(26)
fun createNotificationChannel(context : Context, account : SavedAccount) : NotificationChannel {
return createNotificationChannel(context, account.acct, account.acct, context.getString(R.string.notification_channel_description, account.acct), NotificationManager.IMPORTANCE_DEFAULT // : NotificationManager.IMPORTANCE_LOW;
)
}
@TargetApi(26)
fun createNotificationChannel(
context : Context, channel_id : String // id
, name : String // The user-visible name of the channel.
, description : String? // The user-visible description of the channel.
, importance : Int
) : NotificationChannel {
val notification_manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
?: throw NotImplementedError("missing NotificationManager system service")
var channel : NotificationChannel? = null
try {
channel = notification_manager.getNotificationChannel(channel_id)
} catch(ex : Throwable) {
log.trace(ex)
}
if(channel == null) {
channel = NotificationChannel(channel_id, name, importance)
}
channel.name = name
channel.importance = importance
if(description != null) channel.description = description
notification_manager.createNotificationChannel(channel)
return channel
}
}
| 0 | Kotlin | 0 | 0 | afbe3927e1c832807c3f2d8d8421b97623a4a2b7 | 1,665 | SubwayTooter | Apache License 2.0 |
id/src/main/kotlin/ru/kyamshanov/mission/client/issuer/JwtSigner.kt | KYamshanov | 672,550,797 | false | {"Kotlin": 148114, "Java": 32298, "CSS": 7503, "FreeMarker": 1980, "Shell": 1498, "Dockerfile": 1201} | package ru.kyamshanov.mission.client.issuer
import io.jsonwebtoken.JwtBuilder
import io.jsonwebtoken.Jwts
import java.security.KeyPair
import java.util.*
val keyPair: KeyPair = Jwts.SIG.RS256.keyPair().build() //or RS384, RS512, PS256, etc...
val kid = UUID.randomUUID().toString()
/**
* The Issuer for provide access and refresh tokens
*/
interface JwtSigner {
fun sign(rawJwt: JwtBuilder): String
}
class SignedJwtSigner(
private val issuerUrl: String,
) : JwtSigner {
override fun sign(rawJwt: JwtBuilder): String =
rawJwt.header()
.keyId(kid)
.and()
.claim("iss", issuerUrl)
.signWith(keyPair.private)
.compact()
} | 6 | Kotlin | 0 | 0 | b93ad1b09778b43521733da3cd95bab4e5c856ad | 707 | Mission-backend | Apache License 2.0 |
backend/src/main/java/radar/ApplicationConfig.kt | community-graph | 107,399,783 | false | {"JavaScript": 26063, "Kotlin": 19083, "HTML": 9320, "SCSS": 6334, "CSS": 444} | package kudos
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.module.kotlin.KotlinModule
import org.neo4j.driver.v1.AuthTokens
import org.neo4j.driver.v1.Config
import org.neo4j.driver.v1.Driver
import org.neo4j.driver.v1.GraphDatabase
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.domain.EntityScan
import org.springframework.context.annotation.Bean
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
@SpringBootApplication
@EntityScan("kudos.domain.model.persistent.entities.ogm")
class ApplicationConfig {
companion object {
@JvmStatic
fun main(args: Array<String>) {
SpringApplication.run(ApplicationConfig::class.java, *args)
}
}
@Bean
fun kotlinPropertyConfigurer(): PropertySourcesPlaceholderConfigurer {
val propertyConfigurer = PropertySourcesPlaceholderConfigurer()
propertyConfigurer.setPlaceholderPrefix("@{")
propertyConfigurer.setPlaceholderSuffix("}")
propertyConfigurer.setIgnoreUnresolvablePlaceholders(true)
return propertyConfigurer
}
@Bean
fun defaultPropertyConfigurer() = PropertySourcesPlaceholderConfigurer()
@Bean
fun mapperConfigurer() = Jackson2ObjectMapperBuilder().apply {
serializationInclusion(JsonInclude.Include.NON_NULL)
failOnUnknownProperties(true)
featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
indentOutput(true)
modules(listOf(KotlinModule()))
}
@Bean
fun corsConfigurer(): WebMvcConfigurer {
return object : WebMvcConfigurerAdapter() {
override fun addCorsMappings(registry: CorsRegistry?) {
registry!!.addMapping("/**").allowedOrigins("*")
}
}
}
}
| 4 | JavaScript | 2 | 2 | 356eb3188cff3f1090f427f65557c8b0e1c3518d | 2,284 | community-radar | Apache License 2.0 |
misk-hibernate/src/test/kotlin/misk/hibernate/MoviesTestModule.kt | cashapp | 113,107,217 | false | {"Kotlin": 3843790, "TypeScript": 232251, "Java": 83564, "JavaScript": 5073, "Shell": 3462, "HTML": 1536, "CSS": 58} | package misk.hibernate
import com.google.inject.util.Modules
import misk.MiskTestingServiceModule
import misk.config.MiskConfig
import misk.environment.DeploymentModule
import misk.inject.KAbstractModule
import misk.jdbc.DataSourceClusterConfig
import misk.jdbc.DataSourceConfig
import misk.jdbc.DataSourceType
import misk.logging.LogCollectorModule
import misk.testing.MockTracingBackendModule
import misk.time.FakeClockModule
import wisp.deployment.TESTING
/** This module creates movies, actors, and characters tables for several Hibernate tests. */
class MoviesTestModule(
private val type: DataSourceType = DataSourceType.VITESS_MYSQL,
private val scaleSafetyChecks: Boolean = false,
private val entitiesModule: HibernateEntityModule = object :
HibernateEntityModule(Movies::class) {
override fun configureHibernate() {
addEntities(DbMovie::class, DbActor::class, DbCharacter::class)
}
},
) : KAbstractModule() {
override fun configure() {
install(LogCollectorModule())
install(
Modules.override(MiskTestingServiceModule()).with(
FakeClockModule(),
MockTracingBackendModule()
)
)
install(DeploymentModule(TESTING))
val config = MiskConfig.load<MoviesConfig>("moviestestmodule", TESTING)
val dataSourceConfig = selectDataSourceConfig(config)
install(
HibernateTestingModule(
Movies::class,
dataSourceConfig,
scaleSafetyChecks = scaleSafetyChecks
)
)
install(
HibernateModule(
Movies::class, MoviesReader::class,
DataSourceClusterConfig(writer = dataSourceConfig, reader = dataSourceConfig)
)
)
install(entitiesModule)
}
internal fun selectDataSourceConfig(config: MoviesConfig): DataSourceConfig {
return when (type) {
DataSourceType.VITESS_MYSQL -> config.vitess_mysql_data_source
DataSourceType.MYSQL -> config.mysql_data_source
DataSourceType.COCKROACHDB -> config.cockroachdb_data_source
DataSourceType.POSTGRESQL -> config.postgresql_data_source
DataSourceType.TIDB -> config.tidb_data_source
DataSourceType.HSQLDB -> throw RuntimeException("Not supported (yet?)")
}
}
}
| 169 | Kotlin | 169 | 400 | 13dcba0c4e69cc2856021270c99857e7e91af27d | 2,198 | misk | Apache License 2.0 |
fluxy/src/main/java/com/hoopcarpool/fluxy/Annotations.kt | hoop-carpool | 233,216,485 | false | null | package com.hoopcarpool.fluxy
import kotlin.RequiresOptIn.Level
@Retention(value = AnnotationRetention.BINARY)
@RequiresOptIn(level = Level.WARNING)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.TYPEALIAS, AnnotationTarget.PROPERTY)
annotation class FluxyPreview
@Retention(value = AnnotationRetention.BINARY)
@RequiresOptIn(level = Level.ERROR)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.TYPEALIAS, AnnotationTarget.PROPERTY)
annotation class FluxyPreviewCritical
| 1 | Kotlin | 2 | 26 | d16bbe3a1f6127e74839fc37966dc9d8fd08911f | 531 | fluxy | MIT License |
uast/uast-kotlin-fir/src/org/jetbrains/uast/kotlin/FirKotlinUastLanguagePlugin.kt | JetBrains | 278,369,660 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import com.intellij.lang.Language
import com.intellij.openapi.components.ServiceManager
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.DEFAULT_TYPES_LIST
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.UastLanguagePlugin
import org.jetbrains.uast.kotlin.FirKotlinConverter.convertDeclarationOrElement
import org.jetbrains.uast.kotlin.psi.UastFakeLightPrimaryConstructor
class FirKotlinUastLanguagePlugin : UastLanguagePlugin {
override val priority: Int = 10
override val language: Language
get() = KotlinLanguage.INSTANCE
override fun isFileSupported(fileName: String): Boolean {
return fileName.endsWith(".kt", false) || fileName.endsWith(".kts", false)
}
private val PsiElement.isJvmElement: Boolean
get() {
val resolveProvider = ServiceManager.getService(project, FirKotlinUastResolveProviderService::class.java)
return resolveProvider.isJvmElement(this)
}
override fun convertElement(element: PsiElement, parent: UElement?, requiredType: Class<out UElement>?): UElement? {
if (!element.isJvmElement) return null
return convertDeclarationOrElement(element, parent, elementTypes(requiredType))
}
override fun convertElementWithParent(element: PsiElement, requiredType: Class<out UElement>?): UElement? {
if (!element.isJvmElement) return null
return convertDeclarationOrElement(element, null, elementTypes(requiredType))
}
@Suppress("UNCHECKED_CAST")
override fun <T : UElement> convertElementWithParent(element: PsiElement, requiredTypes: Array<out Class<out T>>): T? {
if (!element.isJvmElement) return null
val nonEmptyRequiredTypes = requiredTypes.nonEmptyOr(DEFAULT_TYPES_LIST)
return convertDeclarationOrElement(element, null, nonEmptyRequiredTypes) as? T
}
@Suppress("UNCHECKED_CAST")
override fun <T : UElement> convertToAlternatives(element: PsiElement, requiredTypes: Array<out Class<out T>>): Sequence<T> {
if (!element.isJvmElement) return emptySequence()
return when {
element is KtFile ->
FirKotlinConverter.convertKtFile(element, null, requiredTypes) as Sequence<T>
element is KtClassOrObject ->
FirKotlinConverter.convertClassOrObject(element, null, requiredTypes) as Sequence<T>
element is KtProperty && !element.isLocal ->
FirKotlinConverter.convertNonLocalProperty(element, null, requiredTypes) as Sequence<T>
element is KtParameter ->
FirKotlinConverter.convertParameter(element, null, requiredTypes) as Sequence<T>
element is UastFakeLightPrimaryConstructor ->
FirKotlinConverter.convertFakeLightConstructorAlternatives(element, null, requiredTypes) as Sequence<T>
else ->
sequenceOf(convertElementWithParent(element, requiredTypes.nonEmptyOr(DEFAULT_TYPES_LIST)) as? T).filterNotNull()
}
}
override fun getConstructorCallExpression(
element: PsiElement,
fqName: String
): UastLanguagePlugin.ResolvedConstructor? {
TODO("Not yet implemented")
}
override fun getMethodCallExpression(
element: PsiElement,
containingClassFqName: String?,
methodName: String
): UastLanguagePlugin.ResolvedMethod? {
TODO("Not yet implemented")
}
override fun isExpressionValueUsed(element: UExpression): Boolean {
TODO("Not yet implemented")
}
}
| 214 | null | 4829 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 3,862 | intellij-kotlin | Apache License 2.0 |
Demos/Javalin/src/main/kotlin/com/groupdocs/ui/model/DescriptionResponse.kt | groupdocs-signature | 85,180,249 | false | null | package com.groupdocs.ui.model
data class LoadDocumentEntity (
/**
* Document Guid
*/
val guid: String,
/**
* list of pages
*/
val pages: MutableList<PageDescriptionEntity> = mutableListOf(),
/**
* Restriction for printing pdf files in viewer
*/
val printAllowed: Boolean = true
)
/**
* PageDescriptionEntity
*
* @author Aspose Pty Ltd
*/
open class PageDescriptionEntity (
open var data: String? = null,
open val angle: Int = 0,
open val width: Int = 0,
open val height: Int = 0,
open var number: Int = 0,
)
| 4 | null | 7 | 3 | 6febc7edac719c1bc5bae0a611e86f72c9fdfa27 | 594 | GroupDocs.Signature-for-Java | MIT License |
app/src/main/java/com/revolgenx/anilib/notification/presenter/NotificationPresenter.kt | AniLibApp | 244,410,204 | false | null | package com.revolgenx.anilib.notification.presenter
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import com.otaliastudios.elements.Element
import com.otaliastudios.elements.Page
import com.revolgenx.anilib.R
import com.revolgenx.anilib.constant.NotificationUnionType
import com.revolgenx.anilib.media.data.meta.MediaInfoMeta
import com.revolgenx.anilib.databinding.NotificationPresenterLayoutBinding
import com.revolgenx.anilib.common.event.OpenActivityInfoEvent
import com.revolgenx.anilib.common.event.OpenMediaInfoEvent
import com.revolgenx.anilib.common.event.OpenUserProfileEvent
import com.revolgenx.anilib.notification.data.model.FollowingNotificationModel
import com.revolgenx.anilib.notification.data.model.activity.*
import com.revolgenx.anilib.notification.data.model.media.MediaDataChangeNotificationModel
import com.revolgenx.anilib.notification.data.model.media.MediaDeletionNotificationModel
import com.revolgenx.anilib.notification.data.model.media.MediaMergeNotificationModel
import com.revolgenx.anilib.notification.data.model.media.RelatedMediaNotificationModel
import com.revolgenx.anilib.notification.data.model.thread.*
import com.revolgenx.anilib.common.presenter.BasePresenter
import com.revolgenx.anilib.notification.data.model.NotificationModel
import com.revolgenx.anilib.util.openLink
import java.util.*
class NotificationPresenter(context: Context) :
BasePresenter<NotificationPresenterLayoutBinding, NotificationModel>(context) {
override val elementTypes: Collection<Int>
get() = listOf(0)
override fun bindView(
inflater: LayoutInflater,
parent: ViewGroup?,
elementType: Int
): NotificationPresenterLayoutBinding {
return NotificationPresenterLayoutBinding.inflate(inflater, parent, false)
}
override fun onBind(page: Page, holder: Holder, element: Element<NotificationModel>) {
super.onBind(page, holder, element)
val item = element.data ?: return
holder.getBinding()?.apply {
notificationReasonTv.text = ""
notificationReasonTv.setOnClickListener(null)
when (item.notificationUnionType) {
NotificationUnionType.ACTIVITY_MESSAGE -> {
val activity = item as ActivityMessageNotification
createActivityNotif(activity)
root.setOnClickListener {
openActivityLink(activity)
}
}
NotificationUnionType.ACTIVITY_REPLY -> {
val activity = item as ActivityReplyNotification
createActivityNotif(activity)
root.setOnClickListener {
openActivityLink(activity)
}
}
NotificationUnionType.ACTIVITY_MENTION -> {
val activity = item as ActivityMentionNotification
createActivityNotif(activity)
root.setOnClickListener {
openActivityLink(activity)
}
}
NotificationUnionType.ACTIVITY_LIKE -> {
val activity = item as ActivityLikeNotification
createActivityNotif(activity)
root.setOnClickListener {
openActivityLink(activity)
}
}
NotificationUnionType.ACTIVITY_REPLY_LIKE -> {
val activity = item as ActivityReplyLikeNotification
createActivityNotif(activity)
root.setOnClickListener {
openActivityLink(activity)
}
}
NotificationUnionType.ACTIVITY_REPLY_SUBSCRIBED -> {
val activity = item as ActivityReplySubscribedNotification
createActivityNotif(activity)
root.setOnClickListener {
openActivityLink(activity)
}
}
NotificationUnionType.THREAD_COMMENT_MENTION -> {
val thread = item as ThreadCommentMentionNotification
createThreadNotif(thread)
root.setOnClickListener {
openThreadLink(thread)
}
}
NotificationUnionType.THREAD_SUBSCRIBED -> {
val thread = item as ThreadCommentSubscribedNotification
createThreadNotif(thread)
root.setOnClickListener {
openThreadLink(thread)
}
}
NotificationUnionType.THREAD_COMMENT_REPLY -> {
val thread = item as ThreadCommentReplyNotification
createThreadNotif(thread)
root.setOnClickListener {
openThreadLink(thread)
}
}
NotificationUnionType.THREAD_LIKE -> {
val thread = item as ThreadLikeNotification
createThreadNotif(thread)
root.setOnClickListener {
openThreadLink(thread)
}
}
NotificationUnionType.THREAD_COMMENT_LIKE -> {
val thread = item as ThreadCommentLikeNotification
createThreadNotif(thread)
root.setOnClickListener {
openThreadLink(thread)
}
}
NotificationUnionType.AIRING -> {
(item as AiringNotificationModel).let {
notificationMediaDrawee.setImageURI(
it.media?.coverImage?.image()
)
notificationCreatedTv.text = it.createdAt
notificationTitleTv.text = String.format(
Locale.getDefault(),
context.getString(R.string.episode_airing_notif),
it.contexts!![0],
it.episode,
it.contexts!![1],
it.media?.title?.title(),
it.contexts!![2]
)
root.setOnClickListener { _ ->
OpenMediaInfoEvent(
MediaInfoMeta(
it.media?.id,
it.media?.type!!,
it.media?.title!!.romaji!!,
it.media?.coverImage!!.image(),
it.media?.coverImage!!.largeImage,
it.media?.bannerImage
)
).postEvent
}
}
}
NotificationUnionType.FOLLOWING -> {
(item as FollowingNotificationModel)
notificationMediaDrawee.setImageURI(item.userModel?.avatar?.image)
notificationTitleTv.text = context.getString(R.string.s_space_s)
.format(item.userModel?.name, item.context)
notificationCreatedTv.text = item.createdAt
root.setOnClickListener {
OpenUserProfileEvent(item.userModel?.id).postEvent
}
}
NotificationUnionType.RELATED_MEDIA_ADDITION -> {
(item as RelatedMediaNotificationModel).let {
notificationMediaDrawee.setImageURI(
it.media?.coverImage?.image()
)
notificationCreatedTv.text = it.createdAt
notificationTitleTv.text =
context.getString(R.string.s_space_s).format(
it.media?.title?.title(), it.context
)
root.setOnClickListener { _ ->
OpenMediaInfoEvent(
MediaInfoMeta(
it.media?.id,
it.media?.type,
it.media?.title!!.romaji!!,
it.media?.coverImage!!.image(),
it.media?.coverImage!!.largeImage,
it.media?.bannerImage
)
).postEvent
}
}
}
NotificationUnionType.MEDIA_DATA_CHANGE -> {
(item as MediaDataChangeNotificationModel).let {
root.setOnClickListener { _ ->
OpenMediaInfoEvent(
MediaInfoMeta(
it.media?.id,
it.media?.type,
it.media?.title!!.romaji!!,
it.media?.coverImage!!.image(),
it.media?.coverImage!!.largeImage,
it.media?.bannerImage
)
).postEvent
}
notificationMediaDrawee.setImageURI(
it.media?.coverImage?.image()
)
notificationCreatedTv.text = it.createdAt
notificationTitleTv.text =
context.getString(R.string.s_space_s).format(
it.media?.title?.title(), it.context
)
notificationReasonTv.setText(R.string.show_reason)
notificationReasonTv.setOnClickListener { _ ->
notificationReasonTv.text = it.reason
}
}
}
NotificationUnionType.MEDIA_MERGE -> {
(item as MediaMergeNotificationModel).let {
root.setOnClickListener { _ ->
OpenMediaInfoEvent(
MediaInfoMeta(
it.media?.id,
it.media?.type,
it.media?.title!!.romaji!!,
it.media?.coverImage!!.image(),
it.media?.coverImage!!.largeImage,
it.media?.bannerImage
)
).postEvent
}
notificationMediaDrawee.setImageURI(
it.media?.coverImage?.image()
)
notificationCreatedTv.text = it.createdAt
notificationTitleTv.text =
context.getString(R.string.s_space_s).format(
it.media?.title?.title(), it.context
)
notificationReasonTv.setText(R.string.show_reason)
notificationReasonTv.setOnClickListener { _ ->
notificationReasonTv.text = it.reason
}
}
}
NotificationUnionType.MEDIA_DELETION -> {
(item as MediaDeletionNotificationModel).let {
notificationMediaDrawee.setActualImageResource(R.drawable.ic_delete)
notificationTitleTv.text = context.getString(R.string.s_space_s)
.format(it.deletedMediaTitle, it.context)
notificationCreatedTv.text = it.createdAt
notificationReasonTv.setText(R.string.show_reason)
notificationReasonTv.setOnClickListener { _ ->
notificationReasonTv.text = it.reason
}
}
}
}
}
}
private fun openThreadLink(thread: ThreadNotification) {
thread.threadModel?.siteUrl?.let {
context.openLink(it)
}
}
private fun openActivityLink(activity: ActivityNotification) {
OpenActivityInfoEvent(activity.activityId ?: -1).postEvent
}
private fun NotificationPresenterLayoutBinding.createActivityNotif(item: ActivityNotification) {
notificationMediaDrawee.setImageURI(item.user?.avatar?.image)
notificationTitleTv.text = context.getString(R.string.s_space_s)
.format(item.user?.name, item.context)
notificationCreatedTv.text = item.createdAt
}
private fun NotificationPresenterLayoutBinding.createThreadNotif(item: ThreadNotification) {
notificationMediaDrawee.setImageURI(item.user?.avatar?.image)
notificationTitleTv.text = context.getString(R.string.thread_notif_s)
.format(item.user?.name, item.context, item.threadModel?.title)
notificationCreatedTv.text = item.createdAt
}
} | 36 | null | 3 | 76 | b3caec5c00779c878e4cf22fb7d2034aefbeee54 | 13,601 | AniLib | Apache License 2.0 |
src/vision/alter/telekot/telegram/model/ChatPhoto.kt | alter-vision | 261,156,045 | false | null | package vision.alter.telekot.telegram.model
import kotlinx.serialization.Serializable
import vision.alter.telekot.telegram.model.markers.TelegramObject
/**
* This object represents a chat photo (https://core.telegram.org/bots/api#chatphoto).
*/
@Serializable
data class ChatPhoto(
/**
* File identifier of small (160x160) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed.
*/
val smallFileId: String = "",
/**
* Unique file identifier of small (160x160) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
*/
val smallFileUniqueId: String = "",
/**
* File identifier of big (640x640) chat photo. This file_id can be used only for photo download and only for as long as the photo is not changed.
*/
val bigFileId: String = "",
/**
* Unique file identifier of big (640x640) chat photo, which is supposed to be the same over time and for different bots. Can't be used to download or reuse the file.
*/
val bigFileUniqueId: String = ""
) : TelegramObject
| 10 | Kotlin | 0 | 2 | 28943db77d5ed7b0759ef180e61c1db78032a408 | 1,159 | telekot | Apache License 2.0 |
engine/src/main/kotlin/com/delphix/sdk/objects/UserObject.kt | CloudSurgeon | 212,463,880 | false | null | /**
* Copyright (c) 2019 by Delphix. All rights reserved.
*/
package com.delphix.sdk.objects
/**
* Super schema for all schemas representing user-visible objects.
*/
interface UserObject : PersistentObject {
val name: String?//Object name.
override val reference: String?//The object reference.
override val namespace: String?//Alternate namespace for this object, for replicated and restored objects.
override val type: String
override fun toMap(): Map<String, Any?>
}
| 0 | null | 0 | 1 | 819f7e9ea1bb0c675e0d04d61cf05302c488d74f | 495 | titan-server | Apache License 2.0 |
dccomics/src/main/java/com/cubidevs/dccomics/data/ApiFactory.kt | Team-111-MisionTic | 426,814,942 | false | null | package com.cubidevs.dccomics.data
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object ApiFactory {
private const val urlAPI = "https://my-json-server.typicode.com/"
private val okkHttpClient = OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
.build()
val retrofit: ApiService = Retrofit.Builder()
.baseUrl(urlAPI)
.addConverterFactory(GsonConverterFactory.create())
.client(okkHttpClient)
.build()
.run{
create(ApiService::class.java)
}
} | 0 | null | 2 | 1 | 5966f252450af93ef4499d182a8952f4f9aa9848 | 700 | Team-111 | MIT License |
spotify-api/src/main/java/com/clipfinder/spotify/api/model/TracksPagingObject.kt | tosoba | 133,674,301 | false | {"Gradle": 33, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 31, "Batchfile": 1, "Kotlin": 409, "Proguard": 24, "XML": 176, "Java": 2, "INI": 4} | /**
* Spotify Web API No description provided (generated by Openapi Generator
* https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 0.0.1
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech Do not edit the class manually.
*/
package com.clipfinder.spotify.api.model
import com.clipfinder.core.model.IPagingObject
import com.squareup.moshi.Json
/**
*
* @param href A link to the Web API endpoint returning the full result of the request
* @param items The requested data.
* @param limit The maximum number of items in the response (as set in the query or by default).
* @param next URL to the next page of items. ( null if none)
* @param offset The offset of the items returned (as set in the query or by default)
* @param previous URL to the previous page of items. ( null if none)
* @param total The total number of items available to return.
*/
data class AlbumsPagingObject(
/* A link to the Web API endpoint returning the full result of the request */
@Json(name = "href") val href: String,
/* The requested data. */
@Json(name = "items") override val items: List<SavedAlbumObject>,
/* The maximum number of items in the response (as set in the query or by default). */
@Json(name = "limit") val limit: Int,
/* URL to the next page of items. ( null if none) */
@Json(name = "next") val next: String? = null,
/* The offset of the items returned (as set in the query or by default) */
@Json(name = "offset") override val offset: Int,
/* URL to the previous page of items. ( null if none) */
@Json(name = "previous") val previous: String? = null,
/* The total number of items available to return. */
@Json(name = "total") override val total: Int
) : IPagingObject<SavedAlbumObject>
| 1 | null | 1 | 1 | 84ae309c8c059308c16902ee43b0cdfd2740794c | 1,873 | ClipFinder | MIT License |
src/main/kotlin/nmcp/NmcpPublishTask.kt | GradleUp | 756,060,949 | false | {"Kotlin": 12916} | package nmcp
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.logging.HttpLoggingInterceptor
import okio.Buffer
import org.gradle.api.DefaultTask
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import org.gradle.api.tasks.*
import org.gradle.work.DisableCachingByDefault
@DisableCachingByDefault
abstract class NmcpPublishTask : DefaultTask() {
@get:InputFile
@get:PathSensitive(PathSensitivity.RELATIVE)
abstract val inputFile: RegularFileProperty
@get:Input
abstract val username: Property<String>
@get:Input
abstract val password: Property<String>
@get:Input
@get:Optional
abstract val publicationType: Property<String>
@get:Input
abstract val publicationName: Property<String>
@get:Input
@get:Optional
abstract val endpoint: Property<String>
@TaskAction
fun taskAction() {
val username = username.get()
val password = password.get()
check(username.isNotBlank()) {
"Ncmp: username must not be empty"
}
check(password.isNotBlank()) {
"Ncmp: password must not be empty"
}
val token = "$username:$password".let {
Buffer().writeUtf8(it).readByteString().base64()
}
val body = MultipartBody.Builder()
.addFormDataPart(
"bundle",
publicationName.get(),
inputFile.get().asFile.asRequestBody("application/zip".toMediaType())
)
.build()
val publicationType = publicationType.orElse("USER_MANAGED").get()
Request.Builder()
.post(body)
.addHeader("Authorization", "UserToken $token")
.url(endpoint.getOrElse("https://central.sonatype.com/api/v1/publisher/upload") + "?publishingType=$publicationType")
.build()
.let {
OkHttpClient.Builder()
.addInterceptor(HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.HEADERS
})
.build()
.newCall(it).execute()
}.use {
if (!it.isSuccessful) {
error("Cannot publish to maven central (status='${it.code}'): ${it.body?.string()}")
}
}
}
} | 0 | Kotlin | 2 | 48 | b6325eac2ca6111a8d22a26be401d021fda90003 | 2,519 | nmcp | MIT License |
openai-gateway/openai-gateway-core/src/commonMain/kotlin/com/tddworks/openai/gateway/api/internal/DefaultOpenAIProviderConfig.kt | tddworks | 755,029,221 | false | {"Kotlin": 328879} | package com.tddworks.openai.gateway.api.internal
import com.tddworks.openai.api.OpenAI
import com.tddworks.openai.api.OpenAIConfig
import com.tddworks.openai.gateway.api.OpenAIProviderConfig
data class DefaultOpenAIProviderConfig(
override val apiKey: () -> String,
override val baseUrl: () -> String = { OpenAI.BASE_URL }
) : OpenAIProviderConfig
fun OpenAIProviderConfig.toOpenAIConfig() = OpenAIConfig(apiKey, baseUrl)
fun OpenAIProviderConfig.Companion.default(
apiKey: () -> String,
baseUrl: () -> String = { OpenAI.BASE_URL }
) = DefaultOpenAIProviderConfig(apiKey, baseUrl) | 0 | Kotlin | 0 | 9 | eeef583fb15610e60fbb4df3550f085f4c6f3908 | 600 | openai-kotlin | Apache License 2.0 |
ktor-network/jvm/src/io/ktor/network/sockets/ConnectUtilsJvm.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.network.sockets
import io.ktor.network.selector.*
import io.ktor.util.network.*
internal actual suspend fun connect(
selector: SelectorManager,
networkAddress: NetworkAddress,
socketOptions: SocketOptions.TCPClientSocketOptions
): Socket = selector.buildOrClose({ openSocketChannel() }) {
assignOptions(socketOptions)
nonBlocking()
SocketImpl(this, socket()!!, selector, socketOptions).apply {
connect(networkAddress)
}
}
internal actual fun bind(
selector: SelectorManager,
localAddress: NetworkAddress?,
socketOptions: SocketOptions.AcceptorOptions
): ServerSocket = selector.buildOrClose({ openServerSocketChannel() }) {
assignOptions(socketOptions)
nonBlocking()
ServerSocketImpl(this, selector).apply {
channel.socket().bind(localAddress, socketOptions.backlogSize)
}
}
| 303 | Kotlin | 755 | 9,053 | 240363d6760754c325e0022f48eb5ea3069bc060 | 994 | ktor | Apache License 2.0 |
spesialist-selve/src/test/kotlin/no/nav/helse/modell/UtbetalingDaoTest.kt | navikt | 244,907,980 | false | null | package no.nav.helse.modell
import DatabaseIntegrationTest
import java.time.LocalDateTime
import java.util.UUID
import no.nav.helse.juli
import no.nav.helse.modell.utbetaling.Utbetaling
import no.nav.helse.modell.utbetaling.Utbetalingsstatus
import no.nav.helse.modell.utbetaling.Utbetalingsstatus.ANNULLERT
import no.nav.helse.modell.utbetaling.Utbetalingsstatus.UTBETALT
import no.nav.helse.modell.utbetaling.Utbetalingtype
import no.nav.helse.spesialist.api.oppgave.Oppgavetype
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertDoesNotThrow
class UtbetalingDaoTest : DatabaseIntegrationTest() {
@Test
fun `Ingen tidligere utbetalinger`() {
nyPerson()
assertFalse(utbetalingDao.erUtbetaltFør(AKTØR))
}
@Test
fun `Er behandlet tidligere hvis hen har en tidligere utbetaling`() {
nyPerson()
val arbeidsgiveroppdragId = lagArbeidsgiveroppdrag(fagsystemId())
val personOppdragId = lagPersonoppdrag(fagsystemId())
val utbetaling_idId = lagUtbetalingId(arbeidsgiveroppdragId, personOppdragId, UUID.randomUUID())
utbetalingDao.nyUtbetalingStatus(utbetaling_idId, UTBETALT, LocalDateTime.now(), "{}")
assertTrue(utbetalingDao.erUtbetaltFør(AKTØR))
}
@Test
fun `finner utbetaling`() {
nyPerson()
val arbeidsgiverFagsystemId = fagsystemId()
val personFagsystemId = fagsystemId()
val arbeidsgiveroppdragId1 = lagArbeidsgiveroppdrag(arbeidsgiverFagsystemId)
val personOppdragId1 = lagPersonoppdrag(personFagsystemId)
val utbetalingId = UUID.randomUUID()
utbetalingDao.opprettUtbetalingId(utbetalingId, FNR, ORGNUMMER, Utbetalingtype.UTBETALING, LocalDateTime.now(), arbeidsgiveroppdragId1, personOppdragId1, 2000, 2000)
val utbetaling = utbetalingDao.utbetalingFor(utbetalingId)
assertEquals(Utbetaling(utbetalingId, 2000, 2000, Utbetalingtype.UTBETALING), utbetaling)
}
@Test
fun `finner utbetaling basert på oppgaveId`() {
nyPerson()
val arbeidsgiverFagsystemId = fagsystemId()
val personFagsystemId = fagsystemId()
val arbeidsgiveroppdragId1 = lagArbeidsgiveroppdrag(arbeidsgiverFagsystemId)
val personOppdragId1 = lagPersonoppdrag(personFagsystemId)
val utbetalingId = UUID.randomUUID()
val oppgaveId = oppgaveDao.opprettOppgave(UUID.randomUUID(), Oppgavetype.SØKNAD, VEDTAKSPERIODE, utbetalingId)
utbetalingDao.opprettUtbetalingId(utbetalingId, FNR, ORGNUMMER, Utbetalingtype.UTBETALING, LocalDateTime.now(), arbeidsgiveroppdragId1, personOppdragId1, 2000, 2000)
val utbetaling = utbetalingDao.utbetalingFor(oppgaveId)
assertEquals(Utbetaling(utbetalingId, 2000, 2000, Utbetalingtype.UTBETALING), utbetaling)
}
@Test
fun `finner ikke utbetaling dersom det ikke finnes noen`() {
val utbetaling = utbetalingDao.utbetalingFor(UUID.randomUUID())
assertNull(utbetaling)
}
@Test
fun `Er behandlet tidligere selvom utbetalingen har blitt annullert`() {
nyPerson()
val arbeidsgiveroppdragId = lagArbeidsgiveroppdrag(fagsystemId())
val personOppdragId = lagPersonoppdrag(fagsystemId())
val utbetaling_idId = lagUtbetalingId(arbeidsgiveroppdragId, personOppdragId, UUID.randomUUID())
utbetalingDao.nyUtbetalingStatus(utbetaling_idId, UTBETALT, LocalDateTime.now(), "{}")
utbetalingDao.nyUtbetalingStatus(utbetaling_idId, ANNULLERT, LocalDateTime.now(), "{}")
assertTrue(utbetalingDao.erUtbetaltFør(AKTØR))
}
@Test
fun `Er behandlet tidligere selvom det finnes tidligere annulleringer`() {
nyPerson()
val arbeidsgiveroppdragId = lagArbeidsgiveroppdrag(fagsystemId())
val personOppdragId = lagPersonoppdrag(fagsystemId())
val utbetaling_idId = lagUtbetalingId(arbeidsgiveroppdragId, personOppdragId, UUID.randomUUID())
utbetalingDao.nyUtbetalingStatus(utbetaling_idId, UTBETALT, LocalDateTime.now(), "{}")
utbetalingDao.nyUtbetalingStatus(utbetaling_idId, ANNULLERT, LocalDateTime.now(), "{}")
val arbeidsgiveroppdragId2 = lagArbeidsgiveroppdrag(fagsystemId())
val personOppdragId2 = lagPersonoppdrag(fagsystemId())
val utbetaling_idId2 = lagUtbetalingId(arbeidsgiveroppdragId2, personOppdragId2, UUID.randomUUID())
utbetalingDao.nyUtbetalingStatus(utbetaling_idId2, UTBETALT, LocalDateTime.now(), "{}")
assertTrue(utbetalingDao.erUtbetaltFør(AKTØR))
}
@Test
fun `lagrer personbeløp og arbeidsgiverbeløp på utbetaling`() {
nyPerson()
val arbeidsgiverFagsystemId = fagsystemId()
val personFagsystemId = fagsystemId()
val arbeidsgiveroppdragId1 = lagArbeidsgiveroppdrag(arbeidsgiverFagsystemId)
val personOppdragId1 = lagPersonoppdrag(personFagsystemId)
val utbetalingId = UUID.randomUUID()
utbetalingDao.opprettUtbetalingId(utbetalingId, FNR, ORGNUMMER, Utbetalingtype.UTBETALING, LocalDateTime.now(), arbeidsgiveroppdragId1, personOppdragId1, 2000, 2000)
assertArbeidsgiverbeløp(2000, utbetalingId)
assertPersonbeløp(2000, utbetalingId)
}
@Test
fun `alle enumer finnes også i db`() {
nyPerson()
val arbeidsgiverFagsystemId = fagsystemId()
val personFagsystemId = fagsystemId()
val arbeidsgiverOppdragId = lagArbeidsgiveroppdrag(arbeidsgiverFagsystemId)
val personOppdragId = lagPersonoppdrag(personFagsystemId)
lagLinje(arbeidsgiverOppdragId, 1.juli(), 10.juli(), 12000)
lagLinje(personOppdragId, 11.juli(), 31.juli(), 10000)
val utbetaling = lagUtbetalingId(arbeidsgiverOppdragId, personOppdragId)
assertDoesNotThrow {
Utbetalingsstatus.values().forEach {
utbetalingDao.nyUtbetalingStatus(utbetaling, it, LocalDateTime.now(), "{}")
}
}
}
private fun assertArbeidsgiverbeløp(beløp: Int, utbetalingId: UUID) {
val arbeidsgiverbeløp = query(
"SELECT arbeidsgiverbeløp FROM utbetaling_id WHERE utbetaling_id = :utbetalingId",
"utbetalingId" to utbetalingId
).single { it.intOrNull("arbeidsgiverbeløp") }
assertEquals(beløp, arbeidsgiverbeløp)
}
private fun assertPersonbeløp(beløp: Int, utbetalingId: UUID) {
val personbeløp = query(
"SELECT personbeløp FROM utbetaling_id WHERE utbetaling_id = :utbetalingId",
"utbetalingId" to utbetalingId
).single { it.intOrNull("personbeløp") }
assertEquals(beløp, personbeløp)
}
}
| 9 | null | 3 | 1 | 9d4136c645cc48337f246413c4b0beb906839ffd | 6,841 | helse-spesialist | MIT License |
multiplatform-crypto-delegated/src/commonTest/kotlin/com/ionspin/kotlin/crypto/hash/blake2b/Blake2bTest.kt | ionspin | 197,911,500 | false | null | package com.ionspin.kotlin.crypto.hash.blake2b
import com.ionspin.kotlin.crypto.Crypto
import com.ionspin.kotlin.crypto.CryptoPrimitives
import com.ionspin.kotlin.crypto.Initializer
import com.ionspin.kotlin.crypto.hash.encodeToUByteArray
import com.ionspin.kotlin.crypto.util.testBlocking
import com.ionspin.kotlin.crypto.util.toHexString
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertTrue
/**
* Created by <NAME>
* <EMAIL>
* on 09-Jun-2020
*/
class Blake2bTest {
@Test
fun statelessSimpleTest() = testBlocking {
Initializer.initialize()
val expected = "a71079d42853dea26e453004338670a53814b78137ffbed07603a41d76a483aa9bc33b582f77d30a65e6f29a89" +
"6c0411f38312e1d66e0bf16386c86a89bea572"
val result = CryptoPrimitives.Blake2b.stateless("test".encodeToUByteArray()).toHexString()
// println("Result: $result")
assertTrue { result == expected }
}
//This is a bad test since it's not larger than one block
//but for now I'm testing that the platform library is being correctly called
@Test
fun updateableSimpleTest() = testBlocking {
Initializer.initialize()
val expected = "a71079d42853dea26e453004338670a53814b78137ffbed07603a41d76a483aa9bc33b582f77d30a65e6f29a89" +
"6c0411f38312e1d66e0bf16386c86a89bea572"
val blake2b = CryptoPrimitives.Blake2b.updateable()
blake2b.update("t".encodeToUByteArray())
blake2b.update(("est".encodeToUByteArray()))
val result = blake2b.digest().toHexString()
// println("Result: $result")
assertTrue { result == expected }
}
}
| 2 | Kotlin | 3 | 36 | 425c066bac867a8899d519d80182e90259b78067 | 1,668 | kotlin-multiplatform-crypto | Apache License 2.0 |
designer/testSrc/com/android/tools/idea/uibuilder/handlers/constraint/WidgetConstraintModelTest.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.android.tools.idea.uibuilder.handlers.constraint
import com.android.AndroidXConstants
import com.android.SdkConstants
import com.android.tools.idea.common.command.NlWriteCommandActionUtil
import com.android.tools.idea.common.fixtures.ModelBuilder
import com.android.tools.idea.common.model.NlModel
import com.android.tools.idea.uibuilder.scene.SceneTest
import com.android.tools.idea.uibuilder.scene.SyncLayoutlibSceneManager
import com.google.common.truth.Truth.assertThat
import com.intellij.testFramework.PlatformTestUtil
import java.awt.event.ActionEvent
import java.util.Locale
import org.mockito.Mockito
class WidgetConstraintModelTest : SceneTest() {
private var defaultLocale: Locale? = null
override fun setUp() {
super.setUp()
defaultLocale = Locale.getDefault()
// Set the default Locale to Arabic which catches bugs where a number is formatted with arabic
// numbers instead of cardinal numbers.
Locale.setDefault(Locale("ar"))
}
override fun tearDown() {
super.tearDown()
defaultLocale?.let { Locale.setDefault(it) }
}
override fun createModel(): ModelBuilder {
return model(
"constraint.xml",
component(AndroidXConstants.CONSTRAINT_LAYOUT.newName())
.withBounds(0, 0, 1000, 1000)
.id("@id/constraint")
.matchParentWidth()
.matchParentHeight()
.children(
component(SdkConstants.TEXT_VIEW)
.withBounds(0, 0, 200, 200)
.id("@id/textView")
.width("100dp")
.height("100dp"),
component(SdkConstants.TEXT_VIEW)
.withBounds(200, 0, 200, 200)
.id("@id/textView2")
.width("100dp")
.height("100dp")
.withAttribute(
SdkConstants.SHERPA_URI,
SdkConstants.ATTR_LAYOUT_TOP_TO_TOP_OF,
"parent",
)
.withAttribute(
SdkConstants.SHERPA_URI,
SdkConstants.ATTR_LAYOUT_BOTTOM_TO_TOP_OF,
"linear",
)
.withAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_VERTICAL_BIAS, "0.632")
.withAttribute(
SdkConstants.SHERPA_URI,
SdkConstants.ATTR_LAYOUT_START_TO_START_OF,
"parent",
)
.withAttribute(
SdkConstants.SHERPA_URI,
SdkConstants.ATTR_LAYOUT_END_TO_END_OF,
"parent",
)
.withAttribute(
SdkConstants.SHERPA_URI,
SdkConstants.ATTR_LAYOUT_HORIZONTAL_BIAS,
"0.411",
),
component(SdkConstants.LINEAR_LAYOUT)
.withBounds(200, 200, 800, 800)
.id("@id/linear")
.width("400dp")
.height("400dp")
.withAttribute(
SdkConstants.TOOLS_URI,
SdkConstants.ATTR_LAYOUT_EDITOR_ABSOLUTE_X,
"100dp",
)
.withAttribute(
SdkConstants.TOOLS_URI,
SdkConstants.ATTR_LAYOUT_EDITOR_ABSOLUTE_Y,
"100dp",
),
component(AndroidXConstants.CONSTRAINT_LAYOUT_GUIDELINE.newName())
.id("@id/guideline")
.withBounds(0, 200, 1000, 1)
.wrapContentWidth()
.wrapContentHeight()
.withAttribute(
SdkConstants.ANDROID_URI,
SdkConstants.ATTR_ORIENTATION,
SdkConstants.VALUE_HORIZONTAL,
)
.withAttribute(
SdkConstants.SHERPA_URI,
SdkConstants.LAYOUT_CONSTRAINT_GUIDE_BEGIN,
"200dp",
),
),
)
}
fun testDeleteAttribute() {
val widgetModel = WidgetConstraintModel {}
val textView2 = myModel.find("textView2")!!
widgetModel.component = textView2
// Test deleting vertical constraints
assertNotNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_TOP_TO_TOP_OF)
)
assertNotNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_BOTTOM_TO_TOP_OF)
)
assertNotNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_VERTICAL_BIAS)
)
widgetModel.removeAttributes(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_TOP_TO_TOP_OF)
assertNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_TOP_TO_TOP_OF)
)
widgetModel.removeAttributes(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_BOTTOM_TO_TOP_OF)
assertNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_BOTTOM_TO_TOP_OF)
)
// Deleting both Top and Bottom will delete vertical bias as well
assertNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_VERTICAL_BIAS)
)
// Test deleting horizontal constraints
assertNotNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_START_TO_START_OF)
)
assertNotNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_END_TO_END_OF)
)
assertNotNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_HORIZONTAL_BIAS)
)
widgetModel.removeAttributes(
SdkConstants.SHERPA_URI,
SdkConstants.ATTR_LAYOUT_START_TO_START_OF,
)
assertNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_START_TO_START_OF)
)
widgetModel.removeAttributes(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_END_TO_END_OF)
assertNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_END_TO_END_OF)
)
// Deleting both Start and End will delete vertical bias as well
assertNull(
textView2.getAttribute(SdkConstants.SHERPA_URI, SdkConstants.ATTR_LAYOUT_HORIZONTAL_BIAS)
)
}
fun testConstraintVerification() {
val widgetModel = WidgetConstraintModel {}
// Test a Widget which is fully constrained
widgetModel.component = myModel.find("textView2")
assertFalse(widgetModel.isMissingHorizontalConstrained)
assertFalse(widgetModel.isMissingVerticalConstrained)
assertFalse(widgetModel.isOverConstrained)
// Test a Widget which isn't constrained.
val linear = myModel.find("linear")!!
widgetModel.component = linear
assertTrue(widgetModel.isMissingHorizontalConstrained)
assertTrue(widgetModel.isMissingVerticalConstrained)
assertFalse(widgetModel.isOverConstrained)
NlWriteCommandActionUtil.run(linear, "Set Params") {
linear.setAttribute(
SdkConstants.SHERPA_URI,
SdkConstants.ATTR_LAYOUT_TOP_TO_TOP_OF,
SdkConstants.ATTR_PARENT,
)
linear.setAttribute(
SdkConstants.SHERPA_URI,
SdkConstants.ATTR_LAYOUT_START_TO_START_OF,
SdkConstants.ATTR_PARENT,
)
}
assertFalse(widgetModel.isMissingHorizontalConstrained)
assertFalse(widgetModel.isMissingVerticalConstrained)
assertFalse(widgetModel.isOverConstrained)
NlWriteCommandActionUtil.run(linear, "Set Constraints") {
linear.setAttribute(
SdkConstants.SHERPA_URI,
SdkConstants.ATTR_LAYOUT_TOP_TO_BOTTOM_OF,
SdkConstants.ATTR_PARENT,
)
}
assertTrue(widgetModel.isOverConstrained)
// Test Constraint Guideline doesn't need to constrained vertically and horizontally.
val guideline = myModel.find("guideline")!!
widgetModel.component = guideline
assertFalse(widgetModel.isMissingHorizontalConstrained)
assertFalse(widgetModel.isMissingVerticalConstrained)
assertFalse(widgetModel.isOverConstrained)
}
fun testTriggerCallbackWhenSettingSurface() {
// The callback in practise is used to update ui components.
val callback = Mockito.mock(Runnable::class.java)
val widgetModel = WidgetConstraintModel(callback)
widgetModel.surface = myScene.designSurface
Mockito.verify(callback, Mockito.times(1)).run()
}
fun testTriggerUpdateAfterModelChanges() {
ignoreRendering()
var count = 0
val updateUICallback = Runnable { count++ }
val widgetModel = WidgetConstraintModel(updateUICallback)
val textView2 = myModel.find("textView2")!!
widgetModel.component = textView2
count = 0 // reset the count which will be incremented after setting the component to textView2
myModel.notifyModified(NlModel.ChangeType.EDIT)
assertThat(count).isAtLeast(1)
}
fun testTriggerUpdateAfterLayoutlibUpdate() {
ignoreRendering()
var count = 0
val updateUICallback = Runnable { count++ }
val widgetModel = WidgetConstraintModel(updateUICallback)
val textView2 = myModel.find("textView2")!!
widgetModel.component = textView2
count = 0 // reset the count which will be incremented after setting the component to textView2
myModel.notifyListenersModelDerivedDataChanged()
assertThat(count).isAtLeast(1)
}
fun testSetLeftMarginMinApi16() {
val widgetModel = WidgetConstraintModel {}
val component = myModel.find("textView2")!!
widgetModel.component = component
widgetModel.setMargin(WidgetConstraintModel.CONNECTION_LEFT, "16dp")
widgetModel.timer.stop()
widgetModel.timer.actionListeners.forEach { it.actionPerformed(ActionEvent(component, 0, "")) }
PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue()
assertThat(
component.getAttribute(SdkConstants.ANDROID_URI, SdkConstants.ATTR_LAYOUT_MARGIN_LEFT)
)
.isEqualTo("16dp")
assertThat(
component.getAttribute(SdkConstants.ANDROID_URI, SdkConstants.ATTR_LAYOUT_MARGIN_START)
)
.isEqualTo("16dp")
}
fun testSetLeftMarginMinApi16TargetApi1() {
val widgetModel = WidgetConstraintModel {}
val component = myModel.find("textView2")!!
widgetModel.component = component
widgetModel.setMargin(WidgetConstraintModel.CONNECTION_LEFT, "16dp")
widgetModel.timer.stop()
widgetModel.timer.actionListeners.forEach { it.actionPerformed(ActionEvent(component, 0, "")) }
PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue()
assertThat(
component.getAttribute(SdkConstants.ANDROID_URI, SdkConstants.ATTR_LAYOUT_MARGIN_LEFT)
)
.isEqualTo("16dp")
}
fun testSetLeftMarginMinApi17() {
val widgetModel = WidgetConstraintModel {}
val component = myModel.find("textView2")!!
widgetModel.component = component
widgetModel.setMargin(WidgetConstraintModel.CONNECTION_LEFT, "16dp")
widgetModel.timer.stop()
widgetModel.timer.actionListeners.forEach { it.actionPerformed(ActionEvent(component, 0, "")) }
PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue()
assertThat(
component.getAttribute(SdkConstants.ANDROID_URI, SdkConstants.ATTR_LAYOUT_MARGIN_LEFT)
)
.isNull()
assertThat(
component.getAttribute(SdkConstants.ANDROID_URI, SdkConstants.ATTR_LAYOUT_MARGIN_START)
)
.isEqualTo("16dp")
}
fun testSetVerticalMargin() {
val widgetModel = WidgetConstraintModel {}
val component = myModel.find("textView2")!!
widgetModel.component = component
widgetModel.setMargin(WidgetConstraintModel.CONNECTION_TOP, "8dp")
widgetModel.setMargin(WidgetConstraintModel.CONNECTION_BOTTOM, "16dp")
widgetModel.timer.stop()
widgetModel.timer.actionListeners.forEach { it.actionPerformed(ActionEvent(component, 0, "")) }
PlatformTestUtil.dispatchAllInvocationEventsInIdeEventQueue()
assertThat(
component.getAttribute(SdkConstants.ANDROID_URI, SdkConstants.ATTR_LAYOUT_MARGIN_TOP)
)
.isEqualTo("8dp")
assertThat(
component.getAttribute(SdkConstants.ANDROID_URI, SdkConstants.ATTR_LAYOUT_MARGIN_BOTTOM)
)
.isEqualTo("16dp")
}
// To speed up the tests ignore all render requests
private fun ignoreRendering() {
val manager = myModel.surface.sceneManager as? SyncLayoutlibSceneManager ?: return
manager.ignoreRenderRequests = true
}
}
| 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 12,721 | android | Apache License 2.0 |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/alexa/ask/CfnSkillDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION")
package cloudshift.awscdk.dsl.alexa.ask
import cloudshift.awscdk.common.CdkDslMarker
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.alexa.ask.CfnSkill
import software.constructs.Construct
import kotlin.String
/**
* The `Alexa::ASK::Skill` resource creates an Alexa skill that enables customers to access new
* abilities.
*
* For more information about developing a skill, see the .
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.alexa.ask.*;
* Object manifest;
* CfnSkill cfnSkill = CfnSkill.Builder.create(this, "MyCfnSkill")
* .authenticationConfiguration(AuthenticationConfigurationProperty.builder()
* .clientId("clientId")
* .clientSecret("clientSecret")
* .refreshToken("refreshToken")
* .build())
* .skillPackage(SkillPackageProperty.builder()
* .s3Bucket("s3Bucket")
* .s3Key("s3Key")
* // the properties below are optional
* .overrides(OverridesProperty.builder()
* .manifest(manifest)
* .build())
* .s3BucketRole("s3BucketRole")
* .s3ObjectVersion("s3ObjectVersion")
* .build())
* .vendorId("vendorId")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ask-skill.html)
*/
@CdkDslMarker
public class CfnSkillDsl(
scope: Construct,
id: String
) {
private val cdkBuilder: CfnSkill.Builder = CfnSkill.Builder.create(scope, id)
/**
* Login with Amazon (LWA) configuration used to authenticate with the Alexa service.
*
* Only Login with Amazon clients created through the are supported. The client ID, client
* secret, and refresh token are required.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ask-skill.html#cfn-ask-skill-authenticationconfiguration)
* @param authenticationConfiguration Login with Amazon (LWA) configuration used to authenticate
* with the Alexa service.
*/
public fun authenticationConfiguration(authenticationConfiguration: IResolvable) {
cdkBuilder.authenticationConfiguration(authenticationConfiguration)
}
/**
* Login with Amazon (LWA) configuration used to authenticate with the Alexa service.
*
* Only Login with Amazon clients created through the are supported. The client ID, client
* secret, and refresh token are required.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ask-skill.html#cfn-ask-skill-authenticationconfiguration)
* @param authenticationConfiguration Login with Amazon (LWA) configuration used to authenticate
* with the Alexa service.
*/
public fun authenticationConfiguration(authenticationConfiguration: CfnSkill.AuthenticationConfigurationProperty) {
cdkBuilder.authenticationConfiguration(authenticationConfiguration)
}
/**
* Configuration for the skill package that contains the components of the Alexa skill.
*
* Skill packages are retrieved from an Amazon S3 bucket and key and used to create and update the
* skill. For more information about the skill package format, see the .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ask-skill.html#cfn-ask-skill-skillpackage)
* @param skillPackage Configuration for the skill package that contains the components of the
* Alexa skill.
*/
public fun skillPackage(skillPackage: IResolvable) {
cdkBuilder.skillPackage(skillPackage)
}
/**
* Configuration for the skill package that contains the components of the Alexa skill.
*
* Skill packages are retrieved from an Amazon S3 bucket and key and used to create and update the
* skill. For more information about the skill package format, see the .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ask-skill.html#cfn-ask-skill-skillpackage)
* @param skillPackage Configuration for the skill package that contains the components of the
* Alexa skill.
*/
public fun skillPackage(skillPackage: CfnSkill.SkillPackageProperty) {
cdkBuilder.skillPackage(skillPackage)
}
/**
* The vendor ID associated with the Amazon developer account that will host the skill.
*
* Details for retrieving the vendor ID are in . The provided LWA credentials must be linked to
* the developer account associated with this vendor ID.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ask-skill.html#cfn-ask-skill-vendorid)
* @param vendorId The vendor ID associated with the Amazon developer account that will host the
* skill.
*/
public fun vendorId(vendorId: String) {
cdkBuilder.vendorId(vendorId)
}
public fun build(): CfnSkill = cdkBuilder.build()
}
| 4 | null | 0 | 3 | c59c6292cf08f0fc3280d61e7f8cff813a608a62 | 5,203 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/com/steleot/jetpackcompose/playground/compose/foundation/SelectableGroupScreen.kt | Vivecstel | 338,792,534 | false | null | package com.steleot.jetpackcompose.playground.compose.foundation
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.selection.selectableGroup
import androidx.compose.material.RadioButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.steleot.jetpackcompose.playground.R
import com.steleot.jetpackcompose.playground.navigation.graph.FoundationNavRoutes
import com.steleot.jetpackcompose.playground.ui.base.material.DefaultScaffold
private const val Url = "foundation/SelectableGroupScreen.kt"
@Composable
fun SelectableGroupScreen() {
DefaultScaffold(
title = FoundationNavRoutes.SelectableGroup,
link = Url,
) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
SelectableGroupExample(stringResource(id = R.string.app_name).split(" "))
}
}
}
@Composable
private fun SelectableGroupExample(
items: List<String>
) {
val state = remember { mutableStateOf("") }
Column(
modifier = Modifier.selectableGroup()
) {
items.forEach { item ->
Row(modifier = Modifier.padding(10.dp)) {
RadioButton(
selected = state.value == item,
onClick = {
state.value = item
}
)
Text(
text = item,
modifier = Modifier
.padding(start = 16.dp)
.align(Alignment.CenterVertically)
)
}
}
}
} | 2 | Kotlin | 40 | 325 | d8c5f09c102110e39c18717300d1ca253b64e2a9 | 1,974 | Jetpack-Compose-Playground | Apache License 2.0 |
uast/uast-common/src/com/intellij/psi/UastReferenceRegistrar.kt | weiqiangzheng | 154,165,897 | true | {"Java": 169603963, "Python": 25582594, "Kotlin": 6740047, "Groovy": 3535139, "HTML": 2117263, "C": 214294, "C++": 180123, "CSS": 172743, "JavaScript": 148969, "Lex": 148871, "XSLT": 113036, "Jupyter Notebook": 93222, "Shell": 60209, "NSIS": 58584, "Batchfile": 49961, "Roff": 37497, "Objective-C": 32636, "TeX": 25473, "AMPL": 20665, "TypeScript": 9958, "J": 5050, "PHP": 2699, "Makefile": 2352, "Thrift": 1846, "CoffeeScript": 1759, "CMake": 1675, "Ruby": 1217, "Perl": 973, "Smalltalk": 906, "C#": 696, "AspectJ": 182, "Visual Basic": 77, "HLSL": 57, "Erlang": 10} | /*
* Copyright 2000-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.
*/
@file:JvmName("UastReferenceRegistrar")
package com.intellij.psi
import com.intellij.openapi.util.Key
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.ElementPatternCondition
import com.intellij.patterns.InitialPatternCondition
import com.intellij.util.ProcessingContext
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UExpression
import org.jetbrains.uast.ULiteralExpression
import org.jetbrains.uast.toUElement
fun PsiReferenceRegistrar.registerUastReferenceProvider(pattern: (UElement, ProcessingContext) -> Boolean,
provider: UastReferenceProvider,
priority: Double = PsiReferenceRegistrar.DEFAULT_PRIORITY) {
this.registerReferenceProvider(UastPatternAdapter(pattern, provider.supportedUElementTypes),
UastReferenceProviderAdapter(provider),
priority)
}
fun PsiReferenceRegistrar.registerUastReferenceProvider(pattern: ElementPattern<out UElement>,
provider: UastReferenceProvider,
priority: Double = PsiReferenceRegistrar.DEFAULT_PRIORITY) {
this.registerReferenceProvider(UastPatternAdapter(pattern::accepts, provider.supportedUElementTypes),
UastReferenceProviderAdapter(provider), priority)
}
abstract class UastReferenceProvider {
open val supportedUElementTypes: List<Class<out UElement>> = listOf(UElement::class.java)
abstract fun getReferencesByElement(element: UElement, context: ProcessingContext): Array<PsiReference>
}
/**
* NOTE: Consider using [uastInjectionHostReferenceProvider] instead.
* @see org.jetbrains.uast.sourceInjectionHost
* @see UastLiteralReferenceProvider
*/
fun uastLiteralReferenceProvider(provider: (ULiteralExpression, PsiLanguageInjectionHost) -> Array<PsiReference>): UastLiteralReferenceProvider =
object : UastLiteralReferenceProvider() {
override fun getReferencesByULiteral(uLiteral: ULiteralExpression,
host: PsiLanguageInjectionHost,
context: ProcessingContext): Array<PsiReference> = provider(uLiteral, host)
}
fun uastInjectionHostReferenceProvider(provider: (UExpression, PsiLanguageInjectionHost) -> Array<PsiReference>): UastInjectionHostReferenceProvider =
object : UastInjectionHostReferenceProvider() {
override fun getReferencesForInjectionHost(uExpression: UExpression,
host: PsiLanguageInjectionHost,
context: ProcessingContext): Array<PsiReference> = provider(uExpression, host)
}
private val cachedUElement = Key.create<UElement>("UastReferenceRegistrar.cachedUElement")
private fun getOrCreateCachedElement(element: PsiElement,
context: ProcessingContext?,
supportedUElementTypes: List<Class<out UElement>>): UElement? =
element as? UElement ?: context?.get(cachedUElement) ?: supportedUElementTypes.asSequence().mapNotNull {
element.toUElement(it)
}.firstOrNull()?.also { context?.put(cachedUElement, it) }
private class UastPatternAdapter(
val predicate: (UElement, ProcessingContext) -> Boolean,
val supportedUElementTypes: List<Class<out UElement>>
) : ElementPattern<PsiElement> {
override fun accepts(o: Any?): Boolean = accepts(o, null)
override fun accepts(o: Any?, context: ProcessingContext?): Boolean = when (o) {
is PsiElement ->
getOrCreateCachedElement(o, context, supportedUElementTypes)
?.let { predicate(it, context ?: ProcessingContext()) }
?: false
else -> false
}
private val condition = ElementPatternCondition(object : InitialPatternCondition<PsiElement>(PsiElement::class.java) {
override fun accepts(o: Any?, context: ProcessingContext?): Boolean = [email protected](o, context)
})
override fun getCondition(): ElementPatternCondition<PsiElement> = condition
}
fun ElementPattern<out UElement>.asPsiPattern(vararg supportedUElementTypes: Class<out UElement>): ElementPattern<PsiElement> = UastPatternAdapter(
this::accepts,
if (supportedUElementTypes.isNotEmpty()) supportedUElementTypes.toList() else listOf(UElement::class.java)
)
private class UastReferenceProviderAdapter(val provider: UastReferenceProvider) : PsiReferenceProvider() {
override fun getReferencesByElement(element: PsiElement, context: ProcessingContext): Array<PsiReference> {
val uElement = getOrCreateCachedElement(element, context, provider.supportedUElementTypes) ?: return PsiReference.EMPTY_ARRAY
return provider.getReferencesByElement(uElement, context)
}
override fun acceptsTarget(target: PsiElement): Boolean = true
} | 1 | Java | 1 | 1 | f8263bc48f0fc98315a796364b827beef5c86a3b | 5,533 | intellij-community | Apache License 2.0 |
build-tools/agp-gradle-core/src/main/java/com/android/build/api/component/impl/TestComponentImpl.kt | RivanParmar | 526,653,590 | false | {"Java": 48334972, "Kotlin": 8896058, "HTML": 109232, "Lex": 13233, "ReScript": 3232, "Makefile": 2194} | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.android.build.api.component.impl
import com.android.build.api.artifact.impl.ArtifactsImpl
import com.android.build.api.variant.ComponentIdentity
import com.android.build.api.variant.TestComponent
import com.android.build.gradle.internal.component.TestComponentCreationConfig
import com.android.build.gradle.internal.component.VariantCreationConfig
import com.android.build.gradle.internal.core.VariantSources
import com.android.build.gradle.internal.core.dsl.TestComponentDslInfo
import com.android.build.gradle.internal.dependency.VariantDependencies
import com.android.build.gradle.internal.scope.BuildFeatureValues
import com.android.build.gradle.internal.scope.MutableTaskContainer
import com.android.build.gradle.internal.services.TaskCreationServices
import com.android.build.gradle.internal.services.VariantServices
import com.android.build.gradle.internal.tasks.factory.GlobalTaskCreationConfig
import com.android.build.gradle.internal.variant.BaseVariantData
import com.android.build.gradle.internal.variant.VariantPathHelper
import com.android.utils.appendCapitalized
import javax.inject.Inject
abstract class TestComponentImpl<DslInfoT: TestComponentDslInfo> @Inject constructor(
componentIdentity: ComponentIdentity,
buildFeatureValues: BuildFeatureValues,
dslInfo: DslInfoT,
variantDependencies: VariantDependencies,
variantSources: VariantSources,
paths: VariantPathHelper,
artifacts: ArtifactsImpl,
variantData: BaseVariantData,
taskContainer: MutableTaskContainer,
override val mainVariant: VariantCreationConfig,
variantServices: VariantServices,
taskCreationServices: TaskCreationServices,
global: GlobalTaskCreationConfig,
) : ComponentImpl<DslInfoT>(
componentIdentity,
buildFeatureValues,
dslInfo,
variantDependencies,
variantSources,
paths,
artifacts,
variantData,
taskContainer,
variantServices,
taskCreationServices,
global
), TestComponent, TestComponentCreationConfig {
override val description: String
get() {
val componentType = dslInfo.componentType
val prefix = if (componentType.isApk) {
"android (on device) tests"
} else {
"unit tests"
}
return if (componentIdentity.productFlavors.isNotEmpty()) {
val sb = StringBuilder(50)
sb.append(prefix)
sb.append(" for the ")
componentIdentity.flavorName?.let { sb.appendCapitalized(it) }
componentIdentity.buildType?.let { sb.appendCapitalized(it) }
sb.append(" build")
sb.toString()
} else {
val sb = StringBuilder(50)
sb.append(prefix)
sb.append(" for the ")
sb.appendCapitalized(componentIdentity.buildType!!)
sb.append(" build")
sb.toString()
}
}
override fun <T> onTestedVariant(action: (VariantCreationConfig) -> T): T {
return action(mainVariant)
}
}
| 0 | Java | 2 | 17 | 8fb2bb1433e734aa9901184b76bc4089a02d76ca | 3,731 | androlabs | Apache License 2.0 |
app/src/main/java/es/npatarino/android/gotchallenge/data/datasource/network/model/ServerAddress.kt | gsanguinetti | 212,910,321 | true | {"Kotlin": 76123} | package es.npatarino.android.gotchallenge.data.datasource.network.model
data class ServerAddress(
val baseUrl: String
) | 0 | Kotlin | 0 | 0 | 8d03826f5de24762f4aff28fc0841b3d3529ab24 | 128 | android-challenge | Apache License 2.0 |
src/main/kotlin/jp/ac/kcg/HouseHoldAccountBookApplication.kt | KcgPrj | 58,903,675 | false | {"Kotlin": 31446, "HTML": 2676} | package jp.ac.kcg
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication()
open class HouseHoldAccountBookApplication
fun main(args: Array<String>) {
SpringApplication.run(HouseHoldAccountBookApplication::class.java, *args)
}
| 8 | Kotlin | 0 | 0 | 8686e7a18e86044e8724b930c9bfe1182f08592b | 319 | HouseHoldAccountBook | MIT License |
sample-mixed/src/main/java/com/speakerboxlite/router/samplemixed/bts/BottomSheetPath.kt | AlexExiv | 688,805,446 | false | {"Kotlin": 412589} | package com.speakerboxlite.router.samplemixed.bts
import com.speakerboxlite.router.RoutePath
import com.speakerboxlite.router.annotations.Route
import com.speakerboxlite.router.controllers.RouteController
class BottomSheetPath: RoutePath
@Route
abstract class BottomRouteController: RouteController<BottomSheetPath, BottomSheetView>()
| 8 | Kotlin | 1 | 3 | dfcb01a763ca40dc62a53bb309b0adc4603a5e88 | 338 | Router-Android | MIT License |
sykepenger-model/src/test/kotlin/no/nav/helse/spleis/e2e/VedtaksperiodeForkastetE2ETest.kt | navikt | 193,907,367 | false | null | package no.nav.helse.spleis.e2e
import no.nav.helse.april
import no.nav.helse.assertForventetFeil
import no.nav.helse.desember
import no.nav.helse.februar
import no.nav.helse.hendelser.Sykmeldingsperiode
import no.nav.helse.hendelser.Søknad.Søknadsperiode.Sykdom
import no.nav.helse.hendelser.til
import no.nav.helse.januar
import no.nav.helse.mars
import no.nav.helse.person.TilstandType.AVSLUTTET
import no.nav.helse.person.TilstandType.AVVENTER_GODKJENNING
import no.nav.helse.person.TilstandType.TIL_INFOTRYGD
import no.nav.helse.økonomi.Prosentdel.Companion.prosent
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
internal class VedtaksperiodeForkastetE2ETest : AbstractEndToEndTest() {
@Test
fun `vedtaksperioder forkastes`() {
nyttVedtak(1.januar, 31.januar)
forlengVedtak(1.februar, 28.februar)
forlengVedtak(1.mars, 31.mars)
forlengPeriode(1.april, 30.april)
håndterYtelser(4.vedtaksperiode)
håndterSimulering(4.vedtaksperiode)
håndterUtbetalingsgodkjenning(4.vedtaksperiode, false) // <- TIL_INFOTRYGD
assertEquals(1, observatør.forkastedePerioder())
assertEquals(AVVENTER_GODKJENNING, observatør.forkastet(4.vedtaksperiode.id(ORGNUMMER)).gjeldendeTilstand)
assertSisteTilstand(1.vedtaksperiode, AVSLUTTET)
assertSisteTilstand(2.vedtaksperiode, AVSLUTTET)
assertSisteTilstand(3.vedtaksperiode, AVSLUTTET)
assertSisteTilstand(4.vedtaksperiode, TIL_INFOTRYGD)
}
@Test
fun `forkaster kort periode`() {
håndterSykmelding(Sykmeldingsperiode(1.januar, 5.januar))
håndterSøknad(Sykdom(1.januar, 5.januar, 100.prosent))
håndterSykmelding(Sykmeldingsperiode(6.januar, 15.januar))
håndterSøknad(Sykdom(6.januar, 15.januar, 100.prosent))
håndterSykmelding(Sykmeldingsperiode(16.januar, 31.januar))
håndterSøknad(Sykdom(16.januar, 31.januar, 100.prosent))
håndterInntektsmelding(listOf(1.januar til 16.januar))
håndterVilkårsgrunnlag(3.vedtaksperiode)
håndterYtelser(3.vedtaksperiode)
håndterSimulering(3.vedtaksperiode)
håndterUtbetalingsgodkjenning(3.vedtaksperiode)
håndterUtbetalt()
håndterAnnullerUtbetaling(ORGNUMMER)
assertEquals(3, observatør.forkastedePerioder())
assertEquals(AVSLUTTET, observatør.forkastet(3.vedtaksperiode.id(ORGNUMMER)).gjeldendeTilstand)
assertSisteTilstand(1.vedtaksperiode, TIL_INFOTRYGD)
assertSisteTilstand(2.vedtaksperiode, TIL_INFOTRYGD)
assertSisteTilstand(3.vedtaksperiode, TIL_INFOTRYGD)
}
@Test
fun `Forventer arbeidsgiveropplysninger for søknad som forkastes pga sendTilGosys = true`() {
håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar))
håndterSøknad(Sykdom(1.januar, 31.januar, 100.prosent), sendTilGosys = true)
assertTrue(observatør.forkastet(1.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer ikke arbeidsgiveropplysninger ved forlengelse av spleis`() {
nyttVedtak(1.januar, 31.januar)
håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar))
håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent), sendTilGosys = true)
assertFalse(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer ikke arbeidsgiveropplysninger ved forlengelse av spleis over helg`() {
nyttVedtak(1.januar, 26.januar)
håndterSykmelding(Sykmeldingsperiode(29.januar, 28.februar))
håndterSøknad(Sykdom(29.januar, 28.februar, 100.prosent), sendTilGosys = true)
assertFalse(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer ikke arbeidsgiveropplysninger ved forlengelse forkastet periode`() {
tilGodkjenning(1.januar, 31.januar, ORGNUMMER)
håndterUtbetalingsgodkjenning(1.vedtaksperiode, utbetalingGodkjent = false)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar))
håndterSøknad(Sykdom(1.februar, 28.februar, 100.prosent), sendTilGosys = true)
assertFalse(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer ikke arbeidsgiveropplysninger ved forlengelse forkastet periode over helg`() {
tilGodkjenning(1.januar, 26.januar, ORGNUMMER)
håndterUtbetalingsgodkjenning(1.vedtaksperiode, utbetalingGodkjent = false)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
håndterSykmelding(Sykmeldingsperiode(29.januar, 28.februar))
håndterSøknad(Sykdom(29.januar, 28.februar, 100.prosent), sendTilGosys = true)
assertFalse(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer arbeidsgiveropplysninger ved kort gap til spleis`() {
nyttVedtak(1.januar, 31.januar)
håndterSykmelding(Sykmeldingsperiode(2.februar, 28.februar))
håndterSøknad(Sykdom(2.februar, 28.februar, 100.prosent), sendTilGosys = true)
assertTrue(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer arbeidsgiveropplysninger ved kort gap til forkastet periode`() {
tilGodkjenning(1.januar, 31.januar, ORGNUMMER)
håndterUtbetalingsgodkjenning(1.vedtaksperiode, utbetalingGodkjent = false)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
håndterSykmelding(Sykmeldingsperiode(2.februar, 28.februar))
håndterSøknad(Sykdom(2.februar, 28.februar, 100.prosent))
assertTrue(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer ikke arbeidsgiveropplysninger ved forkasting av AUU`() {
håndterSykmelding(Sykmeldingsperiode(1.januar, 10.januar))
håndterSøknad(Sykdom(1.januar, 10.januar, 100.prosent), sendTilGosys = true)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
val event = observatør.forkastet(1.vedtaksperiode.id(ORGNUMMER))
assertFalse(event.trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer ikke arbeidsgiveropplysninger ved forlengelse av kort spleisperiode, ny periode er fortsatt innenfor AGP`() {
nyPeriode(1.januar til 10.januar)
håndterSykmelding(Sykmeldingsperiode(11.januar, 15.januar))
håndterSøknad(Sykdom(11.januar, 15.januar, 100.prosent), sendTilGosys = true)
assertFalse(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer arbeidsgiveropplysninger ved forlengelse av kort spleisperiode, ny periode går utover AGP`() {
nyPeriode(1.januar til 10.januar)
håndterSykmelding(Sykmeldingsperiode(11.januar, 17.januar))
håndterSøknad(Sykdom(11.januar, 17.januar, 100.prosent), sendTilGosys = true)
assertTrue(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer ikke arbeidsgiveropplysninger ved forlengelse av kort forkastet periode, ny periode er fortsatt innenfor AGP`() {
håndterSykmelding(Sykmeldingsperiode(1.januar, 10.januar))
håndterSøknad(Sykdom(1.januar, 10.januar, 100.prosent), sendTilGosys = true)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
håndterSykmelding(Sykmeldingsperiode(11.januar, 15.januar))
håndterSøknad(Sykdom(11.januar, 15.januar, 100.prosent))
assertFalse(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer arbeidsgiveropplysninger ved forlengelse av kort forkastet periode, ny periode går utover AGP`() {
håndterSykmelding(Sykmeldingsperiode(1.januar, 10.januar))
håndterSøknad(Sykdom(1.januar, 10.januar, 100.prosent), sendTilGosys = true)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
håndterSykmelding(Sykmeldingsperiode(11.januar, 31.januar))
håndterSøknad(Sykdom(11.januar, 31.januar, 100.prosent))
assertTrue(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer arbeidsgiveropplysninger ved forlengelse av kort forkastet periode, ny periode går utover AGP, men er kortere enn 16 dager`() {
håndterSykmelding(Sykmeldingsperiode(1.januar, 10.januar))
håndterSøknad(Sykdom(1.januar, 10.januar, 100.prosent), sendTilGosys = true)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
håndterSykmelding(Sykmeldingsperiode(11.januar, 17.januar))
håndterSøknad(Sykdom(11.januar, 17.januar, 100.prosent))
assertTrue(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer ikke arbeisgiveropplysninger ved kort periode med gap til kort forkastet periode, ny periode går ikke utover AGP`() {
håndterSykmelding(Sykmeldingsperiode(1.januar, 5.januar))
håndterSøknad(Sykdom(1.januar, 5.januar, 100.prosent), sendTilGosys = true)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
håndterSykmelding(Sykmeldingsperiode(10.januar, 15.januar))
håndterSøknad(Sykdom(10.januar, 15.januar, 100.prosent))
assertFalse(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer arbeisgiveropplysninger ved kort periode med gap til kort forkastet periode, ny periode går utover AGP`() {
håndterSykmelding(Sykmeldingsperiode(1.desember(2017), 10.desember(2017)))
håndterSøknad(Sykdom(1.desember(2017), 10.desember(2017), 100.prosent), sendTilGosys = true)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
håndterSykmelding(Sykmeldingsperiode(1.januar, 10.januar))
håndterSøknad(Sykdom(1.januar, 10.januar, 100.prosent), sendTilGosys = true)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 2.vedtaksperiode, TIL_INFOTRYGD)
håndterSykmelding(Sykmeldingsperiode(15.januar, 25.januar))
håndterSøknad(Sykdom(15.januar, 25.januar, 100.prosent))
assertTrue(observatør.forkastet(3.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer arbeidsgiveropplysninger fra kort periode når den går utover AGP pga kort periode behandlet i spleis og kort forkastet periode`() {
nyPeriode(1.januar til 5.januar)
håndterSykmelding(Sykmeldingsperiode(10.januar, 15.januar))
håndterSøknad(Sykdom(10.januar, 15.januar, 100.prosent), sendTilGosys = true)
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 2.vedtaksperiode, TIL_INFOTRYGD)
håndterSykmelding(Sykmeldingsperiode(20.januar, 31.januar))
håndterSøknad(Sykdom(20.januar, 31.januar, 100.prosent))
assertTrue(observatør.forkastet(3.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
@Test
fun `Forventer ikke arbeidsgiveropplysninger fra periode der arbeidsgiver har sendt inntektsmelding før vi mottar søknad`() {
håndterInntektsmelding(listOf(1.januar til 16.januar))
nyPeriode(1.januar til 31.januar)
person.søppelbøtte(hendelselogg) { true }
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
assertForventetFeil(
forklaring = "Falsk positiv",
nå = {
assertTrue(observatør.forkastet(1.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
},
ønsket = {
assertFalse(observatør.forkastet(1.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
)
}
@Test
fun `Forventer ikke arbeidsgiveropplysninger fra periode med utbetaling som mottar overlappende søknad`() {
nyPeriode(1.januar til 31.januar)
person.søppelbøtte(hendelselogg) { true }
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
nyPeriode(31.januar til 31.januar)
assertForventetFeil(
forklaring = "Falsk positiv",
nå = {
assertTrue(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
},
ønsket = {
assertFalse(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
)
}
@Test
fun `Forventer arbeidsgiveropplysninger fra kort periode som mottar overlappende søknad som gjør at perioden går utover AGP`() {
nyPeriode(1.januar til 1.januar)
person.søppelbøtte(hendelselogg) { true }
assertSisteForkastetPeriodeTilstand(ORGNUMMER, 1.vedtaksperiode, TIL_INFOTRYGD)
nyPeriode(1.januar til 31.januar)
assertTrue(observatør.forkastet(2.vedtaksperiode.id(ORGNUMMER)).trengerArbeidsgiveropplysninger)
}
}
| 2 | Kotlin | 6 | 5 | 314d8a6e32b3dda391bcac31e0b4aeeee68f9f9b | 13,533 | helse-spleis | MIT License |
app/src/main/java/luyao/android/activity/SingleTopActivity.kt | lulululbj | 269,033,034 | false | null | package luyao.android.activity
/**
* Created by luyao
* on 2020/6/1 13:04
*/
class SingleTopActivity : BaseTaskActivity() | 0 | Kotlin | 0 | 0 | 32de1070b2a084dd2fd05b4557097026729cb41e | 125 | Android | Apache License 2.0 |
certifikit/src/jvmMain/kotlin/app/cash/certifikit/pem.kt | cashapp | 279,079,931 | false | null | /*
* Copyright (C) 2022 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("Pem")
package app.cash.certifikit
import okio.Buffer
import okio.ByteString
import okio.ByteString.Companion.decodeBase64
import okio.ByteString.Companion.toByteString
import java.security.GeneralSecurityException
import java.security.KeyFactory
import java.security.KeyPair
import java.security.PrivateKey
import java.security.cert.CertificateFactory
import java.security.cert.X509Certificate
import java.security.interfaces.ECPublicKey
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.PKCS8EncodedKeySpec
/**
* Decodes a multiline string that contains a [certificate][certificatePem] which is
* [PEM-encoded][rfc_7468]. A typical input string looks like this:
*
* ```
* -----BEGIN CERTIFICATE-----
* MIIBYTCCAQegAwIBAgIBKjAKBggqhkjOPQQDAjApMRQwEgYDVQQLEwtlbmdpbmVl
* cmluZzERMA8GA1UEAxMIY2FzaC5hcHAwHhcNNzAwMTAxMDAwMDA1WhcNNzAwMTAx
* MDAwMDEwWjApMRQwEgYDVQQLEwtlbmdpbmVlcmluZzERMA8GA1UEAxMIY2FzaC5h
* cHAwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASda8ChkQXxGELnrV/oBnIAx3dD
* ocUOJfdz4pOJTP6dVQB9U3UBiW5uSX/MoOD0LL5zG3bVyL3Y6pDwKuYvfLNhoyAw
* HjAcBgNVHREBAf8EEjAQhwQBAQEBgghjYXNoLmFwcDAKBggqhkjOPQQDAgNIADBF
* AiAyHHg1N6YDDQiY920+cnI5XSZwEGhAtb9PYWO8bLmkcQIhAI2CfEZf3V/obmdT
* yyaoEufLKVXhrTQhRfodTeigi4RX
* -----END CERTIFICATE-----
* ```
*/
fun String.decodeCertificatePem(): X509Certificate {
try {
val certificateFactory = CertificateFactory.getInstance("X.509")
val certificates = certificateFactory
.generateCertificates(
Buffer().writeUtf8(this).inputStream()
)
return certificates.single() as X509Certificate
} catch (nsee: NoSuchElementException) {
throw IllegalArgumentException("failed to decode certificate", nsee)
} catch (iae: IllegalArgumentException) {
throw IllegalArgumentException("failed to decode certificate", iae)
} catch (e: GeneralSecurityException) {
throw IllegalArgumentException("failed to decode certificate", e)
}
}
/**
* Returns the certificate encoded in [PEM format][rfc_7468].
*
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
*/
fun X509Certificate.certificatePem(): String {
return buildString {
append("-----BEGIN CERTIFICATE-----\n")
encodeBase64Lines(encoded.toByteString())
append("-----END CERTIFICATE-----\n")
}
}
/**
* Returns the certificate encoded in [PEM format][rfc_7468].
*
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
*/
fun Certificate.certificatePem(): String {
val encoded = CertificateAdapters.certificate.toDer(this)
return buildString {
append("-----BEGIN CERTIFICATE-----\n")
encodeBase64Lines(encoded)
append("-----END CERTIFICATE-----\n")
}
}
/**
* Returns the RSA private key encoded in [PKCS #8][rfc_5208] [PEM format][rfc_7468].
*
* [rfc_5208]: https://tools.ietf.org/html/rfc5208
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
*/
fun PrivateKey.privateKeyPkcs8Pem(): String {
return buildString {
append("-----BEGIN PRIVATE KEY-----\n")
encodeBase64Lines(encoded.toByteString())
append("-----END PRIVATE KEY-----\n")
}
}
/**
* Returns the RSA private key encoded in [PKCS #1][rfc_8017] [PEM format][rfc_7468].
*
* [rfc_8017]: https://tools.ietf.org/html/rfc8017
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
*/
fun PrivateKey.privateKeyPkcs1Pem(): String {
check(this is RSAPrivateKey) { "PKCS1 only supports RSA keys" }
return buildString {
append("-----BEGIN RSA PRIVATE KEY-----\n")
encodeBase64Lines(pkcs1Bytes())
append("-----END RSA PRIVATE KEY-----\n")
}
}
fun PrivateKey.pkcs1Bytes(): ByteString {
val decoded = CertificateAdapters.privateKeyInfo.fromDer(this.encoded.toByteString())
return decoded.privateKey
}
/**
* Decodes a multiline string that contains both a [certificate][certificatePem] and a
* [private key][privateKeyPkcs8Pem], both [PEM-encoded][rfc_7468]. A typical input string looks
* like this:
*
* ```
* -----BEGIN CERTIFICATE-----
* MIIBYTCCAQegAwIBAgIBKjAKBggqhkjOPQQDAjApMRQwEgYDVQQLEwtlbmdpbmVl
* cmluZzERMA8GA1UEAxMIY2FzaC5hcHAwHhcNNzAwMTAxMDAwMDA1WhcNNzAwMTAx
* MDAwMDEwWjApMRQwEgYDVQQLEwtlbmdpbmVlcmluZzERMA8GA1UEAxMIY2FzaC5h
* cHAwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASda8ChkQXxGELnrV/oBnIAx3dD
* ocUOJfdz4pOJTP6dVQB9U3UBiW5uSX/MoOD0LL5zG3bVyL3Y6pDwKuYvfLNhoyAw
* HjAcBgNVHREBAf8EEjAQhwQBAQEBgghjYXNoLmFwcDAKBggqhkjOPQQDAgNIADBF
* AiAyHHg1N6YDDQiY920+cnI5XSZwEGhAtb9PYWO8bLmkcQIhAI2CfEZf3V/obmdT
* yyaoEufLKVXhrTQhRfodTeigi4RX
* -----END CERTIFICATE-----
* -----BEGIN PRIVATE KEY-----
* <KEY>
* lu/GJQZoU9lDrCPeUcQ28tzOWw==
* -----END PRIVATE KEY-----
* ```
*
* The string should contain exactly one certificate and one private key in [PKCS #8][rfc_5208]
* format. It should not contain any other PEM-encoded blocks, but it may contain other text
* which will be ignored.
*
* Encode a held certificate into this format by concatenating the results of
* [certificatePem()][certificatePem] and [privateKeyPkcs8Pem()][privateKeyPkcs8Pem].
*
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
* [rfc_5208]: https://tools.ietf.org/html/rfc5208
*/
fun decode(certificateAndPrivateKeyPem: String): Pair<KeyPair, X509Certificate> {
var certificatePem: String? = null
var pkcs8Base64: String? = null
var pkcs1Base64: String? = null
for (match in PEM_REGEX.findAll(certificateAndPrivateKeyPem)) {
when (val label = match.groups[1]!!.value) {
"CERTIFICATE" -> {
require(certificatePem == null) { "string includes multiple certificates" }
certificatePem = match.groups[0]!!.value // Keep --BEGIN-- and --END-- for certificates.
}
"PRIVATE KEY" -> {
require(pkcs8Base64 == null && pkcs1Base64 == null) { "string includes multiple private keys" }
pkcs8Base64 = match.groups[2]!!.value // Include the contents only for PKCS8.
}
"RSA PRIVATE KEY" -> {
require(pkcs8Base64 == null && pkcs1Base64 == null) { "string includes multiple private keys" }
pkcs1Base64 = match.groups[2]!!.value // Include the contents only for PKCS1.
}
else -> {
throw IllegalArgumentException("unexpected type: $label")
}
}
}
require(certificatePem != null) { "string does not include a certificate" }
val certificate = certificatePem.decodeCertificatePem()
when {
pkcs8Base64 != null -> {
val keyType = when (certificate.publicKey) {
is ECPublicKey -> "EC"
is RSAPublicKey -> "RSA"
else -> throw IllegalArgumentException("unexpected key type: ${certificate.publicKey}")
}
val pkcs8Bytes = pkcs8Base64.decodeBase64()
?: throw IllegalArgumentException("failed to decode private key")
val privateKey = decodePkcs8(pkcs8Bytes, keyType)
val keyPair = KeyPair(certificate.publicKey, privateKey)
return Pair(keyPair, certificate)
}
pkcs1Base64 != null -> {
require(certificate.publicKey is RSAPublicKey) { "unexpected key type: ${certificate.publicKey}" }
val pkcs1Bytes = pkcs1Base64.decodeBase64()
?: throw IllegalArgumentException("failed to decode private key")
val privateKey = decodePkcs1(pkcs1Bytes)
val keyPair = KeyPair(certificate.publicKey, privateKey)
return Pair(keyPair, certificate)
}
else -> {
throw IllegalArgumentException("string does not include a private key")
}
}
}
internal fun decodePkcs8(data: ByteString, keyAlgorithm: String): PrivateKey {
try {
val keyFactory = KeyFactory.getInstance(keyAlgorithm)
val x = CertificateAdapters.privateKeyInfo.fromDer(data)
return keyFactory.generatePrivate(PKCS8EncodedKeySpec(data.toByteArray()))
} catch (e: GeneralSecurityException) {
throw IllegalArgumentException("failed to decode private key", e)
}
}
internal fun decodePkcs1(data: ByteString): PrivateKey {
try {
val privateKeyInfo = PrivateKeyInfo(0L, AlgorithmIdentifier("1.2.840.113549.1.1.1", null), data)
val pkcs8data = CertificateAdapters.privateKeyInfo.toDer(privateKeyInfo)
return decodePkcs8(pkcs8data, "RSA")
} catch (e: GeneralSecurityException) {
throw IllegalArgumentException("failed to decode private key", e)
}
}
internal val PEM_REGEX = Regex("""-----BEGIN ([!-,.-~ ]*)-----([^-]*)-----END \1-----""")
internal fun StringBuilder.encodeBase64Lines(data: ByteString) {
val base64 = data.base64()
for (i in base64.indices step 64) {
append(base64, i, minOf(i + 64, base64.length)).append('\n')
}
}
| 7 | null | 12 | 38 | 8a4bae82031dfecc5ace46bd77763313961379ad | 9,100 | certifikit | Apache License 2.0 |
OptiGUI/src/main/kotlin/opekope2/filter/FilterResult.kt | opekope2 | 578,779,647 | false | null | package opekope2.filter
/**
* Represents a filter result.
*
* @param T The type a [Filter] returns
*/
sealed interface FilterResult<T> {
/**
* Represents a skipping filter result.
*
* @param T The type a [Filter] would return in case of a match
*/
class Skip<T> : FilterResult<T> {
override fun toString(): String = "Skip"
}
/**
* Represents a mismatching filter result.
*
* @param T The type a [Filter] would return in case of a match
*/
class Mismatch<T> : FilterResult<T> {
override fun toString(): String = "Mismatch"
}
/**
* Represents a matching filter result.
*
* @param T The type a [Filter] returns
* @param result The result of the filter
*/
class Match<T>(val result: T) : FilterResult<T> {
override fun toString(): String = "Match, result: $result"
}
}
| 9 | Kotlin | 1 | 9 | d61d4c2a70f2d00cb7513bd19a0bfa309e7ee66d | 897 | OptiGUI | MIT License |
feieprinter/src/test/kotlin/com.yingtaohuo/FeieClientTest.kt | menuxx | 96,880,838 | false | {"JavaScript": 1254682, "Kotlin": 162067, "FreeMarker": 67462, "Java": 22082, "CSS": 2227, "HTML": 4} | package com.yingtaohuo
import org.junit.BeforeClass
import org.junit.Test
/**
* 作者: <EMAIL>
* 创建于: 2017/10/15
* 微信: yin80871901
*/
class FeieClientTest {
companion object {
@JvmStatic lateinit var client : FeieClient
@BeforeClass
@JvmStatic
fun setup() {
client = FeieClient("<EMAIL>", "uva5fA5ujzFN43EV")
}
}
@Test
fun printerAddlist() {
try {
client.delPrinterSqs("217506304") // 先删除
val result = client.printerAddlist(arrayListOf(
mapOf("sn" to "217506227", "key" to "qr5sfhsc", "remark" to "阿千木桶饭"),
mapOf("sn" to "217506229", "key" to "y2dabzee", "remark" to "我家的馄饨"),
mapOf("sn" to "217506228", "key" to "9z275x5a", "remark" to "粥饼人家")
))
client.printTestTicket("217506227", 1)
client.printTestTicket("217506229", 1)
client.printTestTicket("217506228", 1)
val ret = result.getInt("ret")
if ( ret != null ) {
print(result.getString("msg"))
print(result.getJSONObject("data").getJSONArray("no"))
print(result.getJSONObject("data").getJSONArray("ok"))
} else {
print(result.getJSONObject("data").getJSONArray("no"))
print(result.getJSONObject("data").getJSONArray("ok"))
}
} catch (ex: FeieException) {
ex.printStackTrace()
}
}
@Test
fun testPrinterAddlist() {
try {
val result = client.printerAddlist(arrayListOf(
mapOf("sn" to "217506304", "key" to "a75npeqj", "remark" to "一台带切刀的测试机")
))
val ret = result.getInt("ret")
if ( ret != null ) {
print(result.getString("msg"))
print(result.getJSONObject("data").getJSONArray("no"))
print(result.getJSONObject("data").getJSONArray("ok"))
} else {
print(result.getJSONObject("data").getJSONArray("no"))
print(result.getJSONObject("data").getJSONArray("ok"))
}
} catch (ex: FeieException) {
ex.printStackTrace()
}
}
@Test
fun printTestTicketTest() {
try {
val res = client.printTestTicket("217506304", 1)
val ret = res.getInt("ret")
if ( ret != 0 ) {
println(res.getString("msg"))
} else {
println(res.getString("msg"))
}
} catch (ex: FeieException) {
ex.printStackTrace()
}
}
@Test
fun queryPrinterStatusTest() {
try {
val res = client.queryPrinterStatus("217506304")
val ret = res.getInt("ret")
if ( ret != 0 ) {
println(res.getString("msg"))
} else {
println(res.getString("data"))
println(res.getString("msg"))
}
} catch (ex: FeieException) {
ex.printStackTrace()
}
}
} | 0 | JavaScript | 0 | 0 | 81ffb601aa4b92024966067574357109ac81e115 | 3,144 | sso | Apache License 2.0 |
app/src/main/java/com/nima/triviaapp/MainActivity.kt | NimaKhajehpour | 592,016,135 | false | null | package com.nima.triviaapp
import android.os.Bundle
import android.text.Html
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.nima.triviaapp.model.Questions
import com.nima.triviaapp.navigation.QuestionNavigation
import com.nima.triviaapp.screens.QuestionViewModel
import com.nima.triviaapp.ui.theme.TriviaAppTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TriviaAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
QuestionNavigation()
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
TriviaAppTheme {
}
} | 0 | Kotlin | 0 | 0 | 1009cd44e10c55ce93fd19277c31a8db13279ef8 | 1,610 | TriviaApp | MIT License |
app/src/main/java/com/nima/triviaapp/MainActivity.kt | NimaKhajehpour | 592,016,135 | false | null | package com.nima.triviaapp
import android.os.Bundle
import android.text.Html
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import com.nima.triviaapp.model.Questions
import com.nima.triviaapp.navigation.QuestionNavigation
import com.nima.triviaapp.screens.QuestionViewModel
import com.nima.triviaapp.ui.theme.TriviaAppTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
TriviaAppTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
QuestionNavigation()
}
}
}
}
}
@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
TriviaAppTheme {
}
} | 0 | Kotlin | 0 | 0 | 1009cd44e10c55ce93fd19277c31a8db13279ef8 | 1,610 | TriviaApp | MIT License |
src/main/kotlin/com/github/surpsg/diffcoverage/extensions/DiffCoverageRunner.kt | SurpSG | 286,551,507 | false | null | package com.github.surpsg.diffcoverage.extensions
import com.github.surpsg.diffcoverage.DiffCoverageBundle
import com.github.surpsg.diffcoverage.domain.CoverageStat
import com.github.surpsg.diffcoverage.domain.ProjectDataWithStat
import com.github.surpsg.diffcoverage.properties.PLUGIN_NAME
import com.github.surpsg.diffcoverage.services.diff.ModifiedFilesService
import com.github.surpsg.diffcoverage.services.notifications.BalloonNotificationService
import com.intellij.coverage.CoverageEngine
import com.intellij.coverage.CoverageRunner
import com.intellij.coverage.CoverageSuite
import com.intellij.notification.NotificationType
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import java.io.File
import java.nio.file.Path
class DiffCoverageRunner(
private val project: Project,
private val classesPath: Set<Path>,
private val execFilesPaths: Set<Path>
) : CoverageRunner() {
override fun loadCoverageData(sessionDataFile: File, baseCoverageSuite: CoverageSuite?): ProjectDataWithStat {
return try {
DiffCoverageLoader().loadDiffExecutionData(
project.service<ModifiedFilesService>().obtainCodeUpdateInfo(),
classesPath,
execFilesPaths
)
} catch (e: Exception) {
LOG.error("Cannot load coverage data", e)
project.service<BalloonNotificationService>().notify(
notificationType = NotificationType.WARNING,
message = DiffCoverageBundle.message("cannot.load.diff.coverage.data", execFilesPaths)
)
ProjectDataWithStat(CoverageStat(emptyMap()))
}
}
override fun getPresentableName(): String = DiffCoverageBundle.message(PLUGIN_NAME)
override fun getId(): String = "diff_coverage"
override fun getDataFileExtension(): String = "exec"
override fun acceptsCoverageEngine(engine: CoverageEngine): Boolean {
val javaCoverageEngineClass = CoverageEngine.EP_NAME.findFirstSafe {
it.javaClass.simpleName.endsWith("JavaCoverageEngine")
}?.javaClass ?: return false
return javaCoverageEngineClass.isInstance(engine)
}
companion object {
private val LOG = Logger.getInstance(DiffCoverageRunner::class.java)
}
}
| 2 | Kotlin | 2 | 4 | 8372cce7cd3c0716cdcfc3d281075381c5bec5e3 | 2,364 | diff-coverage-idea-plugin | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/A.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.A: ImageVector
get() {
if (_a != null) {
return _a!!
}
_a = Builder(name = "A", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth =
24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.713f, 24.0f)
horizontalLineToRelative(2.156f)
lineTo(14.859f, 1.661f)
curveToRelative(-0.511f, -1.024f, -1.54f, -1.661f, -2.684f, -1.661f)
horizontalLineToRelative(-0.002f)
curveToRelative(-1.146f, 0.0f, -2.174f, 0.638f, -2.711f, 1.724f)
lineTo(0.168f, 24.0f)
horizontalLineTo(2.335f)
lineToRelative(2.92f, -7.0f)
horizontalLineToRelative(13.636f)
lineToRelative(2.822f, 7.0f)
close()
moveTo(6.089f, 15.0f)
lineTo(11.28f, 2.554f)
curveToRelative(0.172f, -0.347f, 0.507f, -0.554f, 0.894f, -0.554f)
horizontalLineToRelative(0.0f)
curveToRelative(0.387f, 0.0f, 0.721f, 0.207f, 0.862f, 0.481f)
lineToRelative(5.047f, 12.519f)
horizontalLineTo(6.089f)
close()
}
}
.build()
return _a!!
}
private var _a: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,146 | icons | MIT License |
multiplatform-ui/src/jvmMain/kotlin/main.kt | shalva97 | 371,007,326 | false | null | import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import di.kodein
import org.kodein.di.compose.withDI
import ui.MainScreen
fun main() = application {
Window(
onCloseRequest = ::exitApplication,
title = "Youtube history",
state = rememberWindowState(width = 700.dp, height = 400.dp)
) {
withDI(di = kodein) {
MaterialTheme(colorScheme = lightColorScheme()) {
MainScreen()
}
}
}
} | 22 | null | 0 | 13 | 350cd8d93f0b4b28e9751f7b41c001e05ef9b642 | 697 | Youtube_history_parser | The Unlicense |
token-validation-core/src/main/kotlin/no/nav/security/token/support/core/validation/DefaultJwtClaimsVerifier.kt | navikt | 124,397,000 | false | null | package no.nav.security.token.support.core.validation
import com.nimbusds.jose.proc.SecurityContext
import com.nimbusds.jwt.JWTClaimsSet
import com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier
import com.nimbusds.jwt.util.DateUtils.isBefore
import com.nimbusds.openid.connect.sdk.validators.BadJWTExceptions.IAT_CLAIM_AHEAD_EXCEPTION
import java.util.Date
/**
* Extends [com.nimbusds.jwt.proc.DefaultJWTClaimsVerifier] with a time check for the issued at ("iat") claim.
* The claim is only checked if it exists in the given claim set.
*/
class DefaultJwtClaimsVerifier<C : SecurityContext>(acceptedAudience : Set<String?>?, exactMatchClaims : JWTClaimsSet, requiredClaims : Set<String>, prohibitedClaims : Set<String>) : DefaultJWTClaimsVerifier<C>(acceptedAudience, exactMatchClaims, requiredClaims, prohibitedClaims) {
override fun verify(claimsSet: JWTClaimsSet, context: C?) =
super.verify(claimsSet, context).also {
claimsSet.issueTime?.let { iat ->
if (!isBefore(iat, Date(), maxClockSkew.toLong())) {
throw IAT_CLAIM_AHEAD_EXCEPTION
}
}
}
} | 9 | null | 7 | 15 | efc8bf993d42d153998f79b797a53477be9b1479 | 1,147 | token-support | MIT License |
app/src/test/java/com/gzaber/keepnote/ui/elementsoverview/ElementsOverviewScreenTest.kt | gzaber | 690,170,857 | false | {"Kotlin": 239289} | package com.gzaber.keepnote.ui.elementsoverview
import androidx.compose.ui.test.ExperimentalTestApi
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.hasText
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.longClick
import androidx.compose.ui.test.onNodeWithContentDescription
import androidx.compose.ui.test.onNodeWithText
import androidx.compose.ui.test.performClick
import androidx.compose.ui.test.performTouchInput
import com.gzaber.keepnote.data.repository.FoldersRepository
import com.gzaber.keepnote.data.repository.NotesRepository
import com.gzaber.keepnote.ui.util.model.Element
import com.gzaber.keepnote.ui.util.model.toFolder
import com.gzaber.keepnote.ui.util.model.toNote
import com.gzaber.keepnote.util.RobolectricTestActivity
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import dagger.hilt.android.testing.HiltTestApplication
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import javax.inject.Inject
@OptIn(ExperimentalTestApi::class)
@RunWith(RobolectricTestRunner::class)
@HiltAndroidTest
@Config(application = HiltTestApplication::class)
class ElementsOverviewScreenTest {
@get:Rule(order = 0)
val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1)
val robolectricTestActivityRule = RobolectricTestActivity()
@get:Rule(order = 2)
val composeTestRule = createComposeRule()
@Inject
lateinit var foldersRepository: FoldersRepository
@Inject
lateinit var notesRepository: NotesRepository
@Before
fun setUp() {
hiltRule.inject()
}
@Test
fun elementsOverviewScreen_appTitleIsDisplayed() = runTest {
setContent()
composeTestRule.onNodeWithText("KeepNote").assertIsDisplayed()
}
@Test
fun elementsOverviewScreen_folderAndNoteAreDisplayedAndCanBeClicked() = runTest {
insertElements()
setContent()
composeTestRule.apply {
waitUntilExactlyOneExists(hasText("folder"))
onNodeWithText("folder").assertIsDisplayed().performClick()
onNodeWithText("note").assertIsDisplayed().performClick()
onNodeWithText("content").assertIsDisplayed().performClick()
}
}
@Test
fun elementsOverviewScreen_elementItemIsLongClicked_modalBottomSheetIsDisplayed() = runTest {
insertElements()
setContent()
composeTestRule.apply {
waitUntilExactlyOneExists(hasText("folder"))
onNodeWithText("folder").assertIsDisplayed().performTouchInput { longClick() }
onNodeWithText("Edit").assertIsDisplayed().performClick()
onNodeWithText("note").assertIsDisplayed().performTouchInput { longClick() }
onNodeWithText("Delete").assertIsDisplayed().performClick()
}
}
@Test
fun elementsOverviewScreen_viewIsChanged_folderAndNoteAreDisplayed() = runTest {
insertElements()
setContent()
composeTestRule.apply {
onNodeWithContentDescription("Grid view").assertIsDisplayed().performClick()
waitUntilExactlyOneExists(hasText("folder"))
onNodeWithText("folder").assertIsDisplayed()
onNodeWithText("note").assertIsDisplayed()
onNodeWithText("content").assertIsDisplayed()
}
}
@Test
fun elementsOverviewScreen_sortButtonIsClicked_modalBottomSheetIsDisplayed() = runTest {
setContent()
composeTestRule.apply {
onNodeWithContentDescription("Sort").assertIsDisplayed().performClick()
onNodeWithText("Sort by").assertIsDisplayed()
onNodeWithText("Order").assertIsDisplayed()
onNodeWithText("First elements").assertIsDisplayed()
}
}
@Test
fun elementsOverviewScreen_fabIsClicked_modalBottomSheetIsDisplayed() = runTest {
setContent()
composeTestRule.apply {
onNodeWithContentDescription("Create element").assertIsDisplayed().performClick()
onNodeWithText("Folder").assertIsDisplayed().performClick()
onNodeWithContentDescription("Create element").assertIsDisplayed().performClick()
onNodeWithText("Note").assertIsDisplayed().performClick()
}
}
private suspend fun insertElements() {
foldersRepository.createFolder(Element.empty().copy(name = "folder").toFolder())
notesRepository.createNote(
Element.empty().copy(name = "note", content = "content").toNote()
)
}
private fun setContent() {
composeTestRule.setContent {
ElementsOverviewScreen(
onElementClick = { _, _ -> },
onCreateElement = {},
onUpdateElement = { _, _ -> },
viewModel = ElementsOverviewViewModel(
foldersRepository = foldersRepository,
notesRepository = notesRepository
)
)
}
}
} | 0 | Kotlin | 1 | 0 | 58d4e17785eedda5f0110e0f47b46405b8f47158 | 5,207 | KeepNote | MIT License |
idea/src/org/jetbrains/kotlin/idea/quickfix/crossLanguage/ChangeMethodParameters.kt | JetBrains | 278,369,660 | false | null | /*
* Copyright 2010-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/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.quickfix.crossLanguage
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.lang.jvm.actions.AnnotationRequest
import com.intellij.lang.jvm.actions.ChangeParametersRequest
import com.intellij.lang.jvm.actions.ExpectedParameter
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.JvmPsiConversionHelper
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.ValueParameterDescriptorImpl
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.quickfix.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.load.java.NOT_NULL_ANNOTATIONS
import org.jetbrains.kotlin.load.java.NULLABLE_ANNOTATIONS
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.KotlinType
internal class ChangeMethodParameters(
target: KtNamedFunction,
val request: ChangeParametersRequest
) : KotlinQuickFixAction<KtNamedFunction>(target) {
override fun getText(): String {
val target = element ?: return KotlinBundle.message("fix.change.signature.unavailable")
val helper = JvmPsiConversionHelper.getInstance(target.project)
val parametersString = request.expectedParameters.joinToString(", ", "(", ")") { ep ->
val kotlinType =
ep.expectedTypes.firstOrNull()?.theType?.let { helper.convertType(it).resolveToKotlinType(target.getResolutionFacade()) }
val parameterName = ep.semanticNames.firstOrNull() ?: KotlinBundle.message("fix.change.signature.unnamed.parameter")
"$parameterName: ${kotlinType?.let {
IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(it)
} ?: KotlinBundle.message("fix.change.signature.error")}"
}
val shortenParameterString = StringUtil.shortenTextWithEllipsis(parametersString, 30, 5)
return QuickFixBundle.message("change.method.parameters.text", shortenParameterString)
}
override fun getFamilyName(): String = QuickFixBundle.message("change.method.parameters.family")
override fun isAvailable(project: Project, editor: Editor?, file: KtFile): Boolean = element != null && request.isValid
private sealed class ParameterModification {
data class Keep(val ktParameter: KtParameter) : ParameterModification()
data class Remove(val ktParameter: KtParameter) : ParameterModification()
data class Add(
val name: String,
val ktType: KotlinType,
val expectedAnnotations: Collection<AnnotationRequest>,
val beforeAnchor: KtParameter?
) : ParameterModification()
}
private tailrec fun getParametersModifications(
target: KtNamedFunction,
currentParameters: List<KtParameter>,
expectedParameters: List<ExpectedParameter>,
index: Int = 0,
collected: List<ParameterModification> = ArrayList(expectedParameters.size)
): List<ParameterModification> {
val expectedHead = expectedParameters.firstOrNull() ?: return collected + currentParameters.map { ParameterModification.Remove(it) }
if (expectedHead is ChangeParametersRequest.ExistingParameterWrapper) {
val expectedExistingParameter = expectedHead.existingKtParameter
if (expectedExistingParameter == null) {
LOG.error("can't find the kotlinOrigin for parameter ${expectedHead.existingParameter} at index $index")
return collected
}
val existingInTail = currentParameters.indexOf(expectedExistingParameter)
if (existingInTail == -1) {
throw IllegalArgumentException("can't find existing for parameter ${expectedHead.existingParameter} at index $index")
}
return getParametersModifications(
target,
currentParameters.subList(existingInTail + 1, currentParameters.size),
expectedParameters.subList(1, expectedParameters.size),
index,
collected
+ currentParameters.subList(0, existingInTail).map { ParameterModification.Remove(it) }
+ ParameterModification.Keep(expectedExistingParameter)
)
}
val helper = JvmPsiConversionHelper.getInstance(target.project)
val theType = expectedHead.expectedTypes.firstOrNull()?.theType ?: return emptyList()
val kotlinType = helper.convertType(theType).resolveToKotlinType(target.getResolutionFacade()) ?: return emptyList()
return getParametersModifications(
target,
currentParameters,
expectedParameters.subList(1, expectedParameters.size),
index + 1,
collected + ParameterModification.Add(
expectedHead.semanticNames.firstOrNull() ?: "param$index",
kotlinType,
expectedHead.expectedAnnotations,
currentParameters.firstOrNull { anchor ->
expectedParameters.any {
it is ChangeParametersRequest.ExistingParameterWrapper && it.existingKtParameter == anchor
}
})
)
}
private val ChangeParametersRequest.ExistingParameterWrapper.existingKtParameter
get() = (existingParameter as? KtLightElement<*, *>)?.kotlinOrigin as? KtParameter
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
if (!request.isValid) return
val target = element ?: return
val functionDescriptor = target.resolveToDescriptorIfAny(BodyResolveMode.FULL) ?: return
val parameterActions = getParametersModifications(target, target.valueParameters, request.expectedParameters)
val parametersGenerated = parameterActions.filterIsInstance<ParameterModification.Add>().let {
it zip generateParameterList(project, functionDescriptor, it).parameters
}.toMap()
for (action in parameterActions) {
when (action) {
is ParameterModification.Add -> {
val parameter = parametersGenerated.getValue(action)
for (expectedAnnotation in action.expectedAnnotations) {
addAnnotationEntry(parameter, expectedAnnotation, null)
}
val anchor = action.beforeAnchor
if (anchor != null) {
target.valueParameterList!!.addParameterBefore(parameter, anchor)
} else {
target.valueParameterList!!.addParameter(parameter)
}
}
is ParameterModification.Keep -> {
// Do nothing
}
is ParameterModification.Remove -> {
target.valueParameterList!!.removeParameter(action.ktParameter)
}
}
}
ShortenReferences.DEFAULT.process(target.valueParameterList!!)
}
private fun generateParameterList(
project: Project,
functionDescriptor: FunctionDescriptor,
paramsToAdd: List<ParameterModification.Add>
): KtParameterList {
val newFunctionDescriptor = SimpleFunctionDescriptorImpl.create(
functionDescriptor.containingDeclaration,
functionDescriptor.annotations,
functionDescriptor.name,
functionDescriptor.kind,
SourceElement.NO_SOURCE
).apply {
initialize(
functionDescriptor.extensionReceiverParameter?.copy(this),
functionDescriptor.dispatchReceiverParameter,
functionDescriptor.typeParameters,
paramsToAdd.mapIndexed { index, parameter ->
ValueParameterDescriptorImpl(
this, null, index, Annotations.EMPTY,
Name.identifier(parameter.name),
parameter.ktType, declaresDefaultValue = false,
isCrossinline = false, isNoinline = false, varargElementType = null, source = SourceElement.NO_SOURCE
)
},
functionDescriptor.returnType,
functionDescriptor.modality,
functionDescriptor.visibility
)
}
val renderer = IdeDescriptorRenderers.SOURCE_CODE.withOptions {
defaultParameterValueRenderer = null
}
val newFunction = KtPsiFactory(project).createFunction(renderer.render(newFunctionDescriptor)).apply {
valueParameters.forEach { param ->
param.annotationEntries.forEach { a ->
a.typeReference?.run {
val fqName = FqName(this.text)
if (fqName in (NULLABLE_ANNOTATIONS + NOT_NULL_ANNOTATIONS)) a.delete()
}
}
}
}
return newFunction.valueParameterList!!
}
companion object {
fun create(ktNamedFunction: KtNamedFunction, request: ChangeParametersRequest): ChangeMethodParameters? =
ChangeMethodParameters(ktNamedFunction, request)
}
}
private val LOG = Logger.getInstance(ChangeMethodParameters::class.java) | 191 | null | 4372 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 10,299 | intellij-kotlin | Apache License 2.0 |
sonicinapp/src/main/java/com/orbitalsonic/sonicinapp/interfaces/BillingListener.kt | orbitalsonic | 579,858,666 | false | {"Kotlin": 72244} | package com.orbitalsonic.sonicinapp.interfaces
import com.orbitalsonic.sonicinapp.dataClasses.PurchaseDetail
/**
* @Author: <NAME>
* @Date: 01,October,2024.
* @Accounts
* -> https://github.com/orbitalsonic
* -> https://www.linkedin.com/in/myaqoob7
*/
interface BillingListener {
fun onConnectionResult(isSuccess: Boolean, message: String)
fun purchasesResult(purchaseDetailList: List<PurchaseDetail>)
} | 0 | Kotlin | 1 | 0 | 18fdda950c836fd9e209bf38b59486fef0d602c8 | 429 | SonicInApp | Apache License 2.0 |
app/src/main/kotlin/com/jpaya/englishisfun/statives/ui/adapter/StativesAdapter.kt | jpaya17 | 254,323,532 | false | null | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jpaya.englishisfun.statives.ui.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.jpaya.base.adapter.ListAdapterComparator
import com.jpaya.englishisfun.DataBindingAdapter
import com.jpaya.englishisfun.databinding.StativeListItemBinding
import com.jpaya.englishisfun.statives.ui.model.StativeItem
import com.simplecityapps.recyclerview_fastscroll.views.FastScrollRecyclerView
class StativesAdapter :
ListAdapter<StativeItem, StativesAdapter.ViewHolder>(ListAdapterComparator<StativeItem>()),
FastScrollRecyclerView.SectionedAdapter,
DataBindingAdapter<List<StativeItem>> {
override fun setData(data: List<StativeItem>) = submitList(data)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ViewHolder(StativeListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false))
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(getItem(position))
override fun getSectionName(position: Int): String = getItem(position).category.first().toString()
class ViewHolder(val binding: StativeListItemBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(item: StativeItem) {
binding.stative = item
binding.executePendingBindings()
}
}
}
| 20 | Kotlin | 6 | 49 | 5f6b5583f1a259407e85f6ecad6333b208b98885 | 2,011 | englishisfun | Apache License 2.0 |
QuantasPessoasTemMeuNome/app/src/main/java/com/example/quantaspessoastemmeunome22101195/dadosremotos/RespostaNome.kt | RafaCaire1507 | 759,526,248 | false | {"Kotlin": 24221, "Java": 4506} | package com.example.quantaspessoastemmeunome22101195.dadosremotos
import com.google.gson.annotations.SerializedName
class RespostaNome (
@SerializedName("nome") var nome:String,
@SerializedName("res") var res: List<Frequencia>
)
class Frequencia(
@SerializedName("periodo") var periodo: String,
@SerializedName("frequencia") var frequencia: String
) | 0 | Kotlin | 0 | 0 | a99b4c635fb6bea39df00e33c28c1591ead02f2d | 372 | Android | MIT License |
src/jp/seraphyware/simpleapp5/SimpleApp5Controller.kt | massongit | 95,294,856 | true | {"Kotlin": 40299, "CSS": 1216} | package jp.seraphyware.simpleapp4
import javafx.beans.binding.Bindings
import javafx.event.ActionEvent
import javafx.fxml.FXML
import javafx.fxml.Initializable
import javafx.scene.control.Alert
import javafx.scene.control.Alert.AlertType
import javafx.scene.control.Button
import javafx.scene.control.CheckBox
import javafx.scene.control.TextField
import javafx.scene.layout.BorderPane
import javafx.stage.Stage
import java.net.URL
import java.util.*
/**
* 入れ子になったFXMLを使うアプリケーション作成例.
* (リソースバンドル使用)
* @author seraphy, <NAME>
*/
class SimpleApp4Controller : Initializable {
/**
* 入れ子になったFXMLのルートがパイントされる.
* フィールド名は子FXMLのidと同じでなければならない.
*/
@FXML
private lateinit var dirTextField: BorderPane
/**
* 入れ子になったFXMLでインスタンス化されたコントローラがバインドされる
* フィールド名は"子FXMLのid + Controller"でなければならない.
*/
@FXML
private lateinit var dirTextFieldController: DirTextFieldController
@FXML
private lateinit var txtNamePattern: TextField
@FXML
private lateinit var chkSubdir: CheckBox
@FXML
private lateinit var btnOK: Button
override fun initialize(location: URL, resources: ResourceBundle) {
// OKボタンの活性制御
this.btnOK.disableProperty().bind(Bindings.or(this.dirTextFieldController.textProperty.isEmpty, this.txtNamePattern.textProperty().isEmpty))
// ディレクトリ選択テキストにフォーカスを当てる
this.dirTextField.requestFocus()
}
@FXML
private fun onOK() = Alert(AlertType.INFORMATION).apply {
headerText = "実行!"
contentText = listOf("dir=${dirTextFieldController.text}", "namePattern=${txtNamePattern.text}", "subdir=" + if (chkSubdir.isSelected) "Yes" else "No").joinToString(System.lineSeparator())
showAndWait()
}
/**
* 現在ボタンを表示しているシーンを表示しているステージに対してクローズを要求する.
*/
@FXML
private fun onCancel(evt: ActionEvent) = ((evt.source as Button).scene.window as Stage).close()
}
| 0 | Kotlin | 0 | 1 | 20dba4bc8c166b81b85ff2089a0711bf70ea53f2 | 1,911 | JavaFXSimpleAppForKotlin | MIT License |
app/src/main/java/io/zoemeow/dutschedule/ui/view/settings/controls/DeleteAllSubjectFilterDialog.kt | ZoeMeow1027 | 504,228,485 | false | {"Kotlin": 684767} | package io.zoemeow.dutschedule.ui.component.settings
import android.content.Context
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ElevatedButton
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import io.zoemeow.dutschedule.R
import io.zoemeow.dutschedule.activity.SettingsActivity
import io.zoemeow.dutschedule.ui.component.base.DialogBase
@Composable
fun SettingsActivity.DeleteAllSubjectFilterDialog(
context: Context,
isVisible: Boolean = false,
onDismiss: (() -> Unit)? = null,
onDone: (() -> Unit)? = null
) {
DialogBase(
modifier = Modifier.fillMaxWidth().padding(25.dp),
title = context.getString(R.string.settings_newsnotify_newsfilter_dialogdeleteall_title),
isVisible = isVisible,
canDismiss = false,
dismissClicked = { onDismiss?.let { it() } },
content = {
Column(
horizontalAlignment = Alignment.Start,
verticalArrangement = Arrangement.Top,
modifier = Modifier.fillMaxWidth(),
) {
Text(
text = context.getString(R.string.settings_newsnotify_newsfilter_dialogdeleteall_description),
modifier = Modifier.padding(bottom = 5.dp)
)
}
},
actionButtons = {
TextButton(
onClick = { onDismiss?.let { it() } },
content = { Text(context.getString(R.string.settings_newsnotify_newsfilter_dialogdelete_no)) },
modifier = Modifier.padding(start = 8.dp),
)
ElevatedButton(
colors = ButtonDefaults.elevatedButtonColors().copy(
containerColor = Color.Red,
contentColor = Color.White
),
onClick = { onDone?.let { it() } },
content = { Text(context.getString(R.string.settings_newsnotify_newsfilter_dialogdelete_yes)) },
modifier = Modifier.padding(start = 8.dp),
)
}
)
} | 0 | Kotlin | 0 | 1 | f2a2759a5df84a3665ec7f2a589606890b6bcd14 | 2,510 | DutSchedule | MIT License |
sample/src/main/java/io/github/onreg/todo/main/MainViewModel.kt | onreg | 349,964,657 | false | null | package io.github.onreg.todo.main
import androidx.lifecycle.ViewModel
import io.github.onreg.flowcache.statusCache
import io.github.onreg.todo.db.Database
import io.github.onreg.todo.db.TodoEntity
class MainViewModel : ViewModel() {
val todos by statusCache<List<TodoEntity>> {
Database.todoDao
.getTodos()
}
} | 0 | Kotlin | 0 | 5 | 4974cd747474a4b081d39fb06f4e528c849ff9d9 | 341 | flow-cache | Apache License 2.0 |
src/main/kotlin/com/imran/api/repos/GenreRepository.kt | imran94 | 800,413,385 | false | {"Kotlin": 37483} | package com.imran.api.repos
import com.imran.api.models.Genre
import org.springframework.data.jpa.repository.JpaRepository
interface GenreRepository: JpaRepository<Genre, Long> | 0 | Kotlin | 0 | 0 | 6544e4194335c4ee386dd6296ebe5f8990959117 | 178 | spring-boot-api | Apache License 2.0 |
src/test/kotlin/no/nav/syfo/testhelper/generator/DialogmeldingFraBehandlerGenerator.kt | navikt | 602,146,320 | false | {"Kotlin": 404554, "Dockerfile": 226} | package no.nav.syfo.testhelper.generator
import no.nav.syfo.melding.kafka.domain.*
import no.nav.syfo.testhelper.UserConstants
import no.nav.syfo.domain.PersonIdent
import no.nav.syfo.melding.kafka.domain.Dialogmelding
import no.nav.syfo.melding.kafka.domain.ForesporselFraSaksbehandlerForesporselSvar
import no.nav.syfo.melding.kafka.domain.KafkaDialogmeldingFraBehandlerDTO
import no.nav.syfo.melding.kafka.domain.TemaKode
import java.time.LocalDateTime
import java.util.*
val fellesformatXML = """<?xml version="1.0" ?>
<EI_fellesformat xmlns="http://www.nav.no/xml/eiff/2/" >
<MsgHead xmlns="http://www.kith.no/xmlstds/msghead/2006-05-24">
<Type DN="Notat" V="DIALOG_NOTAT" />
<MIGversion>v1.2 2006-05-24</MIGversion>
<GenDate>2019-01-16T22:51:35.5317672+01:00</GenDate>
<MsgId>37340D30-FE14-42B5-985F-A8FF8FFA0CB5</MsgId>
<ConversationRef>
<RefToConversation>37340D30-FE14-42B5-985F-A8FF8FFA0C99</RefToConversation>
<RefToParent>37340D30-FE14-42B5-985F-A8FF8FFA0CB5</RefToParent>
</ConversationRef>
<Ack DN="Ja" V="J" />
<Sender>
<Organisation>
<OrganisationName>Kule helsetjenester AS</OrganisationName>
<Ident>
<Id>223456789</Id>
<TypeId DN="Organisasjonsnummeret i Enhetsregister (Brønnøysund)" S="1.16.578.1.12.3.1.1.9051" V="ENH" />
</Ident>
<Ident>
<Id>0123</Id>
<TypeId DN="Identifikator fra Helsetjenesteenhetsregisteret (HER-id)" V="HER" S="1.23.456.7.89.1.2.3.4567.8912" />
</Ident>
<Address>
<StreetAdr>Oppdiktet gate 203</StreetAdr>
<PostalCode>1234</PostalCode>
<City>Oslo</City>
</Address>
<Organisation/>
<HealthcareProfessional>
<Ident>
<Id>${UserConstants.BEHANDLER_PERSONIDENT.value}</Id>
<TypeId V="FNR" S="2.16.578.1.12.4.1.1.8116" DN="Fødselsnummer Norsk fødselsnummer"/>
</Ident>
<Ident>
<Id>${UserConstants.HPRID}</Id>
<TypeId V="HPR" S="2.16.578.1.12.4.1.1.8116" DN="HPR-nummer"/>
</Ident>
<Ident>
<Id>${UserConstants.HERID}</Id>
<TypeId V="HER" S="2.16.578.1.12.4.1.1.8116" DN="Identifikator fra Helsetjenesteenhetsregisteret"/>
</Ident>
</HealthcareProfessional>
</Organisation>
</Sender>
<Receiver>
<Organisation>
<OrganisationName>NAV</OrganisationName>
<Ident>
<Id>889640782</Id>
<TypeId DN="Organisasjonsnummeret i Enhetsregister (Brønnøysund)" S="2.16.578.1.12.4.1.1.9051" V="ENH" />
</Ident>
<Ident>
<Id>79768</Id>
<TypeId DN="Identifikator fra Helsetjenesteenhetsregisteret (HER-id)" S="2.16.578.1.12.4.1.1.9051" V="HER" />
</Ident>
</Organisation>
</Receiver>
<Patient>
<FamilyName>Test</FamilyName>
<GivenName>Etternavn</GivenName>
<DateOfBirth>1991-12-4</DateOfBirth>
<Sex DN="Mann" V="1" />
<Ident>
<Id>${UserConstants.ARBEIDSTAKER_PERSONIDENT.value}</Id>
<TypeId DN="Fødselsnummer" S="2.16.578.1.12.4.1.1.8116" V="FNR" />
</Ident>
<Address>
<Type DN="Postadresse" V="PST" />
<StreetAdr>Sannergata 2</StreetAdr>
<PostalCode>0655</PostalCode>
<City>OSLO</City>
<County DN="OSLO" V="0712" />
</Address>
</Patient>
</MsgHead>
<MottakenhetBlokk avsender="12312341" avsenderFnrFraDigSignatur="${UserConstants.BEHANDLER_PERSONIDENT.value}" avsenderRef="SERIALNUMBER=996871045, CN=LEGEHUSET NOVA DA, O=LEGEHUSET NOVA DA, C=NO" ebAction="Henvendelse" ebRole="Sykmelder" ebService="HenvendelseFraLege" ebXMLSamtaleId="615356d4-f5e6-4138-a868-bbb63bd6195d" ediLoggId="1901162157lege21826.1" herIdentifikator="" meldingsType="xml" mottattDatotid="2019-01-16T21:57:43" partnerReferanse="${UserConstants.PARTNERID}" />
</EI_fellesformat>"""
fun generateDialogmeldingFraBehandlerDialogNotatDTO(
uuid: UUID = UUID.randomUUID(),
personIdent: PersonIdent = UserConstants.ARBEIDSTAKER_PERSONIDENT,
conversationRef: String = UUID.randomUUID().toString(),
antallVedlegg: Int = 0,
) = KafkaDialogmeldingFraBehandlerDTO(
msgId = uuid.toString(),
msgType = DialogmeldingType.DIALOG_NOTAT.name,
navLogId = "1234asd123",
mottattTidspunkt = LocalDateTime.now(),
conversationRef = conversationRef,
parentRef = UUID.randomUUID().toString(),
personIdentPasient = personIdent.value,
personIdentBehandler = UserConstants.BEHANDLER_PERSONIDENT.value,
legekontorOrgNr = "987654321",
legekontorHerId = "",
legekontorOrgName = "",
legehpr = UserConstants.HPRID.toString(),
fellesformatXML = fellesformatXML,
antallVedlegg = antallVedlegg,
dialogmelding = Dialogmelding(
id = uuid.toString(),
henvendelseFraLegeHenvendelse = HenvendelseFraLegeHenvendelse(
temaKode = TemaKode(KODEVERK_MELDING_TIL_NAV, "Henvendelse om sykefraværsoppfølging", HENVENDELSE_OM_SYKEFRAVAR, "", "", ""),
tekstNotatInnhold = "Dette er innholdet i et notat",
dokIdNotat = null,
foresporsel = null,
rollerRelatertNotat = null,
),
navnHelsepersonell = UserConstants.BEHANDLER_NAVN,
signaturDato = LocalDateTime.now(),
foresporselFraSaksbehandlerForesporselSvar = null,
innkallingMoterespons = null,
)
)
fun generateDialogmeldingFraBehandlerDialogNotatIkkeSykefravrDTO(
uuid: UUID = UUID.randomUUID(),
personIdent: PersonIdent = UserConstants.ARBEIDSTAKER_PERSONIDENT_INACTIVE,
conversationRef: String = UUID.randomUUID().toString(),
antallVedlegg: Int = 0,
) = KafkaDialogmeldingFraBehandlerDTO(
msgId = uuid.toString(),
msgType = DialogmeldingType.DIALOG_NOTAT.name,
navLogId = "1234asd123",
mottattTidspunkt = LocalDateTime.now(),
conversationRef = conversationRef,
parentRef = UUID.randomUUID().toString(),
personIdentPasient = personIdent.value,
personIdentBehandler = UserConstants.BEHANDLER_PERSONIDENT.value,
legekontorOrgNr = "987654321",
legekontorHerId = "",
legekontorOrgName = "",
legehpr = UserConstants.HPRID.toString(),
fellesformatXML = fellesformatXML,
antallVedlegg = antallVedlegg,
dialogmelding = Dialogmelding(
id = uuid.toString(),
henvendelseFraLegeHenvendelse = HenvendelseFraLegeHenvendelse(
temaKode = TemaKode(KODEVERK_MELDING_TIL_NAV, "Henvendelse om pasient", HENVENDELSE_OM_PASIENT, "", "", ""),
tekstNotatInnhold = "Dette er innholdet i et notat",
dokIdNotat = null,
foresporsel = null,
rollerRelatertNotat = null,
),
navnHelsepersonell = UserConstants.BEHANDLER_NAVN,
signaturDato = LocalDateTime.now(),
foresporselFraSaksbehandlerForesporselSvar = null,
innkallingMoterespons = null,
)
)
fun generateDialogmeldingFraBehandlerForesporselSvarDTO(
uuid: UUID = UUID.randomUUID(),
personIdent: PersonIdent = UserConstants.ARBEIDSTAKER_PERSONIDENT,
conversationRef: String = UUID.randomUUID().toString(),
parentRef: String = UUID.randomUUID().toString(),
kodeverk: String = "2.16.578.1.12.4.1.1.9069",
kodeTekst: String = "Svar på forespørsel",
kode: String = "5",
antallVedlegg: Int = 0,
) = KafkaDialogmeldingFraBehandlerDTO(
msgId = uuid.toString(),
msgType = DialogmeldingType.DIALOG_SVAR.name,
navLogId = "1234asd123",
mottattTidspunkt = LocalDateTime.now(),
conversationRef = conversationRef,
parentRef = parentRef,
personIdentPasient = personIdent.value,
personIdentBehandler = UserConstants.BEHANDLER_PERSONIDENT.value,
legekontorOrgNr = "987654321",
legekontorHerId = "",
legekontorOrgName = "",
legehpr = UserConstants.HPRID.toString(),
fellesformatXML = fellesformatXML,
antallVedlegg = antallVedlegg,
dialogmelding = Dialogmelding(
id = uuid.toString(),
henvendelseFraLegeHenvendelse = null,
navnHelsepersonell = UserConstants.BEHANDLER_NAVN,
signaturDato = LocalDateTime.now(),
foresporselFraSaksbehandlerForesporselSvar = ForesporselFraSaksbehandlerForesporselSvar(
temaKode = TemaKode(kodeverk, kodeTekst, kode, "", "", ""),
datoNotat = LocalDateTime.now(),
dokIdNotat = null,
tekstNotatInnhold = "Dette er innholdet i et notat"
),
innkallingMoterespons = null,
)
)
| 3 | Kotlin | 0 | 0 | f4fff2694a3e2121ab60b12520d297b77f26611d | 9,106 | isbehandlerdialog | MIT License |
frontend/app/src/main/java/com/kasiry/app/viewmodel/ProfileViewModel.kt | alfianandinugraha | 585,695,566 | false | null | package com.kasiry.app.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kasiry.app.models.data.Profile
import com.kasiry.app.repositories.AuthRepository
import com.kasiry.app.repositories.ProfileRepository
import com.kasiry.app.utils.datastore.accessToken
import com.kasiry.app.utils.http.HttpCallback
import com.kasiry.app.utils.http.HttpState
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class ProfileViewModel(
application: Application,
private val authRepository: AuthRepository,
private val profileRepository: ProfileRepository
): AndroidViewModel(application) {
private val _profileState = MutableStateFlow<HttpState<Profile>?>(null)
val profileState = _profileState.asStateFlow()
private val _logout = MutableStateFlow<HttpState<Any>?>(null)
val logout = _logout.asStateFlow()
fun logout(
callback: HttpCallback<Any>.() -> Unit,
): Job {
_logout.value = HttpState.Loading()
val context = getApplication<Application>().applicationContext
return viewModelScope.launch {
val response = authRepository.logout()
_logout.value = response
context.accessToken = null
callback(HttpCallback(response))
}
}
fun setProfile(profile: Profile) {
_profileState.value = HttpState.Success(profile)
}
fun removeProfile() {
_profileState.value = HttpState.Error("Profile not found")
}
fun getProfile(
callback: (HttpCallback<Profile>.() -> Unit)? = null,
) {
_profileState.value = HttpState.Loading()
viewModelScope.launch(Dispatchers.Main) {
val result = profileRepository.get()
_profileState.value = result
if (callback != null) {
callback(HttpCallback(result))
}
}
}
private val _update = MutableStateFlow<HttpState<Profile>?>(null)
val update = _update.asStateFlow()
fun update(
profile: Profile,
callback: HttpCallback<Profile>.() -> Unit,
) {
_update.value = HttpState.Loading()
viewModelScope.launch {
val response = profileRepository.update(profile)
_update.value = response
callback(HttpCallback(response))
}
}
} | 0 | Kotlin | 0 | 1 | 6dc3a367acc255e7c2b1fe75543311b4bbb38b17 | 2,596 | kasiry | MIT License |
gson-provider/src/test/kotlin/org/javando/http/problem/impl/test/GsonProviderTest.kt | nickayl | 327,589,485 | false | {"Kotlin": 88411, "Java": 24700} | package org.javando.http.problem.impl.test
import com.google.gson.Gson
import org.hamcrest.CoreMatchers.*
import org.hamcrest.MatcherAssert.assertThat
import org.javando.http.problem.*
import org.javando.http.problem.impl.GsonProvider
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.Assertions.*
import org.slf4j.LoggerFactory
import java.lang.Exception
import java.net.MalformedURLException
import java.net.URI
import java.net.URL
import java.time.Instant
import java.util.*
import kotlin.time.milliseconds
//@TestInstance(value = TestInstance.Lifecycle.PER_CLASS)
internal class GsonProviderTest {
private lateinit var provider: JsonProvider
private lateinit var testProblemBuilder: ProblemBuilderClassic
private val log = LoggerFactory.getLogger(GsonProviderTest::class.java)
private data class CreditInfo22(val balance2: Double, val currency: String = "EUR")
private data class CreditInfo(val balance: Double, val currency: String = "EUR")
@BeforeEach
fun setUp() {
provider = GsonProvider()
testProblemBuilder = Problem.create(provider)
.title("Hello World!")
.details("What a wonderful world we live in!")
.type(URI.create("https://www.helloworld.com"))
.instance(URI.create("/hello-world"))
.status(HttpStatus.OK)
}
private val providerGson
get() = provider as GsonProvider
private val testProblem: Problem
get() = testProblemBuilder
.addExtension("credit_info", CreditInfo(34.5, "EUR"))
.build()
@Test
fun getDateFormatPattern() {
assertNotNull(providerGson.dateFormatPattern)
assertTrue(providerGson.dateFormatPattern.toPattern() == JsonProvider.defaultDatePattern)
}
@Test
fun registerExtensionClass() {
providerGson.registerExtensionClass("credit_info", CreditInfo::class.java)
assertTrue(providerGson.extensionClasses.isNotEmpty())
assertEquals(providerGson.extensionClasses["credit_info"]!!.simpleName, CreditInfo::class.java.simpleName)
}
@Test
fun registerExtensionClassWithoutPropertyName() {
providerGson.registerExtensionClass(CreditInfo::class.java)
assertTrue(providerGson.extensionClasses.isNotEmpty())
assertTrue(providerGson.extensionClasses.containsKey("credit_info"))
assertEquals(providerGson.extensionClasses["credit_info"]!!.simpleName, CreditInfo::class.java.simpleName)
}
@Test
fun setDateFormat() {
providerGson.setDateFormat("dd/MM/yyyy")
assertNotNull(providerGson.dateFormatPattern)
assertFalse(providerGson.dateFormatPattern.toPattern() == JsonProvider.defaultDatePattern)
assertTrue(providerGson.dateFormatPattern.toPattern() == "dd/MM/yyyy")
}
@Test
fun setDateIdentifier() {
assertNotNull(providerGson.dateIdentifier)
assertTrue(providerGson.dateIdentifier == JsonProvider.defaultDateIdentifier)
providerGson.setDateIdentifier("myDate")
assertFalse(providerGson.dateIdentifier == JsonProvider.defaultDateIdentifier)
assertTrue(providerGson.dateIdentifier == "myDate")
}
@Test
fun integrateAll() {
try {
testProblemBuilder.addExtension("credit_info", CreditInfo(34.5, "EUR"))
.addExtension("credit_info2", CreditInfo22(39.5, "GBP"))
try {
URL("http//wrongurl")
} catch (e: MalformedURLException) {
throw RuntimeException("This is my text!\"", e)
}
} catch (e: Exception) {
//e.printStackTrace()
testProblemBuilder.addExtension(e)
testProblemBuilder.addExtension(e.stackTrace, depth = 3, "*junit*")
val pr = testProblemBuilder.build()
assertNotNull(pr.extensions)
assertFalse(pr.extensions.isEmpty())
pr.extensions.forEach { assertNotNull(it.value.referencedProblem) }
assertTrue(pr.extensions.containsKey("exceptions"))
assertTrue(pr.extensions.containsKey("stacktrace"))
val exs = pr.extensions["exceptions"]!!.asArray()
assertTrue(exs!!.size > 0)
val stk = pr.extensions["stacktrace"]!!.asArray()
assertTrue(stk!!.size > 0)
println(pr.toJson())
}
}
@Test
fun testNewValues() {
val number = 10f
val date = Date()
val newInt = provider.newValue(number.toInt())
val newFloat = provider.newValue(number)
val newDouble = provider.newValue(number.toDouble())
val newString = provider.newValue("hello")
val newBoolean = provider.newValue(true)
val newDate = provider.newValue(date)
assertTrue(newInt.int == number.toInt() && newInt.isPrimitive)
assertFalse(newInt.isObject || newInt.isArray)
assertTrue(newFloat.float == number && newFloat.isPrimitive)
assertFalse(newFloat.isObject || newFloat.isArray)
assertTrue(newDouble.double == number.toDouble() && newDouble.isPrimitive)
assertFalse(newDouble.isObject || newDouble.isArray)
assertTrue(newString.string == "hello" && newString.isPrimitive)
assertFalse(newString.isObject || newString.isArray)
assertTrue(newBoolean.boolean && newBoolean.isPrimitive)
assertFalse(newBoolean.isObject || newBoolean.isArray)
assertTrue(newDate.date == date && !newDate.isPrimitive)
assertFalse(newDate.isObject || newDate.isArray)
}
@Test
fun get() {
assertNotNull(provider.get)
assertTrue(provider.get is Gson)
}
} | 1 | Kotlin | 1 | 2 | a760ea5761fa980c36e1b8fc4f7528f814aa90dd | 5,731 | noproblem | Apache License 2.0 |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/update/VersionComparator.kt | covid-be-app | 281,650,940 | false | null | package de.rki.coronawarnapp.update
/**
* Helper to compare 2 version strings
*/
object VersionComparator {
/**
* Checks if currentVersion is older than versionToCompareTo
*
* Expected input format: <major>.<minor>.<patch>
* major, minor and patch are Int
*
* @param currentVersion
* @param versionToCompareTo
* @return true if currentVersion is older than versionToCompareTo, else false
*/
fun isVersionOlder(currentVersion: String, versionToCompareTo: String): Boolean {
var isVersionOlder = false
val delimiter = "."
val currentVersionParts = currentVersion.split(delimiter)
val currentVersionMajor = currentVersionParts[0].toInt()
val currentVersionMinor = currentVersionParts[1].toInt()
val currentVersionPatch = currentVersionParts[2].toInt()
val versionToCompareParts = versionToCompareTo.split(delimiter)
val versionToCompareMajor = versionToCompareParts[0].toInt()
val versionToCompareMinor = versionToCompareParts[1].toInt()
val versionToComparePatch = versionToCompareParts[2].toInt()
if (versionToCompareMajor > currentVersionMajor) {
isVersionOlder = true
} else if (versionToCompareMajor == currentVersionMajor) {
if (versionToCompareMinor > currentVersionMinor) {
isVersionOlder = true
} else if ((versionToCompareMinor == currentVersionMinor) &&
(versionToComparePatch > currentVersionPatch)
) {
isVersionOlder = true
}
}
return isVersionOlder
}
}
| 13 | Kotlin | 10 | 55 | d556b0b9f29e76295b59be2a1ba89bc4cf6ec33b | 1,649 | cwa-app-android | Apache License 2.0 |
android/src/main/java/com/reactnativepedometerdetails/step/background/RebootActionReceiver.kt | zaixiaoqu | 437,058,689 | false | {"Kotlin": 90481, "JavaScript": 2795} | package com.reactnativepedometerdetails.step.background
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import androidx.core.content.ContextCompat
class RebootActionReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (context == null || intent == null) {
return
}
val action = intent.action
action?.let {
if (action == Intent.ACTION_BOOT_COMPLETED || action == Intent.ACTION_LOCKED_BOOT_COMPLETED) {
val serviceIntent = Intent(context, StepCounterService::class.java)
ContextCompat.startForegroundService(context, serviceIntent)
}
}
}
}
| 6 | Kotlin | 9 | 7 | 77eba39e286c7799920c87a9b676e367b0810a3b | 757 | react-native-pedometer-details | MIT License |
src/main/kotlin/org/opensearch/commons/alerting/action/IndexMonitorResponse.kt | opensearch-project | 354,136,133 | false | null | package org.opensearch.commons.alerting.action
import org.opensearch.common.io.stream.StreamInput
import org.opensearch.common.io.stream.StreamOutput
import org.opensearch.commons.alerting.model.Monitor
import org.opensearch.commons.alerting.util.IndexUtils.Companion._ID
import org.opensearch.commons.alerting.util.IndexUtils.Companion._PRIMARY_TERM
import org.opensearch.commons.alerting.util.IndexUtils.Companion._SEQ_NO
import org.opensearch.commons.alerting.util.IndexUtils.Companion._VERSION
import org.opensearch.commons.notifications.action.BaseResponse
import org.opensearch.core.xcontent.ToXContent
import org.opensearch.core.xcontent.XContentBuilder
import java.io.IOException
class IndexMonitorResponse : BaseResponse {
var id: String
var version: Long
var seqNo: Long
var primaryTerm: Long
var monitor: Monitor
constructor(
id: String,
version: Long,
seqNo: Long,
primaryTerm: Long,
monitor: Monitor
) : super() {
this.id = id
this.version = version
this.seqNo = seqNo
this.primaryTerm = primaryTerm
this.monitor = monitor
}
@Throws(IOException::class)
constructor(sin: StreamInput) : this(
sin.readString(), // id
sin.readLong(), // version
sin.readLong(), // seqNo
sin.readLong(), // primaryTerm
Monitor.readFrom(sin) as Monitor // monitor
)
@Throws(IOException::class)
override fun writeTo(out: StreamOutput) {
out.writeString(id)
out.writeLong(version)
out.writeLong(seqNo)
out.writeLong(primaryTerm)
monitor.writeTo(out)
}
@Throws(IOException::class)
override fun toXContent(builder: XContentBuilder, params: ToXContent.Params): XContentBuilder {
return builder.startObject()
.field(_ID, id)
.field(_VERSION, version)
.field(_SEQ_NO, seqNo)
.field(_PRIMARY_TERM, primaryTerm)
.field("monitor", monitor)
.endObject()
}
}
| 25 | null | 93 | 7 | d221aa35182c323a191144cdb3668f08df45d964 | 2,052 | common-utils | Apache License 2.0 |
app/src/main/java/eu/kanade/tachiyomi/di/AppModule.kt | mihonapp | 743,704,912 | false | null | package eu.kanade.tachiyomi.di
import android.app.Application
import android.os.Build
import androidx.core.content.ContextCompat
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.framework.FrameworkSQLiteOpenHelperFactory
import app.cash.sqldelight.db.SqlDriver
import app.cash.sqldelight.driver.android.AndroidSqliteDriver
import eu.kanade.domain.track.store.DelayedTrackingStore
import eu.kanade.tachiyomi.BuildConfig
import eu.kanade.tachiyomi.data.cache.ChapterCache
import eu.kanade.tachiyomi.data.cache.CoverCache
import eu.kanade.tachiyomi.data.download.DownloadCache
import eu.kanade.tachiyomi.data.download.DownloadManager
import eu.kanade.tachiyomi.data.download.DownloadProvider
import eu.kanade.tachiyomi.data.saver.ImageSaver
import eu.kanade.tachiyomi.data.track.TrackerManager
import eu.kanade.tachiyomi.extension.ExtensionManager
import eu.kanade.tachiyomi.network.JavaScriptEngine
import eu.kanade.tachiyomi.network.NetworkHelper
import eu.kanade.tachiyomi.source.AndroidSourceManager
import io.requery.android.database.sqlite.RequerySQLiteOpenHelperFactory
import kotlinx.serialization.json.Json
import kotlinx.serialization.protobuf.ProtoBuf
import nl.adaptivity.xmlutil.XmlDeclMode
import nl.adaptivity.xmlutil.core.XmlVersion
import nl.adaptivity.xmlutil.serialization.XML
import tachiyomi.core.storage.AndroidStorageFolderProvider
import tachiyomi.data.AndroidDatabaseHandler
import tachiyomi.data.Database
import tachiyomi.data.DatabaseHandler
import tachiyomi.data.DateColumnAdapter
import tachiyomi.data.History
import tachiyomi.data.Mangas
import tachiyomi.data.StringListColumnAdapter
import tachiyomi.data.UpdateStrategyColumnAdapter
import tachiyomi.domain.source.service.SourceManager
import tachiyomi.domain.storage.service.StorageManager
import tachiyomi.source.local.image.LocalCoverManager
import tachiyomi.source.local.io.LocalSourceFileSystem
import uy.kohesive.injekt.api.InjektModule
import uy.kohesive.injekt.api.InjektRegistrar
import uy.kohesive.injekt.api.addSingleton
import uy.kohesive.injekt.api.addSingletonFactory
import uy.kohesive.injekt.api.get
class AppModule(val app: Application) : InjektModule {
override fun InjektRegistrar.registerInjectables() {
addSingleton(app)
addSingletonFactory<SqlDriver> {
AndroidSqliteDriver(
schema = Database.Schema,
context = app,
name = "tachiyomi.db",
factory = if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Support database inspector in Android Studio
FrameworkSQLiteOpenHelperFactory()
} else {
RequerySQLiteOpenHelperFactory()
},
callback = object : AndroidSqliteDriver.Callback(Database.Schema) {
override fun onOpen(db: SupportSQLiteDatabase) {
super.onOpen(db)
setPragma(db, "foreign_keys = ON")
setPragma(db, "journal_mode = WAL")
setPragma(db, "synchronous = NORMAL")
}
private fun setPragma(db: SupportSQLiteDatabase, pragma: String) {
val cursor = db.query("PRAGMA $pragma")
cursor.moveToFirst()
cursor.close()
}
},
)
}
addSingletonFactory {
Database(
driver = get(),
historyAdapter = History.Adapter(
last_readAdapter = DateColumnAdapter,
),
mangasAdapter = Mangas.Adapter(
genreAdapter = StringListColumnAdapter,
update_strategyAdapter = UpdateStrategyColumnAdapter,
),
)
}
addSingletonFactory<DatabaseHandler> { AndroidDatabaseHandler(get(), get()) }
addSingletonFactory {
Json {
ignoreUnknownKeys = true
explicitNulls = false
}
}
addSingletonFactory {
XML {
defaultPolicy {
ignoreUnknownChildren()
}
autoPolymorphic = true
xmlDeclMode = XmlDeclMode.Charset
indent = 2
xmlVersion = XmlVersion.XML10
}
}
addSingletonFactory<ProtoBuf> {
ProtoBuf
}
addSingletonFactory { ChapterCache(app, get()) }
addSingletonFactory { CoverCache(app) }
addSingletonFactory { NetworkHelper(app, get()) }
addSingletonFactory { JavaScriptEngine(app) }
addSingletonFactory<SourceManager> { AndroidSourceManager(app, get(), get()) }
addSingletonFactory { ExtensionManager(app) }
addSingletonFactory { DownloadProvider(app) }
addSingletonFactory { DownloadManager(app) }
addSingletonFactory { DownloadCache(app) }
addSingletonFactory { TrackerManager() }
addSingletonFactory { DelayedTrackingStore(app) }
addSingletonFactory { ImageSaver(app) }
addSingletonFactory { AndroidStorageFolderProvider(app) }
addSingletonFactory { LocalSourceFileSystem(get()) }
addSingletonFactory { LocalCoverManager(app, get()) }
addSingletonFactory { StorageManager(app, get()) }
// Asynchronously init expensive components for a faster cold start
ContextCompat.getMainExecutor(app).execute {
get<NetworkHelper>()
get<SourceManager>()
get<Database>()
get<DownloadManager>()
}
}
}
| 93 | null | 98 | 9,867 | f3a2f566c8a09ab862758ae69b43da2a2cd8f1db | 5,745 | mihon | Apache License 2.0 |
src/main/kotlin/com/github/shanpark/mqtt5/packet/primitive/Utf8EncodedString.kt | shanpark | 422,818,919 | false | {"Kotlin": 141602} | package com.github.shanpark.mqtt5.packet.primitive
import com.github.shanpark.buffers.ReadBuffer
import com.github.shanpark.buffers.WriteBuffer
import com.github.shanpark.mqtt5.exception.ExceedLimitException
import com.github.shanpark.mqtt5.exception.NotEnoughDataException
import io.netty.buffer.ByteBuf
/**
* MQTT 5.0 규격의 [MQTT-1.5.4-1], [MQTT-1.5.4-2], [MQTT-1.5.4-3] 는
* 무시하고 Java의 UTF-8 문자열 규칙을 따른다.
*
* TODO Java의 규칙에 이미 적용이 되어있는지 테스트 필요.
*/
object Utf8EncodedString {
fun length(value: String): Int {
val byteArray = value.toByteArray(Charsets.UTF_8)
try {
return TwoByteInteger.length(byteArray.size) + byteArray.size
} catch (e: ExceedLimitException) {
throw ExceedLimitException(
"Too long to be expressed in Utf8EncodedString",
e
)
}
}
fun writeTo(buf: ByteBuf, value: String) {
val byteArray = value.toByteArray(Charsets.UTF_8)
try {
TwoByteInteger.writeTo(buf, byteArray.size)
} catch (e: ExceedLimitException) {
throw ExceedLimitException("Try to write too long string(>= 64k).")
}
buf.writeBytes(byteArray)
}
fun writeTo(buf: WriteBuffer, value: String) {
val byteArray = value.toByteArray(Charsets.UTF_8)
try {
TwoByteInteger.writeTo(buf, byteArray.size)
} catch (e: ExceedLimitException) {
throw ExceedLimitException("Try to write too long string(>= 64k).")
}
buf.write(byteArray)
}
fun readFrom(buf: ByteBuf): String {
val length = TwoByteInteger.readFrom(buf)
if (length > buf.readableBytes())
throw NotEnoughDataException("Not enough data for Utf8EncodedString")
return buf.readCharSequence(length, Charsets.UTF_8).toString()
}
fun readFrom(buf: ReadBuffer): String {
val length = TwoByteInteger.readFrom(buf)
if (length > buf.readableBytes)
throw NotEnoughDataException("Not enough data for Utf8EncodedString")
return buf.readString(length, Charsets.UTF_8)
}
} | 0 | Kotlin | 0 | 0 | dc2d803a3e23455bdc3d2bb729c4fa975e172b1c | 2,132 | Mqtt5 | MIT License |
src/main/java/com/example/navigation/ui/destination/NavigationUiDestinationListenerFragmentTwo.kt | vshpyrka | 754,325,488 | false | {"Kotlin": 183594} | package com.example.navigation.ui.destination
import android.os.Bundle
import android.text.method.ScrollingMovementMethod
import android.view.View
import androidx.fragment.app.Fragment
import com.example.navigation.R
import com.example.navigation.applyWindowInsets
import com.example.navigation.databinding.FragmentNavigationUiDestinationListenerTwoBinding
import com.example.navigation.getLoremIpsum
class NavigationUiDestinationListenerFragmentTwo : Fragment(
R.layout.fragment_navigation_ui_destination_listener_two
) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val binding = FragmentNavigationUiDestinationListenerTwoBinding.bind(view)
binding.root.applyWindowInsets()
binding.text.movementMethod = ScrollingMovementMethod()
binding.text.text = getLoremIpsum()
}
}
| 0 | Kotlin | 0 | 0 | bf0d3e6ca9c31116a5ebb77576dc01b62c896e13 | 898 | android-navigation-example | Apache License 2.0 |
libtrip-notification/src/test/java/com/mapbox/navigation/trip/notification/internal/MapboxTripNotificationTest.kt | niilante | 439,334,238 | false | null | package com.mapbox.navigation.trip.notification
import android.app.Notification
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.content.res.Resources
import android.text.SpannableString
import android.text.TextUtils
import android.text.format.DateFormat
import android.widget.RemoteViews
import com.mapbox.api.directions.v5.models.BannerInstructions
import com.mapbox.api.directions.v5.models.BannerText
import com.mapbox.navigation.base.formatter.DistanceFormatter
import com.mapbox.navigation.base.options.NavigationOptions
import com.mapbox.navigation.base.trip.model.RouteLegProgress
import com.mapbox.navigation.base.trip.model.RouteProgress
import com.mapbox.navigation.trip.notification.internal.TimeFormatter
import com.mapbox.navigation.utils.internal.NOTIFICATION_ID
import io.mockk.Runs
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.slot
import io.mockk.verify
import java.util.Locale
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
private const val STOP_SESSION = "Stop session"
private const val END_NAVIGATION = "End Navigation"
private const val FORMAT_STRING = "%s 454545 ETA"
private const val MANEUVER_TYPE = "MANEUVER TYPE"
private const val MANEUVER_MODIFIER = "MANEUVER MODIFIER"
class MapboxTripNotificationTest {
private lateinit var notification: MapboxTripNotification
private lateinit var mockedContext: Context
private lateinit var collapsedViews: RemoteViews
private lateinit var expandedViews: RemoteViews
private val navigationOptions: NavigationOptions = mockk(relaxed = true)
private val distanceSpannable: SpannableString = mockk()
private val distanceFormatter: DistanceFormatter
init {
val distanceSlot = slot<Double>()
distanceFormatter = mockk()
every { distanceFormatter.formatDistance(capture(distanceSlot)) } returns distanceSpannable
every { navigationOptions.distanceFormatter } returns distanceFormatter
}
@Before
fun setUp() {
mockkStatic(DateFormat::class)
mockkStatic(PendingIntent::class)
mockedContext = createContext()
every { mockedContext.applicationContext } returns mockedContext
every { navigationOptions.applicationContext } returns mockedContext
mockRemoteViews()
notification = MapboxTripNotification(
navigationOptions
)
}
private fun mockRemoteViews() {
mockkObject(RemoteViewsProvider)
collapsedViews = mockk(relaxUnitFun = true)
expandedViews = mockk(relaxUnitFun = true)
every {
RemoteViewsProvider.createRemoteViews(
any(),
R.layout.collapsed_navigation_notification_layout
)
} returns collapsedViews
every {
RemoteViewsProvider.createRemoteViews(
any(),
R.layout.expanded_navigation_notification_layout
)
} returns expandedViews
}
@Test
fun generateSanityTest() {
assertNotNull(notification)
}
private fun createContext(): Context {
val mockedContext = mockk<Context>()
val mockedBroadcastReceiverIntent = mockk<Intent>()
val mockPendingIntentForActivity = mockk<PendingIntent>(relaxed = true)
val mockPendingIntentForBroadcast = mockk<PendingIntent>(relaxed = true)
val mockedConfiguration = Configuration()
mockedConfiguration.locale = Locale("en")
val mockedResources = mockk<Resources>(relaxed = true)
every { mockedResources.configuration } returns (mockedConfiguration)
every { mockedContext.resources } returns (mockedResources)
val mockedPackageManager = mockk<PackageManager>(relaxed = true)
every { mockedContext.packageManager } returns (mockedPackageManager)
every { mockedContext.packageName } returns ("com.mapbox.navigation.trip.notification")
every { mockedContext.getString(any()) } returns FORMAT_STRING
every { mockedContext.getString(R.string.stop_session) } returns STOP_SESSION
every { mockedContext.getString(R.string.end_navigation) } returns END_NAVIGATION
val notificationManager = mockk<NotificationManager>(relaxed = true)
every { mockedContext.getSystemService(Context.NOTIFICATION_SERVICE) } returns (notificationManager)
every { DateFormat.is24HourFormat(mockedContext) } returns (false)
every {
PendingIntent.getActivity(
mockedContext,
any(),
any(),
any()
)
} returns (mockPendingIntentForActivity)
every {
PendingIntent.getBroadcast(
mockedContext,
any(),
any(),
any()
)
} returns (mockPendingIntentForBroadcast)
every {
mockedContext.registerReceiver(
any(),
any()
)
} returns (mockedBroadcastReceiverIntent)
every { mockedContext.unregisterReceiver(any()) } just Runs
return mockedContext
}
@Test
fun whenTripStartedThenRegisterReceiverCalledOnce() {
notification.onTripSessionStarted()
verify(exactly = 1) { mockedContext.registerReceiver(any(), any()) }
}
@Test
fun whenTripStoppedThenCleanupIsDone() {
val notificationManager =
mockedContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notification.onTripSessionStopped()
verify(exactly = 1) { mockedContext.unregisterReceiver(any()) }
verify(exactly = 1) { notificationManager.cancel(NOTIFICATION_ID) }
assertEquals(
true,
MapboxTripNotification.notificationActionButtonChannel.isClosedForReceive
)
assertEquals(true, MapboxTripNotification.notificationActionButtonChannel.isClosedForSend)
}
@Test
fun whenGetNotificationCalledThenNavigationNotificationProviderInteractedOnlyOnce() {
mockNotificationCreation()
notification.getNotification()
verify(exactly = 1) { NavigationNotificationProvider.buildNotification(any()) }
notification.getNotification()
notification.getNotification()
verify(exactly = 1) { NavigationNotificationProvider.buildNotification(any()) }
}
@Test
fun whenUpdateNotificationCalledThenPrimaryTextIsSetToRemoteViews() {
val routeProgress = mockk<RouteProgress>(relaxed = true)
val primaryText = { "Primary Text" }
val bannerText = mockBannerText(routeProgress, primaryText)
mockUpdateNotificationAndroidInteractions()
notification.updateNotification(routeProgress)
verify(exactly = 1) { bannerText.text() }
verify(exactly = 1) { collapsedViews.setTextViewText(any(), primaryText()) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), primaryText()) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), END_NAVIGATION) }
verify(exactly = 0) { expandedViews.setTextViewText(any(), STOP_SESSION) }
assertEquals(notification.currentManeuverType, MANEUVER_TYPE)
assertEquals(notification.currentManeuverModifier, MANEUVER_MODIFIER)
}
@Test
fun whenUpdateNotificationCalledThenDistanceTextIsSetToRemoteViews() {
val routeProgress = mockk<RouteProgress>(relaxed = true)
val distance = 30f
val duration = 112.4
val distanceText = distanceSpannable.toString()
mockLegProgress(routeProgress, distance, duration)
mockUpdateNotificationAndroidInteractions()
notification.updateNotification(routeProgress)
verify(exactly = 1) { collapsedViews.setTextViewText(any(), distanceText) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), distanceText) }
}
@Test
fun whenUpdateNotificationCalledThenArrivalTimeIsSetToRemoteViews() {
val routeProgress = mockk<RouteProgress>(relaxed = true)
val distance = 30f
val duration = 112.4
mockLegProgress(routeProgress, distance, duration)
mockUpdateNotificationAndroidInteractions()
val suffix = "this is nice formatting"
mockTimeFormatter(suffix)
val result = String.format(FORMAT_STRING, suffix + duration.toDouble().toString())
notification.updateNotification(routeProgress)
verify(exactly = 1) { collapsedViews.setTextViewText(any(), result) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), result) }
}
@Test
fun whenUpdateNotificationCalledTwiceWithSameDataThenRemoteViewAreNotUpdatedTwice() {
val routeProgress = mockk<RouteProgress>(relaxed = true)
val primaryText = { "Primary Text" }
val bannerText = mockBannerText(routeProgress, primaryText)
mockUpdateNotificationAndroidInteractions()
notification.updateNotification(routeProgress)
verify(exactly = 1) { bannerText.text() }
verify(exactly = 1) { collapsedViews.setTextViewText(any(), primaryText()) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), primaryText()) }
notification.updateNotification(routeProgress)
verify(exactly = 2) { bannerText.text() }
verify(exactly = 1) { collapsedViews.setTextViewText(any(), primaryText()) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), primaryText()) }
assertEquals(notification.currentManeuverType, MANEUVER_TYPE)
assertEquals(notification.currentManeuverModifier, MANEUVER_MODIFIER)
}
@Test
fun whenUpdateNotificationCalledTwiceWithDifferentDataThenRemoteViewUpdatedTwice() {
val routeProgress = mockk<RouteProgress>(relaxed = true)
val initialPrimaryText = "Primary Text"
val changedPrimaryText = "Changed Primary Text"
var primaryText = initialPrimaryText
val primaryTextLambda = { primaryText }
val bannerText = mockBannerText(routeProgress, primaryTextLambda)
mockUpdateNotificationAndroidInteractions()
notification.updateNotification(routeProgress)
primaryText = changedPrimaryText
notification.updateNotification(routeProgress)
verify(exactly = 2) { bannerText.text() }
verify(exactly = 1) { collapsedViews.setTextViewText(any(), initialPrimaryText) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), initialPrimaryText) }
verify(exactly = 1) { collapsedViews.setTextViewText(any(), changedPrimaryText) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), changedPrimaryText) }
assertEquals(notification.currentManeuverType, MANEUVER_TYPE)
assertEquals(notification.currentManeuverModifier, MANEUVER_MODIFIER)
}
@Test
fun whenGoThroughStartUpdateStopCycleThenNotificationCacheDropped() {
val routeProgress = mockk<RouteProgress>(relaxed = true)
val primaryText = { "Primary Text" }
val bannerText = mockBannerText(routeProgress, primaryText)
mockUpdateNotificationAndroidInteractions()
notification.onTripSessionStarted()
notification.updateNotification(routeProgress)
notification.onTripSessionStopped()
notification.onTripSessionStarted()
verify(exactly = 1) { bannerText.text() }
verify(exactly = 1) { collapsedViews.setTextViewText(any(), primaryText()) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), primaryText()) }
assertNull(notification.currentManeuverType)
assertNull(notification.currentManeuverModifier)
notification.updateNotification(routeProgress)
verify(exactly = 2) { bannerText.text() }
verify(exactly = 2) { collapsedViews.setTextViewText(any(), primaryText()) }
verify(exactly = 2) { expandedViews.setTextViewText(any(), primaryText()) }
assertEquals(notification.currentManeuverType, MANEUVER_TYPE)
assertEquals(notification.currentManeuverModifier, MANEUVER_MODIFIER)
}
@Test
fun whenGoThroughStartUpdateStopCycleThenStartStopSessionDontAffectRemoteViews() {
val routeProgress = mockk<RouteProgress>(relaxed = true)
val primaryText = { "Primary Text" }
val bannerText = mockBannerText(routeProgress, primaryText)
mockUpdateNotificationAndroidInteractions()
notification.onTripSessionStarted()
notification.updateNotification(routeProgress)
verify(exactly = 1) { bannerText.text() }
verify(exactly = 1) { collapsedViews.setTextViewText(any(), primaryText()) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), primaryText()) }
assertEquals(notification.currentManeuverType, MANEUVER_TYPE)
assertEquals(notification.currentManeuverModifier, MANEUVER_MODIFIER)
notification.onTripSessionStopped()
notification.onTripSessionStarted()
verify(exactly = 1) { bannerText.text() }
verify(exactly = 1) { collapsedViews.setTextViewText(any(), primaryText()) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), primaryText()) }
notification.onTripSessionStopped()
verify(exactly = 1) { bannerText.text() }
verify(exactly = 1) { collapsedViews.setTextViewText(any(), primaryText()) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), primaryText()) }
assertNull(notification.currentManeuverType)
assertNull(notification.currentManeuverModifier)
}
@Test
fun whenFreeDrive() {
val nullRouteProgress = null
mockUpdateNotificationAndroidInteractions()
notification.onTripSessionStarted()
notification.updateNotification(nullRouteProgress)
verify(exactly = 0) { expandedViews.setTextViewText(any(), END_NAVIGATION) }
verify(exactly = 1) { expandedViews.setTextViewText(any(), STOP_SESSION) }
}
private fun mockUpdateNotificationAndroidInteractions() {
mockkStatic(TextUtils::class)
val slot = slot<CharSequence>()
every { TextUtils.isEmpty(capture(slot)) } answers { slot.captured.isEmpty() }
mockNotificationCreation()
}
private fun mockNotificationCreation() {
mockkObject(NavigationNotificationProvider)
val notificationMock = mockk<Notification>()
every { NavigationNotificationProvider.buildNotification(any()) } returns notificationMock
}
private fun mockBannerText(
routeProgress: RouteProgress,
primaryText: () -> String,
primaryType: () -> String = { MANEUVER_TYPE },
primaryModifier: () -> String = { MANEUVER_MODIFIER }
): BannerText {
val bannerText = mockk<BannerText>()
val bannerInstructions = mockk<BannerInstructions>()
every { routeProgress.bannerInstructions } returns bannerInstructions
every { bannerInstructions.primary() } returns bannerText
every { bannerText.text() } answers { primaryText() }
every { bannerText.type() } answers { primaryType() }
every { bannerText.modifier() } answers { primaryModifier() }
return bannerText
}
@Suppress("SameParameterValue")
private fun mockLegProgress(
routeProgress: RouteProgress,
distance: Float,
duration: Double
): RouteLegProgress {
val currentLegProgress = mockk<RouteLegProgress>(relaxed = true)
every { routeProgress.currentLegProgress } returns currentLegProgress
every { currentLegProgress.currentStepProgress?.distanceRemaining } returns distance
every { currentLegProgress.durationRemaining } returns duration
return currentLegProgress
}
private fun mockTimeFormatter(@Suppress("SameParameterValue") suffix: String) {
mockkStatic(TimeFormatter::class)
val durationSlot = slot<Double>()
every {
TimeFormatter.formatTime(any(), capture(durationSlot), any(), any())
} answers { "$suffix${durationSlot.captured}" }
}
}
| 9 | null | 1 | 1 | c7fd13f6c363e0902cf2e12d55d4bc3647700400 | 16,470 | mapbox-navigation-android | Apache License 2.0 |
project/skyway_android_sdk/app/src/main/java/com/ntt/skyway/App.kt | skyway | 594,002,280 | false | null | package com.ntt.skyway
import android.app.Application
import android.content.Context
import android.util.Log
import com.ntt.skyway.authtoken.AuthTokenBuilder
import com.ntt.skyway.core.SkyWayContext
import com.ntt.skyway.core.util.Logger
import com.ntt.skyway.manager.ChannelManager
import com.ntt.skyway.manager.Manager
import com.ntt.skyway.manager.RoomManager
import com.ntt.skyway.manager.SFURoomManager
import com.ntt.skyway.plugin.sfuBot.SFUBotPlugin
import kotlinx.coroutines.runBlocking
class App : Application() {
companion object {
lateinit var appContext: Context
private val logLevel = Logger.LogLevel.VERBOSE
private val authToken = AuthTokenBuilder.CreateToken(
BuildConfig.APP_ID,
BuildConfig.SECRET_KEY
)
val option = SkyWayContext.Options(
authToken,
logLevel,
rtcConfig = SkyWayContext.RtcConfig(policy = SkyWayContext.TurnPolicy.ENABLE),
// webRTCLog = true
)
val channelManager = ChannelManager()
val roomManager = RoomManager()
val sfuManager = SFURoomManager()
var currentManager: Manager = channelManager
fun showMessage(message:String){
// Toast.makeText(appContext, message, Toast.LENGTH_SHORT)
// .show()
Log.d("ReferenceApp",message)
}
}
override fun onCreate() {
super.onCreate()
appContext = applicationContext
runBlocking {
SkyWayContext.registerPlugin(SFUBotPlugin())
SkyWayContext.onReconnectStartHandler = {
showMessage("onReconnectStartHandler")
}
SkyWayContext.onReconnectSuccessHandler = {
showMessage("onReconnectSuccessHandler")
}
SkyWayContext.onErrorHandler = {
showMessage("onErrorHandler : ${it.message}")
}
Logger.onLogHandler = { logLevel: Logger.LogLevel, s: String ->
// Log.e("onLogHandler", "$logLevel $s")
}
val result = SkyWayContext.setup(applicationContext, option)
if (result) {
showMessage("setup success")
}
}
}
}
| 0 | null | 0 | 4 | 15991d539a6a1000015dd721c082ab3693a682f0 | 2,249 | android-sdk | MIT License |
DiceGame/app/src/main/java/com/example/dicegame/MainActivity.kt | vardaan-raj | 413,309,056 | false | {"Dart": 504070, "HTML": 473817, "TeX": 182782, "JavaScript": 45951, "CSS": 24613, "Python": 7999, "EJS": 4446, "C++": 4004, "Kotlin": 2720, "Swift": 404, "Objective-C": 38} | package com.example.dicegame
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
rollDice()
val rollbutton: Button = findViewById(R.id.button)
rollbutton.setOnClickListener {
//val t = Toast.makeText(this, "Dice Rolled", Toast.LENGTH_SHORT)
//t.show()
rollDice()
}
}
private fun rollDice() {
val dice1 = Dice(6)
val diceRoll = dice1.roll()
val diceImage: ImageView = findViewById(R.id.imageView)
//diceImage.setImageResource(R.drawable.dice_1)
val drawableResource = when (diceRoll) {
1 -> R.drawable.dice_1
2 -> R.drawable.dice_2
3 -> R.drawable.dice_3
4 -> R.drawable.dice_4
5 -> R.drawable.dice_5
else -> R.drawable.dice_6
}
diceImage.setImageResource(drawableResource)
diceImage.contentDescription=diceRoll.toString()
// val dice2 = Dice(6)
// val diceRoll2 = dice2.roll()
// val resultTextView2: TextView = findViewById(R.id.dice2)
// resultTextView2.text=diceRoll2.toString()
}
}
class Dice(private val numSides: Int) {
fun roll(): Int {
return (1..numSides).random()
}
} | 2 | Dart | 93 | 1 | 3ac86ba2d73896d684ce96e1dfe5847b6fa5c5ac | 1,573 | Small_Projects | MIT License |
app/src/main/java/com/github/iielse/imageviewer/demo/business/ViewerHelper.kt | iielse | 79,318,521 | false | null | package com.github.iielse.imageviewer.demo.business
import androidx.fragment.app.FragmentActivity
import com.github.iielse.imageviewer.ImageViewerBuilder
import com.github.iielse.imageviewer.ImageViewerDialogFragment
import com.github.iielse.imageviewer.core.DataProvider
import com.github.iielse.imageviewer.core.Transformer
import com.github.iielse.imageviewer.demo.core.viewer.FullScreenImageViewerDialogFragment
import com.github.iielse.imageviewer.demo.core.viewer.MyImageLoader
import com.github.iielse.imageviewer.demo.core.viewer.MyTransformer
import com.github.iielse.imageviewer.demo.core.viewer.provideViewerDataProvider
import com.github.iielse.imageviewer.demo.data.Api
import com.github.iielse.imageviewer.demo.data.MyData
import com.github.iielse.imageviewer.demo.data.myData
/**
* viewer的自定义初始化方案
*/
object ViewerHelper {
var orientationH: Boolean = true
var loadAllAtOnce: Boolean = false
var fullScreen: Boolean = false
var simplePlayVideo: Boolean = true
fun provideImageViewerBuilder(context: FragmentActivity, clickedData: MyData): ImageViewerBuilder {
val builder = ImageViewerBuilder(
context = context,
initKey = clickedData.id,
dataProvider = myDataProvider(clickedData),
imageLoader = MyImageLoader(),
transformer = MyTransformer()
)
MyViewerEx(context).attach(builder)
if (fullScreen) {
builder.setViewerFactory(object : ImageViewerDialogFragment.Factory() {
override fun build() = FullScreenImageViewerDialogFragment()
})
}
return builder
}
private fun myDataProvider(clickedData: MyData): DataProvider {
return if (loadAllAtOnce) {
provideViewerDataProvider { myData }
} else {
provideViewerDataProvider(
loadInitial = { listOf(clickedData) },
loadAfter = { id, callback -> Api.asyncQueryAfter(id, callback) },
loadBefore = { id, callback -> Api.asyncQueryBefore(id, callback) }
)
}
}
}
| 2 | null | 275 | 1,874 | bf0cd1f46c97c6fbc41ea78242a513c7fe54b24a | 2,145 | imageviewer | MIT License |
app/src/full/java/com/celzero/bravedns/ui/fragment/CustomDomainFragment.kt | celzero | 270,683,546 | false | null | /*
* Copyright 2021 RethinkDNS and its authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.celzero.bravedns.ui.fragment
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.Toast
import androidx.appcompat.widget.SearchView
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import by.kirich1409.viewbindingdelegate.viewBinding
import com.celzero.bravedns.R
import com.celzero.bravedns.adapter.CustomDomainAdapter
import com.celzero.bravedns.databinding.DialogAddCustomDomainBinding
import com.celzero.bravedns.databinding.FragmentCustomDomainBinding
import com.celzero.bravedns.service.DomainRulesManager
import com.celzero.bravedns.service.DomainRulesManager.isValidDomain
import com.celzero.bravedns.service.DomainRulesManager.isWildCardEntry
import com.celzero.bravedns.ui.activity.CustomRulesActivity
import com.celzero.bravedns.util.Constants.Companion.INTENT_UID
import com.celzero.bravedns.util.Constants.Companion.UID_EVERYBODY
import com.celzero.bravedns.util.Utilities
import com.celzero.bravedns.util.Utilities.removeLeadingAndTrailingDots
import com.celzero.bravedns.viewmodel.CustomDomainViewModel
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.android.ext.android.inject
class CustomDomainFragment :
Fragment(R.layout.fragment_custom_domain), SearchView.OnQueryTextListener {
private val b by viewBinding(FragmentCustomDomainBinding::bind)
private var layoutManager: RecyclerView.LayoutManager? = null
private val viewModel by inject<CustomDomainViewModel>()
private var uid = UID_EVERYBODY
private var rule = CustomRulesActivity.RULES.APP_SPECIFIC_RULES
companion object {
fun newInstance(uid: Int, rules: CustomRulesActivity.RULES): CustomDomainFragment {
val args = Bundle()
args.putInt(INTENT_UID, uid)
args.putInt(CustomRulesActivity.INTENT_RULES, rules.type)
val fragment = CustomDomainFragment()
fragment.arguments = args
return fragment
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView()
}
private fun initView() {
uid = arguments?.getInt(INTENT_UID, UID_EVERYBODY) ?: UID_EVERYBODY
rule =
arguments?.getInt(CustomRulesActivity.INTENT_RULES)?.let {
CustomRulesActivity.RULES.getType(it)
} ?: CustomRulesActivity.RULES.APP_SPECIFIC_RULES
b.cdaSearchView.setOnQueryTextListener(this)
setupRecyclerView()
setupClickListeners()
b.cdaRecycler.requestFocus()
}
private fun setupRecyclerView() {
layoutManager = LinearLayoutManager(requireContext())
b.cdaRecycler.layoutManager = layoutManager
b.cdaRecycler.setHasFixedSize(true)
if (rule == CustomRulesActivity.RULES.APP_SPECIFIC_RULES) {
b.cdaAddFab.visibility = View.VISIBLE
setupAppSpecificRules(rule)
} else {
b.cdaAddFab.visibility = View.GONE
setupAllRules(rule)
}
}
private fun setupAppSpecificRules(rule: CustomRulesActivity.RULES) {
observeCustomRules()
val adapter = CustomDomainAdapter(requireContext(), rule)
b.cdaRecycler.adapter = adapter
viewModel.setUid(uid)
viewModel.customDomains.observe(this as LifecycleOwner) {
adapter.submitData(this.lifecycle, it)
}
}
private fun setupAllRules(rule: CustomRulesActivity.RULES) {
observeAllRules()
val adapter = CustomDomainAdapter(requireContext(), rule)
b.cdaRecycler.adapter = adapter
viewModel.allDomainRules.observe(this as LifecycleOwner) {
adapter.submitData(this.lifecycle, it)
}
}
private fun setupClickListeners() {
// see CustomIpFragment#setupClickListeners#bringToFront()
b.cdaAddFab.bringToFront()
b.cdaAddFab.setOnClickListener { showAddDomainDialog() }
b.cdaSearchDeleteIcon.setOnClickListener { showDomainRulesDeleteDialog() }
}
private fun observeCustomRules() {
viewModel.domainRulesCount(uid).observe(viewLifecycleOwner) {
if (it <= 0) {
showNoRulesUi()
hideRulesUi()
return@observe
}
hideNoRulesUi()
showRulesUi()
}
}
private fun observeAllRules() {
viewModel.allDomainRulesCount().observe(viewLifecycleOwner) {
if (it <= 0) {
showNoRulesUi()
hideRulesUi()
return@observe
}
hideNoRulesUi()
showRulesUi()
}
}
private fun hideRulesUi() {
b.cdaShowRulesRl.visibility = View.GONE
}
private fun showRulesUi() {
b.cdaShowRulesRl.visibility = View.VISIBLE
}
private fun hideNoRulesUi() {
b.cdaNoRulesRl.visibility = View.GONE
}
private fun showNoRulesUi() {
b.cdaNoRulesRl.visibility = View.VISIBLE
}
/**
* Shows dialog to add custom domain. Provides user option to user to add DOMAIN, TLD and
* WILDCARD. If entered option and text-input is valid, then the dns requests will be filtered
* based on it. User can either select the entered domain to be added in whitelist or blocklist.
*/
private fun showAddDomainDialog() {
val dBind = DialogAddCustomDomainBinding.inflate(layoutInflater)
val builder = MaterialAlertDialogBuilder(requireContext()).setView(dBind.root)
val lp = WindowManager.LayoutParams()
val dialog = builder.create()
dialog.show()
lp.copyFrom(dialog.window?.attributes)
lp.width = WindowManager.LayoutParams.MATCH_PARENT
lp.height = WindowManager.LayoutParams.WRAP_CONTENT
dialog.setCancelable(true)
dialog.window?.attributes = lp
var selectedType: DomainRulesManager.DomainType = DomainRulesManager.DomainType.DOMAIN
dBind.dacdDomainEditText.addTextChangedListener {
if (it?.contains("*") == true) {
dBind.dacdWildcardChip.isChecked = true
}
}
dBind.dacdDomainChip.setOnCheckedChangeListener { _, isSelected ->
if (isSelected) {
selectedType = DomainRulesManager.DomainType.DOMAIN
dBind.dacdDomainEditText.hint =
resources.getString(
R.string.cd_dialog_edittext_hint,
getString(R.string.lbl_domain)
)
dBind.dacdTextInputLayout.hint =
resources.getString(
R.string.cd_dialog_edittext_hint,
getString(R.string.lbl_domain)
)
}
}
dBind.dacdWildcardChip.setOnCheckedChangeListener { _, isSelected ->
if (isSelected) {
selectedType = DomainRulesManager.DomainType.WILDCARD
dBind.dacdDomainEditText.hint =
resources.getString(
R.string.cd_dialog_edittext_hint,
getString(R.string.lbl_wildcard)
)
dBind.dacdTextInputLayout.hint =
resources.getString(
R.string.cd_dialog_edittext_hint,
getString(R.string.lbl_wildcard)
)
}
}
dBind.dacdUrlTitle.text = getString(R.string.cd_dialog_title)
dBind.dacdDomainEditText.hint =
resources.getString(R.string.cd_dialog_edittext_hint, getString(R.string.lbl_domain))
dBind.dacdTextInputLayout.hint =
resources.getString(R.string.cd_dialog_edittext_hint, getString(R.string.lbl_domain))
dBind.dacdBlockBtn.setOnClickListener {
handleDomain(dBind, selectedType, DomainRulesManager.Status.BLOCK)
}
dBind.dacdTrustBtn.setOnClickListener {
handleDomain(dBind, selectedType, DomainRulesManager.Status.TRUST)
}
dBind.dacdCancelBtn.setOnClickListener { dialog.dismiss() }
dialog.show()
}
private fun handleDomain(
dBind: DialogAddCustomDomainBinding,
selectedType: DomainRulesManager.DomainType,
status: DomainRulesManager.Status
) {
dBind.dacdFailureText.visibility = View.GONE
val url = dBind.dacdDomainEditText.text.toString()
when (selectedType) {
DomainRulesManager.DomainType.WILDCARD -> {
if (!isWildCardEntry(url)) {
dBind.dacdFailureText.text =
getString(R.string.cd_dialog_error_invalid_wildcard)
dBind.dacdFailureText.visibility = View.VISIBLE
return
}
}
DomainRulesManager.DomainType.DOMAIN -> {
if (!isValidDomain(url)) {
dBind.dacdFailureText.text = getString(R.string.cd_dialog_error_invalid_domain)
dBind.dacdFailureText.visibility = View.VISIBLE
return
}
}
}
insertDomain(removeLeadingAndTrailingDots(url), selectedType, status)
}
private fun insertDomain(
domain: String,
type: DomainRulesManager.DomainType,
status: DomainRulesManager.Status
) {
io { DomainRulesManager.addDomainRule(domain, status, type, uid = uid) }
Utilities.showToastUiCentered(
requireContext(),
resources.getString(R.string.cd_toast_added),
Toast.LENGTH_SHORT
)
}
override fun onQueryTextSubmit(query: String): Boolean {
viewModel.setFilter(query)
return true
}
override fun onQueryTextChange(query: String): Boolean {
viewModel.setFilter(query)
return true
}
private fun showDomainRulesDeleteDialog() {
val builder = MaterialAlertDialogBuilder(requireContext())
builder.setTitle(R.string.univ_delete_firewall_dialog_title)
builder.setMessage(R.string.univ_delete_firewall_dialog_message)
builder.setPositiveButton(getString(R.string.univ_ip_delete_dialog_positive)) { _, _ ->
io {
if (rule == CustomRulesActivity.RULES.APP_SPECIFIC_RULES) {
DomainRulesManager.deleteRulesByUid(uid)
} else {
DomainRulesManager.deleteAllRules()
}
}
Utilities.showToastUiCentered(
requireContext(),
getString(R.string.cd_deleted_toast),
Toast.LENGTH_SHORT
)
}
builder.setNegativeButton(getString(R.string.lbl_cancel)) { _, _ ->
// no-op
}
builder.setCancelable(true)
builder.create().show()
}
private fun io(f: suspend () -> Unit) {
lifecycleScope.launch(Dispatchers.IO) { f() }
}
}
| 361 | null | 92 | 2,928 | d618c0935011642592e958d2b420d5d154e0cd79 | 11,979 | rethink-app | Apache License 2.0 |
app/src/main/java/com/avanisoam/nordicnews/di/DataSourceModule.kt | avanisoam | 803,286,041 | false | {"Kotlin": 172341} | package com.avanisoam.nordicnews.di
import com.avanisoam.nordicnews.data.repository.ApiRepository
import org.koin.dsl.module
val remoteDataSourceModule = module {
factory { ApiRepository(get()) }
} | 0 | Kotlin | 0 | 0 | b1b100ce848e914d8b0849a563408dd5d0eae70c | 204 | NordicNews | MIT License |
idea/tests/testData/inspectionsLocal/replaceNegatedIsEmptyWithIsNotEmpty/simple.kt | JetBrains | 278,369,660 | false | null | // WITH_STDLIB
// FIX: Replace negated 'isEmpty' with 'isNotEmpty'
fun test() {
val list = listOf(1,2,3)
if (!list.<caret>isEmpty()) {
}
} | 1 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 151 | intellij-kotlin | Apache License 2.0 |
app/src/main/java/com/xuan/knowshine/logic/network/PlaceService.kt | wangxuanzhu | 399,161,400 | false | null | package com.xuan.knowshine.logic.network
import com.xuan.knowshine.KnowShineApplication
import com.xuan.knowshine.logic.model.PlaceResponse
import retrofit2.http.GET
import retrofit2.http.Query
import retrofit2.Call
interface PlaceService {
@GET("v2/city/lookup?key=${KnowShineApplication.TOKEN}")
fun searchPlaces(@Query("location") query: String): Call<PlaceResponse>
} | 0 | Kotlin | 0 | 0 | 0488a12ecbcfa33a65598e183c775d2ac86bc365 | 381 | KnowShine | Apache License 2.0 |
core/network/src/main/kotlin/org/skyfaced/network/model/CharacterDto.kt | SkyfaceD | 538,354,635 | false | {"Kotlin": 110832} | package org.skyfaced.network.model
import kotlinx.serialization.Serializable
import org.skyfaced.network.model.filter.util.Gender
import org.skyfaced.network.model.filter.util.GenderSerializer
import org.skyfaced.network.model.filter.util.Status
import org.skyfaced.network.model.filter.util.StatusSerializer
@Serializable
data class CharacterDto(
val id: Int,
val name: String,
@Serializable(StatusSerializer::class)
val status: Status,
val species: String,
val type: String,
@Serializable(GenderSerializer::class)
val gender: Gender,
val origin: LocationShortDto,
val location: LocationShortDto,
val image: String,
val episode: List<String>,
val url: String,
val created: String,
) | 0 | Kotlin | 0 | 0 | 4350bcc84f191f5756d507fcb871d86a346432e5 | 741 | rick-and-morty | MIT License |
fladle-plugin/src/main/java/com/osacky/flank/gradle/FlankJavaExec.kt | uberbinge | 352,751,848 | true | {"Kotlin": 163449, "Java": 1344} | package com.osacky.flank.gradle
import org.gradle.api.file.ProjectLayout
import org.gradle.api.tasks.JavaExec
import javax.inject.Inject
open class FlankJavaExec @Inject constructor(projectLayout: ProjectLayout) : JavaExec() {
init {
group = FladlePluginDelegate.TASK_GROUP
main = "ftl.Main"
workingDir(projectLayout.fladleDir)
}
fun setUpWorkingDir(configName: String) = workingDir(project.layout.buildDirectory.dir("fladle/$configName"))
}
| 0 | Kotlin | 0 | 0 | f93fc27404d6f6c5f45ebcf20244103526cb7b57 | 463 | fladle | Apache License 2.0 |
app/src/main/java/com/diegoalvis/composechat/features/conversation/ConversationComponent.kt | diegoalvis | 773,009,887 | false | {"Kotlin": 13516} | package com.diegoalvis.composechat.features.conversation
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material3.InputChip
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.diegoalvis.composechat.data.mockMessagesMessage
import com.diegoalvis.composechat.data.model.Conversation
import com.diegoalvis.composechat.data.model.Message
import com.diegoalvis.composechat.theme.AppTheme
@Composable
fun ConversationScreen(
modifier: Modifier = Modifier,
uiViewState: ConversationViewState,
navigateToParticipant: (String) -> Unit,
onNavIconPressed: () -> Unit,
) {
val scrollState = rememberLazyListState()
Scaffold(
topBar = {
// Add Top Bar
}
) { paddingValues ->
Column(
Modifier
.fillMaxSize()
.padding(paddingValues)
) {
MessageList(
messages = uiViewState.messages,
modifier = Modifier.weight(1f),
scrollState = scrollState,
)
}
}
}
@Composable
fun MessageList(
modifier: Modifier = Modifier,
scrollState: LazyListState,
messages: List<Message>,
) {
LazyColumn(
reverseLayout = true,
state = scrollState,
modifier = Modifier
.fillMaxSize()
) {
for (index in messages.indices) {
// val prevAuthor = messages.getOrNull(index - 1)?.author
// val nextAuthor = messages.getOrNull(index + 1)?.author
val message = messages[index]
// val isFirstMessageByAuthor = prevAuthor != content.author
// val isLastMessageByAuthor = nextAuthor != content.author
item {
MessageContent(
onAuthorClick = {},
message = message,
isFirstMessageByAuthor = true,
isLastMessageByAuthor = false,
)
}
}
}
}
@Composable
fun MessageContent(
onAuthorClick: (String) -> Unit,
message: Message,
isFirstMessageByAuthor: Boolean,
isLastMessageByAuthor: Boolean
) {
val borderColor = if (message.isUserMe) {
MaterialTheme.colorScheme.primary
} else {
MaterialTheme.colorScheme.tertiary
}
val spaceBetweenAuthors = if (isLastMessageByAuthor) Modifier.padding(top = 8.dp) else Modifier
Row(modifier = spaceBetweenAuthors) {
if (isLastMessageByAuthor) {
// Avatar
// Image(...)
} else {
Spacer(modifier = Modifier.width(74.dp))
}
val styledMessage = AnnotatedString(
text = message.content,
)
val ChatBubbleShape = RoundedCornerShape(4.dp, 20.dp, 20.dp, 20.dp)
Surface(
color = borderColor,
shape = ChatBubbleShape
) {
ClickableText(
text = styledMessage,
style = MaterialTheme.typography.bodyLarge.copy(color = LocalContentColor.current),
modifier = Modifier.padding(16.dp),
onClick = {
}
)
}
}
}
@Composable
fun UserInput(
modifier: Modifier = Modifier,
selected: Boolean,
) {
InputChip(
selected = selected,
onClick = { /*TODO*/ },
label = {
Text(text = "some text")
},
)
}
@Preview(showBackground = true)
@Composable
fun MessageContentPreview() {
val msg = mockMessagesMessage.last()
val isUserMe = false
AppTheme {
MessageContent(
message = msg,
onAuthorClick = {},
isFirstMessageByAuthor = true,
isLastMessageByAuthor = true,
)
}
}
@Preview(showBackground = true)
@Composable
fun ConversationScreenPreview() {
val viewState = ConversationViewState(
isLoading = true,
conversation = null,
messages = mockMessagesMessage,
)
AppTheme {
ConversationScreen(
uiViewState = viewState,
navigateToParticipant = {
},
onNavIconPressed = {},
)
}
}
@Preview(showBackground = true)
@Composable
fun UserIanputPreview() {
Text(text = "asdasd")
} | 0 | Kotlin | 0 | 0 | 67cf0ca7440174fec6703c79b55f47fdbb52ce60 | 5,235 | chat-app-compose | MIT License |
http4k-serverless/lambda/src/main/kotlin/org/http4k/serverless/InvocationLambdaFunction.kt | s4nchez | 258,724,328 | false | null | package org.http4k.serverless
import com.amazonaws.services.lambda.runtime.Context
import com.amazonaws.services.lambda.runtime.RequestStreamHandler
import org.http4k.core.HttpHandler
import org.http4k.core.Method.POST
import org.http4k.core.Request
import org.http4k.core.Response
import java.io.InputStream
import java.io.OutputStream
/**
* This is the main entry point for lambda invocations using the direct invocations.
* It uses the local environment to instantiate the HttpHandler which can be used
* for further invocations.
*/
abstract class InvocationLambdaFunction(appLoader: AppLoaderWithContexts)
: AwsLambdaFunction<InputStream, InputStream>(InvocationLambdaAwsHttpAdapter, appLoader), RequestStreamHandler {
constructor(input: AppLoader) : this(AppLoaderWithContexts { env, _ -> input(env) })
constructor(input: HttpHandler) : this(AppLoader { input })
override fun handleRequest(input: InputStream, output: OutputStream, context: Context) {
handle(input, context).copyTo(output)
}
}
object InvocationLambdaAwsHttpAdapter : AwsHttpAdapter<InputStream, InputStream> {
override fun invoke(req: InputStream, ctx: Context) =
Request(POST, "/2015-03-31/functions/${ctx.functionName}/invocations")
.header("X-Amz-Invocation-Type", "RequestResponse")
.header("X-Amz-Log-Type", "Tail").body(req)
override fun invoke(resp: Response) = resp.body.stream
}
| 1 | null | 1 | 1 | 220590204fe37a9a22723dbdc9b6cfbbcaf5f975 | 1,437 | http4k | Apache License 2.0 |
src/main/kotlin/dev/paulshields/chronomancy/common/KoinExtensions.kt | Pkshields | 333,756,390 | false | null | package dev.paulshields.chronomancy.common
import org.koin.core.KoinApplication
inline fun <reified TClass : Any> KoinApplication.getInstance() = this.koin.get<TClass>()
| 0 | Kotlin | 0 | 0 | 9a6cfe2ba145c5904d98c391417a23ef01876923 | 172 | Chronomancy | MIT License |
todo-inmemory-repository/src/commonTest/kotlin/com/kmpdroidcon/inmemory/repository/InMemoryTodoDataSourceTest.kt | kmpdroidcon20 | 296,592,134 | false | null | package com.kmpdroidcon.inmemory.repository
import com.kmpdroidcon.core.model.TodoItem
import com.kmpdroidcon.todokmp.datasource.InMemoryTodoDataSourceImpl
import com.kmpdroidcon.util.threadedTest
import kotlinx.atomicfu.atomic
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class InMemoryTodoDataSourceTest {
private val todoListMemoryRepository = InMemoryTodoDataSourceImpl()
@Test
fun testAddTodo() {
val count = 5
val todoList = buildTestTodo(count)
todoList.forEach { todoListMemoryRepository.addTodo(it) }
val runs = atomic(0)
threadedTest {
val todo = buildTestTodo(1, runs.value.toString()).first()
todoListMemoryRepository.addTodo(todo)
assertTrue { todoListMemoryRepository.getAll().contains(todo) }
}
}
@Test
fun testGetAll() {
val todoList = buildTestTodo(5)
todoList.forEach { todoListMemoryRepository.addTodo(it) }
threadedTest {
assertEquals(todoList, todoListMemoryRepository.getAll())
}
}
companion object {
private fun buildTestTodo(count: Int, prefix: String = ""): List<TodoItem> {
return (0 until count).mapIndexed { index, _ ->
TodoItem(
timestamp = 12345L + index,
todo = "$prefix TODO$index"
)
}
}
}
} | 1 | Kotlin | 0 | 7 | 67f788a9c952152649123057fc10e33a484728ea | 1,447 | todokmp | Apache License 2.0 |
src/main/kotlin/com/networkedassets/gherkin/runner/specification/FeatureSpecification.kt | NetworkedAssets | 120,890,153 | false | null | package com.networkedassets.gherkin.runner.specification
import com.networkedassets.gherkin.runner.GherkinRunner
import com.networkedassets.gherkin.runner.exception.InvalidMetadataManipulationException
import com.networkedassets.gherkin.runner.gherkin.GherkinFeature
import com.networkedassets.gherkin.runner.gherkin.StepKeyword
import com.networkedassets.gherkin.runner.gherkin.StepKeyword.AND
import com.networkedassets.gherkin.runner.gherkin.StepKeyword.GIVEN
import com.networkedassets.gherkin.runner.gherkin.StepKeyword.THEN
import com.networkedassets.gherkin.runner.gherkin.StepKeyword.WHEN
import com.networkedassets.gherkin.runner.metadata.MetadataListeners
import groovy.lang.Closure
import org.junit.runner.RunWith
@RunWith(GherkinRunner::class)
abstract class FeatureSpecification {
val stepDefs = mutableMapOf<Pair<StepKeyword, String>, Closure<Any>>()
lateinit var bindings: ExampleBindings
lateinit var feature: GherkinFeature
private var lastType: StepKeyword = GIVEN
val metadataListeners = MetadataListeners()
fun given(stepText: String, closure: Closure<Any>) {
stepDefs.put(Pair(GIVEN, stepText), closure)
lastType = GIVEN
}
fun `when`(stepText: String, closure: Closure<Any>) {
stepDefs.put(Pair(WHEN, stepText), closure)
lastType = WHEN
}
fun then(stepText: String, closure: Closure<Any>) {
stepDefs.put(Pair(THEN, stepText), closure)
lastType = THEN
}
fun and(stepText: String, closure: Closure<Any>) {
when (lastType) {
GIVEN -> given(stepText, closure)
WHEN -> `when`(stepText, closure)
THEN -> then(stepText, closure)
AND -> throw IllegalStateException("Should never happen. AND token is illegal to be lastType")
}
}
fun clearStepDefs() {
stepDefs.clear()
}
fun setFeatureMetadata(metadata: Any) {
setMetadata(metadataListeners.featureMetadataListener, metadata, "setFeatureMetadata invoked out of feature implementation scope")
}
fun setScenarioMetadata(metadata: Any) {
setMetadata(metadataListeners.scenarioMetadataListener, metadata, "setScenarioMetadata invoked out of scenario implementation scope")
}
fun setStepMetadata(metadata: Any) {
setMetadata(metadataListeners.stepMetadataListener, metadata, "setStepMetadata invoked out of step implementation scope")
}
private fun setMetadata(listener: ((Any) -> Unit)?, metadata: Any, errorMessage: String) {
if (listener != null) {
listener(metadata)
} else {
throw InvalidMetadataManipulationException(errorMessage)
}
}
} | 3 | Kotlin | 4 | 7 | b57d6f90acd5183511aa988040d4f33ddcba5bdb | 2,695 | gherkin-runner | Apache License 2.0 |
samples/user-interface/haptics/src/main/java/com/example/platform/ui/haptics/bounce/BounceRoute.kt | android | 623,336,962 | false | null | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.haptics.samples.ui.bounce
import android.content.Context
import android.os.Build
import android.os.VibrationEffect
import android.os.Vibrator
import androidx.compose.animation.core.Easing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.TouchApp
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.example.android.haptics.samples.R
import com.example.android.haptics.samples.ui.components.Screen
import com.example.android.haptics.samples.ui.modifiers.noRippleClickable
import com.example.android.haptics.samples.ui.shapes.ElasticTopShape
import com.example.android.haptics.samples.ui.theme.HapticSamplerTheme
import kotlin.math.pow
/**
* The two positions of the animated ball. Start refers to the elevated state in which
* the ball drops from, and End once the ball is at rest on the "floor".
*/
private enum class BallPosition {
Start,
End,
}
private val BALL_SIZE = 64.dp
private val BALL_DROP_HEIGHT_DP = 300.dp
private val BALL_START_POSITION = -(BALL_DROP_HEIGHT_DP)
private val BALL_END_POSITION = 0.dp
// If recomposition occurs within these ranges, we consider it a collision and will vibrate.
// Speed of animation impacts the ranges we select. For example, we must have a larger range to
// detect initial collision with floor as ball animates quickly through it, otherwise
// it'd be possible for no recomposition to occur within range.
private val DISTANCE_FROM_END_POSITION_FOR_COLLISION = 5.dp
private val DISTANCE_FROM_START_POSITION_FOR_COLLISION = 1.dp
private val FLOOR_SIZE = 80.dp
private const val DROP_ANIMATION_TIME_MS = 3000
private const val RESET_ANIMATION_TIME_MS = 1000
@Composable
fun BounceRoute(viewModel: BounceViewModel) {
BounceExampleScreen(messageToUser = viewModel.messageToUser)
}
@Composable
private fun BounceExampleScreen(messageToUser: String) {
var ballPosition by remember { mutableStateOf(BallPosition.Start) }
var bounceCount by remember { mutableStateOf(0) }
val vibrator = LocalContext.current.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
var transitionData = updateTransitionData(ballPosition)
val collisionData = updateCollisionData(transitionData)
// Execute a click vibration once the ball has been reset.
var hasVibratedForReset by remember { mutableStateOf(false) }
if (collisionData.collisionWithReset) {
if (!hasVibratedForReset) {
clickVibration(vibrator)
hasVibratedForReset = true
}
} else {
hasVibratedForReset = false
}
// Ball is about to contact floor, only vibrating once per collision.
var hasVibratedForBallContact by remember { mutableStateOf(false) }
if (collisionData.collisionWithFloor) {
if (!hasVibratedForBallContact) {
thudVibration(vibrator, 0.7.pow(bounceCount++).toFloat())
hasVibratedForBallContact = true
}
} else {
// Reset for next contact with floor.
hasVibratedForBallContact = false
}
Screen(pageTitle = stringResource(R.string.bounce), messageToUser = messageToUser) {
Box(
Modifier
.fillMaxSize()
.noRippleClickable {
if (transitionData.isAtStart) {
ballPosition = BallPosition.End
} else {
// Reset the position, with a thud vibration to simulate bounce off the floor.
ballPosition = BallPosition.Start
bounceCount = 0
thudVibration(vibrator)
}
},
) {
var instructionsText: String = "" // Don't display any instructions when bouncing.
if (transitionData.isAtStart) {
instructionsText = stringResource(R.string.bounce_tap_to_drop)
} else if (transitionData.isAtEnd || transitionData.isResetting) {
// Display instructions to reset only when the ball is on floor or resetting.
instructionsText = stringResource(R.string.bounce_tap_to_reset)
}
Box(modifier = Modifier.align(Alignment.BottomCenter).offset(y = -FLOOR_SIZE)) {
Column(Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
Text(
text = instructionsText,
modifier = Modifier
.padding(16.dp)
.offset(y = -BALL_DROP_HEIGHT_DP)
)
Ball(
offsetY = transitionData.ballOffsetY,
displayTouchIndicator = transitionData.isAtStart
)
}
}
Box(
modifier = Modifier.align(Alignment.BottomCenter),
) {
var elasticTopPercent = 0f
// If ballOffsetY is greater than BALL_END_POSITION, ball compresses floor.
if (transitionData.ballOffsetY > BALL_END_POSITION) {
elasticTopPercent = transitionData.ballOffsetY / FLOOR_SIZE
}
Box(
modifier = Modifier
.background(Color.Transparent)
) {
Box(modifier = Modifier.align(Alignment.BottomCenter)) {
Floor(elasticTopPercent)
}
}
}
}
}
}
@Composable
private fun Ball(offsetY: Dp = 0.dp, displayTouchIndicator: Boolean = false) {
Box(
modifier = Modifier
.offset(y = offsetY)
.size(BALL_SIZE)
.clip(CircleShape)
.background(MaterialTheme.colors.primaryVariant)
) {
if (displayTouchIndicator) {
Icon(
Icons.Outlined.TouchApp, contentDescription = null,
Modifier.align(
Alignment.Center
),
MaterialTheme.colors.onPrimary
)
}
}
}
/**
* Floor the ball impacts against.
*/
@Composable
private fun Floor(elasticTopPercent: Float) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(FLOOR_SIZE * 2)
.clip(ElasticTopShape(elasticTopPercent))
.background(MaterialTheme.colors.primaryVariant)
.offset(y = -FLOOR_SIZE)
)
}
/**
* Hold the transition values for the ball being dropped and reset.
*/
private data class TransitionData(
val ballOffsetY: Dp,
val isAtStart: Boolean, // Transition is complete and ball is in start position.
val isAtEnd: Boolean, // Transition is complete and now at rest on floor.
val isResetting: Boolean, // Currently being reset (ball raising back up) to starting position.
val isBouncing: Boolean, // Ball has been released and is bouncing.
)
/**
* Create a transition and return animation values for animating the ball drop.
*/
@Composable
private fun updateTransitionData(ballPosition: BallPosition): TransitionData {
val transition =
updateTransition(ballPosition, label = "Transition between ball raised and dropped.")
val ballOffsetY by transition.animateDp(
transitionSpec = {
when {
BallPosition.Start isTransitioningTo BallPosition.End ->
tween(DROP_ANIMATION_TIME_MS, easing = BounceEasing())
else ->
tween(RESET_ANIMATION_TIME_MS, easing = LinearOutSlowInEasing)
}
}, label = "Ball drop y offset."
) { position ->
when (position) {
BallPosition.Start -> BALL_START_POSITION
BallPosition.End -> BALL_END_POSITION
}
}
val isAtTargetState = transition.currentState === transition.targetState
return TransitionData(
ballOffsetY = ballOffsetY,
isAtStart = isAtTargetState && transition.currentState == BallPosition.Start,
isAtEnd = isAtTargetState && transition.currentState == BallPosition.End,
isBouncing = !isAtTargetState && transition.targetState == BallPosition.End,
isResetting = !isAtTargetState && transition.targetState == BallPosition.Start,
)
}
/**
* Holder for when the ball is currently colliding with floor or reset.
*/
private class BallCollisionData(val collisionWithFloor: Boolean, val collisionWithReset: Boolean)
/**
* Uses the current transition data to return booleans of whether the ball is currently colliding.
*
* When the ball is navigating through a certain range we indicate a collision. A range is necessary
* because we do not know specifically which frames will be drawn during animation.
*/
private fun updateCollisionData(transitionData: TransitionData): BallCollisionData {
val ballOffsetY = transitionData.ballOffsetY
return BallCollisionData(
collisionWithFloor = transitionData.isBouncing &&
ballOffsetY > -(DISTANCE_FROM_END_POSITION_FOR_COLLISION),
collisionWithReset = transitionData.isResetting &&
ballOffsetY > BALL_START_POSITION &&
ballOffsetY < (BALL_START_POSITION + DISTANCE_FROM_START_POSITION_FOR_COLLISION)
)
}
private fun thudVibration(vibrator: Vibrator, intensity: Float = 1f) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return
vibrator.vibrate(
VibrationEffect.startComposition()
.addPrimitive(
VibrationEffect.Composition.PRIMITIVE_THUD,
intensity
)
.compose()
)
}
private fun clickVibration(vibrator: Vibrator) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return
vibrator.vibrate(
VibrationEffect.startComposition()
.addPrimitive(
VibrationEffect.Composition.PRIMITIVE_CLICK,
)
.compose()
)
}
/**
* An easing function that simulates bouncing on a wobbly surface.
*
* This easing function was adapted from https://android.googlesource.com/platform/frameworks/base/+/master/core/java/android/view/animation/BounceInterpolator.java
* for more bounces in the same amount of time.
*/
private class BounceEasing : Easing {
override fun transform(fraction: Float): Float {
var t = fraction
t *= 1.5986f
return when {
t < 0.3535f -> bounce(t) + 0.1f // Final addition is how much to compress floor.
t < 0.8007f -> bounce(t - 0.5771f) + 0.6f + 0.08f
t < 1.1169f -> bounce(t - 0.9588f) + 0.8f + 0.06f
t < 1.3405f -> bounce(t - 1.2287f) + 0.9f + 0.04f
t < 1.4986f -> bounce(t - 1.419557f) + 0.95f + 0.02f
else -> bounce(t - 1.5486f) + 0.98f
}
}
private fun bounce(t: Float): Float {
return t * t * 8.0f
}
}
@Preview(showBackground = true)
@Composable
fun BounceExampleScreenScreenPreview() {
HapticSamplerTheme {
BounceExampleScreen(
messageToUser = "A message to display to user."
)
}
}
| 197 | null | 185 | 977 | 0479d2e8697c5d986d8ac7c135399e408bea78c8 | 13,118 | platform-samples | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.