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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
core/src/main/kotlin/com/wafflestudio/snuttev/core/domain/lecture/model/SnuttLectureIdMap.kt
|
wafflestudio
| 379,143,639
| false
|
{"Kotlin": 172741, "Dockerfile": 229}
|
package com.wafflestudio.snuttev.core.domain.lecture.model
import com.wafflestudio.snuttev.core.common.model.BaseEntity
import jakarta.persistence.Column
import jakarta.persistence.Entity
import jakarta.persistence.FetchType
import jakarta.persistence.JoinColumn
import jakarta.persistence.ManyToOne
@Entity
class SnuttLectureIdMap(
@Column(name = "snutt_id", columnDefinition = "char(24)")
var snuttId: String,
@ManyToOne(optional = false, fetch = FetchType.LAZY)
@JoinColumn(name = "semester_lecture_id", nullable = false, unique = true)
var semesterLecture: SemesterLecture,
) : BaseEntity()
| 0
|
Kotlin
|
2
| 4
|
255c6dea41eb3d1d49ff2b9dfaabec082f0ca66f
| 618
|
snutt-ev
|
MIT License
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/ecs/FirelensLogRouterPropsDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.ecs
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Boolean
import kotlin.Number
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.Map
import kotlin.collections.MutableList
import software.amazon.awscdk.Duration
import software.amazon.awscdk.services.ecs.ContainerImage
import software.amazon.awscdk.services.ecs.EnvironmentFile
import software.amazon.awscdk.services.ecs.FirelensConfig
import software.amazon.awscdk.services.ecs.FirelensLogRouter
import software.amazon.awscdk.services.ecs.HealthCheck
import software.amazon.awscdk.services.ecs.LinuxParameters
import software.amazon.awscdk.services.ecs.LogDriver
import software.amazon.awscdk.services.ecs.PortMapping
import software.amazon.awscdk.services.ecs.Secret
import software.amazon.awscdk.services.ecs.SystemControl
import software.amazon.awscdk.services.ecs.TaskDefinition
import software.amazon.awscdk.services.ecs.Ulimit
import software.constructs.Construct
/**
* Firelens log router.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.*;
* import software.amazon.awscdk.services.ecs.*;
* AppProtocol appProtocol;
* ContainerImage containerImage;
* EnvironmentFile environmentFile;
* LinuxParameters linuxParameters;
* LogDriver logDriver;
* Secret secret;
* TaskDefinition taskDefinition;
* FirelensLogRouter firelensLogRouter = FirelensLogRouter.Builder.create(this,
* "MyFirelensLogRouter")
* .firelensConfig(FirelensConfig.builder()
* .type(FirelensLogRouterType.FLUENTBIT)
* // the properties below are optional
* .options(FirelensOptions.builder()
* .configFileType(FirelensConfigFileType.S3)
* .configFileValue("configFileValue")
* .enableECSLogMetadata(false)
* .build())
* .build())
* .image(containerImage)
* .taskDefinition(taskDefinition)
* // the properties below are optional
* .command(List.of("command"))
* .containerName("containerName")
* .cpu(123)
* .disableNetworking(false)
* .dnsSearchDomains(List.of("dnsSearchDomains"))
* .dnsServers(List.of("dnsServers"))
* .dockerLabels(Map.of(
* "dockerLabelsKey", "dockerLabels"))
* .dockerSecurityOptions(List.of("dockerSecurityOptions"))
* .entryPoint(List.of("entryPoint"))
* .environment(Map.of(
* "environmentKey", "environment"))
* .environmentFiles(List.of(environmentFile))
* .essential(false)
* .extraHosts(Map.of(
* "extraHostsKey", "extraHosts"))
* .gpuCount(123)
* .healthCheck(HealthCheck.builder()
* .command(List.of("command"))
* // the properties below are optional
* .interval(Duration.minutes(30))
* .retries(123)
* .startPeriod(Duration.minutes(30))
* .timeout(Duration.minutes(30))
* .build())
* .hostname("hostname")
* .inferenceAcceleratorResources(List.of("inferenceAcceleratorResources"))
* .linuxParameters(linuxParameters)
* .logging(logDriver)
* .memoryLimitMiB(123)
* .memoryReservationMiB(123)
* .portMappings(List.of(PortMapping.builder()
* .containerPort(123)
* // the properties below are optional
* .appProtocol(appProtocol)
* .hostPort(123)
* .name("name")
* .protocol(Protocol.TCP)
* .build()))
* .privileged(false)
* .pseudoTerminal(false)
* .readonlyRootFilesystem(false)
* .secrets(Map.of(
* "secretsKey", secret))
* .startTimeout(Duration.minutes(30))
* .stopTimeout(Duration.minutes(30))
* .systemControls(List.of(SystemControl.builder()
* .namespace("namespace")
* .value("value")
* .build()))
* .ulimits(List.of(Ulimit.builder()
* .hardLimit(123)
* .name(UlimitName.CORE)
* .softLimit(123)
* .build()))
* .user("user")
* .workingDirectory("workingDirectory")
* .build();
* ```
*/
@CdkDslMarker
public class FirelensLogRouterDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: FirelensLogRouter.Builder = FirelensLogRouter.Builder.create(scope, id)
private val _command: MutableList<String> = mutableListOf()
private val _dnsSearchDomains: MutableList<String> = mutableListOf()
private val _dnsServers: MutableList<String> = mutableListOf()
private val _dockerSecurityOptions: MutableList<String> = mutableListOf()
private val _entryPoint: MutableList<String> = mutableListOf()
private val _environmentFiles: MutableList<EnvironmentFile> = mutableListOf()
private val _inferenceAcceleratorResources: MutableList<String> = mutableListOf()
private val _portMappings: MutableList<PortMapping> = mutableListOf()
private val _systemControls: MutableList<SystemControl> = mutableListOf()
private val _ulimits: MutableList<Ulimit> = mutableListOf()
/**
* The command that is passed to the container.
*
* If you provide a shell command as a single string, you have to quote command-line arguments.
*
* Default: - CMD value built into container image.
*
* @param command The command that is passed to the container.
*/
public fun command(vararg command: String) {
_command.addAll(listOf(*command))
}
/**
* The command that is passed to the container.
*
* If you provide a shell command as a single string, you have to quote command-line arguments.
*
* Default: - CMD value built into container image.
*
* @param command The command that is passed to the container.
*/
public fun command(command: Collection<String>) {
_command.addAll(command)
}
/**
* The name of the container.
*
* Default: - id of node associated with ContainerDefinition.
*
* @param containerName The name of the container.
*/
public fun containerName(containerName: String) {
cdkBuilder.containerName(containerName)
}
/**
* The minimum number of CPU units to reserve for the container.
*
* Default: - No minimum CPU units reserved.
*
* @param cpu The minimum number of CPU units to reserve for the container.
*/
public fun cpu(cpu: Number) {
cdkBuilder.cpu(cpu)
}
/**
* Specifies whether networking is disabled within the container.
*
* When this parameter is true, networking is disabled within the container.
*
* Default: false
*
* @param disableNetworking Specifies whether networking is disabled within the container.
*/
public fun disableNetworking(disableNetworking: Boolean) {
cdkBuilder.disableNetworking(disableNetworking)
}
/**
* A list of DNS search domains that are presented to the container.
*
* Default: - No search domains.
*
* @param dnsSearchDomains A list of DNS search domains that are presented to the container.
*/
public fun dnsSearchDomains(vararg dnsSearchDomains: String) {
_dnsSearchDomains.addAll(listOf(*dnsSearchDomains))
}
/**
* A list of DNS search domains that are presented to the container.
*
* Default: - No search domains.
*
* @param dnsSearchDomains A list of DNS search domains that are presented to the container.
*/
public fun dnsSearchDomains(dnsSearchDomains: Collection<String>) {
_dnsSearchDomains.addAll(dnsSearchDomains)
}
/**
* A list of DNS servers that are presented to the container.
*
* Default: - Default DNS servers.
*
* @param dnsServers A list of DNS servers that are presented to the container.
*/
public fun dnsServers(vararg dnsServers: String) {
_dnsServers.addAll(listOf(*dnsServers))
}
/**
* A list of DNS servers that are presented to the container.
*
* Default: - Default DNS servers.
*
* @param dnsServers A list of DNS servers that are presented to the container.
*/
public fun dnsServers(dnsServers: Collection<String>) {
_dnsServers.addAll(dnsServers)
}
/**
* A key/value map of labels to add to the container.
*
* Default: - No labels.
*
* @param dockerLabels A key/value map of labels to add to the container.
*/
public fun dockerLabels(dockerLabels: Map<String, String>) {
cdkBuilder.dockerLabels(dockerLabels)
}
/**
* A list of strings to provide custom labels for SELinux and AppArmor multi-level security
* systems.
*
* Default: - No security labels.
*
* @param dockerSecurityOptions A list of strings to provide custom labels for SELinux and
* AppArmor multi-level security systems.
*/
public fun dockerSecurityOptions(vararg dockerSecurityOptions: String) {
_dockerSecurityOptions.addAll(listOf(*dockerSecurityOptions))
}
/**
* A list of strings to provide custom labels for SELinux and AppArmor multi-level security
* systems.
*
* Default: - No security labels.
*
* @param dockerSecurityOptions A list of strings to provide custom labels for SELinux and
* AppArmor multi-level security systems.
*/
public fun dockerSecurityOptions(dockerSecurityOptions: Collection<String>) {
_dockerSecurityOptions.addAll(dockerSecurityOptions)
}
/**
* The ENTRYPOINT value to pass to the container.
*
* Default: - Entry point configured in container.
*
* [Documentation](https://docs.docker.com/engine/reference/builder/#entrypoint)
* @param entryPoint The ENTRYPOINT value to pass to the container.
*/
public fun entryPoint(vararg entryPoint: String) {
_entryPoint.addAll(listOf(*entryPoint))
}
/**
* The ENTRYPOINT value to pass to the container.
*
* Default: - Entry point configured in container.
*
* [Documentation](https://docs.docker.com/engine/reference/builder/#entrypoint)
* @param entryPoint The ENTRYPOINT value to pass to the container.
*/
public fun entryPoint(entryPoint: Collection<String>) {
_entryPoint.addAll(entryPoint)
}
/**
* The environment variables to pass to the container.
*
* Default: - No environment variables.
*
* @param environment The environment variables to pass to the container.
*/
public fun environment(environment: Map<String, String>) {
cdkBuilder.environment(environment)
}
/**
* The environment files to pass to the container.
*
* Default: - No environment files.
*
* [Documentation](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/taskdef-envfiles.html)
* @param environmentFiles The environment files to pass to the container.
*/
public fun environmentFiles(vararg environmentFiles: EnvironmentFile) {
_environmentFiles.addAll(listOf(*environmentFiles))
}
/**
* The environment files to pass to the container.
*
* Default: - No environment files.
*
* [Documentation](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/taskdef-envfiles.html)
* @param environmentFiles The environment files to pass to the container.
*/
public fun environmentFiles(environmentFiles: Collection<EnvironmentFile>) {
_environmentFiles.addAll(environmentFiles)
}
/**
* Specifies whether the container is marked essential.
*
* If the essential parameter of a container is marked as true, and that container fails
* or stops for any reason, all other containers that are part of the task are stopped.
* If the essential parameter of a container is marked as false, then its failure does not
* affect the rest of the containers in a task. All tasks must have at least one essential
* container.
*
* If this parameter is omitted, a container is assumed to be essential.
*
* Default: true
*
* @param essential Specifies whether the container is marked essential.
*/
public fun essential(essential: Boolean) {
cdkBuilder.essential(essential)
}
/**
* A list of hostnames and IP address mappings to append to the /etc/hosts file on the container.
*
* Default: - No extra hosts.
*
* @param extraHosts A list of hostnames and IP address mappings to append to the /etc/hosts file
* on the container.
*/
public fun extraHosts(extraHosts: Map<String, String>) {
cdkBuilder.extraHosts(extraHosts)
}
/**
* Firelens configuration.
*
* @param firelensConfig Firelens configuration.
*/
public fun firelensConfig(firelensConfig: FirelensConfigDsl.() -> Unit = {}) {
val builder = FirelensConfigDsl()
builder.apply(firelensConfig)
cdkBuilder.firelensConfig(builder.build())
}
/**
* Firelens configuration.
*
* @param firelensConfig Firelens configuration.
*/
public fun firelensConfig(firelensConfig: FirelensConfig) {
cdkBuilder.firelensConfig(firelensConfig)
}
/**
* The number of GPUs assigned to the container.
*
* Default: - No GPUs assigned.
*
* @param gpuCount The number of GPUs assigned to the container.
*/
public fun gpuCount(gpuCount: Number) {
cdkBuilder.gpuCount(gpuCount)
}
/**
* The health check command and associated configuration parameters for the container.
*
* Default: - Health check configuration from container.
*
* @param healthCheck The health check command and associated configuration parameters for the
* container.
*/
public fun healthCheck(healthCheck: HealthCheckDsl.() -> Unit = {}) {
val builder = HealthCheckDsl()
builder.apply(healthCheck)
cdkBuilder.healthCheck(builder.build())
}
/**
* The health check command and associated configuration parameters for the container.
*
* Default: - Health check configuration from container.
*
* @param healthCheck The health check command and associated configuration parameters for the
* container.
*/
public fun healthCheck(healthCheck: HealthCheck) {
cdkBuilder.healthCheck(healthCheck)
}
/**
* The hostname to use for your container.
*
* Default: - Automatic hostname.
*
* @param hostname The hostname to use for your container.
*/
public fun hostname(hostname: String) {
cdkBuilder.hostname(hostname)
}
/**
* The image used to start a container.
*
* This string is passed directly to the Docker daemon.
* Images in the Docker Hub registry are available by default.
* Other repositories are specified with either repository-url/image:tag or
* repository-url/image@digest.
* TODO: Update these to specify using classes of IContainerImage
*
* @param image The image used to start a container.
*/
public fun image(image: ContainerImage) {
cdkBuilder.image(image)
}
/**
* The inference accelerators referenced by the container.
*
* Default: - No inference accelerators assigned.
*
* @param inferenceAcceleratorResources The inference accelerators referenced by the container.
*/
public fun inferenceAcceleratorResources(vararg inferenceAcceleratorResources: String) {
_inferenceAcceleratorResources.addAll(listOf(*inferenceAcceleratorResources))
}
/**
* The inference accelerators referenced by the container.
*
* Default: - No inference accelerators assigned.
*
* @param inferenceAcceleratorResources The inference accelerators referenced by the container.
*/
public fun inferenceAcceleratorResources(inferenceAcceleratorResources: Collection<String>) {
_inferenceAcceleratorResources.addAll(inferenceAcceleratorResources)
}
/**
* Linux-specific modifications that are applied to the container, such as Linux kernel
* capabilities.
*
* For more information see
* [KernelCapabilities](https://docs.aws.amazon.com/AmazonECS/latest/APIReference/API_KernelCapabilities.html).
*
* Default: - No Linux parameters.
*
* @param linuxParameters Linux-specific modifications that are applied to the container, such as
* Linux kernel capabilities.
*/
public fun linuxParameters(linuxParameters: LinuxParameters) {
cdkBuilder.linuxParameters(linuxParameters)
}
/**
* The log configuration specification for the container.
*
* Default: - Containers use the same logging driver that the Docker daemon uses.
*
* @param logging The log configuration specification for the container.
*/
public fun logging(logging: LogDriver) {
cdkBuilder.logging(logging)
}
/**
* The amount (in MiB) of memory to present to the container.
*
* If your container attempts to exceed the allocated memory, the container
* is terminated.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required for non-Fargate services.
*
* Default: - No memory limit.
*
* @param memoryLimitMiB The amount (in MiB) of memory to present to the container.
*/
public fun memoryLimitMiB(memoryLimitMiB: Number) {
cdkBuilder.memoryLimitMiB(memoryLimitMiB)
}
/**
* The soft limit (in MiB) of memory to reserve for the container.
*
* When system memory is under heavy contention, Docker attempts to keep the
* container memory to this soft limit. However, your container can consume more
* memory when it needs to, up to either the hard limit specified with the memory
* parameter (if applicable), or all of the available memory on the container
* instance, whichever comes first.
*
* At least one of memoryLimitMiB and memoryReservationMiB is required for non-Fargate services.
*
* Default: - No memory reserved.
*
* @param memoryReservationMiB The soft limit (in MiB) of memory to reserve for the container.
*/
public fun memoryReservationMiB(memoryReservationMiB: Number) {
cdkBuilder.memoryReservationMiB(memoryReservationMiB)
}
/**
* The port mappings to add to the container definition.
*
* Default: - No ports are mapped.
*
* @param portMappings The port mappings to add to the container definition.
*/
public fun portMappings(portMappings: PortMappingDsl.() -> Unit) {
_portMappings.add(PortMappingDsl().apply(portMappings).build())
}
/**
* The port mappings to add to the container definition.
*
* Default: - No ports are mapped.
*
* @param portMappings The port mappings to add to the container definition.
*/
public fun portMappings(portMappings: Collection<PortMapping>) {
_portMappings.addAll(portMappings)
}
/**
* Specifies whether the container is marked as privileged.
*
* When this parameter is true, the container is given elevated privileges on the host container
* instance (similar to the root user).
*
* Default: false
*
* @param privileged Specifies whether the container is marked as privileged.
*/
public fun privileged(privileged: Boolean) {
cdkBuilder.privileged(privileged)
}
/**
* When this parameter is true, a TTY is allocated.
*
* This parameter maps to Tty in the "Create a container section" of the
* Docker Remote API and the --tty option to `docker run`.
*
* Default: - false
*
* [Documentation](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definition_pseudoterminal)
* @param pseudoTerminal When this parameter is true, a TTY is allocated.
*/
public fun pseudoTerminal(pseudoTerminal: Boolean) {
cdkBuilder.pseudoTerminal(pseudoTerminal)
}
/**
* When this parameter is true, the container is given read-only access to its root file system.
*
* Default: false
*
* @param readonlyRootFilesystem When this parameter is true, the container is given read-only
* access to its root file system.
*/
public fun readonlyRootFilesystem(readonlyRootFilesystem: Boolean) {
cdkBuilder.readonlyRootFilesystem(readonlyRootFilesystem)
}
/**
* The secret environment variables to pass to the container.
*
* Default: - No secret environment variables.
*
* @param secrets The secret environment variables to pass to the container.
*/
public fun secrets(secrets: Map<String, Secret>) {
cdkBuilder.secrets(secrets)
}
/**
* Time duration (in seconds) to wait before giving up on resolving dependencies for a container.
*
* Default: - none
*
* @param startTimeout Time duration (in seconds) to wait before giving up on resolving
* dependencies for a container.
*/
public fun startTimeout(startTimeout: Duration) {
cdkBuilder.startTimeout(startTimeout)
}
/**
* Time duration (in seconds) to wait before the container is forcefully killed if it doesn't exit
* normally on its own.
*
* Default: - none
*
* @param stopTimeout Time duration (in seconds) to wait before the container is forcefully killed
* if it doesn't exit normally on its own.
*/
public fun stopTimeout(stopTimeout: Duration) {
cdkBuilder.stopTimeout(stopTimeout)
}
/**
* A list of namespaced kernel parameters to set in the container.
*
* Default: - No system controls are set.
*
* [Documentation](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definition_systemcontrols)
* @param systemControls A list of namespaced kernel parameters to set in the container.
*/
public fun systemControls(systemControls: SystemControlDsl.() -> Unit) {
_systemControls.add(SystemControlDsl().apply(systemControls).build())
}
/**
* A list of namespaced kernel parameters to set in the container.
*
* Default: - No system controls are set.
*
* [Documentation](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#container_definition_systemcontrols)
* @param systemControls A list of namespaced kernel parameters to set in the container.
*/
public fun systemControls(systemControls: Collection<SystemControl>) {
_systemControls.addAll(systemControls)
}
/**
* The name of the task definition that includes this container definition.
*
* [disable-awslint:ref-via-interface]
*
* @param taskDefinition The name of the task definition that includes this container definition.
*/
public fun taskDefinition(taskDefinition: TaskDefinition) {
cdkBuilder.taskDefinition(taskDefinition)
}
/**
* An array of ulimits to set in the container.
*
* @param ulimits An array of ulimits to set in the container.
*/
public fun ulimits(ulimits: UlimitDsl.() -> Unit) {
_ulimits.add(UlimitDsl().apply(ulimits).build())
}
/**
* An array of ulimits to set in the container.
*
* @param ulimits An array of ulimits to set in the container.
*/
public fun ulimits(ulimits: Collection<Ulimit>) {
_ulimits.addAll(ulimits)
}
/**
* The user to use inside the container.
*
* This parameter maps to User in the Create a container section of the Docker Remote API and
* the --user option to docker run.
*
* Default: root
*
* [Documentation](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definition_parameters.html#ContainerDefinition-user)
* @param user The user to use inside the container.
*/
public fun user(user: String) {
cdkBuilder.user(user)
}
/**
* The working directory in which to run commands inside the container.
*
* Default: /
*
* @param workingDirectory The working directory in which to run commands inside the container.
*/
public fun workingDirectory(workingDirectory: String) {
cdkBuilder.workingDirectory(workingDirectory)
}
public fun build(): FirelensLogRouter {
if(_command.isNotEmpty()) cdkBuilder.command(_command)
if(_dnsSearchDomains.isNotEmpty()) cdkBuilder.dnsSearchDomains(_dnsSearchDomains)
if(_dnsServers.isNotEmpty()) cdkBuilder.dnsServers(_dnsServers)
if(_dockerSecurityOptions.isNotEmpty()) cdkBuilder.dockerSecurityOptions(_dockerSecurityOptions)
if(_entryPoint.isNotEmpty()) cdkBuilder.entryPoint(_entryPoint)
if(_environmentFiles.isNotEmpty()) cdkBuilder.environmentFiles(_environmentFiles)
if(_inferenceAcceleratorResources.isNotEmpty())
cdkBuilder.inferenceAcceleratorResources(_inferenceAcceleratorResources)
if(_portMappings.isNotEmpty()) cdkBuilder.portMappings(_portMappings)
if(_systemControls.isNotEmpty()) cdkBuilder.systemControls(_systemControls)
if(_ulimits.isNotEmpty()) cdkBuilder.ulimits(_ulimits)
return cdkBuilder.build()
}
}
| 1
|
Kotlin
|
0
| 0
|
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 24,217
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
ui/src/main/java/com/yumodev/ui/recyclerview/Define.kt
|
YumoDevTest
| 104,735,993
| false
|
{"Java": 1284385, "Kotlin": 46687}
|
package com.yumodev.ui.recyclerview
/**
* Created by yumodev on 17/12/15.
*/
object Define {
val LOG_TAG : String = "ymui"
}
| 1
| null |
1
| 1
|
3787405bd521f58e1e0d72de05532f20a1a60184
| 131
|
AndroidOpenTest
|
Apache License 2.0
|
mobilesdk/src/main/java/com/swedbankpay/mobilesdk/Operation.kt
|
SwedbankPay
| 209,749,704
| false
| null |
package com.swedbankpay.mobilesdk.merchantbackend
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonSyntaxException
import com.google.gson.annotations.JsonAdapter
import com.swedbankpay.mobilesdk.merchantbackend.internal.asStringOrNull
import java.lang.reflect.Type
/**
* Swedbank Pay Operation. Operations are invoked by making an HTTP request.
*
* Please refer to the
* [Swedbank Pay documentation](https://developer.swedbankpay.com/checkout/other-features#operations).
*/
@JsonAdapter(Operation.Deserializer::class)
data class Operation(
/**
* The purpose of the operation. The exact meaning is dependent on the Operation context.
*/
val rel: String?,
/**
* The request method
*/
val method: String?,
/**
* The request URL
*/
val href: String?,
/**
* The Content-Type of the response
*/
val contentType: String?
) {
internal class Deserializer : JsonDeserializer<Operation?> {
override fun deserialize(
element: JsonElement,
typeOfT: Type?,
context: JsonDeserializationContext?
): Operation? {
if (element.isJsonNull) return null
val json = try {
element.asJsonObject
} catch (e: Exception) {
throw JsonSyntaxException(e)
}
return Operation(
rel = json["rel"]?.asStringOrNull,
method = json["method"]?.asStringOrNull,
href = json["href"]?.asStringOrNull,
contentType = json["contentType"]?.asStringOrNull
)
}
}
}
| 27
| null |
2
| 5
|
98df28d4dda025aebef4f7ab415811ca687f3d73
| 1,734
|
swedbank-pay-sdk-android
|
Apache License 2.0
|
tray-gtk/src/main/kotlin/com/hristogochev/tray/gtk/util/AttachUtil.kt
|
hristogochev
| 634,594,951
| false
| null |
package com.hristogochev.tray.gtk.util
import com.hristogochev.tray.gtk.components.BaseMenu
import com.hristogochev.tray.gtk.components.MenuEntry
/**
* Executes an action on a submenu entry and then attaches it to a parent
*/
internal inline fun <T : MenuEntry> opcr(parent: BaseMenu, entry: T, op: T.() -> Unit = {}) = entry.apply {
op(this)
parent.attach(entry)
}
| 0
|
Kotlin
|
0
| 1
|
b05910164e45b3962c7753f729a17693e20c1912
| 377
|
tray-gtk
|
Apache License 2.0
|
src/main/kotlin/de/eternalwings/bukkit/konversation/ChainablePrompt.kt
|
kumpelblase2
| 413,042,405
| false
| null |
package de.eternalwings.bukkit.konversation
import org.bukkit.conversations.Prompt
/**
* A prompt which allows setting a next prompt, so chaining them together.
*/
interface ChainablePrompt : Prompt {
/**
* Sets the prompt that should follow this prompt. What follow means, may depend
* on how the prompt works.
*/
fun addNextPrompt(next: ChainablePrompt)
}
| 0
|
Kotlin
|
0
| 2
|
b2b0ff9cc7616cdc7e93fc7a462e09c4d4a2658d
| 385
|
konversation
|
MIT License
|
compiler/testData/codegen/box/ieee754/differentTypesComparison.kt
|
JakeWharton
| 99,388,807
| false
| null |
// IGNORE_BACKEND: JS_IR
fun box(): String {
if (0.toByte().compareTo(-0.0) != 1) return "fail 1.1"
if (0.toByte().compareTo(-0.0F) != 1) return "fail 1.2"
if (0.toByte().compareTo(Double.NaN) != -1) return "fail 1.3"
if (0.toByte().compareTo(Float.NaN) != -1) return "fail 1.4"
if (0.toShort().compareTo(-0.0) != 1) return "fail 2.1"
if (0.toShort().compareTo(-0.0F) != 1) return "fail 2.2"
if (0.toShort().compareTo(Double.NaN) != -1) return "fail 2.3"
if (0.toShort().compareTo(Float.NaN) != -1) return "fail 2.4"
if (0.compareTo(-0.0) != 1) return "fail 3.1"
if (0.compareTo(-0.0F) != 1) return "fail 3.2"
if (0.compareTo(Double.NaN) != -1) return "fail 3.3"
if (0.compareTo(Float.NaN) != -1) return "fail 3.4"
if (0.0F.compareTo(-0.0) != 1) return "fail 4.1"
if (0.0F.compareTo(-0.0F) != 1) return "fail 4.2"
if (0.0F.compareTo(Double.NaN) != -1) return "fail 4.3"
if (0.0F.compareTo(Float.NaN) != -1) return "fail 4.4"
if (0.0.compareTo(-0.0) != 1) return "fail 5.1"
if (0.0.compareTo(-0.0F) != 1) return "fail 5.2"
if (0.0.compareTo(Double.NaN) != -1) return "fail 5.3"
if (0.0.compareTo(Float.NaN) != -1) return "fail 5.4"
if (0L.compareTo(-0.0) != 1) return "fail 6.1"
if (0L.compareTo(-0.0F) != 1) return "fail 6.2"
if (0L.compareTo(Double.NaN) != -1) return "fail 6.3"
if (0L.compareTo(Float.NaN) != -1) return "fail 6.4"
if ((-0.0).compareTo(0.toByte()) != -1) return "fail 7.1"
if ((-0.0).compareTo(0.toShort()) != -1) return "fail 7.2"
if ((-0.0).compareTo(0) != -1) return "fail 7.3"
if ((-0.0).compareTo(0.0F) != -1) return "fail 7.4"
if ((-0.0).compareTo(0.0) != -1) return "fail 7.5"
if ((-0.0).compareTo(0L) != -1) return "fail 7.6"
if ((-0.0F).compareTo(0.toByte()) != -1) return "fail 8.1"
if ((-0.0F).compareTo(0.toShort()) != -1) return "fail 8.2"
if ((-0.0F).compareTo(0) != -1) return "fail 8.3"
if ((-0.0F).compareTo(0.0F) != -1) return "fail 8.4"
if ((-0.0F).compareTo(0.0) != -1) return "fail 8.5"
if ((-0.0F).compareTo(0L) != -1) return "fail 8.6"
if (Double.NaN.compareTo(0.toByte()) != 1) return "fail 9.1"
if (Double.NaN.compareTo(0.toShort()) != 1) return "fail 9.2"
if (Double.NaN.compareTo(0) != 1) return "fail 9.3"
if (Double.NaN.compareTo(0.0F) != 1) return "fail 9.4"
if (Double.NaN.compareTo(0.0) != 1) return "fail 9.5"
if (Double.NaN.compareTo(0L) != 1) return "fail 9.6"
if (Float.NaN.compareTo(0.toByte()) != 1) return "fail 10.1"
if (Float.NaN.compareTo(0.toShort()) != 1) return "fail 10.2"
if (Float.NaN.compareTo(0) != 1) return "fail 10.3"
if (Float.NaN.compareTo(0.0F) != 1) return "fail 10.4"
if (Float.NaN.compareTo(0.0) != 1) return "fail 10.5"
if (Float.NaN.compareTo(0L) != 1) return "fail 10.6"
return "OK"
}
| 179
| null |
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 2,871
|
kotlin
|
Apache License 2.0
|
app/src/main/java/io/github/namhyungu/keymap/ui/home/KeyModel.kt
|
namhyun-gu
| 270,440,101
| false
| null |
package io.github.namhyungu.keymap.ui.home
import android.annotation.SuppressLint
import android.graphics.Typeface
import android.view.View
import android.widget.TextView
import androidx.core.view.isVisible
import com.airbnb.epoxy.EpoxyAttribute
import com.airbnb.epoxy.EpoxyModelClass
import com.airbnb.epoxy.EpoxyModelWithHolder
import com.airbnb.paris.Paris
import com.airbnb.paris.extensions.alpha
import com.airbnb.paris.extensions.textColor
import com.airbnb.paris.extensions.textStyle
import com.airbnb.paris.extensions.textViewStyle
import io.github.namhyungu.keymap.R
import io.github.namhyungu.keymap.util.Util
import io.github.namhyungu.keymap.util.epoxy.KotlinEpoxyHolder
import io.github.namhyungu.keymap.util.getColorFromAttr
@SuppressLint("NonConstantResourceId")
@EpoxyModelClass(layout = R.layout.item_key)
abstract class KeyModel : EpoxyModelWithHolder<KeyModel.KeyHolder>() {
@EpoxyAttribute
var content: String = ""
@EpoxyAttribute
var description: String = ""
@EpoxyAttribute
var address: String = ""
@EpoxyAttribute
var addressDetail: String = ""
@EpoxyAttribute
var buildingName: String = ""
@EpoxyAttribute
var distance: Float = 0f
@EpoxyAttribute(EpoxyAttribute.Option.DoNotHash)
var clickListener: View.OnClickListener? = null
override fun bind(holder: KeyHolder) {
super.bind(holder)
val context = holder.rootView.context
holder.rootView.setOnClickListener(clickListener)
holder.contentView.text = content
if (description.isNotEmpty()) {
holder.descriptionView.text = description
} else {
holder.descriptionView.isVisible = false
}
val builder = Paris.spannableBuilder()
.append(Util.getDistanceString(distance), textViewStyle {
textColor(context.getColorFromAttr(R.attr.colorSecondary))
})
.append(" | ", textViewStyle {
alpha(0.24f)
})
.append(address, textViewStyle {
// textColor(context.getColorFromAttr(R.attr.colorOnBackground))
})
if (addressDetail.isNotEmpty()) {
builder.append(", $addressDetail", textViewStyle {
// textColor(context.getColorFromAttr(R.attr.colorOnBackground))
textStyle(Typeface.BOLD)
})
}
if (buildingName.isNotEmpty()) {
builder.append(" ($buildingName)", textViewStyle {
// textColor(context.getColorFromAttr(R.attr.colorOnBackground))
})
}
builder.applyTo(holder.placeView)
}
inner class KeyHolder : KotlinEpoxyHolder() {
val rootView by bind<View>(R.id.root)
val contentView by bind<TextView>(R.id.content)
val descriptionView by bind<TextView>(R.id.description)
val placeView by bind<TextView>(R.id.place)
}
}
| 0
|
Kotlin
|
0
| 0
|
68129a5a6841b85f0ad89de769a133b6d39ab337
| 2,933
|
key-map
|
Apache License 2.0
|
app/src/main/java/com/github/edwnmrtnz/posko/data/model/User.kt
|
AndroidOnRails
| 148,235,181
| false
| null |
package com.github.edwnmrtnz.posko.data.model
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import com.google.gson.annotations.SerializedName
import java.lang.reflect.Type
data class User(@SerializedName("email") val email : String,
@SerializedName("first_name") val firstName: String,
@SerializedName("last_name") val lastName : String,
@SerializedName("token") val token : String,
@SerializedName("auth_token") val authToken : String,
@SerializedName("created_at") val created_at : String)
| 0
|
Kotlin
|
1
| 0
|
9cfce6c785bce9d6628e50e657e734539bbd7619
| 687
|
posko-android
|
MIT License
|
base/src/main/java/com/chrisjanusa/base/interfaces/BaseRestaurantFragment.kt
|
miamiheat710
| 209,855,968
| false
|
{"Kotlin": 223559}
|
package com.chrisjanusa.base.interfaces
import android.content.Context
import android.os.Bundle
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import com.chrisjanusa.base.CommunicationHelper
import com.chrisjanusa.base.models.RandomizerState
import com.chrisjanusa.base.models.RandomizerViewModel
import com.chrisjanusa.base.preferences.PreferenceHelper
import kotlinx.coroutines.launch
import java.util.*
open class BaseRestaurantFragment : Fragment() {
val randomizerViewModel: RandomizerViewModel by lazy {
activity?.let { CommunicationHelper.getViewModel(it) } ?: throw Exception("Invalid Activity")
}
open fun getFeatureUIManagers() : List<FeatureUIManager> = LinkedList()
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val render = fun(newState: RandomizerState) {
for (uiManager in getFeatureUIManagers()) {
uiManager.render(newState, this)
}
}
randomizerViewModel.state.observe(viewLifecycleOwner, Observer<RandomizerState>(render))
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
for (uiManager in getFeatureUIManagers()) {
uiManager.init(randomizerViewModel, this)
}
lifecycleScope.launch {
for (event in randomizerViewModel.eventChannel) {
event.handleEvent(this@BaseRestaurantFragment)
}
}
}
override fun onStop() {
super.onStop()
randomizerViewModel.state.value?.let {
PreferenceHelper.saveState(it, activity?.getPreferences(Context.MODE_PRIVATE))
}
}
}
| 1
|
Kotlin
|
0
| 0
|
cd1bfe507e320d2774869d926fd35bc721d2c218
| 1,838
|
RandomRestaurantKotlin
|
MIT License
|
adaptive-ui/src/commonMain/kotlin/fun/adaptive/ui/instruction/decoration/Color.kt
|
spxbhuhb
| 788,711,010
| false
|
{"Kotlin": 2251135, "Java": 24502, "HTML": 7707, "JavaScript": 3880, "Shell": 687}
|
package `fun`.adaptive.ui.instruction.decoration
import `fun`.adaptive.adat.Adat
@Adat
class Color(
val value: UInt
) {
constructor(value: String) : this(value.parse())
/**
* @return [value] in "#ffffff" format
*/
fun toHexColor(): String =
"#${value.toString(16).padStart(6, '0')}"
companion object {
fun String.parse(): UInt {
val cleanedValue = this.trim().removePrefix("#")
return when (cleanedValue.length) {
3 -> cleanedValue.flatMap { listOf(it, it) }.joinToString("").toUInt(16)
6 -> cleanedValue.toUInt(16)
else -> throw IllegalArgumentException("Invalid color string format")
}
}
}
}
| 30
|
Kotlin
|
0
| 3
|
d6c0623918922416e3f2d6666b66626e25fb0704
| 741
|
adaptive
|
Apache License 2.0
|
app/src/main/java/com/flowfoundation/wallet/page/notification/model/WalletNotification.kt
|
Outblock
| 692,942,645
| false
|
{"Kotlin": 2412500, "Java": 104150}
|
package com.flowfoundation.wallet.page.notification.model
import com.flowfoundation.wallet.utils.svgToPng
import com.google.gson.annotations.SerializedName
import java.util.Date
data class WalletNotification(
@SerializedName("id")
val id: String,
@SerializedName("priority")
val priority: Priority,
@SerializedName("type")
val type: Type,
@SerializedName("title")
val title: String? = null,
@SerializedName("body")
val body: String? = null,
@SerializedName("icon")
val icon: String? = null,
@SerializedName("image")
val image: String? = null,
@SerializedName("url")
val url: String? = null,
@SerializedName("expiry_time")
val expiryTime: Date,
@SerializedName("display_type")
val displayType: DisplayType
) {
fun icon(): String? {
return icon?.svgToPng()
}
fun isExpired(): Boolean {
if (displayType == DisplayType.EXPIRY) {
val currentTime = Date()
return currentTime.after(expiryTime)
} else {
return false
}
}
}
enum class Type {
@SerializedName("message")
MESSAGE,
@SerializedName("image")
IMAGE,
@SerializedName("pending_request")
PENDING_REQUEST
}
enum class Priority {
@SerializedName("urgent")
URGENT,
@SerializedName("high")
HIGH,
@SerializedName("medium")
MEDIUM,
@SerializedName("low")
LOW
}
enum class DisplayType {
@SerializedName("once")
ONCE, // 只显示一次
@SerializedName("click")
CLICK, // 用户点击,或者关闭后,不再显示
@SerializedName("expiry")
EXPIRY // 一直显示直到过期,用户关闭后,下次启动再显示
}
| 65
|
Kotlin
|
5
| 0
|
119cbc780cd345e9698a73e50bc68fba0eb71385
| 1,645
|
FRW-Android
|
Apache License 2.0
|
src/main/java/net/boreeas/reweave/data/WelcomeMessage.kt
|
strangeglyph
| 81,772,362
| false
|
{"Kotlin": 60457}
|
/*
* Copyright 2017 <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 net.boreeas.reweave.data
/**
* @author <NAME>
*/
data class EndpointAddress(
val ip: String? = null,
val port: Int = 0
)
| 0
|
Kotlin
|
0
| 0
|
ea5e5685c61bd443c40057120535d8303546c005
| 769
|
reweave
|
Apache License 2.0
|
src/test/kotlin/com/aemtools/lang/htl/annotator/RedundantELQuickFixTest.kt
|
iannovic
| 107,144,305
| true
|
{"Kotlin": 618081, "HTML": 14958, "Lex": 3652}
|
package com.aemtools.lang.htl.annotator
import com.aemtools.constant.const.DOLLAR
import com.aemtools.util.writeCommand
import com.intellij.testFramework.InspectionFixtureTestCase
/**
* @author <NAME> */
class RedundantELQuickFixTest : InspectionFixtureTestCase() {
fun testRedundantELQuickFixForDataSlyUse() {
myFixture.configureByText("test.html", """
<div data-sly-use="$DOLLAR{'com.test.Bean'}"></div>
""".trimIndent())
val fix = myFixture.getAllQuickFixes("test.html")
.first()
writeCommand(project) {
fix.invoke(project, editor, file)
}
myFixture.checkResult("""
<div data-sly-use="com.test.Bean"></div>
""".trimIndent())
}
fun testRedundantELQuickFixForDataSlyUse1() {
myFixture.configureByText("test.html", """
<div data-sly-use="$DOLLAR{'com.test.Bean'}"></div>
""".trimIndent())
val fix = myFixture.getAllQuickFixes("test.html")
.first()
writeCommand(project) {
fix.invoke(project, editor, file)
}
myFixture.checkResult("""
<div data-sly-use="com.test.Bean"></div>
""".trimIndent())
}
fun testRedundantELQuickFixForDataSlyInclude() {
myFixture.configureByText("test.html", """
<div data-sly-include="$DOLLAR{'template.html'}"></div>
""".trimIndent())
val fix = myFixture.getAllQuickFixes("test.html")
.first()
writeCommand(project) {
fix.invoke(project, editor, file)
}
myFixture.checkResult("""
<div data-sly-include="template.html"></div>
""".trimIndent())
}
}
| 0
|
Kotlin
|
0
| 0
|
d9c1558872fd5e32f18e0bab0afa8f4495da95b0
| 1,736
|
aemtools
|
MIT License
|
kotlin-ext/src/main/kotlin/Base64.kt
|
nhalase
| 603,235,279
| false
| null |
@file:Suppress("unused")
package dev.nhalase.kotlin
import java.nio.charset.Charset
import java.util.Base64
import java.util.UUID
internal val base64Encoder: Base64.Encoder = Base64.getEncoder()
internal val base64Decoder: Base64.Decoder = Base64.getDecoder()
fun UUID.toByteArray(charset: Charset = Charsets.UTF_8): ByteArray {
return toString().toByteArray(charset = charset)
}
fun String.base64Encode(charset: Charset = Charsets.UTF_8): String {
return base64Encoder.encodeToString(this.toByteArray(charset = charset))
}
fun ByteArray.base64Encode(): String {
return base64Encoder.encodeToString(this)
}
fun String.base64Decode(charset: Charset = Charsets.UTF_8): String {
return String(bytes = base64Decoder.decode(this), charset = charset)
}
fun String.tryBase64Decode(charset: Charset = Charsets.UTF_8): String {
val bytes = try {
base64Decoder.decode(this)
} catch (e: Exception) {
null
}
return if (bytes != null) {
String(bytes = bytes, charset = charset)
} else {
this
}
}
| 0
|
Kotlin
|
0
| 0
|
223b5c94b75cc9e17289415d5d210bef2c260142
| 1,063
|
gradle-kotlin-starter
|
The Unlicense
|
TimeTracker/app/src/main/java/github/informramiz/timetracker/data/cloudfunctions/model/GetUserWorkingHoursResponseApiModel.kt
|
informramiz
| 336,497,767
| false
| null |
package github.informramiz.timetracker.data.cloudfunctions.model
import kotlinx.serialization.Serializable
@Serializable
data class GetUserWorkingHoursResponseApiModel(val preferredWorkingHours: Float? = null)
| 0
|
Kotlin
|
0
| 0
|
4a3ff709f0ce1e8526422cd0183cc263b2ee9139
| 212
|
WorkLogTracker
|
MIT License
|
src/test/kotlin/icfp2019/EatCloserThenFatherTests.kt
|
bspradling
| 193,332,580
| true
|
{"JavaScript": 797310, "Kotlin": 85937, "CSS": 9434, "HTML": 5859}
|
package icfp2019
import icfp2019.model.*
import icfp2019.strategies.EatCloserThenFarther
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
class EatCloserThenFatherTests {
@Test
fun testSimple() {
val problem3Input =
"(15,23),(16,23),(16,17),(15,17),(15,20),(12,20),(12,19),(10,19),(10,16),(12,16),(12,17),(13,17)," +
"(13,14),(14,14),(14,8),(16,8),(16,15),(18,15),(18,0),(27,0),(27,15),(22,15),(22,23),(19,23)," +
"(19,25),(24,25),(24,27),(18,27),(18,33),(16,33),(16,32),(11,32),(11,30),(16,30),(16,27),(15,27)," +
"(15,25),(13,25),(13,24),(12,24),(12,29),(9,29),(9,27),(8,27),(8,37),(2,37),(2,27),(3,27),(3,24)," +
"(9,24),(9,23),(0,23),(0,22),(9,22),(9,21),(13,21),(13,22),(15,22)#(0,22)#(20,7),(24,7),(24,5),(22,5)," +
"(22,6),(21,6),(21,5),(19,5),(19,4),(20,4),(20,3),(19,3),(19,2),(20,2),(20,1),(21,1),(21,4),(22,4),(22,3)," +
"(23,3),(23,4),(24,4),(24,3),(25,3),(25,7),(26,7),(26,13),(24,13),(24,14),(23,14),(23,13),(22,13),(22,14)," +
"(21,14),(21,13),(20,13)#X(16,25);L(19,19);F(4,30);F(17,21);B(4,31)"
val p = parseDesc(problem3Input)
val gs = GameState.gameStateOf(p, Point(20, 0))
val s = EatCloserThenFarther().compute(gs)
val m1 = s(gs)
Assertions.assertEquals(Action.MoveRight, m1.nextMove)
}
@Test
fun test2() {
val problem = """
...XX
w@...
.w.XX
""".toProblem()
val gs = GameState.gameStateOf(problem)
val s = EatCloserThenFarther().compute(gs)
val m1 = s(gs)
Assertions.assertEquals(Action.MoveUp, m1.nextMove)
}
@Test
fun test3() {
val problem = """
.w.XX
w@...
.w.XX
""".toProblem()
val gs = GameState.gameStateOf(problem)
val s = EatCloserThenFarther().compute(gs)
val m1 = s(gs)
Assertions.assertEquals(Action.MoveRight, m1.nextMove)
}
@Test
fun test4() {
val problem = """
.w.XX
w@w..
.w.XX
""".toProblem()
val gs = GameState.gameStateOf(problem)
val s = EatCloserThenFarther().compute(gs)
val m1 = s(gs)
Assertions.assertEquals(Action.MoveRight, m1.nextMove)
Assertions.assertEquals(Int.MAX_VALUE, m1.estimatedDistance.distance)
}
}
| 0
|
JavaScript
|
0
| 0
|
9f7e48cce858cd6a517d4fb69b9a0ec2d2a69dc5
| 2,448
|
icfp-2019
|
The Unlicense
|
app/src/main/java/com/afl/waterReminderDrinkAlarmMonitor/utils/Dao.kt
|
sinansonmez
| 399,841,253
| false
| null |
package com.afl.waterReminderDrinkAlarmMonitor.utils
import androidx.lifecycle.LiveData
import androidx.room.*
import androidx.room.Dao
import com.afl.waterReminderDrinkAlarmMonitor.model.Drink
import com.afl.waterReminderDrinkAlarmMonitor.model.Notification
import com.afl.waterReminderDrinkAlarmMonitor.model.Sum
import com.afl.waterReminderDrinkAlarmMonitor.model.User
private const val DATABASE_NAME = "SQLITE_DATABASE.db"
private const val TABLE_NAME = "User"
private const val COL_ID = "id"
private const val COL_AGE = "age"
private const val COL_WEIGHT = "weight"
private const val COL_GENDER = "gender"
private const val COL_METRIC = "metric"
private const val COL_WATER = "water"
private const val TABLE_NAME_DRUNK = "Drunk"
private const val COL_ID_DRUNK = "id"
private const val COL_DATE_DRUNK = "date"
private const val COL_TIME_DRUNK = "time"
private const val COL_DRINK_DRUNK = "drink"
private const val COL_AMOUNT_DRUNK = "amount"
private const val COL_METRIC_DRUNK = "metric"
private const val TABLE_NAME_NOT = "Notification"
private const val COL_ID_NOT = "id"
private const val COL_PREF_NOT = "notificationPreference"
private const val COL_START_NOT = "startingTime"
private const val COL_FINISH_NOT = "finishingTime"
private const val COL_INTERVAL_NOT = "intervalTime"
@Dao
interface Dao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertData(user: User)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertDrinkData(drink: Drink)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertNotificationInfo(not: Notification)
@Update(onConflict = OnConflictStrategy.REPLACE)
suspend fun updateUser(user: User)
@Update(onConflict = OnConflictStrategy.REPLACE)
suspend fun updateNotificationInfo(not: Notification)
@Delete
suspend fun deleteSelectedDrinkData(drink: Drink)
@Query("SELECT $COL_DATE_DRUNK, SUM($COL_AMOUNT_DRUNK) as Total FROM $TABLE_NAME_DRUNK GROUP BY $COL_DATE_DRUNK")
fun readDrinkData(): LiveData<MutableList<Sum>>
@Query("SELECT $COL_DATE_DRUNK, SUM($COL_AMOUNT_DRUNK) as Total FROM $TABLE_NAME_DRUNK GROUP BY $COL_DATE_DRUNK")
suspend fun readDrinkSumData(): MutableList<Sum>
@Query("SELECT * FROM $TABLE_NAME_DRUNK WHERE $COL_DATE_DRUNK= :date")
suspend fun readDrinkDataDetailsSelectedDay(date: String): MutableList<Drink>
@Query("SELECT $COL_ID_DRUNK, $COL_TIME_DRUNK, $COL_DATE_DRUNK, $COL_DRINK_DRUNK, SUM($COL_AMOUNT_DRUNK) as amount, $COL_METRIC_DRUNK FROM $TABLE_NAME_DRUNK GROUP BY $COL_DATE_DRUNK")
suspend fun readDrinkDataDetailsDaySum(): MutableList<Drink>
@Query("SELECT * FROM $TABLE_NAME LIMIT 1")
fun readData(): LiveData<User>
@Query("SELECT * FROM $TABLE_NAME LIMIT 1")
suspend fun readUserData(): User
@Query("SELECT * FROM $TABLE_NAME_NOT LIMIT 1")
suspend fun readNotData(): Notification
}
| 0
|
Kotlin
|
3
| 28
|
428c9283e4e54894ee6455e73af6f4564e7abba0
| 2,916
|
WaterTracker
|
MIT License
|
app/src/main/java/com/pratthamarora/todoapp/ui/fragments/AddFragment.kt
|
haarrisahmed
| 287,224,584
| true
|
{"Kotlin": 28447}
|
package com.pratthamarora.todoapp.ui.fragments
import android.os.Bundle
import android.view.*
import android.widget.EditText
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.pratthamarora.todoapp.R
import com.pratthamarora.todoapp.data.model.TodoData
import com.pratthamarora.todoapp.utils.Utility.hideTheKeyboard
import com.pratthamarora.todoapp.viewmodel.SharedViewModel
import com.pratthamarora.todoapp.viewmodel.ToDoViewModel
import kotlinx.android.synthetic.main.fragment_add.*
import kotlinx.android.synthetic.main.fragment_add.view.*
class AddFragment : Fragment() {
private val viewModel by viewModels<ToDoViewModel>()
private val sharedViewModel by viewModels<SharedViewModel>()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_add, container, false)
setHasOptionsMenu(true)
view.spinnerPriority.onItemSelectedListener = sharedViewModel.listener
return view
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.add_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.add_menu -> {
insertData()
}
}
return super.onOptionsItemSelected(item)
}
private fun insertData() {
val title = titleET.text.toString()
val priority = spinnerPriority.selectedItem.toString()
val desc = descriptionET.text.toString()
val validate = sharedViewModel.checkData(title, desc)
if (validate) {
requireContext().hideTheKeyboard(descriptionET as EditText)
val newTodo = TodoData(
0,
title,
sharedViewModel.setPriority(priority),
desc
)
viewModel.insertData(newTodo)
Toast.makeText(requireContext(), "Successfully Added!", Toast.LENGTH_SHORT).show()
findNavController().navigate(R.id.action_addFragment_to_listFragment)
} else {
Toast.makeText(requireContext(), "Please fill in all the fields", Toast.LENGTH_SHORT)
.show()
}
}
}
| 0
| null |
0
| 0
|
7d561daa3d1db3440cc460ed1fcd8ae71a5d0e3c
| 2,432
|
TodoList_App
|
MIT License
|
ktfx-commons/src/main/kotlin/ktfx/bindings/ComparisonsBinding.kt
|
hanggrian
| 102,934,147
| false
| null |
@file:Suppress("NOTHING_TO_INLINE")
package ktfx.bindings
import javafx.beans.binding.Bindings
import javafx.beans.binding.DoubleBinding
import javafx.beans.binding.NumberBinding
import javafx.beans.value.ObservableNumberValue
/** @see kotlin.comparisons.maxOf */
inline fun maxOf(a: ObservableNumberValue, b: ObservableNumberValue): NumberBinding =
Bindings.max(a, b,)
/** @see kotlin.comparisons.maxOf */
inline fun maxOf(a: ObservableNumberValue, b: Double): DoubleBinding = Bindings.max(a, b)
/** @see kotlin.comparisons.maxOf */
inline fun maxOf(a: Double, b: ObservableNumberValue): DoubleBinding = Bindings.max(a, b)
/** @see kotlin.comparisons.maxOf */
inline fun maxOf(a: ObservableNumberValue, b: Float): NumberBinding = Bindings.max(a, b)
/** @see kotlin.comparisons.maxOf */
inline fun maxOf(a: Float, b: ObservableNumberValue): NumberBinding = Bindings.max(a, b)
/** @see kotlin.comparisons.maxOf */
inline fun maxOf(a: ObservableNumberValue, b: Long): NumberBinding = Bindings.max(a, b)
/** @see kotlin.comparisons.maxOf */
inline fun maxOf(a: Long, b: ObservableNumberValue): NumberBinding = Bindings.max(a, b)
/** @see kotlin.comparisons.maxOf */
inline fun maxOf(a: ObservableNumberValue, b: Int): NumberBinding = Bindings.max(a, b)
/** @see kotlin.comparisons.maxOf */
inline fun maxOf(a: Int, b: ObservableNumberValue): NumberBinding = Bindings.max(a, b)
/** @see kotlin.comparisons.minOf */
inline fun minOf(a: ObservableNumberValue, b: ObservableNumberValue): NumberBinding =
Bindings.min(a, b,)
/** @see kotlin.comparisons.minOf */
inline fun minOf(a: ObservableNumberValue, b: Double): DoubleBinding = Bindings.min(a, b)
/** @see kotlin.comparisons.minOf */
inline fun minOf(a: Double, b: ObservableNumberValue): DoubleBinding = Bindings.min(a, b)
/** @see kotlin.comparisons.minOf */
inline fun minOf(a: ObservableNumberValue, b: Float): NumberBinding = Bindings.min(a, b)
/** @see kotlin.comparisons.minOf */
inline fun minOf(a: Float, b: ObservableNumberValue): NumberBinding = Bindings.min(a, b)
/** @see kotlin.comparisons.minOf */
inline fun minOf(a: ObservableNumberValue, b: Long): NumberBinding = Bindings.min(a, b)
/** @see kotlin.comparisons.minOf */
inline fun minOf(a: Long, b: ObservableNumberValue): NumberBinding = Bindings.min(a, b)
/** @see kotlin.comparisons.minOf */
inline fun minOf(a: ObservableNumberValue, b: Int): NumberBinding = Bindings.min(a, b)
/** @see kotlin.comparisons.minOf */
inline fun minOf(a: Int, b: ObservableNumberValue): NumberBinding = Bindings.min(a, b)
| 1
| null |
2
| 19
|
6e5ec9fedf8359423c31a2ba64cd175bc9864cd2
| 2,549
|
ktfx
|
Apache License 2.0
|
data/RF01081/rnartist.kts
|
fjossinet
| 449,239,232
| false
|
{"Kotlin": 8214424}
|
import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF01081"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
8 to 11
23 to 26
}
value = "#15149f"
}
color {
location {
8 to 11
23 to 26
}
value = "#15149f"
}
color {
location {
12 to 22
}
value = "#f39c2f"
}
color {
location {
1 to 7
}
value = "#517549"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3016050675602d506a0e308f07d071abf1524b67
| 805
|
Rfam-for-RNArtist
|
MIT License
|
auth/src/main/java/com/albro/storyapp/auth/AuthActivity.kt
|
rifkyhaekal
| 640,716,208
| false
| null |
package com.codersandeep.shopeaze
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class AuthActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_auth)
}
}
| 0
|
Kotlin
|
0
| 1
|
606a83047bc734d616615d70bf5b7bf9026a4be5
| 370
|
StoryApp
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/CheckOutCalendar.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.CheckOutCalendar: ImageVector
get() {
if (_checkOutCalendar != null) {
return _checkOutCalendar!!
}
_checkOutCalendar = Builder(name = "CheckOutCalendar", defaultWidth = 24.0.dp, defaultHeight
= 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(19.0f, 2.0f)
horizontalLineToRelative(-1.0f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f)
reflectiveCurveToRelative(-1.0f, 0.448f, -1.0f, 1.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(-8.0f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f)
reflectiveCurveToRelative(-1.0f, 0.448f, -1.0f, 1.0f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(-1.0f)
curveTo(2.243f, 2.0f, 0.0f, 4.243f, 0.0f, 7.0f)
verticalLineToRelative(3.0f)
curveToRelative(0.0f, 0.552f, 0.448f, 1.0f, 1.0f, 1.0f)
reflectiveCurveToRelative(1.0f, -0.448f, 1.0f, -1.0f)
horizontalLineToRelative(20.0f)
verticalLineToRelative(9.0f)
curveToRelative(0.0f, 1.654f, -1.346f, 3.0f, -3.0f, 3.0f)
lineTo(4.146f, 22.0f)
curveToRelative(-0.732f, 0.0f, -1.436f, -0.266f, -1.983f, -0.75f)
curveToRelative(-0.415f, -0.366f, -1.046f, -0.326f, -1.412f, 0.087f)
curveToRelative(-0.366f, 0.414f, -0.326f, 1.046f, 0.087f, 1.412f)
curveToRelative(0.914f, 0.807f, 2.088f, 1.25f, 3.308f, 1.25f)
horizontalLineToRelative(14.854f)
curveToRelative(2.757f, 0.0f, 5.0f, -2.243f, 5.0f, -5.0f)
lineTo(24.0f, 7.0f)
curveToRelative(0.0f, -2.757f, -2.243f, -5.0f, -5.0f, -5.0f)
close()
moveTo(2.0f, 8.0f)
verticalLineToRelative(-1.0f)
curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f)
horizontalLineToRelative(14.0f)
curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f)
verticalLineToRelative(1.0f)
lineTo(2.0f, 8.0f)
close()
moveTo(4.623f, 13.429f)
lineToRelative(-1.571f, 1.571f)
horizontalLineToRelative(6.948f)
curveToRelative(0.552f, 0.0f, 1.0f, 0.448f, 1.0f, 1.0f)
reflectiveCurveToRelative(-0.448f, 1.0f, -1.0f, 1.0f)
lineTo(3.052f, 17.0f)
lineToRelative(1.571f, 1.571f)
curveToRelative(0.391f, 0.391f, 0.391f, 1.023f, 0.0f, 1.414f)
curveToRelative(-0.195f, 0.195f, -0.451f, 0.293f, -0.707f, 0.293f)
reflectiveCurveToRelative(-0.512f, -0.098f, -0.707f, -0.293f)
lineToRelative(-2.659f, -2.659f)
curveToRelative(-0.731f, -0.731f, -0.731f, -1.92f, 0.0f, -2.651f)
lineToRelative(2.659f, -2.659f)
curveToRelative(0.391f, -0.391f, 1.023f, -0.391f, 1.414f, 0.0f)
reflectiveCurveToRelative(0.391f, 1.023f, 0.0f, 1.414f)
close()
}
}
.build()
return _checkOutCalendar!!
}
private var _checkOutCalendar: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,310
|
icons
|
MIT License
|
src/main/kotlin/flowexamples/e05/E05SimpleScript.kt
|
utilihive
| 379,294,885
| false
| null |
package flowexamples.e05
import org.intellij.lang.annotations.Language
object E05SimpleScript {
@Language("ES6")
val simpleScript = """
return {
message : input.payload.value
}
""".trimIndent()
}
| 0
|
Kotlin
|
2
| 4
|
00228fe692e65ce9ab400c811d69de4049cec3f9
| 249
|
flow-developer-example-project-mvn
|
Apache License 2.0
|
src/main/kotlin/uk/gov/justice/digital/assessments/jpa/repositories/GroupRepository.kt
|
uk-gov-mirror
| 356,783,294
| true
|
{"Kotlin": 334511, "JavaScript": 24640, "Mustache": 4105, "Dockerfile": 1313, "Shell": 181}
|
package uk.gov.justice.digital.assessments.jpa.repositories
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.stereotype.Repository
import uk.gov.justice.digital.assessments.jpa.entities.GroupEntity
import java.util.UUID
@Repository
interface GroupRepository : JpaRepository<GroupEntity, String> {
fun findByGroupUuid(groupId: UUID): GroupEntity?
fun findByGroupCode(groupCode: String): GroupEntity?
}
| 0
|
Kotlin
|
0
| 0
|
708a25169cd7b73075bb996ea379fe982d6f5649
| 446
|
ministryofjustice.hmpps-assessments-api
|
MIT License
|
subprojects/common/elastic/src/main/kotlin/com/avito/android/elastic/ElasticRoundRobinHttpServiceFactory.kt
|
avito-tech
| 230,265,582
| false
| null |
package com.avito.android.elastic
import com.avito.http.RetryInterceptor
import com.google.gson.Gson
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.create
internal class ElasticRoundRobinHttpServiceFactory(
private val endpoints: List<HttpUrl>,
private val okHttpClientBuilder: OkHttpClient.Builder,
private val gson: Gson
) : ElasticServiceFactory {
private val roundRobin = object : ThreadLocal<RoundRobinIterable<HttpUrl>>() {
override fun initialValue(): RoundRobinIterable<HttpUrl> = RoundRobinIterable(endpoints)
}
override fun provide(): ElasticService =
Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.client(
okHttpClientBuilder
.addInterceptor(
RoundRobinInterceptor(
roundRobin = roundRobin,
)
)
.addInterceptor(
RetryInterceptor(
tries = 6,
allowedMethods = listOf("GET", "POST"),
delayMs = 500
) { originalRequest ->
RoundRobinInterceptor.requestOnNextUrl(
originalRequest = originalRequest,
nextUrl = roundRobin.get().next()
)
}
)
.build()
)
.baseUrl("http://localhost") // real url will be set in [RoundRobinInterceptor]
.build()
.create()
}
| 8
| null |
50
| 414
|
bc94abf5cbac32ac249a653457644a83b4b715bb
| 1,770
|
avito-android
|
MIT License
|
app/src/main/java/com/detmir/kkppt3/views/ProjectItemView.kt
|
detmir
| 358,579,304
| false
| null |
package com.detmir.kkppt3.views
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.TextView
import com.detmir.kkppt3.R
import com.detmir.recycli.annotations.RecyclerItemStateBinder
import com.detmir.recycli.annotations.RecyclerItemView
@RecyclerItemView
class ProjectItemView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr) {
private val projectTitle: TextView
private val projectDescription: TextView
init {
LayoutInflater.from(context).inflate(R.layout.project_item_view, this)
projectTitle = findViewById(R.id.project_item_title)
projectDescription = findViewById(R.id.project_item_description)
}
@RecyclerItemStateBinder
fun bindState(projectItem: ProjectItem) {
projectTitle.text = projectItem.title
when (projectItem) {
is ProjectItem.Failed -> projectDescription.text = "Failed"
is ProjectItem.New -> projectDescription.text = "New"
is ProjectItem.Done.AfterDeadline -> projectDescription.text = "After deadline"
is ProjectItem.Done.BeforeDeadline -> projectDescription.text = "Before deadline"
}
}
}
| 2
|
Kotlin
|
2
| 22
|
35a3592de39a97e86081e7c048d9a5d187337bb0
| 1,338
|
recycli
|
Apache License 2.0
|
feature-search/src/main/java/de/niklasbednarczyk/nbweather/feature/search/screens/overview/SearchOverviewScreen.kt
|
NiklasBednarczyk
| 529,683,941
| false
| null |
package de.niklasbednarczyk.nbweather.feature.search.screens.overview
import androidx.activity.compose.BackHandler
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.hilt.navigation.compose.hiltViewModel
import com.google.accompanist.permissions.MultiplePermissionsState
import com.google.accompanist.permissions.rememberMultiplePermissionsState
import de.niklasbednarczyk.nbweather.core.ui.icons.NBIconButton
import de.niklasbednarczyk.nbweather.core.ui.icons.NBIcons
import de.niklasbednarczyk.nbweather.core.ui.icons.emptyIcon
import de.niklasbednarczyk.nbweather.core.ui.resource.NBLoadingView
import de.niklasbednarczyk.nbweather.core.ui.resource.NBResourceWithoutLoadingView
import de.niklasbednarczyk.nbweather.core.ui.scaffold.NBScaffold
import de.niklasbednarczyk.nbweather.core.ui.scaffold.topappbar.NBSearchTopAppBar
import de.niklasbednarczyk.nbweather.feature.search.screens.overview.views.SearchOverviewManageView
import de.niklasbednarczyk.nbweather.feature.search.screens.overview.views.SearchOverviewSearchView
@Composable
fun SearchOverviewScreen(
viewModel: SearchOverviewViewModel = hiltViewModel(),
navigationIcon: @Composable () -> Unit,
navigateToLocation: (Double, Double) -> Unit,
) {
val uiState = viewModel.uiState.collectAsState()
NBResourceWithoutLoadingView(uiState.value.visitedLocationsInfoResource) { visitedLocationsInfo ->
val showNavigationIcon =
visitedLocationsInfo.currentLocation != null && !uiState.value.findingLocationInProgress
val navIcon = if (showNavigationIcon) navigationIcon else emptyIcon
BackHandler(visitedLocationsInfo.isInitialCurrentLocationSet && !showNavigationIcon) {
viewModel.onBackPressedWhenNoCurrentLocation()
}
NBScaffold(
topBar = {
NBSearchTopAppBar(
searchTerm = uiState.value.searchTerm,
navigationIcon = navIcon,
trailingIconWhenEmpty = {
FindCurrentLocation(
shouldShowFindLocation = uiState.value.shouldShowFindLocation,
onFindCurrentLocationClicked = { state ->
viewModel.onFindCurrentLocationClicked(
state,
navigateToLocation
)
},
onLocationPermissionResult = { map ->
viewModel.onLocationPermissionsResult(map, navigateToLocation)
}
)
},
onSearchTermChanged = viewModel::onSearchTermChanged,
onClearSearchTerm = viewModel::onClearSearchTerm,
enabled = !uiState.value.findingLocationInProgress
)
},
snackbarChannel = viewModel.snackbarChannel
) {
if (uiState.value.findingLocationInProgress) {
NBLoadingView()
} else {
if (uiState.value.searchTerm.isEmpty()) {
SearchOverviewManageView(
visitedLocations = visitedLocationsInfo.visitedLocations,
navigateToLocation = navigateToLocation,
removeVisitedLocation = viewModel::removeVisitedLocation
)
} else {
SearchOverviewSearchView(
searchedLocationsResource = uiState.value.searchedLocationsResource,
navigateToLocation = navigateToLocation
)
}
}
}
}
}
@Composable
private fun FindCurrentLocation(
shouldShowFindLocation: Boolean,
onFindCurrentLocationClicked: (MultiplePermissionsState) -> Unit,
onLocationPermissionResult: (Map<String, Boolean>) -> Unit,
) {
val locationPermissionsState = rememberMultiplePermissionsState(
listOf(
SearchOverviewViewModel.LOCATION_PERMISSION_COARSE,
SearchOverviewViewModel.LOCATION_PERMISSION_FINE
),
onLocationPermissionResult
)
if (shouldShowFindLocation) {
NBIconButton(
icon = NBIcons.FindLocation,
onClick = { onFindCurrentLocationClicked(locationPermissionsState) }
)
} else {
emptyIcon()
}
}
| 15
|
Kotlin
|
0
| 0
|
e6af34b6b65007853acc6cf2bf4c3f9b5ff26359
| 4,522
|
NBWeather
|
MIT License
|
app/src/main/java/com/suromo/magic/util/ListUtil.kt
|
weixingtai
| 485,994,313
| false
| null |
package com.suromo.magic.util
import androidx.compose.foundation.lazy.LazyListState
/**
* author : weixingtai
* e-mail : <EMAIL>
* time : 2022/04/2022/4/29
* desc :
*/
val LazyListState.isScrolled: Boolean
get() = firstVisibleItemIndex > 0 || firstVisibleItemScrollOffset > 0
| 0
|
Kotlin
|
0
| 0
|
ac40dcdf3f41a81ee895b0be957d1802529a71a6
| 291
|
Magic
|
MIT License
|
libs/rest/rest/src/main/kotlin/net/corda/httprpc/HttpFileUpload.kt
|
corda
| 346,070,752
| false
| null |
package net.corda.httprpc
import java.io.InputStream
/**
* This object allows custom [RestResource] endpoints to upload a file and gives the implementation a handle on the
* file's content and metadata.
*
* To add file upload to an [RestResource] endpoint, declare a parameter with this type on the function with the
* request body annotation
* [net.corda.httprpc.annotations.RestRequestBodyParameter].
*
* Alternatively, if the extra metadata is not necessary and only the file content is required, you can use declare
* a parameter of type
* [InputStream] instead.
*
* Example usage:
* ```
* @HttpPOST(path = "fileUpload")
* fun fileUpload(@RestRequestBodyParameter file: HttpFileUpload): String
*
* @HttpPOST(path = "multiFileUpload")
* fun multiFileUpload(@RestRequestBodyParameter file1: HttpFileUpload,
* @RestRequestBodyParameter file2: HttpFileUpload): String
*
* @HttpPOST(path = "fileUploadUsingInputStream")
* fun fileUploadUsingInputStream(@RestRequestBodyParameter file: InputStream): String
* ```
*/
class HttpFileUpload(
val content: InputStream,
val contentType: String?,
val extension: String?,
val fileName: String,
val size: Long?
) {
constructor(content: InputStream, fileName: String) : this(content, null, null, fileName, null)
constructor(content: InputStream, contentType: String, fileName: String) : this(content, contentType, null, fileName, null)
}
| 82
|
Kotlin
|
7
| 24
|
17f5d2e5585a8ac56e559d1c099eaee414e6ec5a
| 1,449
|
corda-runtime-os
|
Apache License 2.0
|
app/src/main/java/com/berteodosio/seriemesmo/presentation/home/viewModel/HomeNavigationEvent.kt
|
berteodosio
| 362,337,835
| false
| null |
package com.berteodosio.seriemesmo.presentation.home.viewModel
sealed class HomeNavigationEvent {
class NavigateToShowDetails(val showId: Long) : HomeNavigationEvent()
}
| 0
|
Kotlin
|
0
| 0
|
79acd890ffdab3f37ef9fe82a6b7dc6073714b00
| 176
|
serie-mesmo
|
MIT License
|
filesystem/src/commonMain/kotlin/error/Interrupted.kt
|
illarionov
| 848,247,126
| false
|
{"Kotlin": 1306808, "ANTLR": 6038, "TypeScript": 3148, "CSS": 1042, "FreeMarker": 450, "JavaScript": 89}
|
/*
* Copyright 2024, the wasi-emscripten-host project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package at.released.weh.filesystem.error
import at.released.weh.filesystem.model.FileSystemErrno
import at.released.weh.filesystem.model.FileSystemErrno.INTR
public data class Interrupted(
override val message: String,
) : FileSystemOperationError,
AdvisoryLockError,
CloseError,
FdAttributesError,
OpenError,
ReadError,
SyncError,
WriteError {
override val errno: FileSystemErrno = INTR
}
| 1
|
Kotlin
|
0
| 4
|
8cb136a17cbece15d9e2b0cc9286f35613a149a4
| 698
|
wasi-emscripten-host
|
Apache License 2.0
|
core/src/main/java/com/example/core/Utils.kt
|
Rarj
| 587,352,870
| false
| null |
package com.example.movee
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
fun formatDate(date: String): String {
val parser = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val formatter = SimpleDateFormat("dd MMM yyyy", Locale.getDefault())
return formatter.format(parser.parse(date) as Date)
}
| 0
|
Kotlin
|
0
| 0
|
baaa7c7a0a5c84cae42c209dcc23c768d907808b
| 346
|
moveee
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/presentation/ui/components/home/HomeScreen.kt
|
timlam9
| 348,776,523
| false
| null |
/*
* Copyright 2021 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.androiddevchallenge.presentation.ui.components.home
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.runtime.Composable
import com.example.androiddevchallenge.presentation.activity.MainViewModel
import com.example.androiddevchallenge.presentation.ui.components.home.bottomsheet.BottomSheet
@ExperimentalMaterialApi
@Composable
fun HomeScreen(viewModel: MainViewModel) {
BottomSheet(
viewModel = viewModel
) {
HomeContent(
viewModel = viewModel,
actionLeft = {},
actionRight = {}
)
}
}
| 0
|
Kotlin
|
0
| 1
|
6ba21d49459b88ded2be8d032dc3355242563fac
| 1,227
|
ComposeWeatherApp
|
Apache License 2.0
|
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonregister/integration/GetPrisonNames.kt
|
ministryofjustice
| 337,466,567
| false
|
{"Kotlin": 321410, "Dockerfile": 1443, "Shell": 238}
|
package uk.gov.justice.digital.hmpps.prisonregister.integration
import org.assertj.core.api.Assertions
import org.junit.jupiter.api.Test
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.CsvSource
import org.springframework.test.web.reactive.server.WebTestClient
import uk.gov.justice.digital.hmpps.prisonregister.resource.dto.PrisonNameDto
class GetPrisonNames : IntegrationTest() {
@Test
fun `should return prisons`() {
// Given
val endpoint = "/prisons"
// When
val responseSpec = webTestClient.get().uri(endpoint)
.exchange()
// Then
responseSpec.expectStatus().isOk
val prisonNames = getPrisonNames(responseSpec.expectBody())
Assertions.assertThat(prisonNames).isNotEmpty
}
@Test
fun `should return prison names and ids by name order`() {
// Given
val endPont = "/prisons/names"
// When
val responseSpec = webTestClient.get().uri(endPont)
.exchange()
// Then
responseSpec.expectStatus().isOk
val prisonNames = getPrisonNames(responseSpec.expectBody())
Assertions.assertThat(prisonNames).isNotEmpty
with(prisonNames[0]) {
Assertions.assertThat(prisonId).isEqualTo("AKI")
Assertions.assertThat(prisonName).isEqualTo("Acklington (HMP)")
}
with(prisonNames.last()) {
Assertions.assertThat(prisonId).isEqualTo("WMI")
Assertions.assertThat(prisonName).isEqualTo("Wymott (HMP & YOI)")
}
}
@Test
fun `should return prison names active only and ids by name order`() {
// Given
val endPoint = "/prisons/names?active=true"
// When
val responseSpec = webTestClient.get().uri(endPoint)
.exchange()
// Then
responseSpec.expectStatus().isOk
val prisonNames = getPrisonNames(responseSpec.expectBody())
Assertions.assertThat(prisonNames).isNotEmpty
with(prisonNames[0]) {
Assertions.assertThat(prisonId).isEqualTo("ACI")
Assertions.assertThat(prisonName).isEqualTo("Altcourse (HMP & YOI)")
}
with(prisonNames.last()) {
Assertions.assertThat(prisonId).isEqualTo("WMI")
Assertions.assertThat(prisonName).isEqualTo("Wymott (HMP & YOI)")
}
}
@Test
fun `should return prison non active names only and ids by name order`() {
// Given
val endPoint = "/prisons/names?active=false"
// When
val responseSpec = webTestClient.get().uri(endPoint)
.exchange()
// Then
responseSpec.expectStatus().isOk
val prisonNames = getPrisonNames(responseSpec.expectBody())
Assertions.assertThat(prisonNames).isNotEmpty
with(prisonNames[0]) {
Assertions.assertThat(prisonId).isEqualTo("AKI")
Assertions.assertThat(prisonName).isEqualTo("Acklington (HMP)")
}
with(prisonNames.last()) {
Assertions.assertThat(prisonId).isEqualTo("WOI")
Assertions.assertThat(prisonName).isEqualTo("Wolds (HMP)")
}
}
/**
* Different combinations of 'active' and 'name' for positive (is not empty result) and negative (is empty result) scenarios,
* CVS(active,prisonId,isNotEmpty)
*
* WDI : active prisonID with name "Wakefield (HMP)"
* WOI : non active prisonID with name "Wolds (HMP)"
*/
@ParameterizedTest
@CsvSource(
"true,WDI,true",
"null,WDI,true",
"false,WOI,true",
"null,WOI,true",
"false,WDI,false",
"true,WOI,false",
"false,XXX,false",
"true,XXX,false",
"null,XXX,false",
)
fun `should return prison names based on any kind of active value, name, positive scenarios`(active: String?, prison_id: String?, isNotEmpty: Boolean) {
val queryParams = mutableListOf<String>()
if (active != "null") {
queryParams.add("active=$active")
}
if (prison_id != "null") {
queryParams.add("prison_id=$prison_id")
}
val endPoint = "/prisons/names?" + queryParams.joinToString("&")
// When
val responseSpec = webTestClient.get().uri(endPoint)
.exchange()
// Then
responseSpec.expectStatus().isOk
val prisonNames = getPrisonNames(responseSpec.expectBody())
when (isNotEmpty) {
true -> {
Assertions.assertThat(prisonNames).isNotEmpty
when (prison_id) {
"WDI" -> with(prisonNames.last()) {
Assertions.assertThat(prisonId).isEqualTo("WDI")
Assertions.assertThat(prisonName).isEqualTo("Wakefield (HMP)")
}
"WOI" -> with(prisonNames.last()) {
Assertions.assertThat(prisonId).isEqualTo("WOI")
Assertions.assertThat(prisonName).isEqualTo("Wolds (HMP)")
}
}
}
false -> Assertions.assertThat(prisonNames).isEmpty()
}
}
fun getPrisonNames(returnResult: WebTestClient.BodyContentSpec): Array<PrisonNameDto> {
return objectMapper.readValue(returnResult.returnResult().responseBody, Array<PrisonNameDto>::class.java)
}
}
| 2
|
Kotlin
|
1
| 2
|
23ad6fd7c134253c7830d43a4cf090c6bef3e9b3
| 4,873
|
prison-register
|
MIT License
|
core/model/src/main/java/online/partyrun/partyrunapplication/core/model/running_result/ui/RunnerRecordUiModel.kt
|
SWM-KAWAI-MANS
| 649,352,661
| false
|
{"Kotlin": 734078}
|
package online.partyrun.partyrunapplication.core.model.running_result.ui
import java.time.LocalDateTime
data class RunnerRecordUiModel(
val altitude: Double,
val latitude: Double,
val longitude: Double,
val time: LocalDateTime,
val distance: Double
)
| 2
|
Kotlin
|
1
| 14
|
5d982218815afb4c08e700113cfd8957906994a4
| 273
|
party-run-application
|
MIT License
|
idea/src/org/jetbrains/kotlin/idea/findUsages/findUsageUtils.kt
|
JakeWharton
| 99,388,807
| false
| null |
/*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.findUsages
import com.intellij.find.findUsages.FindUsagesManager
import com.intellij.find.findUsages.FindUsagesOptions
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.impl.light.LightMemberReference
import com.intellij.psi.search.LocalSearchScope
import com.intellij.psi.search.SearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.usageView.UsageInfo
import com.intellij.usages.UsageViewManager
import com.intellij.util.Query
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.asJava.toLightElements
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.psi.KtConstructor
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtPsiUtil
import org.jetbrains.kotlin.utils.SmartList
fun PsiElement.processAllExactUsages(
options: () -> FindUsagesOptions,
processor: (UsageInfo) -> Unit
) {
fun elementsToCheckReferenceAgainst(reference: PsiReference): List<PsiElement> {
if (reference is KtReference || this !is KtDeclaration) return listOf(this)
return SmartList<PsiElement>().also { list ->
list += this
list += toLightElements()
if (this is KtConstructor<*>) {
getContainingClassOrObject().toLightClass()?.let { list += it }
}
}
}
val project = project
FindUsagesManager(project, UsageViewManager.getInstance(project))
.getFindUsagesHandler(this, true)
?.processElementUsages(
this,
{
val reference = it.reference ?: return@processElementUsages true
if (reference is LightMemberReference || elementsToCheckReferenceAgainst(reference).any { reference.isReferenceTo(it) }) {
processor(it)
}
true
},
options()
)
}
fun KtDeclaration.processAllUsages(
options: FindUsagesOptions,
processor: (UsageInfo) -> Unit
) {
val findUsagesHandler = KotlinFindUsagesHandlerFactory(project).createFindUsagesHandler(this, true)
findUsagesHandler.processElementUsages(
this,
{
processor(it)
true
},
options
)
}
object ReferencesSearchScopeHelper {
fun search(declaration: KtDeclaration, defaultScope: SearchScope? = null): Query<PsiReference> {
val enclosingElement = KtPsiUtil.getEnclosingElementForLocalDeclaration(declaration)
return when {
enclosingElement != null -> ReferencesSearch.search(declaration, LocalSearchScope(enclosingElement))
defaultScope != null -> ReferencesSearch.search(declaration, defaultScope)
else -> ReferencesSearch.search(declaration)
}
}
}
| 1
| null |
37
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 3,591
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/app/whakaara/data/preferences/converters/PreferencesConverter.kt
|
ahudson20
| 531,856,934
| false
|
{"Kotlin": 293477, "Shell": 761}
|
package com.app.whakaara.data.preferences.converters
import androidx.room.TypeConverter
import com.app.whakaara.data.preferences.AppTheme
import com.app.whakaara.data.preferences.SettingsTime
import com.app.whakaara.data.preferences.VibrationPattern
class PreferencesConverter {
@TypeConverter
fun toVibrationPattern(value: Int) = enumValues<VibrationPattern>()[value]
@TypeConverter
fun fromVibrationPattern(value: VibrationPattern) = value.ordinal
@TypeConverter
fun toTime(value: Int) = enumValues<SettingsTime>()[value]
@TypeConverter
fun fromTime(value: SettingsTime) = value.ordinal
@TypeConverter
fun toAppTheme(value: Int) = enumValues<AppTheme>()[value]
@TypeConverter
fun fromAppTheme(value: AppTheme) = value.ordinal
}
| 1
|
Kotlin
|
1
| 3
|
e73647f133f90ce203fa073f69724d8f89341fc7
| 785
|
whakaara
|
MIT License
|
kgl-vulkan/src/jvmMain/kotlin/com/kgl/vulkan/enums/ExternalMemoryFeatureNV.kt
|
NikkyAI
| 168,431,916
| true
|
{"Kotlin": 1894114, "C": 1742775}
|
/**
* Copyright [2019] [<NAME>]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kgl.vulkan.enums
import com.kgl.vulkan.utils.VkFlag
import org.lwjgl.vulkan.NVExternalMemoryCapabilities
actual enum class ExternalMemoryFeatureNV(override val value: Int) : VkFlag<ExternalMemoryFeatureNV> {
DEDICATED_ONLY(NVExternalMemoryCapabilities.VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT_NV),
EXPORTABLE(NVExternalMemoryCapabilities.VK_EXTERNAL_MEMORY_FEATURE_EXPORTABLE_BIT_NV),
IMPORTABLE(NVExternalMemoryCapabilities.VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT_NV);
companion object {
private val enumLookUpMap: Map<Int, ExternalMemoryFeatureNV> =
enumValues<ExternalMemoryFeatureNV>().associateBy({ it.value })
fun fromMultiple(value: Int): VkFlag<ExternalMemoryFeatureNV> = VkFlag(value)
fun from(value: Int): ExternalMemoryFeatureNV = enumLookUpMap[value]!!
}
}
| 0
|
Kotlin
|
0
| 0
|
51dfa8a4c655ff8bcf017d8d4a2eb660e14473ed
| 1,402
|
kgl
|
Apache License 2.0
|
android/versioned-abis/expoview-abi48_0_0/src/main/java/abi48_0_0/expo/modules/cellular/CellularGeneration.kt
|
betomoedano
| 462,599,485
| true
|
{"TypeScript": 7804102, "Kotlin": 3383974, "Objective-C": 2722124, "Swift": 1723956, "Java": 1686584, "JavaScript": 847793, "C++": 310224, "C": 237463, "Objective-C++": 191888, "Ruby": 167983, "Shell": 59271, "HTML": 31107, "CMake": 25754, "Batchfile": 89, "CSS": 42}
|
package abi48_0_0.expo.modules.cellular
import abi48_0_0.expo.modules.kotlin.types.Enumerable
enum class CellularGeneration(val value: Int) : Enumerable {
UNKNOWN(0),
CG_2G(1),
CG_3G(2),
CG_4G(3),
CG_5G(4),
}
| 0
|
TypeScript
|
0
| 4
|
52d6405570a39a87149648d045d91098374f4423
| 221
|
expo
|
MIT License
|
mayazuc/android/app/src/main/java/ionic/mayazuc/MediaNotificationBuilder.kt
|
brabebhin
| 786,996,718
| false
|
{"Kotlin": 118384, "TypeScript": 26252, "CSS": 8666, "Java": 4918, "HTML": 1049, "JavaScript": 351}
|
package ionic.mayazuc
import android.content.Context
import android.os.Bundle
import androidx.media3.common.Player.*
import androidx.media3.session.CommandButton
import androidx.media3.session.DefaultMediaNotificationProvider
import androidx.media3.session.MediaSession
import com.google.common.collect.ImmutableList
class MediaNotificationBuilder(val context: Context) : DefaultMediaNotificationProvider(context) {
override fun getMediaButtons(
session: MediaSession,
playerCommands: Commands,
customLayout: ImmutableList<CommandButton>,
showPauseButton: Boolean
): ImmutableList<CommandButton> {
session.setSessionExtras(Bundle().apply { });
val mediaButtons = mutableListOf<CommandButton>()
val skipPreviousCommandButton = CommandButton.Builder().setPlayerCommand(COMMAND_SEEK_TO_PREVIOUS).setEnabled(true).setIconResId(androidx.media3.ui.R.drawable.exo_ic_skip_previous)
.setExtras(Bundle().apply { putInt("androidx.media3.session.command.COMPACT_VIEW_INDEX", 0)}).build();
val playCommandButton = CommandButton.Builder().setPlayerCommand(COMMAND_PLAY_PAUSE).setEnabled(true).setIconResId(if(showPauseButton) androidx.media3.ui.R.drawable.exo_icon_pause else androidx.media3.ui.R.drawable.exo_icon_play)
.setExtras(Bundle().apply { putInt("androidx.media3.session.command.COMPACT_VIEW_INDEX", 1)}).build();
val skipNextCommandButton = CommandButton.Builder().setPlayerCommand(COMMAND_SEEK_TO_NEXT).setEnabled(true).setIconResId(androidx.media3.ui.R.drawable.exo_ic_skip_next)
.setExtras(Bundle().apply { putInt("androidx.media3.session.command.COMPACT_VIEW_INDEX", 2)}).build();
mediaButtons.clear()
mediaButtons.add(skipPreviousCommandButton)
mediaButtons.add(playCommandButton)
mediaButtons.add(skipNextCommandButton)
return ImmutableList.copyOf(mediaButtons);
}
}
| 0
|
Kotlin
|
0
| 0
|
2dc63409d5f2e6489e62f12372723338e80b00e6
| 1,939
|
Mayazuc-Android
|
MIT License
|
src/main/kotlin/io/archx/txblog/data/service/UserService.kt
|
wang-si-yuan
| 327,761,173
| false
|
{"JavaScript": 227980, "Kotlin": 115816, "PLpgSQL": 32635, "HTML": 24475, "Sass": 3921}
|
package io.archx.txblog.data.service
import com.baomidou.mybatisplus.extension.kotlin.KtUpdateWrapper
import com.baomidou.mybatisplus.extension.service.IService
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import io.archx.txblog.common.def.CodeDef
import io.archx.txblog.common.exception.MessageCodeException
import io.archx.txblog.common.util.DateUtils
import io.archx.txblog.data.domain.User
import io.archx.txblog.data.mapper.UserMapper
import org.springframework.stereotype.Service
import org.springframework.util.DigestUtils
import java.security.SecureRandom
import java.util.*
interface UserService : IService<User> {
/**
* 初始化管理员
*/
fun init(): User?
/**
* 根据用户查找用户
*/
fun findByUsername(username: String): User?
/**
* 修改密码
*/
fun changepwd(id: Int, checkpwd: String, password: String)
}
@Service
class UserServiceImpl : ServiceImpl<UserMapper, User>(), UserService {
override fun init(): User? {
val admin = getById(1)
if (admin != null) {
return admin
}
// 初始化 密码123456
val salt = createSalt()
val password = DigestUtils.md5DigestAsHex(("123456\n$salt").byteInputStream())
val u = User(1, "admin", password, salt, "admin@example.com", 0, DateUtils.timestamp())
return if (save(u)) u else null
}
override fun findByUsername(username: String): User? {
return baseMapper.findByUsername(username)
}
override fun changepwd(id: Int, checkpwd: String, password: String) {
val u = getById(id) ?: throw MessageCodeException(CodeDef.RECORD_NOT_FOUND)
if (u.password == DigestUtils.md5DigestAsHex((checkpwd + "\n" + u.salt).byteInputStream())) {
val salt = createSalt()
val npwd = DigestUtils.md5DigestAsHex((password + "\n" + salt).byteInputStream())
val update = KtUpdateWrapper(User::class.java)
update.eq(User::id, id).set(User::password, npwd).set(User::salt, salt).set(User::updatedAt, DateUtils.timestamp())
update(update)
} else {
throw MessageCodeException(CodeDef.INVALID_CERTIFICATE)
}
}
private fun createSalt(): String {
val salt = ByteArray(16)
val r = SecureRandom()
r.nextBytes(salt)
return Base64.getEncoder().encodeToString(salt)
}
}
| 0
|
JavaScript
|
0
| 0
|
d3a6d560ef0ebd76223b2620a55356e0fb632393
| 2,394
|
tx-blog-kotlin
|
MIT License
|
j2k/new/tests/testData/newJ2k/enum/implicitlyPrivateConstructorsEnum.kt
|
JetBrains
| 278,369,660
| false
| null |
enum class JavaEnum {
A("a"),
B;
constructor(x: String) {
this.x = x
}
constructor() {
x = "default"
}
protected var x: String
}
| 284
| null |
5162
| 82
|
cc81d7505bc3e9ad503d706998ae8026c067e838
| 176
|
intellij-kotlin
|
Apache License 2.0
|
app/src/main/java/com/kylecorry/trail_sense/shared/sensors/Accelerometer.kt
|
TrendingTechnology
| 268,941,914
| true
|
{"Kotlin": 217677}
|
package com.kylecorry.trail_sense.shared.sensors
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorManager
import com.kylecorry.trail_sense.weather.domain.LowPassFilter
class Accelerometer(context: Context): BaseSensor(context, Sensor.TYPE_GRAVITY, SensorManager.SENSOR_DELAY_FASTEST) {
val filterSize = 0.03
val filters = listOf(
LowPassFilter(filterSize),
LowPassFilter(filterSize),
LowPassFilter(filterSize)
)
var acceleration = FloatArray(3)
private set
override fun handleSensorEvent(event: SensorEvent) {
acceleration = event.values.mapIndexed { index, value -> filters[index].filter(value.toDouble()).toFloat() }.toFloatArray()
}
}
| 0
| null |
0
| 0
|
ba8786be4ac8deb02f3f0cbc71f4b11420cd09fa
| 786
|
Trail-Sense
|
MIT License
|
typescript-kotlin/src/main/kotlin/typescript/CaseClause.kt
|
turansky
| 393,199,102
| false
| null |
// Automatically generated - do not modify!
package typescript
external interface CaseClause : Node {
/*
readonly kind: SyntaxKind.CaseClause;
readonly parent: CaseBlock;
readonly expression: Expression;
readonly statements: NodeArray<Statement>;
*/
}
| 0
|
Kotlin
|
1
| 10
|
bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0
| 278
|
react-types-kotlin
|
Apache License 2.0
|
library/src/main/java/io/callstats/event/special/LogEvent.kt
|
callstats-io
| 129,705,126
| false
| null |
package io.callstats.event.special
import io.callstats.event.SessionEvent
/**
* You can submit application error logs using this event. You will be able to search for them and also categorize them.
*
* @param level "debug" "info" "warn" "error" "fatal"
* @param message application message
* @param messageType "text" "json" "domError"
*/
internal class LogEvent(
val level: String,
val message: String,
val messageType: String) : SessionEvent()
{
override fun path() = "events/app/logs"
}
| 1
|
Kotlin
|
2
| 5
|
65b22d6d4154169b0e32bc5e5b1441a4615a7ac0
| 511
|
callstats-android
|
MIT License
|
app/src/main/java/com/github/liaoheng/codec/demo/MApplication.kt
|
liaoheng
| 368,392,831
| false
|
{"C": 1019340, "Java": 149028, "C++": 49610, "Kotlin": 5666, "Objective-C": 3945, "CMake": 3622}
|
package com.github.liaoheng.codec.demo
import android.app.Application
import com.github.liaoheng.codec.Codec
import com.github.liaoheng.codec.view.CodecView
import com.github.liaoheng.common.Common
/**
* @author liaoheng
* @version 2020-04-20 21:19
*/
class MApplication : Application() {
override fun onCreate() {
super.onCreate()
Common.baseInit(this, "codec", BuildConfig.DEBUG)
Codec.init(this)
CodecView.init(this, BuildConfig.DEBUG)
}
}
| 0
|
C
|
1
| 0
|
6b87daa15b5d351fc5266e7791c0f32f6bc60ace
| 489
|
android-codec
|
Apache License 2.0
|
idea/testData/checker/TypeArgumentsNotAllowed.kt
|
JakeWharton
| 99,388,807
| false
| null |
package foo
open class A<T>
fun <T> f(<warning descr="[UNUSED_PARAMETER] Parameter 't' is never used">t</warning>: T<error descr="[TYPE_ARGUMENTS_NOT_ALLOWED] Type arguments are not allowed for type parameters"><T></error>) {}
fun <T> use(<warning descr="[UNUSED_PARAMETER] Parameter 'b' is never used">b</warning>: foo<error descr="[TYPE_ARGUMENTS_NOT_ALLOWED] Type arguments are not allowed here"><T></error>.A<T>) {}
| 0
| null |
28
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 423
|
kotlin
|
Apache License 2.0
|
app/src/main/java/com/hamzasharuf/runningtracker/utils/LineChartConfiguration.kt
|
hamzasharuf
| 295,946,507
| false
| null |
package com.hamzasharuf.runningtracker.utils
import android.content.Context
import android.graphics.Color
import androidx.core.content.res.ResourcesCompat
import com.hamzasharuf.runningtracker.R
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
object LineChartConfiguration {
private val blue_light = Color.parseColor("#B22196F3")
private val blue = Color.parseColor("#2196F3")
private val red_light = Color.parseColor("#B2F44336")
private val red = Color.parseColor("#F44336")
private val CIRCLE_COLORS_ARRAY = arrayListOf(
red
)
val circleColors = CIRCLE_COLORS_ARRAY
val lineColor = red_light
val axisLineColor = blue_light
val valueTextColor = Color.parseColor("#009688")
val circleRadius = 8f
val valueTextSize = 14f
val fillAlpha = 110
val lineWidth = 5f
val xAxisAnimationSpeed = 700
val visibleXRangeMaximum = 5f
}
| 0
|
Kotlin
|
0
| 1
|
3e7be9df2833084a50cf934694678433c51692aa
| 935
|
RunningTracker
|
Apache License 2.0
|
src/commonMain/kotlin/pw/binom/property/AbstractMutableProperty.kt
|
caffeine-mgn
| 516,913,057
| false
|
{"Kotlin": 49553}
|
package pw.binom.property
import pw.binom.web.Listener
abstract class AbstractMutableProperty<T> : MutableProperty<T>, AbstractProperty<T>() {
private var bindedListener: Listener? = null
protected open suspend fun onValueUpdated(oldValue: T, newValue: T) {}
private var firstCallAfterBind = false
private var bindedToProvider: Property<T>? = null
override suspend fun setValue(value: T) {
val oldValue = this.internalGetValue()
unbind()
updateValue(value)
onValueUpdated(oldValue = oldValue, newValue = value)
}
override fun bind(provider: Property<T>): Listener {
unbind()
firstCallAfterBind = true
val newListener = provider.addListener { old, new ->
setValue(new)
}
bindedToProvider = provider
bindedListener = newListener
return Listener {
newListener.stopListen()
if (bindedListener === newListener) {
bindedListener = null
}
}
}
override fun unbind() {
val listener = bindedListener
bindedToProvider = null
bindedListener = null
listener?.stopListen()
}
override suspend fun getValue(): T {
val bindedToProvider = bindedToProvider
if (firstCallAfterBind && bindedToProvider != null) {
firstCallAfterBind = true
val newValue = bindedToProvider.getValue()
updateValue(newValue)
return newValue
}
return super.getValue()
}
}
| 0
|
Kotlin
|
0
| 0
|
a10748ab1fbcdb39c8b117ab1efdbcc7afc1bdba
| 1,557
|
web-ui
|
Apache License 2.0
|
designer/src/com/android/tools/idea/uibuilder/surface/layout/LayoutUtils.kt
|
JetBrains
| 60,701,247
| false
| null |
/*
* 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.tools.idea.uibuilder.surface.layout
import java.awt.Insets
/** The minimum scale zoom-to-fit scale value. For now, the legal minimum zoom level is 1%. */
internal const val MINIMUM_SCALE = 0.01
/**
* The unit of scale when calculating the zoom-to-fit scale by calling
* [GridSurfaceLayoutManager.getFitIntoScale]. The recursion stops when the differences of two
* zoom-to-fit value is smaller than this value. We don't display the zoom level lower than 1% in
* the zoom panel, so we use 0.01 here.
*/
internal const val SCALE_UNIT = 0.01
/**
* Max iteration times of the binary search. Iterate 10 times can search 1% to 1024% range which is
* enough in the most use cases.
*/
internal const val MAX_ITERATION_TIMES = 10
/** Returns the sum of both the top and bottom margins */
val Insets.vertical: Int
get() = top + bottom
/** Returns the sum of both the left and right margins */
val Insets.horizontal: Int
get() = left + right
| 5
| null |
230
| 948
|
10110983c7e784122d94c7467e9d243aba943bf4
| 1,588
|
android
|
Apache License 2.0
|
src/main/kotlin/Solvers.kt
|
thomasnield
| 128,618,143
| false
| null |
import javafx.application.Platform
import org.ojalgo.okalgo.expression
import org.ojalgo.okalgo.expressionsbasedmodel
import org.ojalgo.okalgo.variable
import org.ojalgo.optimisation.Variable
enum class Solver {
TOMS_BRANCH_AND_PRUNE {
// A branch-and-bound algorithm
inner class GridCellBranch(val selectedValue: Int,
val gridCell: GridCell,
val previous: GridCellBranch? = null) {
val x = gridCell.x
val y = gridCell.y
val squareX = gridCell.squareX
val squareY = gridCell.squareY
// traverses this entire branch backwards, revealing the solution so far
val traverseBackwards = generateSequence(this) { it.previous }.toList()
// Be able to retrieve a given row, column, or square of assigned values from this branch
val allRow = traverseBackwards.filter { it.y == y && it.squareY == squareY }
val allColumn = traverseBackwards.filter { it.x == x && it.squareX == squareX }
val allSquare = traverseBackwards.filter { it.squareY == squareY && it.squareX== squareX }
// Determines whether our current branch does not break any Sudoku rules
val constraintsMet = allRow.filter { it.selectedValue == selectedValue }.count() <= 1
&& allColumn.filter { it.selectedValue == selectedValue }.count() <= 1
&& allSquare.filter { it.selectedValue == selectedValue }.count() <= 1
// Determines whether this branch should continue to be traversed
val isContinuable = constraintsMet && traverseBackwards.count() < 81
// Determines if this branch is a full solution
val isSolution = traverseBackwards.count() == 81 && constraintsMet
// Animations put back on the game board
fun applyToCell() {
Platform.runLater { gridCell.value = selectedValue }
}
init {
if (isContinuable) applyToCell()
}
}
override fun solve() {
// Order Sudoku cells by count of how many candidate values they have left
// Starting with the most constrained cells (with fewest possible values left) will greatly reduce the search space
// Fixed cells will have only 1 candidate and will be processed first
val sortedByCandidateCount = GridModel.grid.asSequence()
.sortedBy { it.candidatesLeft.count() }
.toList()
// hold onto fixed values snapshot as they are going to mutate during animation
val fixedCellValues = GridModel.grid.asSequence().map { it to it.value }
.filter { it.second != null }
.toMap()
// this is a recursive function for exploring nodes in a branch-and-bound tree
fun traverse(index: Int, currentBranch: GridCellBranch): GridCellBranch? {
val nextCell = sortedByCandidateCount[index+1]
val fixedValue = fixedCellValues[nextCell]
// we want to explore possible values 1..9 unless this cell is fixed already
// infeasible values should terminate the branch
val range = if (fixedValue == null) (1..9) else (fixedValue..fixedValue)
for (candidateValue in range) {
val nextBranch = GridCellBranch(candidateValue, nextCell, currentBranch)
if (nextBranch.isSolution)
return nextBranch
if (nextBranch.isContinuable) {
val terminalBranch = traverse(index + 1, nextBranch)
if (terminalBranch?.isSolution == true) {
return terminalBranch
}
}
}
return null
}
// start with the first sorted Sudoku cell and set it as the seed
val seed = sortedByCandidateCount.first()
.let { GridCellBranch(it.value?:1, it) }
// recursively traverse from the seed and get a solution
val solution = traverse(0, seed)
// apply solution back to game baoard
solution?.traverseBackwards?.forEach { it.applyToCell() }
Platform.runLater { GridModel.status = if (solution == null) "INFEASIBLE" else "FEASIBLE" }
}
},
OJALGO_LINEAR_PROGRAMMING {
inner class TripletKey(val i1: Int, val i2: Int, val i3: Int)
override fun solve() {
expressionsbasedmodel {
// A VariableItem is used to pair a GridCell to each candidate number 1-9, and it's corresponding binary variable to be optimized
data class VariableItem(val cell: GridCell, val candidateInt: Int, val variable: Variable)
val variableItems = GridModel.grid.asSequence().flatMap { cell ->
(1..9).asSequence()
.map { VariableItem(cell,it,variable()) }
.onEach { v ->
when {
v.cell.value != null && v.cell.value != v.candidateInt -> v.variable.level(0)
v.cell.value != null && v.cell.value == v.candidateInt -> v.variable.level(1)
else -> v.variable.binary()
}
}
}.toList()
// constrain individual cell so its variables only add to 1
variableItems.groupBy { it.cell }.values.forEach { grp ->
expression {
level(1)
grp.forEach { set(it.variable, 1) }
}
}
// constrain each row so variables of each number only add to 1
variableItems.groupBy { TripletKey(it.cell.squareY, it.cell.y, it.candidateInt) }.values.forEach { grp ->
expression {
level(1)
grp.forEach { set(it.variable,1) }
}
}
// constrain each column so variables of each number only add to 1
variableItems.groupBy { TripletKey(it.cell.squareX, it.cell.x, it.candidateInt) }.values.forEach { grp ->
expression {
level(1)
grp.forEach { set(it.variable,1) }
}
}
// constrain each square so variables of each number only add to 1
variableItems.groupBy { TripletKey(it.cell.squareX, it.cell.squareY, it.candidateInt) }.values.forEach { grp ->
expression {
level(1)
grp.forEach { set(it.variable,1) }
}
}
// minimize number of solutions to seek
options.iterations_suffice = 1
// no optimization objective, but just call minimize()
minimise().also {
Platform.runLater { GridModel.statusProperty.set(it.state.toString()) }
}
// set optimized variables back to GridCells for display
variableItems.asSequence().filter { it.variable.value.toInt() == 1 }.forEach {
Platform.runLater { it.cell.value = it.candidateInt }
}
}
}
};
override fun toString() = name.replace("_", " ")
abstract fun solve()
}
| 0
|
Kotlin
|
15
| 56
|
b221ae31726ffe8dacc22caba31ae46cdc6d5003
| 7,753
|
kotlin-sudoku-solver
|
Apache License 2.0
|
src/main/kotlin/com/theapache64/stackzy/data/local/AndroidApp.kt
|
mulieriq
| 339,401,559
| true
|
{"Kotlin": 109341}
|
package com.theapache64.stackzy.data.local
import com.malinskiy.adam.request.pkg.Package
import com.theapache64.stackzy.ui.common.AlphabetCircle
class AndroidApp(
val appPackage: Package
) : AlphabetCircle() {
override fun getTitle(): String {
return appPackage.name.split(".").last().capitalize()
}
override fun getSubtitle(): String {
return appPackage.name
}
override fun getAlphabet(): Char {
return getTitle().first()
}
}
| 0
| null |
0
| 1
|
11cb821d8b0d29b3afff19ed219b50a7587b0ab3
| 483
|
stackzy
|
Apache License 2.0
|
navigation/graph-builder/src/main/kotlin/ru/maksonic/beresta/navigation/graph_builder/destination/EditNoteDestination.kt
|
maksonic
| 580,058,579
| false
| null |
package ru.maksonic.beresta.navigation.graph_builder.destination
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.ui.Modifier
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavType
import androidx.navigation.navArgument
import com.google.accompanist.navigation.animation.composable
import ru.maksonic.beresta.feature.edit_note.api.EditNoteApi
import ru.maksonic.beresta.navigation.router.AbstractNavigator
import ru.maksonic.beresta.navigation.router.Destination
/**
* @Author maksonic on 04.03.2023
*/
@OptIn(ExperimentalAnimationApi::class)
internal fun NavGraphBuilder.editNoteScreen(api: EditNoteApi.Ui, navigator: AbstractNavigator) {
composable(
route = Destination.EditNote.routeWithArg,
arguments = listOf(navArgument(Destination.EditNote.passedKey) { type = NavType.LongType })
) { navBackStackEntry ->
val router = navigator.editNoteRouter(navBackStackEntry)
api.ExpandableScreen(router, isEntryPoint = true, Modifier)
}
}
| 0
|
Kotlin
|
0
| 0
|
f01672d89b5772c250d237ce5f3db4f73e3af819
| 1,037
|
Beresta
|
MIT License
|
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/models/dataclass/Notification.kt
|
Kroguc
| 112,961,848
| false
|
{"Gradle": 4, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "YAML": 1, "Proguard": 1, "Kotlin": 377, "XML": 225, "Java": 1}
|
package io.github.feelfreelinux.wykopmobilny.models.dataclass
data class Notification(
val author : Author,
val body : String,
val date : String,
val url : String,
var new : Boolean
)
| 1
| null |
1
| 1
|
63bdf6c1c168b747714a7051f7637dca7e48c88d
| 224
|
WykopMobilny
|
MIT License
|
compose-macos-theme/src/commonMain/kotlin/io/chozzle/composemacostheme/modifiedofficial/MacTextFieldDefaults.kt
|
Chozzle
| 319,032,373
| false
| null |
package io.chozzle.composemacostheme.modifiedofficial
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.FastOutLinearInEasing
import androidx.compose.animation.core.keyframes
import androidx.compose.animation.core.tween
import androidx.compose.foundation.interaction.InteractionSource
import androidx.compose.foundation.interaction.collectIsFocusedAsState
import androidx.compose.material.ContentAlpha
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.LocalContentColor
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.TextFieldColors
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.ui.graphics.Color
import io.chozzle.composemacostheme.MacTheme
object MacTextFieldDefaults {
/**
* Creates a [TextFieldColors] that represents the default input text, background and content
* (including label, placeholder, leading and trailing icons) colors used in an
* [OutlinedTextField].
*/
@Composable
fun outlinedTextFieldColors(
textColor: Color = LocalContentColor.current.copy(LocalContentAlpha.current),
disabledTextColor: Color = textColor.copy(ContentAlpha.disabled),
backgroundColor: Color = Color.Transparent,
cursorColor: Color = MaterialTheme.colors.onSurface,
errorCursorColor: Color = MaterialTheme.colors.error,
focusedBorderColor: Color =
MacTheme.colors.highlight,
unfocusedBorderColor: Color =
MacTheme.colors.border.copy(alpha = ContentAlpha.disabled),
disabledBorderColor: Color = unfocusedBorderColor.copy(alpha = ContentAlpha.disabled),
errorBorderColor: Color = MaterialTheme.colors.error,
leadingIconColor: Color =
MaterialTheme.colors.onSurface.copy(alpha = TextFieldDefaults.IconOpacity),
disabledLeadingIconColor: Color = leadingIconColor.copy(alpha = ContentAlpha.disabled),
errorLeadingIconColor: Color = leadingIconColor,
trailingIconColor: Color =
MaterialTheme.colors.onSurface.copy(alpha = TextFieldDefaults.IconOpacity),
disabledTrailingIconColor: Color = trailingIconColor.copy(alpha = ContentAlpha.disabled),
errorTrailingIconColor: Color = MaterialTheme.colors.error,
focusedLabelColor: Color =
MaterialTheme.colors.primary.copy(alpha = ContentAlpha.high),
unfocusedLabelColor: Color = MaterialTheme.colors.onSurface.copy(ContentAlpha.medium),
disabledLabelColor: Color = unfocusedLabelColor.copy(ContentAlpha.disabled),
errorLabelColor: Color = MaterialTheme.colors.error,
placeholderColor: Color = MacTheme.colors.surfaceBorder,
disabledPlaceholderColor: Color = placeholderColor.copy(ContentAlpha.disabled)
): TextFieldColors =
DefaultTextFieldColors(
textColor = textColor,
disabledTextColor = disabledTextColor,
cursorColor = cursorColor,
errorCursorColor = errorCursorColor,
focusedIndicatorColor = focusedBorderColor,
unfocusedIndicatorColor = unfocusedBorderColor,
errorIndicatorColor = errorBorderColor,
disabledIndicatorColor = disabledBorderColor,
leadingIconColor = leadingIconColor,
disabledLeadingIconColor = disabledLeadingIconColor,
errorLeadingIconColor = errorLeadingIconColor,
trailingIconColor = trailingIconColor,
disabledTrailingIconColor = disabledTrailingIconColor,
errorTrailingIconColor = errorTrailingIconColor,
backgroundColor = backgroundColor,
focusedLabelColor = focusedLabelColor,
unfocusedLabelColor = unfocusedLabelColor,
disabledLabelColor = disabledLabelColor,
errorLabelColor = errorLabelColor,
placeholderColor = placeholderColor,
disabledPlaceholderColor = disabledPlaceholderColor
)
}
@Immutable
private class DefaultTextFieldColors(
private val textColor: Color,
private val disabledTextColor: Color,
private val cursorColor: Color,
private val errorCursorColor: Color,
private val focusedIndicatorColor: Color,
private val unfocusedIndicatorColor: Color,
private val errorIndicatorColor: Color,
private val disabledIndicatorColor: Color,
private val leadingIconColor: Color,
private val disabledLeadingIconColor: Color,
private val errorLeadingIconColor: Color,
private val trailingIconColor: Color,
private val disabledTrailingIconColor: Color,
private val errorTrailingIconColor: Color,
private val backgroundColor: Color,
private val focusedLabelColor: Color,
private val unfocusedLabelColor: Color,
private val disabledLabelColor: Color,
private val errorLabelColor: Color,
private val placeholderColor: Color,
private val disabledPlaceholderColor: Color
) : TextFieldColors {
@Composable
override fun leadingIconColor(enabled: Boolean, isError: Boolean): State<Color> {
return rememberUpdatedState(
when {
!enabled -> disabledLeadingIconColor
isError -> errorLeadingIconColor
else -> leadingIconColor
}
)
}
@Composable
override fun trailingIconColor(enabled: Boolean, isError: Boolean): State<Color> {
return rememberUpdatedState(
when {
!enabled -> disabledTrailingIconColor
isError -> errorTrailingIconColor
else -> trailingIconColor
}
)
}
@Composable
override fun indicatorColor(
enabled: Boolean,
isError: Boolean,
interactionSource: InteractionSource
): State<Color> {
val focused by interactionSource.collectIsFocusedAsState()
val targetValue = when {
!enabled -> disabledIndicatorColor
isError -> errorIndicatorColor
focused -> focusedIndicatorColor
else -> unfocusedIndicatorColor
}
return if (enabled) {
// TODO: MacTheme: Tried keyframe animation here to start focus animation at 0% alpha, but there always
// seems to be 1 frame of of 100% alpha which ruins animation
animateColorAsState(targetValue, tween(durationMillis = AnimationDuration))
} else {
rememberUpdatedState(targetValue)
}
}
@Composable
private fun animateMacFlash(targetValue: Color) = animateColorAsState(
targetValue, keyframes {
durationMillis = AnimationDuration
targetValue.copy(alpha = 0f) at 0 with FastOutLinearInEasing
}
)
@Composable
override fun backgroundColor(enabled: Boolean): State<Color> {
return rememberUpdatedState(backgroundColor)
}
@Composable
override fun placeholderColor(enabled: Boolean): State<Color> {
return rememberUpdatedState(if (enabled) placeholderColor else disabledPlaceholderColor)
}
@Composable
override fun labelColor(
enabled: Boolean,
error: Boolean,
interactionSource: InteractionSource
): State<Color> {
val focused by interactionSource.collectIsFocusedAsState()
val targetValue = when {
!enabled -> disabledLabelColor
error -> errorLabelColor
focused -> focusedLabelColor
else -> unfocusedLabelColor
}
return if (enabled) {
animateColorAsState(targetValue, tween(durationMillis = AnimationDuration))
} else {
rememberUpdatedState(targetValue)
}
}
@Composable
override fun textColor(enabled: Boolean): State<Color> {
return rememberUpdatedState(if (enabled) textColor else disabledTextColor)
}
@Composable
override fun cursorColor(isError: Boolean): State<Color> {
return rememberUpdatedState(if (isError) errorCursorColor else cursorColor)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as DefaultTextFieldColors
if (textColor != other.textColor) return false
if (disabledTextColor != other.disabledTextColor) return false
if (cursorColor != other.cursorColor) return false
if (errorCursorColor != other.errorCursorColor) return false
if (focusedIndicatorColor != other.focusedIndicatorColor) return false
if (unfocusedIndicatorColor != other.unfocusedIndicatorColor) return false
if (errorIndicatorColor != other.errorIndicatorColor) return false
if (disabledIndicatorColor != other.disabledIndicatorColor) return false
if (leadingIconColor != other.leadingIconColor) return false
if (disabledLeadingIconColor != other.disabledLeadingIconColor) return false
if (errorLeadingIconColor != other.errorLeadingIconColor) return false
if (trailingIconColor != other.trailingIconColor) return false
if (disabledTrailingIconColor != other.disabledTrailingIconColor) return false
if (errorTrailingIconColor != other.errorTrailingIconColor) return false
if (backgroundColor != other.backgroundColor) return false
if (focusedLabelColor != other.focusedLabelColor) return false
if (unfocusedLabelColor != other.unfocusedLabelColor) return false
if (disabledLabelColor != other.disabledLabelColor) return false
if (errorLabelColor != other.errorLabelColor) return false
if (placeholderColor != other.placeholderColor) return false
if (disabledPlaceholderColor != other.disabledPlaceholderColor) return false
return true
}
override fun hashCode(): Int {
var result = textColor.hashCode()
result = 31 * result + disabledTextColor.hashCode()
result = 31 * result + cursorColor.hashCode()
result = 31 * result + errorCursorColor.hashCode()
result = 31 * result + focusedIndicatorColor.hashCode()
result = 31 * result + unfocusedIndicatorColor.hashCode()
result = 31 * result + errorIndicatorColor.hashCode()
result = 31 * result + disabledIndicatorColor.hashCode()
result = 31 * result + leadingIconColor.hashCode()
result = 31 * result + disabledLeadingIconColor.hashCode()
result = 31 * result + errorLeadingIconColor.hashCode()
result = 31 * result + trailingIconColor.hashCode()
result = 31 * result + disabledTrailingIconColor.hashCode()
result = 31 * result + errorTrailingIconColor.hashCode()
result = 31 * result + backgroundColor.hashCode()
result = 31 * result + focusedLabelColor.hashCode()
result = 31 * result + unfocusedLabelColor.hashCode()
result = 31 * result + disabledLabelColor.hashCode()
result = 31 * result + errorLabelColor.hashCode()
result = 31 * result + placeholderColor.hashCode()
result = 31 * result + disabledPlaceholderColor.hashCode()
return result
}
}
| 1
|
Kotlin
|
7
| 235
|
1f966daa7d8e00eca0a6a02dc289236af39469e9
| 11,471
|
compose-macos-theme
|
Apache License 2.0
|
app/src/main/java/eu/kanade/tachiyomi/ui/player/settings/sheets/StreamsCatalogSheet.kt
|
aniyomiorg
| 358,887,741
| false
| null |
package eu.kanade.tachiyomi.ui.player.settings.sheets
import android.content.Context
import android.content.Intent
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
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.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import eu.kanade.presentation.components.TabbedDialog
import eu.kanade.presentation.components.TabbedDialogPaddings
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.animesource.model.Track
import eu.kanade.tachiyomi.ui.player.PlayerViewModel
import eu.kanade.tachiyomi.ui.player.settings.sheetDialogPadding
import `is`.xyz.mpv.MPVLib
import tachiyomi.presentation.core.components.material.padding
import java.io.File
@Composable
fun StreamsCatalogSheet(
isEpisodeOnline: Boolean?,
videoStreams: PlayerViewModel.VideoStreams,
openContentFd: (Uri) -> String?,
onQualitySelected: (Int) -> Unit,
onSubtitleSelected: (Int) -> Unit,
onAudioSelected: (Int) -> Unit,
onSettingsClicked: () -> Unit,
onDismissRequest: () -> Unit,
) {
val tabTitles = mutableListOf(
stringResource(id = R.string.subtitle_dialog_header),
stringResource(id = R.string.audio_dialog_header),
)
if (isEpisodeOnline == true) {
tabTitles.add(0, stringResource(id = R.string.quality_dialog_header))
}
TabbedDialog(
onDismissRequest = onDismissRequest,
tabTitles = tabTitles,
onOverflowMenuClicked = onSettingsClicked,
overflowIcon = Icons.Outlined.Settings,
hideSystemBars = true,
) { contentPadding, page ->
Column(
modifier = Modifier
.padding(contentPadding)
.padding(vertical = TabbedDialogPaddings.Vertical)
.verticalScroll(rememberScrollState()),
) {
@Composable fun QualityTracksPage() = StreamsPageBuilder(
externalTrackCode = null,
stream = videoStreams.quality,
openContentFd = openContentFd,
onTrackSelected = onQualitySelected,
)
@Composable fun SubtitleTracksPage() = StreamsPageBuilder(
externalTrackCode = "sub",
stream = videoStreams.subtitle,
openContentFd = openContentFd,
onTrackSelected = onSubtitleSelected,
)
@Composable fun AudioTracksPage() = StreamsPageBuilder(
externalTrackCode = "audio",
stream = videoStreams.audio,
openContentFd = openContentFd,
onTrackSelected = onAudioSelected,
)
when (page) {
0 -> if (isEpisodeOnline == true) QualityTracksPage() else SubtitleTracksPage()
1 -> if (isEpisodeOnline == true) SubtitleTracksPage() else AudioTracksPage()
2 -> if (isEpisodeOnline == true) AudioTracksPage()
}
}
}
}
@Composable
private fun StreamsPageBuilder(
externalTrackCode: String?,
stream: PlayerViewModel.VideoStreams.Stream,
openContentFd: (Uri) -> String?,
onTrackSelected: (Int) -> Unit,
) {
var tracks by remember { mutableStateOf(stream.tracks) }
var index by remember { mutableStateOf(stream.index) }
val onSelected: (Int) -> Unit = {
onTrackSelected(it)
index = it
stream.index = it
}
if (externalTrackCode != null) {
val addExternalTrack = rememberLauncherForActivityResult(
object : ActivityResultContracts.GetContent() {
override fun createIntent(context: Context, input: String): Intent {
val intent = super.createIntent(context, input)
return if (externalTrackCode == "audio") {
Intent.createChooser(intent, context.getString(R.string.player_add_external_audio_intent))
} else {
Intent.createChooser(intent, context.getString(R.string.player_add_external_subtitles_intent))
}
}
},
) {
if (it != null) {
val url = it.toString()
val path = if (url.startsWith("content://")) {
openContentFd(Uri.parse(url))
} else {
url
} ?: return@rememberLauncherForActivityResult
MPVLib.command(arrayOf("$externalTrackCode-add", path, "cached"))
val title = File(path).name
tracks += Track(path, title)
stream.tracks += Track(path, title)
index = tracks.lastIndex
stream.index = tracks.lastIndex
}
}
val addTrackRes = if (externalTrackCode == "sub") R.string.player_add_external_subtitles else R.string.player_add_external_audio
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = { addExternalTrack.launch("*/*") })
.padding(sheetDialogPadding),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
modifier = Modifier.padding(end = MaterialTheme.padding.tiny),
imageVector = Icons.Default.Add,
contentDescription = stringResource(id = addTrackRes),
)
Text(
text = stringResource(id = addTrackRes),
style = MaterialTheme.typography.bodyMedium,
)
}
}
tracks.forEachIndexed { i, track ->
val selected = index == i
Row(
modifier = Modifier
.fillMaxWidth()
.clickable(onClick = { onSelected(i) })
.padding(sheetDialogPadding),
) {
Text(
text = track.lang,
fontWeight = if (selected) FontWeight.Bold else FontWeight.Normal,
fontStyle = if (selected) FontStyle.Italic else FontStyle.Normal,
style = MaterialTheme.typography.bodyMedium,
color = if (selected) MaterialTheme.colorScheme.primary else Color.Unspecified,
)
}
}
}
| 24
| null |
8
| 4,992
|
823099f775ef608b7c11f096da1f50762dab82df
| 7,292
|
aniyomi
|
Apache License 2.0
|
app/src/main/java/com/twoics/geo/map/Map.kt
|
DiabloZX
| 646,790,672
| false
| null |
package com.twoics.geo.map
import android.content.Context
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import com.twoics.geo.R
import com.twoics.geo.data.models.BookMark
import org.osmdroid.api.IGeoPoint
import org.osmdroid.config.Configuration
import org.osmdroid.events.DelayedMapListener
import org.osmdroid.events.MapListener
import org.osmdroid.events.ScrollEvent
import org.osmdroid.events.ZoomEvent
import org.osmdroid.util.BoundingBox
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.MapView
import org.osmdroid.views.overlay.Marker
private object MapConstants {
const val WEST_BORDER = -180.0
const val SOUTH_BORDER = -85.0
const val NORTH_BORDER = 85.0
const val EAST_BORDER = 180.0
const val MAX_ZOOM_LEVEL = 20.0
const val MIN_ZOOM_LEVEL = 4.0
const val START_ZOOM = 12.0
}
private data class MapMarker(
val bookmark: BookMark,
val marker: Marker
)
class Map(
defaultAreaRadius: Double,
defaultMapLocation: GeoPoint,
) : IMap {
private lateinit var map: MapView
private lateinit var addingBookmark: Marker
private var bookmarkActive = true
private var foundedBookMarks = ArrayList<MapMarker>()
private var zoom: Double = MapConstants.START_ZOOM
override var areaRadius: Double = defaultAreaRadius
override var centerMapLocation: GeoPoint = defaultMapLocation
private set
private fun drawCurrentPlaces() {
fun drawPlace(mapMarker: MapMarker) {
val marker = mapMarker.marker
val bookmark = mapMarker.bookmark
marker.position = GeoPoint(bookmark.latitude, bookmark.longitude)
map.overlays.add(marker);
}
foundedBookMarks.forEach {
drawPlace(mapMarker = it)
}
map.invalidate()
}
override fun clearPlaces() {
foundedBookMarks.forEach {
map.overlays.remove(it.marker)
}
foundedBookMarks.clear()
map.invalidate()
}
private fun addingBookmarkInit() {
addingBookmark = Marker(map)
bookmarkActive = false
map.overlays.add(addingBookmark);
}
private fun drawAddingBookmark() {
if (bookmarkActive) {
addingBookmark.position = GeoPoint(
centerMapLocation.latitude,
centerMapLocation.longitude
)
}
map.invalidate()
}
override fun changeBookmarkActiveState() {
bookmarkActive = !bookmarkActive
if (bookmarkActive) {
addingBookmark.alpha = 1f
}
else {
addingBookmark.alpha = 0f
}
drawAddingBookmark()
map.invalidate()
}
@Composable
override fun redrawMap(): MapView {
this.map = generateMap()
configureMap()
return this.map
}
override fun updateBookMarks(bookMarks: List<BookMark>) {
clearPlaces()
bookMarks.forEach {
foundedBookMarks.add(
MapMarker(
bookmark = it,
marker = Marker(map)
)
)
}
drawCurrentPlaces()
}
private fun configureMap() {
fun setScrollBorders() {
map.setScrollableAreaLimitDouble(
BoundingBox(
MapConstants.NORTH_BORDER,
MapConstants.EAST_BORDER,
MapConstants.SOUTH_BORDER,
MapConstants.WEST_BORDER
)
)
}
fun setScaleBorders() {
map.maxZoomLevel = MapConstants.MAX_ZOOM_LEVEL
map.minZoomLevel = MapConstants.MIN_ZOOM_LEVEL
map.isHorizontalMapRepetitionEnabled = false
map.isVerticalMapRepetitionEnabled = false
map.setScrollableAreaLimitLatitude(
MapView.getTileSystem().maxLatitude,
MapView.getTileSystem().minLatitude, 0
)
}
fun makeTouchable() {
map.setMultiTouchControls(true)
}
fun setMapView() {
map.controller.setZoom(zoom)
map.controller.setCenter(centerMapLocation)
}
fun setMapListeners() {
fun setMapCenter(point: IGeoPoint) {
centerMapLocation = GeoPoint(point)
}
fun setCurrentZoom(zoom: Double) {
this.zoom = zoom
}
this.map.setMapListener(DelayedMapListener(object : MapListener {
override fun onScroll(paramScrollEvent: ScrollEvent): Boolean {
setMapCenter(map.mapCenter)
drawAddingBookmark()
return true
}
override fun onZoom(event: ZoomEvent): Boolean {
setCurrentZoom(map.zoomLevelDouble)
setMapCenter(map.mapCenter)
drawAddingBookmark()
return false
}
}))
}
setScrollBorders()
setScaleBorders()
makeTouchable()
setMapView()
setMapListeners()
drawCurrentPlaces()
addingBookmarkInit()
drawAddingBookmark()
}
@Composable
private fun rememberMapLifecycleObserver(mapView: MapView): LifecycleEventObserver =
remember(mapView) {
LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> mapView.onResume()
Lifecycle.Event.ON_PAUSE -> mapView.onPause()
else -> {}
}
}
}
@Composable
private fun generateMap(context: Context = LocalContext.current): MapView {
val mapView = remember {
MapView(context).apply {
id = R.id.map
}
}
val lifecycleObserver = rememberMapLifecycleObserver(mapView)
val lifecycle = LocalLifecycleOwner.current.lifecycle
DisposableEffect(lifecycle) {
lifecycle.addObserver(lifecycleObserver)
onDispose {
lifecycle.removeObserver(lifecycleObserver)
}
}
Configuration.getInstance().userAgentValue = context.packageName
return mapView
}
}
| 0
|
Kotlin
|
0
| 0
|
4c09313a547ca1fe505e103b1bb9ab37a6d54b92
| 6,602
|
RMP
|
MIT License
|
app/src/main/java/com/skyyo/samples/features/navigationCores/tab2/Tab2ViewModel.kt
|
Skyyo
| 385,529,955
| false
|
{"Kotlin": 557302}
|
package com.skyyo.samples.features.navigationCores.tab2
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import com.skyyo.samples.utils.NavigationDispatcher
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@HiltViewModel
class Tab2ViewModel @Inject constructor(
private val navigationDispatcher: NavigationDispatcher,
private val handle: SavedStateHandle,
) : ViewModel()
| 5
|
Kotlin
|
5
| 77
|
1319c3d29da4865d6f1931ee18137cdfc1715891
| 441
|
samples
|
MIT License
|
valuedef-common/src/main/java/com/bennyhuo/kotlin/valuedef/common/utils/KtNameFunctionExtensions.kt
|
bennyhuo
| 439,819,685
| false
| null |
package com.bennyhuo.kotlin.valuedef.common.utils
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.psiUtil.lastBlockStatementOrThis
/**
* Created by benny at 2022/1/17 10:37 AM.
*/
val KtNamedFunction.returningExpression: KtExpression?
get() {
return if (hasBlockBody()) {
bodyBlockExpression?.lastBlockStatementOrThis()
?.safeAs<KtReturnExpression>()?.returnedExpression
} else if (hasInitializer()) {
initializer
} else {
null
}
}
| 0
|
Kotlin
|
0
| 4
|
5b5ebfe900e25372d3c076b24dfb175945866a38
| 656
|
KotlinValueDef
|
MIT License
|
src/main/kotlin/com/bfkelsey/api/ApiApplication.kt
|
bfkelsey
| 49,966,208
| false
| null |
package com.bfkelsey.api
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.bfkelsey.api.jdbi.ProviderDAO
import com.bfkelsey.api.resources.ProviderResource
import io.dropwizard.Application
import io.dropwizard.db.DataSourceFactory
import io.dropwizard.jdbi.DBIFactory
import io.dropwizard.migrations.MigrationsBundle
import io.dropwizard.setup.Bootstrap
import io.dropwizard.setup.Environment
import io.dropwizard.assets.AssetsBundle
class ApiApplication : Application<ApiConfiguration>() {
companion object {
@JvmStatic public fun main(args: Array<String>) {
ApiApplication().run(*args)
}
}
override fun run(configuration: ApiConfiguration, environment: Environment) {
val factory = DBIFactory()
val jdbi = factory.build(environment, configuration.dataSourceFactory, "postgresql")
val providerDAO = jdbi.onDemand(ProviderDAO::class.java)
environment.jersey().register(ProviderResource(providerDAO))
}
override fun initialize(bootstrap: Bootstrap<ApiConfiguration>) {
bootstrap.objectMapper.registerModule(KotlinModule())
bootstrap.addBundle(object: MigrationsBundle<ApiConfiguration>() {
override fun getDataSourceFactory(configuration: ApiConfiguration): DataSourceFactory {
return configuration.dataSourceFactory
}
})
bootstrap.addBundle(AssetsBundle("/assets/", "/"))
}
override fun getName(): String {
return "api"
}
}
| 0
|
Kotlin
|
1
| 3
|
9831193cc3f70b3faf6d9c482d0ed6f321eda531
| 1,521
|
dropwizard-kotlin-api-example
|
MIT License
|
compiler/backend/src/org/jetbrains/kotlin/codegen/intrinsics/ArrayConstructor.kt
|
JakeWharton
| 99,388,807
| true
| null |
/*
* Copyright 2010-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.codegen.intrinsics
import org.jetbrains.kotlin.codegen.Callable
import org.jetbrains.kotlin.codegen.CallableMethod
import org.jetbrains.kotlin.name.FqName
object ArrayConstructor : IntrinsicMethod() {
override fun toCallable(method: CallableMethod): Callable {
return object : IntrinsicCallable(method.owner, method.valueParameterTypes, null, null) {}
}
}
| 179
|
Kotlin
|
5640
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 1,005
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/net/stellarica/packserve/command/configReloadCommand.kt
|
Stellarica
| 637,239,505
| false
| null |
package net.stellarica.packserve.command
import com.mojang.brigadier.Command
import com.mojang.brigadier.builder.LiteralArgumentBuilder
import com.velocitypowered.api.command.BrigadierCommand
import com.velocitypowered.api.command.CommandSource
import net.stellarica.packserve.PackServe
fun configReloadCommand() = BrigadierCommand(
LiteralArgumentBuilder
.literal<CommandSource>("packreload")
.requires { source: CommandSource -> source.hasPermission("packserve.reload") }
.executes {
PackServe.instance.loadConfig()
PackServe.instance.createPackManager()
Command.SINGLE_SUCCESS
}
.build()
)
| 0
|
Kotlin
|
0
| 2
|
ffc67b6f8eaab6a5fe9d987f413778bd45c0af43
| 615
|
PackServe
|
MIT License
|
KotlinIntlAndroid/kotlin-intl-android/src/main/java/com/nativeframe/kotlin/intl/android/ui/CountriesSpinnerAdapter.kt
|
nativeframe
| 782,114,259
| false
|
{"Kotlin": 41539}
|
package com.nativeframe.kotlin.intl.android.ui
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.ImageView
import android.widget.SpinnerAdapter
import android.widget.TextView
import com.nativeframe.kotlin.intl.android.Country
import com.nativeframe.kotlin.intl.android.R
/**
* Adapter for the countries list spinner
*
* @author Ismail Almetwally created on 5/6/16 (java).
* @author Antonio Johnson modified 03/26/24 (kotlin).
*
* @param context Context
* @param countries Countries
*/
class CountriesSpinnerAdapter(
context: Context,
countries: Array<Country>
) : ArrayAdapter<Country>(context, R.layout.kia_view_country, R.id.name, countries),
SpinnerAdapter {
private val inflater = LayoutInflater.from(context)
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var cView = convertView
val country = getItem(position)!!
if (cView == null) {
cView = inflater.inflate(R.layout.kia_view_spinner, parent, false)
}
val imageView = cView!!.findViewById<ImageView>(R.id.flag)
imageView.setImageResource(country.drawable)
imageView.contentDescription = country.name
return cView
}
override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View {
return getCustomView(position, convertView, parent)
}
private fun getCustomView(position: Int, convertView: View?, parent: ViewGroup): View {
var cView: View? = convertView
val viewHolder: ViewHolder
if (cView == null) {
cView = inflater.inflate(R.layout.kia_view_country, parent, false)
viewHolder = ViewHolder().apply {
name = cView!!.findViewById(R.id.name)
dialCode = cView.findViewById(R.id.dial_code)
flag = cView.findViewById(R.id.flag)
cView.tag = this
}
} else {
viewHolder = cView.tag as ViewHolder
}
val country = getItem(position)!!
viewHolder.flag!!.setImageResource(country.drawable)
viewHolder.name!!.text = country.displayName
viewHolder.dialCode!!.text = country.dialCode.toString()
return cView!!
}
private class ViewHolder {
var name: TextView? = null
var dialCode: TextView? = null
var flag: ImageView? = null
}
}
| 0
|
Kotlin
|
0
| 1
|
6f2cf5cf802c1fdfff22e006feec75b25f445a86
| 2,522
|
kotlin-intl-android
|
Apache License 2.0
|
src/main/kotlin/io/codenetics/ann/graphql/dto/NeuronDto.kt
|
PaulMllr
| 153,035,869
| false
| null |
package io.codenetics.ann.graphql.dto
/**
* Created by Pavel Laktiushkin on 14.03.2019
*/
data class NeuronDto(
val id: String,
val description: String?)
| 0
|
Kotlin
|
0
| 0
|
0180f40ccdb36f1ca3be4a16324a7e8340e3054c
| 173
|
ann
|
Apache License 2.0
|
tezos-core/src/main/kotlin/it/airgap/tezos/core/converter/encoded/Ed25519Signature.kt
|
airgap-it
| 460,351,851
| false
| null |
package it.airgap.tezos.core.converter.encoded
import it.airgap.tezos.core.Tezos
import it.airgap.tezos.core.internal.annotation.InternalTezosSdkApi
import it.airgap.tezos.core.internal.context.withTezosContext
import it.airgap.tezos.core.internal.converter.Converter
import it.airgap.tezos.core.internal.coreModule
import it.airgap.tezos.core.type.encoded.Address
import it.airgap.tezos.core.type.encoded.Ed25519Signature
import it.airgap.tezos.core.type.encoded.GenericSignature
/**
* Creates [Ed25519Signature] from [genericSignature].
* Takes an optional [tezos] object to provide context. If the argument was omitted, the default [Tezos] instance will be used.
*
* See `samples/src/test/kotlin/type/Ed25519Signature/Ed25519SignatureSamples.Usage#fromGeneric` for a sample usage.
*/
public fun Ed25519Signature.Companion.fromGenericSignature(genericSignature: GenericSignature, tezos: Tezos = Tezos.Default): Ed25519Signature = withTezosContext {
Ed25519Signature.fromGenericSignature(genericSignature, tezos.coreModule.dependencyRegistry.genericSignatureToEd25519SignatureConverter)
}
@InternalTezosSdkApi
public interface Ed25519SignatureConverterContext {
public fun Ed25519Signature.Companion.fromGenericSignature(genericSignature: GenericSignature, converter: Converter<GenericSignature, Ed25519Signature>): Ed25519Signature =
converter.convert(genericSignature)
}
| 0
|
Kotlin
|
2
| 1
|
c5af5ffdd4940670bd66842580d82c2b9d682d84
| 1,397
|
tezos-kotlin-sdk
|
MIT License
|
user/src/main/kotlin/it/unibo/lss/parking_system/entity/UserInfo.kt
|
lbracchi
| 600,515,402
| false
| null |
package it.unibo.lss.parking_system.entity
import kotlinx.serialization.Serializable
@Serializable
data class UserInfo(
val email: String,
val name: String
)
| 0
|
Kotlin
|
0
| 0
|
f7aea6e6cad6475c2f7ae654671456e796865b19
| 167
|
test-parking
|
MIT License
|
frontend-example/modules/material-design/src/main/kotlin/io/github/andrewk2112/kjsbox/frontend/example/materialdesign/components/header/sections/notificationMessage.kt
|
andrew-k-21-12
| 497,585,003
| false
| null |
package io.github.andrewk2112.kjsbox.frontend.example.materialdesign.components.header.sections
import io.github.andrewk2112.kjsbox.frontend.designtokens.Context
import io.github.andrewk2112.kjsbox.frontend.designtokens.StyleValues
import io.github.andrewk2112.kjsbox.frontend.designtokens.Theme
import io.github.andrewk2112.kjsbox.frontend.extensions.invoke
import io.github.andrewk2112.kjsbox.frontend.stylesheets.DynamicCssProvider
import io.github.andrewk2112.kjsbox.frontend.stylesheets.DynamicStyleSheet
import io.github.andrewk2112.kjsbox.frontend.stylesheets.NamedRuleSet
import io.github.andrewk2112.kjsbox.frontend.example.materialdesign.styles.FontStyles
import io.github.andrewk2112.kjsbox.frontend.example.resourcewrappers.icons.materialdesign.arrowRightThinIcon
import io.github.andrewk2112.kjsbox.frontend.utility.safeBlankHref
import kotlinx.css.*
import kotlinx.css.properties.TextDecoration
import react.ChildrenBuilder
import react.dom.html.ReactHTML.a
import react.dom.html.ReactHTML.div
import react.dom.html.ReactHTML.p
// Components.
fun ChildrenBuilder.notificationMessage(
context: Context,
title: String,
description: String,
actionLabel: String,
actionDestinationEndpoint: String
) =
container(context) {
titleAndDescription(context, title, description)
actionButton(context, actionLabel, actionDestinationEndpoint)
}
private inline fun ChildrenBuilder.container(context: Context, crossinline children: ChildrenBuilder.() -> Unit) =
+div(clazz = NotificationMessageStyles.container(context).name, children)
private fun ChildrenBuilder.titleAndDescription(context: Context, title: String, description: String) =
+div(clazz = NotificationMessageStyles.titleAndDescriptionWrapper.name) {
+p(clazz = NotificationMessageStyles.title(context).name) { +title }
+p(clazz = NotificationMessageStyles.description(context).name) { +description }
}
private fun ChildrenBuilder.actionButton(context: Context, label: String, destinationEndpoint: String) =
+a(clazz = NotificationMessageStyles.actionButton(context).name) {
safeBlankHref = destinationEndpoint
+label
+arrowRightThinIcon(clazz = NotificationMessageStyles.actionButtonArrow.name)
}
// Styles.
private object NotificationMessageStyles : DynamicStyleSheet() {
val container: DynamicCssProvider<Context> by dynamicCss {
display = Display.flex
backgroundColor = Theme.palette.backSpecial1(it)
}
val titleAndDescriptionWrapper: NamedRuleSet by css { flexGrow = 1.0 }
val title: DynamicCssProvider<Context> by dynamicCss {
+FontStyles.bold.rules
padding(
top = StyleValues.spacing.absolute25,
left = StyleValues.spacing.absolute40,
right = StyleValues.spacing.absolute40,
)
fontSize = StyleValues.fontSizes.relative1p2
color = Theme.palette.onBackSpecial1(it)
}
val description: DynamicCssProvider<Context> by dynamicCss {
padding(
top = StyleValues.spacing.absolute8,
horizontal = StyleValues.spacing.absolute40,
bottom = StyleValues.spacing.absolute26,
)
fontSize = StyleValues.fontSizes.relativep85
color = Theme.palette.onBackSpecial1(it)
}
val actionButton: DynamicCssProvider<Context> by dynamicCss {
display = Display.flex
alignItems = Align.center
alignSelf = Align.center
flexShrink = 0
padding(
top = StyleValues.spacing.absolute11p5,
bottom = StyleValues.spacing.absolute11p5,
left = StyleValues.spacing.absolute15,
right = StyleValues.spacing.absolute18,
)
marginRight = StyleValues.spacing.absolute40
borderRadius = StyleValues.radii.cornerAbsolute24
fontSize = StyleValues.fontSizes.relativep9
textDecoration = TextDecoration.none
color = Theme.palette.onAction2(it)
backgroundColor = Theme.palette.action2(it)
hover {
backgroundColor = Theme.palette.actionFocused2(it)
}
}
val actionButtonArrow: NamedRuleSet by css {
marginLeft = StyleValues.spacing.absolute12
}
}
| 0
|
Kotlin
|
0
| 2
|
dc496b07d07b47ef69301d591a83619fecdcc956
| 4,299
|
kjs-box
|
MIT License
|
packages/library-base/src/commonMain/kotlin/io/realm/kotlin/internal/RealmSetInternal.kt
|
realm
| 235,075,339
| false
| null |
/*
* Copyright 2022 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.kotlin.internal
import io.realm.kotlin.UpdatePolicy
import io.realm.kotlin.internal.RealmValueArgumentConverter.convertToQueryArgs
import io.realm.kotlin.internal.interop.Callback
import io.realm.kotlin.internal.interop.ClassKey
import io.realm.kotlin.internal.interop.RealmChangesPointer
import io.realm.kotlin.internal.interop.RealmInterop
import io.realm.kotlin.internal.interop.RealmInterop.realm_set_get
import io.realm.kotlin.internal.interop.RealmNotificationTokenPointer
import io.realm.kotlin.internal.interop.RealmObjectInterop
import io.realm.kotlin.internal.interop.RealmSetPointer
import io.realm.kotlin.internal.interop.ValueType
import io.realm.kotlin.internal.interop.getterScope
import io.realm.kotlin.internal.interop.inputScope
import io.realm.kotlin.internal.query.ObjectBoundQuery
import io.realm.kotlin.internal.query.ObjectQuery
import io.realm.kotlin.notifications.SetChange
import io.realm.kotlin.notifications.internal.DeletedSetImpl
import io.realm.kotlin.notifications.internal.InitialSetImpl
import io.realm.kotlin.notifications.internal.UpdatedSetImpl
import io.realm.kotlin.query.RealmQuery
import io.realm.kotlin.types.BaseRealmObject
import io.realm.kotlin.types.RealmSet
import kotlinx.coroutines.channels.ChannelResult
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.flow.Flow
import kotlin.reflect.KClass
/**
* Implementation for unmanaged sets, backed by a [MutableSet].
*/
internal class UnmanagedRealmSet<E> : RealmSet<E>, InternalDeleteable, MutableSet<E> by mutableSetOf() {
override fun asFlow(): Flow<SetChange<E>> {
throw UnsupportedOperationException("Unmanaged sets cannot be observed.")
}
override fun delete() {
throw UnsupportedOperationException("Unmanaged sets cannot be deleted.")
}
}
/**
* Implementation for managed sets, backed by Realm.
*/
internal class ManagedRealmSet<E> constructor(
internal val parent: RealmObjectReference<*>,
internal val nativePointer: RealmSetPointer,
val operator: SetOperator<E>
) : AbstractMutableSet<E>(), RealmSet<E>, InternalDeleteable, Observable<ManagedRealmSet<E>, SetChange<E>>, Flowable<SetChange<E>> {
override val size: Int
get() {
operator.realmReference.checkClosed()
return RealmInterop.realm_set_size(nativePointer).toInt()
}
override fun add(element: E): Boolean {
operator.realmReference.checkClosed()
try {
return operator.add(element)
} catch (exception: Throwable) {
throw CoreExceptionConverter.convertToPublicException(
exception,
"Could not add element to set"
)
}
}
override fun clear() {
operator.realmReference.checkClosed()
RealmInterop.realm_set_clear(nativePointer)
}
override fun contains(element: E): Boolean {
operator.realmReference.checkClosed()
return operator.contains(element)
}
override fun iterator(): MutableIterator<E> {
operator.realmReference.checkClosed()
return object : MutableIterator<E> {
private var pos = -1
override fun hasNext(): Boolean = pos + 1 < size
override fun next(): E {
pos = pos.inc()
if (pos >= size) {
throw NoSuchElementException("Cannot access index $pos when size is $size. Remember to check hasNext() before using next().")
}
return operator.get(pos)
}
override fun remove() {
if (pos < 0) {
throw NoSuchElementException("Could not remove last element returned by the iterator: iterator never returned an element.")
}
if (isEmpty()) {
throw NoSuchElementException("Could not remove last element returned by the iterator: set is empty.")
}
val erased = getterScope {
val transport = realm_set_get(nativePointer, pos.toLong())
RealmInterop.realm_set_erase(nativePointer, transport)
}
if (!erased) {
throw NoSuchElementException("Could not remove last element returned by the iterator: was there an element to remove?")
}
}
}
}
override fun asFlow(): Flow<SetChange<E>> {
operator.realmReference.checkClosed()
return operator.realmReference.owner.registerObserver(this)
}
override fun freeze(frozenRealm: RealmReference): ManagedRealmSet<E>? {
return RealmInterop.realm_set_resolve_in(nativePointer, frozenRealm.dbPointer)?.let {
ManagedRealmSet(parent, it, operator.copy(frozenRealm, it))
}
}
override fun thaw(liveRealm: RealmReference): ManagedRealmSet<E>? {
return RealmInterop.realm_set_resolve_in(nativePointer, liveRealm.dbPointer)?.let {
ManagedRealmSet(parent, it, operator.copy(liveRealm, it))
}
}
override fun registerForNotification(
callback: Callback<RealmChangesPointer>
): RealmNotificationTokenPointer {
return RealmInterop.realm_set_add_notification_callback(nativePointer, callback)
}
override fun emitFrozenUpdate(
frozenRealm: RealmReference,
change: RealmChangesPointer,
channel: SendChannel<SetChange<E>>
): ChannelResult<Unit>? {
val frozenSet: ManagedRealmSet<E>? = freeze(frozenRealm)
return if (frozenSet != null) {
val builder = SetChangeSetBuilderImpl(change)
if (builder.isEmpty()) {
channel.trySend(InitialSetImpl(frozenSet))
} else {
channel.trySend(UpdatedSetImpl(frozenSet, builder.build()))
}
} else {
channel.trySend(DeletedSetImpl(UnmanagedRealmSet()))
.also {
channel.close()
}
}
}
override fun delete() {
RealmInterop.realm_set_remove_all(nativePointer)
}
internal fun isValid(): Boolean {
return !nativePointer.isReleased() && RealmInterop.realm_set_is_valid(nativePointer)
}
}
internal fun <E : BaseRealmObject> ManagedRealmSet<E>.query(
query: String,
args: Array<out Any?>
): RealmQuery<E> {
val operator: RealmObjectSetOperator<E> = operator as RealmObjectSetOperator<E>
return ObjectQuery.tryCatchCoreException {
val queryPointer = inputScope {
val queryArgs = convertToQueryArgs(args)
RealmInterop.realm_query_parse_for_set(
this@query.nativePointer,
query,
queryArgs
)
}
ObjectBoundQuery(
parent,
ObjectQuery(
operator.realmReference,
operator.classKey,
operator.clazz,
operator.mediator,
queryPointer,
)
)
}
}
/**
* Operator interface abstracting the connection between the API and and the interop layer.
*/
internal interface SetOperator<E> : CollectionOperator<E> {
fun add(
element: E,
updatePolicy: UpdatePolicy = UpdatePolicy.ALL,
cache: UnmanagedToManagedObjectCache = mutableMapOf()
): Boolean
fun addAll(
elements: Collection<E>,
updatePolicy: UpdatePolicy = UpdatePolicy.ALL,
cache: UnmanagedToManagedObjectCache = mutableMapOf()
): Boolean {
@Suppress("VariableNaming")
var changed = false
for (e in elements) {
val hasChanged = add(e, updatePolicy, cache)
if (hasChanged) {
changed = true
}
}
return changed
}
fun get(index: Int): E
fun contains(element: E): Boolean
fun copy(realmReference: RealmReference, nativePointer: RealmSetPointer): SetOperator<E>
}
internal class PrimitiveSetOperator<E>(
override val mediator: Mediator,
override val realmReference: RealmReference,
override val converter: RealmValueConverter<E>,
private val nativePointer: RealmSetPointer
) : SetOperator<E> {
@Suppress("UNCHECKED_CAST")
override fun get(index: Int): E {
return getterScope {
with(converter) {
val transport = realm_set_get(nativePointer, index.toLong())
with(converter) {
realmValueToPublic(transport)
}
} as E
}
}
override fun add(
element: E,
updatePolicy: UpdatePolicy,
cache: UnmanagedToManagedObjectCache
): Boolean {
return inputScope {
with(converter) {
val transport = publicToRealmValue(element)
RealmInterop.realm_set_insert(nativePointer, transport)
}
}
}
override fun contains(element: E): Boolean {
return inputScope {
with(converter) {
val transport = publicToRealmValue(element)
RealmInterop.realm_set_find(nativePointer, transport)
}
}
}
override fun copy(
realmReference: RealmReference,
nativePointer: RealmSetPointer
): SetOperator<E> =
PrimitiveSetOperator(mediator, realmReference, converter, nativePointer)
}
internal class RealmObjectSetOperator<E> constructor(
override val mediator: Mediator,
override val realmReference: RealmReference,
override val converter: RealmValueConverter<E>,
private val nativePointer: RealmSetPointer,
val clazz: KClass<E & Any>,
val classKey: ClassKey
) : SetOperator<E> {
override fun add(
element: E,
updatePolicy: UpdatePolicy,
cache: UnmanagedToManagedObjectCache
): Boolean {
return inputScope {
val objRef = realmObjectToRealmReferenceWithImport(
element as BaseRealmObject?,
mediator,
realmReference,
updatePolicy,
cache
)
val transport = realmObjectTransport(objRef as RealmObjectInterop)
RealmInterop.realm_set_insert(nativePointer, transport)
}
}
@Suppress("UNCHECKED_CAST")
override fun get(index: Int): E {
return getterScope {
with(converter) {
realm_set_get(nativePointer, index.toLong())
.let { transport ->
when (ValueType.RLM_TYPE_NULL) {
transport.getType() -> null
else -> realmValueToPublic(transport)
}
} as E
}
}
}
override fun contains(element: E): Boolean {
return inputScope {
val objRef = realmObjectToRealmReferenceWithImport(
element as BaseRealmObject?,
mediator,
realmReference,
UpdatePolicy.ALL,
mutableMapOf()
)
val transport = realmObjectTransport(objRef as RealmObjectInterop)
RealmInterop.realm_set_find(nativePointer, transport)
}
}
override fun copy(
realmReference: RealmReference,
nativePointer: RealmSetPointer
): SetOperator<E> {
val converter =
converter<E>(clazz, mediator, realmReference) as CompositeConverter<E, *>
return RealmObjectSetOperator(mediator, realmReference, converter, nativePointer, clazz, classKey)
}
}
internal fun <T> Array<out T>.asRealmSet(): RealmSet<T> =
UnmanagedRealmSet<T>().apply { addAll(this@asRealmSet) }
| 188
|
Kotlin
|
42
| 610
|
107ad3b592fd9adccb476b1835d4579f13d7e765
| 12,351
|
realm-kotlin
|
Apache License 2.0
|
common/src/test/kotlin/io/rippledown/model/TestEventTest.kt
|
TimLavers
| 513,037,911
| false
|
{"Kotlin": 1309914, "Gherkin": 117611}
|
package io.rippledown.model
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
// ORD1
internal class TestEventTest {
val tsh = Attribute(3, "TSH")
@Test
fun construction() {
val te = TestEvent(tsh, defaultDate)
assertEquals(te.attribute, tsh)
assertEquals(te.date, defaultDate)
}
@Test
fun equalityRequiresSameDate() {
val te1 = TestEvent(tsh, defaultDate)
val te2 = TestEvent(tsh, defaultDate + 1234L)
assertNotEquals(te1, te2)
}
@Test
fun jsonSerialisation() {
val te = TestEvent(tsh, defaultDate)
val sd = serializeDeserialize(te)
assertEquals(sd, te)
}
private fun serializeDeserialize(testEvent: TestEvent):TestEvent {
val serialized = Json.encodeToString(testEvent)
return Json.decodeFromString(serialized)
}
}
| 0
|
Kotlin
|
0
| 0
|
4d3a0820aa4d27b84e9e07159e877fe9ada47bdb
| 982
|
OpenRDR
|
MIT License
|
twint-action/src/test/java/com/adyen/checkout/twint/action/internal/ui/DefaultTwintActionDelegateTest.kt
|
Adyen
| 91,104,663
| false
| null |
/*
* Copyright (c) 2023 <NAME>.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by oscars on 21/11/2023.
*/
package com.adyen.checkout.twint.internal.ui
import android.app.Activity
import androidx.lifecycle.SavedStateHandle
import ch.twint.payment.sdk.TwintPayResult
import com.adyen.checkout.components.core.ActionComponentData
import com.adyen.checkout.components.core.CheckoutConfiguration
import com.adyen.checkout.components.core.action.Action
import com.adyen.checkout.components.core.action.AwaitAction
import com.adyen.checkout.components.core.action.RedirectAction
import com.adyen.checkout.components.core.action.SdkAction
import com.adyen.checkout.components.core.action.TwintSdkData
import com.adyen.checkout.components.core.action.WeChatPaySdkData
import com.adyen.checkout.components.core.internal.ActionObserverRepository
import com.adyen.checkout.components.core.internal.PaymentDataRepository
import com.adyen.checkout.components.core.internal.data.model.StatusResponse
import com.adyen.checkout.components.core.internal.test.TestStatusRepository
import com.adyen.checkout.components.core.internal.ui.model.CommonComponentParamsMapper
import com.adyen.checkout.components.core.internal.ui.model.GenericComponentParamsMapper
import com.adyen.checkout.components.core.internal.util.StatusResponseUtils
import com.adyen.checkout.core.Environment
import com.adyen.checkout.test.LoggingExtension
import com.adyen.checkout.test.extensions.test
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.json.JSONObject
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments.arguments
import org.junit.jupiter.params.provider.MethodSource
import org.mockito.junit.jupiter.MockitoExtension
import java.io.IOException
import java.util.Locale
@OptIn(ExperimentalCoroutinesApi::class)
@ExtendWith(MockitoExtension::class, LoggingExtension::class)
internal class DefaultTwintDelegateTest {
private lateinit var statusRepository: TestStatusRepository
private lateinit var delegate: DefaultTwintDelegate
@BeforeEach
fun beforeEach() {
statusRepository = TestStatusRepository()
delegate = createDelegate()
}
@Test
fun `when handling action successfully, then a pay event should be emitted`() = runTest {
val payEventFlow = delegate.payEventFlow.test(testScheduler)
val action = SdkAction(paymentData = "something", sdkData = TwintSdkData("token"))
delegate.handleAction(action, Activity())
assertEquals(action.sdkData?.token, payEventFlow.latestValue)
}
@ParameterizedTest
@MethodSource("handleActionSource")
fun `when handling action, then expect`(action: Action, expectedErrorMessage: String) = runTest {
val testFlow = delegate.exceptionFlow.test(testScheduler)
delegate.handleAction(action, Activity())
assertEquals(expectedErrorMessage, testFlow.latestValue.message)
}
@ParameterizedTest
@MethodSource("handleTwintResult")
fun `when handling twint result, then expect`(result: TwintPayResult, testResult: TwintTestResult) = runTest {
delegate.initialize(CoroutineScope(UnconfinedTestDispatcher()))
statusRepository.pollingResults = listOf(
Result.success(StatusResponse(resultCode = StatusResponseUtils.RESULT_AUTHORIZED, payload = TEST_PAYLOAD)),
)
val detailsFlow = delegate.detailsFlow.test(testScheduler)
val exceptionFlow = delegate.exceptionFlow.test(testScheduler)
delegate.handleAction(SdkAction(paymentData = "test", sdkData = TwintSdkData("token")), Activity())
delegate.handleTwintResult(result)
when (testResult) {
is TwintTestResult.Error -> {
assertEquals(testResult.expectedMessage, exceptionFlow.latestValue.message)
}
is TwintTestResult.Success -> {
with(detailsFlow.latestValue) {
assertEquals(testResult.expectedActionComponentData.paymentData, paymentData)
assertEquals(testResult.expectedActionComponentData.details.toString(), details.toString())
}
}
}
}
@Nested
@DisplayName("when polling and")
inner class PollingTest {
@Test
fun `paymentData is missing, then an error is propagated`() = runTest {
delegate.initialize(CoroutineScope(UnconfinedTestDispatcher()))
val exceptionFlow = delegate.exceptionFlow.test(testScheduler)
delegate.handleTwintResult(TwintPayResult.TW_B_SUCCESS)
val expectedErrorMessage = "PaymentData should not be null."
assertEquals(expectedErrorMessage, exceptionFlow.latestValue.message)
}
@Test
fun `polling fails, then an error is propagated`() = runTest {
statusRepository.pollingResults = listOf(Result.failure(IOException("Test")))
delegate.initialize(CoroutineScope(UnconfinedTestDispatcher()))
val exceptionFlow = delegate.exceptionFlow.test(testScheduler)
delegate.handleAction(SdkAction(paymentData = "test", sdkData = TwintSdkData("token")), Activity())
delegate.handleTwintResult(TwintPayResult.TW_B_SUCCESS)
val expectedErrorMessage = "Error while polling status."
assertEquals(expectedErrorMessage, exceptionFlow.latestValue.message)
}
@Test
fun `polling succeeds and payload is missing, then an error is propagated`() = runTest {
statusRepository.pollingResults = listOf(
Result.success(StatusResponse(resultCode = StatusResponseUtils.RESULT_AUTHORIZED, payload = null)),
)
delegate.initialize(CoroutineScope(UnconfinedTestDispatcher()))
val exceptionFlow = delegate.exceptionFlow.test(testScheduler)
delegate.handleAction(SdkAction(paymentData = "test", sdkData = TwintSdkData("token")), Activity())
delegate.handleTwintResult(TwintPayResult.TW_B_SUCCESS)
val expectedErrorMessage = "Payload is missing from StatusResponse."
assertEquals(expectedErrorMessage, exceptionFlow.latestValue.message)
}
@Test
fun `polling succeeds and payload is available, then details are emitted`() = runTest {
statusRepository.pollingResults = listOf(
Result.success(
StatusResponse(
resultCode = StatusResponseUtils.RESULT_AUTHORIZED,
payload = TEST_PAYLOAD,
),
),
)
delegate.initialize(CoroutineScope(UnconfinedTestDispatcher()))
val detailsFlow = delegate.detailsFlow.test(testScheduler)
delegate.handleAction(SdkAction(paymentData = "test", sdkData = TwintSdkData("token")), Activity())
delegate.handleTwintResult(TwintPayResult.TW_B_SUCCESS)
val expected = ActionComponentData(
paymentData = null,
details = JSONObject().put(DefaultTwintDelegate.PAYLOAD_DETAILS_KEY, TEST_PAYLOAD),
)
with(detailsFlow.latestValue) {
assertNull(paymentData)
assertEquals(expected.details.toString(), details.toString())
}
}
}
@Test
fun `when initializing and action is set, then state is restored`() = runTest {
statusRepository.pollingResults = listOf(
Result.success(StatusResponse(resultCode = "finished", payload = "testpayload")),
)
val savedStateHandle = SavedStateHandle().apply {
set(DefaultTwintDelegate.ACTION_KEY, SdkAction(paymentData = "test", sdkData = TwintSdkData("token")))
set(DefaultTwintDelegate.IS_POLLING_KEY, true)
}
delegate = createDelegate(savedStateHandle)
val detailsFlow = delegate.detailsFlow.test(testScheduler)
delegate.initialize(CoroutineScope(UnconfinedTestDispatcher()))
assertTrue(detailsFlow.values.isNotEmpty())
}
@Test
fun `when details are emitted, then state is cleared`() = runTest {
statusRepository.pollingResults = listOf(
Result.success(StatusResponse(resultCode = "finished", payload = "testpayload")),
)
val savedStateHandle = SavedStateHandle()
delegate = createDelegate(savedStateHandle)
delegate.initialize(CoroutineScope(UnconfinedTestDispatcher()))
delegate.handleTwintResult(TwintPayResult.TW_B_SUCCESS)
assertNull(savedStateHandle[DefaultTwintDelegate.ACTION_KEY])
}
@Test
fun `when an error is emitted, then state is cleared`() = runTest {
val savedStateHandle = SavedStateHandle().apply {
set(DefaultTwintDelegate.ACTION_KEY, SdkAction(paymentData = "test", sdkData = TwintSdkData("token")))
}
delegate = createDelegate(savedStateHandle)
delegate.initialize(CoroutineScope(UnconfinedTestDispatcher()))
delegate.handleAction(RedirectAction(paymentMethodType = "test", paymentData = "paymentData"), Activity())
assertNull(savedStateHandle[DefaultTwintDelegate.ACTION_KEY])
}
private fun createDelegate(
savedStateHandle: SavedStateHandle = SavedStateHandle()
): DefaultTwintDelegate {
val configuration = CheckoutConfiguration(Environment.TEST, TEST_CLIENT_KEY)
return DefaultTwintDelegate(
observerRepository = ActionObserverRepository(),
savedStateHandle = savedStateHandle,
componentParams = GenericComponentParamsMapper(CommonComponentParamsMapper())
.mapToParams(configuration, Locale.US, null, null),
paymentDataRepository = PaymentDataRepository(SavedStateHandle()),
statusRepository = statusRepository,
)
}
companion object {
private const val TEST_CLIENT_KEY = "<KEY>"
private const val TEST_PAYLOAD = "TEST_PAYLOAD"
@JvmStatic
fun handleActionSource() = listOf(
arguments(AwaitAction(), "Unsupported action"),
arguments(
SdkAction(paymentData = "something", sdkData = WeChatPaySdkData()),
"SDK Data is null or of wrong type",
),
arguments(SdkAction<WeChatPaySdkData>(paymentData = "something"), "SDK Data is null or of wrong type"),
arguments(SdkAction(paymentData = null, sdkData = TwintSdkData("")), "Payment data is null"),
arguments(
SdkAction<TwintSdkData>(paymentData = "something", sdkData = null),
"SDK Data is null or of wrong type",
),
)
@JvmStatic
fun handleTwintResult() = listOf(
arguments(
TwintPayResult.TW_B_SUCCESS,
TwintTestResult.Success(
ActionComponentData(null, JSONObject().put(DefaultTwintDelegate.PAYLOAD_DETAILS_KEY, TEST_PAYLOAD)),
),
),
arguments(
TwintPayResult.TW_B_ERROR,
TwintTestResult.Error("Twint encountered an error."),
),
arguments(
TwintPayResult.TW_B_APP_NOT_INSTALLED,
TwintTestResult.Error("Twint app not installed."),
),
)
}
sealed class TwintTestResult {
data class Success(val expectedActionComponentData: ActionComponentData) : TwintTestResult()
data class Error(val expectedMessage: String) : TwintTestResult()
}
}
| 27
| null |
66
| 126
|
c45a6ee4d2039163ae075436a9d1231ffcb16f5c
| 12,184
|
adyen-android
|
MIT License
|
core/app_ui_compose/src/main/java/tw/com/deathhit/core/app_ui_compose/Color.kt
|
Deathhit
| 718,070,517
| false
|
{"Kotlin": 159032}
|
package tw.com.deathhit.core.app_ui_compose
import androidx.compose.ui.graphics.Color
val md_theme_light_primary = Color(0xFF246D00)
val md_theme_light_onPrimary = Color(0xFFFFFFFF)
val md_theme_light_primaryContainer = Color(0xFFA6F780)
val md_theme_light_onPrimaryContainer = Color(0xFF062100)
val md_theme_light_secondary = Color(0xFF55624C)
val md_theme_light_onSecondary = Color(0xFFFFFFFF)
val md_theme_light_secondaryContainer = Color(0xFFD8E7CB)
val md_theme_light_onSecondaryContainer = Color(0xFF131F0D)
val md_theme_light_tertiary = Color(0xFF386667)
val md_theme_light_onTertiary = Color(0xFFFFFFFF)
val md_theme_light_tertiaryContainer = Color(0xFFBBEBEC)
val md_theme_light_onTertiaryContainer = Color(0xFF002021)
val md_theme_light_error = Color(0xFFBA1A1A)
val md_theme_light_errorContainer = Color(0xFFFFDAD6)
val md_theme_light_onError = Color(0xFFFFFFFF)
val md_theme_light_onErrorContainer = Color(0xFF410002)
val md_theme_light_background = Color(0xFFFDFDF6)
val md_theme_light_onBackground = Color(0xFF1A1C18)
val md_theme_light_surface = Color(0xFFFDFDF6)
val md_theme_light_onSurface = Color(0xFF1A1C18)
val md_theme_light_surfaceVariant = Color(0xFFDFE4D7)
val md_theme_light_onSurfaceVariant = Color(0xFF43483E)
val md_theme_light_outline = Color(0xFF73796D)
val md_theme_light_inverseOnSurface = Color(0xFFF1F1EA)
val md_theme_light_inverseSurface = Color(0xFF2F312D)
val md_theme_light_inversePrimary = Color(0xFF8BDA67)
val md_theme_light_shadow = Color(0xFF000000)
val md_theme_light_surfaceTint = Color(0xFF246D00)
val md_theme_light_outlineVariant = Color(0xFFC3C8BB)
val md_theme_light_scrim = Color(0xFF000000)
val md_theme_dark_primary = Color(0xFF8BDA67)
val md_theme_dark_onPrimary = Color(0xFF0F3900)
val md_theme_dark_primaryContainer = Color(0xFF195200)
val md_theme_dark_onPrimaryContainer = Color(0xFFA6F780)
val md_theme_dark_secondary = Color(0xFFBCCBB0)
val md_theme_dark_onSecondary = Color(0xFF273421)
val md_theme_dark_secondaryContainer = Color(0xFF3E4A36)
val md_theme_dark_onSecondaryContainer = Color(0xFFD8E7CB)
val md_theme_dark_tertiary = Color(0xFFA0CFD0)
val md_theme_dark_onTertiary = Color(0xFF003738)
val md_theme_dark_tertiaryContainer = Color(0xFF1E4E4F)
val md_theme_dark_onTertiaryContainer = Color(0xFFBBEBEC)
val md_theme_dark_error = Color(0xFFFFB4AB)
val md_theme_dark_errorContainer = Color(0xFF93000A)
val md_theme_dark_onError = Color(0xFF690005)
val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6)
val md_theme_dark_background = Color(0xFF1A1C18)
val md_theme_dark_onBackground = Color(0xFFE3E3DC)
val md_theme_dark_surface = Color(0xFF1A1C18)
val md_theme_dark_onSurface = Color(0xFFE3E3DC)
val md_theme_dark_surfaceVariant = Color(0xFF43483E)
val md_theme_dark_onSurfaceVariant = Color(0xFFC3C8BB)
val md_theme_dark_outline = Color(0xFF8D9287)
val md_theme_dark_inverseOnSurface = Color(0xFF1A1C18)
val md_theme_dark_inverseSurface = Color(0xFFE3E3DC)
val md_theme_dark_inversePrimary = Color(0xFF246D00)
val md_theme_dark_shadow = Color(0xFF000000)
val md_theme_dark_surfaceTint = Color(0xFF8BDA67)
val md_theme_dark_outlineVariant = Color(0xFF43483E)
val md_theme_dark_scrim = Color(0xFF000000)
val seed = Color(0xFF256F00)
| 0
|
Kotlin
|
0
| 1
|
8ec8cc77acac5e29a67e3194cff5769202f51687
| 3,207
|
SunflowerClone
|
Apache License 2.0
|
sample/src/main/java/com/facebook/samples/litho/kotlin/collection/TabsCollectionKComponent.kt
|
facebook
| 80,179,724
| false
| null |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.samples.litho.kotlin.collection
import android.graphics.Color
import android.graphics.Typeface
import com.facebook.litho.Component
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.ResourcesScope
import com.facebook.litho.Row
import com.facebook.litho.State
import com.facebook.litho.Style
import com.facebook.litho.core.padding
import com.facebook.litho.flexbox.flex
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.useState
import com.facebook.litho.view.backgroundColor
import com.facebook.litho.view.onClick
import com.facebook.litho.widget.TextAlignment
import com.facebook.litho.widget.collection.LazyList
import com.facebook.rendercore.colorRes
import com.facebook.rendercore.dp
import com.facebook.rendercore.sp
import com.facebook.samples.litho.R
class TabsCollectionKComponent : KComponent() {
enum class Tab(val title: String) {
Tab1("Tab1"),
Tab2("Tab2"),
Tab3("Tab3"),
}
override fun ComponentScope.render(): Component {
val selectedTab = useState { Tab.Tab1 }
return LazyList {
child(tabBar(selectedTab))
when (selectedTab.value) {
Tab.Tab1 -> {
child(id = "tab1_tile", component = Text("Tab1 Title"))
child(id = "tab1_subtitle", component = Text("Tab1 Subtitle"))
}
Tab.Tab2 -> {
child(id = "tab2_tile", component = Text("Tab2 Title"))
child(id = "tab2_subtitle", component = Text("Tab2 Subtitle"))
}
Tab.Tab3 -> {
child(id = "tab3_tile", component = Text("Tab3 Title"))
child(id = "tab3_subtitle", component = Text("Tab3 Subtitle"))
}
}
}
}
private fun ResourcesScope.tabBar(selectedTab: State<Tab>): Component = Row {
Tab.values().forEach { tab ->
val isSelected = tab == selectedTab.value
child(
Text(
tab.title.uppercase(),
textSize = 16.sp,
alignment = TextAlignment.CENTER,
textColor = if (isSelected) colorRes(R.color.primaryColor) else Color.DKGRAY,
textStyle = if (isSelected) Typeface.BOLD else Typeface.NORMAL,
style =
Style.padding(all = 16.dp)
.flex(grow = 1f)
.backgroundColor(
if (isSelected) colorRes(R.color.colorPrimaryLightBg) else Color.WHITE)
.onClick { selectedTab.update { tab } }))
}
}
}
| 88
| null |
765
| 7,703
|
8bde23649ae0b1c594b9bdfcb4668feb7d8a80c0
| 3,137
|
litho
|
Apache License 2.0
|
mobile/core/data/dao/src/main/java/co/kr/parkjonghun/whatishedoingwithandroid/outside/dao/datastore/UserDataStoreDao.kt
|
ParkJong-Hun
| 695,838,859
| false
|
{"Kotlin": 173854}
|
package co.kr.parkjonghun.whatishedoingwithandroid.outside.dao.datastore
import android.content.Context
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import co.kr.parkjonghun.whatishedoingwithandroid.outside.datastore.userDataStore
import co.kr.parkjonghun.whatishedoingwithandroid.outside.extension.decryptAnyAsJson
import co.kr.parkjonghun.whatishedoingwithandroid.outside.extension.encryptAnyAsJson
import co.kr.parkjonghun.whatishedoingwithandroid.outside.model.AuthCodeInfo
import co.kr.parkjonghun.whatishedoingwithandroid.outside.model.TokenInfo
import co.kr.parkjonghun.whatishedoingwithandroid.outside.utility.key.SecurityUtil
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import timber.log.Timber
interface UserDataStoreDao {
val tokenInfo: Flow<TokenInfo?>
val authCodeInfo: Flow<AuthCodeInfo?>
suspend fun saveTokenInfo(tokenInfo: TokenInfo)
suspend fun resetTokenInfo()
suspend fun saveAuthCodeInfo(authCodeInfo: AuthCodeInfo)
suspend fun resetAuthCodeInfo()
}
internal class UserDataStoreDaoImpl(
private val context: Context,
private val securityUtil: SecurityUtil,
) : UserDataStoreDao {
private val userDataStore get() = context.userDataStore
override val tokenInfo: Flow<TokenInfo?> = userDataStore.data.map {
it[KEY_TOKEN_INFO]?.let { encryptedString ->
securityUtil.decryptAnyAsJson(encryptedString)
}
}
override val authCodeInfo: Flow<AuthCodeInfo?> = userDataStore.data.map {
it[KEY_AUTH_CODE_INFO]?.let { encryptedString ->
securityUtil.decryptAnyAsJson(encryptedString)
}
}
override suspend fun saveTokenInfo(tokenInfo: TokenInfo) {
userDataStore.edit {
it[KEY_TOKEN_INFO] = securityUtil.encryptAnyAsJson(tokenInfo)
}
}
override suspend fun resetTokenInfo() {
Timber.w("your token is invalid. So, will reset the token stored in the device.")
userDataStore.edit {
it.remove(KEY_TOKEN_INFO)
}
}
override suspend fun saveAuthCodeInfo(authCodeInfo: AuthCodeInfo) {
userDataStore.edit {
it[KEY_AUTH_CODE_INFO] = securityUtil.encryptAnyAsJson(tokenInfo)
}
}
override suspend fun resetAuthCodeInfo() {
Timber.w("your token is invalid. So, will reset the token stored in the device.")
userDataStore.edit {
it.remove(KEY_AUTH_CODE_INFO)
}
}
companion object {
private val KEY_TOKEN_INFO = stringPreferencesKey("token_info")
private val KEY_AUTH_CODE_INFO = stringPreferencesKey("auth_code_info")
}
}
| 19
|
Kotlin
|
1
| 2
|
c7cca67357dac308a2fb4644e31058ae8dc0d9f7
| 2,710
|
wihd
|
Apache License 2.0
|
data/slack-jackson-dto/src/main/kotlin/io/hndrs/slack/api/contract/jackson/group/conversations/Create.kt
|
hndrs
| 168,710,332
| false
| null |
package com.kreait.slack.api.contract.jackson.group.conversations
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonSubTypes
import com.fasterxml.jackson.annotation.JsonTypeInfo
import com.kreait.slack.api.contract.jackson.common.types.Channel
import com.kreait.slack.api.contract.jackson.util.JacksonDataClass
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "ok",
visible = true)
@JsonSubTypes(
JsonSubTypes.Type(value = SuccessfulConversationCreateResponse::class, name = "true"),
JsonSubTypes.Type(value = ErrorConversationCreateResponse::class, name = "false")
)
@JacksonDataClass
sealed class ConversationCreateResponse constructor(@JsonProperty("ok") open val ok: Boolean)
/**
* Success-response of this request.
*
* @property ok will be true
* @property channel the new channel object you created
*/
data class SuccessfulConversationCreateResponse(
override val ok: Boolean,
@JsonProperty("channel") val channel: Channel
) : ConversationCreateResponse(ok) {
companion object
}
/**
* Failure-response of this request
*
* @property ok will be false
* @property error contains the error description
*/
@JacksonDataClass
data class ErrorConversationCreateResponse constructor(override val ok: Boolean,
@JsonProperty("error") val error: String)
: ConversationCreateResponse(ok) {
companion object
}
/**
* Initiates a public or private channel-based conversation
*
* @property name the channel name for the channel you want to create
* @property isPrivate true if you want to create a private channel
*/
data class ConversationCreateRequest(@JsonProperty("name") val name: String,
@JsonProperty("is_private") val isPrivate: Boolean? = null) {
companion object
}
| 57
| null |
13
| 16
|
89c5a6ddd0cbac522dd9cd4324901bf2907369a8
| 1,935
|
slack-spring-boot-starter
|
MIT License
|
kotpass/src/test/kotlin/app/keemobile/kotpass/resources/ChaChaRes.kt
|
keemobile
| 384,214,968
| false
| null |
package app.keemobile.kotpass.resources
internal object ChaChaRes {
val ChaChaTestCases = listOf(
StreamCipherTestCase(
rounds = 8,
key = "00000000000000000000000000000000" +
"00000000000000000000000000000000",
iv = "0000000000000000",
output = "3E00EF2F895F40D67F5BB8E81F09A5A1" +
"2C840EC3CE9A7F3B181BE188EF711A1E" +
"984CE172B9216F419F445367456D5619" +
"314A42A3DA86B001387BFDB80E0CFE42"
),
StreamCipherTestCase(
rounds = 12,
key = "00000000000000000000000000000000" +
"00000000000000000000000000000000",
iv = "0000000000000000",
output = "9BF49A6A0755F953811FCE125F2683D5" +
"0429C3BB49E074147E0089A52EAE155F" +
"0564F879D27AE3C02CE82834ACFA8C79" +
"3A629F2CA0DE6919610BE82F411326BE"
),
StreamCipherTestCase(
rounds = 8,
key = "01000000000000000000000000000000" +
"00000000000000000000000000000000",
iv = "0000000000000000",
output = "CF5EE9A0494AA9613E05D5ED725B804B" +
"12F4A465EE635ACC3A311DE8740489EA" +
"289D04F43C7518DB56EB4433E498A123" +
"<KEY>"
),
StreamCipherTestCase(
rounds = 12,
key = "01000000000000000000000000000000" +
"00000000000000000000000000000000",
iv = "0000000000000000",
output = "12056E595D56B0F6EEF090F0CD25A209" +
"49248C2790525D0F930218FF0B4DDD10" +
"A6002239D9A454E29E107A7D06FEFDFE" +
"F0210FEBA044F9F29B1772C960DC29C0"
),
StreamCipherTestCase(
rounds = 8,
key = "00000000000000000000000000000000" +
"00000000000000000000000000000000",
iv = "0100000000000000",
output = "2B8F4BB3798306CA5130D47C4F8D4ED1" +
"3AA0EDCCC1BE6942090FAEECA0D7599B" +
"7FF0FE616BB25AA0153AD6FDC88B9549" +
"<KEY>"
),
StreamCipherTestCase(
rounds = 12,
key = "00000000000000000000000000000000" +
"00000000000000000000000000000000",
iv = "0100000000000000",
output = "64B8BDF87B828C4B6DBAF7EF698DE03D" +
"F8B33F635714418F9836ADE59BE12969" +
"46C953A0F38ECFFC9ECB98E81D5D99A5" +
"EDFC8F9A0A45B9E41EF3B31F028F1D0F"
),
StreamCipherTestCase(
rounds = 8,
key = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
iv = "FFFFFFFFFFFFFFFF",
output = "E163BBF8C9A739D18925EE8362DAD2CD" +
"C973DF05225AFB2AA26396F2A9849A4A" +
"445E0547D31C1623C537DF4BA85C70A9" +
"884A35BCBF3DFAB077E98B0F68135F54"
),
StreamCipherTestCase(
rounds = 12,
key = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF" +
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
iv = "FFFFFFFFFFFFFFFF",
output = "04BF88DAE8E47A228FA47B7E6379434B" +
"A664A7D28F4DAB84E5F8B464ADD20C3A" +
"CAA69C5AB221A23A57EB5F345C96F4D1" +
"322D0A2FF7A9CD43401CD536639A615A"
),
StreamCipherTestCase(
rounds = 8,
key = "55555555555555555555555555555555" +
"55555555555555555555555555555555",
iv = "5555555555555555",
output = "7CB78214E4D3465B6DC62CF7A1538C88" +
"996952B4FB72CB6105F1243CE3442E29" +
"75A59EBCD2B2A598290D7538491FE65B" +
"DBFEFD060D88798120A70D049DC2677D"
),
StreamCipherTestCase(
rounds = 12,
key = "55555555555555555555555555555555" +
"55555555555555555555555555555555",
iv = "5555555555555555",
output = "A600F07727FF93F3DA00DD74CC3E8BFB" +
"5CA7302F6A0A2944953DE00450EECD40" +
"B860F66049F2EAED63B2EF39CC310D2C" +
"<KEY>"
),
StreamCipherTestCase(
rounds = 8,
key = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
iv = "AAAAAAAAAAAAAAAA",
output = "40F9AB86C8F9A1A0CDC05A75E5531B61" +
"2D71EF7F0CF9E387DF6ED6972F0AAE21" +
"311AA581F816C90E8A99DE990B6B95AA" +
"C92450F4E112712667B804C99E9C6EDA"
),
StreamCipherTestCase(
rounds = 12,
key = "<KEY>" +
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA",
iv = "AAAAAAAAAAAAAAAA",
output = "856505B01D3B47AAE03D6A97AA0F033A" +
"9ADCC94377BABD8608864FB3F625B6E3" +
"14F086158F9F725D811EEB953B7F7470" +
"76E4C3F639FA841FAD6C9A709E621397"
),
StreamCipherTestCase(
rounds = 8,
key = "<KEY> +
"FFEEDDCCBBAA99887766554433221100",
iv = "0F1E2D3C4B5A6978",
output = "DB43AD9D1E842D1272E4530E276B3F56" +
"8F8859B3F7CF6D9D2C74FA53808CB515" +
"7A8EBF46AD3DCC4B6C7DADDE131784B0" +
"120E0E22F6D5F9FFA7407D4A21B695D9"
),
StreamCipherTestCase(
rounds = 12,
key = "<KEY>" +
"FFEEDDCCBBAA99887766554433221100",
iv = "0F1E2D3C4B5A6978",
output = "7ED12A3A63912AE941BA6D4C0D5E862E" +
"568B0E5589346935505F064B8C2698DB" +
"F7D850667D8E67BE639F3B4F6A16F92E" +
"65EA80F6C7429445DA1FC2C1B9365040"
),
StreamCipherTestCase(
rounds = 8,
key = "<KEY>" +
"1F68ED2E194C79FBC6AEBEE1A667975D",
iv = "1ADA31D5CF688221",
output = "838751B42D8DDD8A3D77F48825A2BA75" +
"2CF4047CB308A5978EF274973BE374C9" +
"6AD848065871417B08F034E681FE46A9" +
"3F7D5C61D1306614D4AAF257A7CFF08B"
),
StreamCipherTestCase(
rounds = 12,
key = "<KEY>" +
"1F68ED2E194C79FBC6AEBEE1A667975D",
iv = "1ADA31D5CF688221",
output = "1482072784BC6D06B4E73BDC118BC010" +
"3C7976786CA918E06986AA251F7E9CC1" +
"B2749A0A16EE83B4242D2E99B08D7C20" +
"092B80BC466C87283B61B1B39D0FFBAB"
)
)
}
| 4
|
Kotlin
|
1
| 9
|
0e123c087c6ec516492f33c0140497debfb3ba15
| 6,686
|
kotpass
|
MIT License
|
src/main/kotlin/org/wfanet/measurement/measurementconsumer/stats/MetricStatistics.kt
|
world-federation-of-advertisers
| 349,561,061
| false
| null |
/*
* Copyright 2023 The Cross-Media Measurement 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wfanet.measurement.measurementconsumer.stats
sealed interface Methodology
data class CustomDirectScalarMethodology(val variance: Double) : Methodology
data class CustomDirectFrequencyMethodology(
val relativeVariances: FrequencyVariance,
val kPlusRelativeVariances: FrequencyVariance
) : Methodology
object DeterministicMethodology : Methodology
data class LiquidLegionsSketchMethodology(val decayRate: Double, val sketchSize: Long) :
Methodology
data class LiquidLegionsV2Methodology(
val decayRate: Double,
val sketchSize: Long,
val samplingIndicatorSize: Long
) : Methodology
data class WeightedReachMeasurementVarianceParams(
val binaryRepresentation: Int,
val weight: Int,
val measurementVarianceParams: ReachMeasurementVarianceParams,
val methodology: Methodology
)
data class WeightedFrequencyMeasurementVarianceParams(
val binaryRepresentation: Int,
val weight: Int,
val measurementVarianceParams: FrequencyMeasurementVarianceParams,
val methodology: Methodology
)
data class WeightedImpressionMeasurementVarianceParams(
val binaryRepresentation: Int,
val weight: Int,
val measurementVarianceParams: ImpressionMeasurementVarianceParams,
val methodology: Methodology
)
data class WeightedWatchDurationMeasurementVarianceParams(
val binaryRepresentation: Int,
val weight: Int,
val measurementVarianceParams: WatchDurationMeasurementVarianceParams,
val methodology: Methodology
)
/** The parameters used to compute the variance of a reach metric. */
data class ReachMetricVarianceParams(
val weightedMeasurementVarianceParamsList: List<WeightedReachMeasurementVarianceParams>
)
/** The parameters used to compute the variance of a reach-and-frequency metric. */
data class FrequencyMetricVarianceParams(
val weightedMeasurementVarianceParamsList: List<WeightedFrequencyMeasurementVarianceParams>
)
/** The parameters used to compute the variance of an impression metric. */
data class ImpressionMetricVarianceParams(
val weightedMeasurementVarianceParamsList: List<WeightedImpressionMeasurementVarianceParams>
)
/** The parameters used to compute the variance of a watch duration metric. */
data class WatchDurationMetricVarianceParams(
val weightedMeasurementVarianceParamsList: List<WeightedWatchDurationMeasurementVarianceParams>
)
| 88
| null |
11
| 36
|
ba2d2d8d3d4527d844e6d168273b1c2fabfd5d4e
| 2,938
|
cross-media-measurement
|
Apache License 2.0
|
src/main/kotlin/org/wfanet/measurement/measurementconsumer/stats/MetricStatistics.kt
|
world-federation-of-advertisers
| 349,561,061
| false
| null |
/*
* Copyright 2023 The Cross-Media Measurement 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wfanet.measurement.measurementconsumer.stats
sealed interface Methodology
data class CustomDirectScalarMethodology(val variance: Double) : Methodology
data class CustomDirectFrequencyMethodology(
val relativeVariances: FrequencyVariance,
val kPlusRelativeVariances: FrequencyVariance
) : Methodology
object DeterministicMethodology : Methodology
data class LiquidLegionsSketchMethodology(val decayRate: Double, val sketchSize: Long) :
Methodology
data class LiquidLegionsV2Methodology(
val decayRate: Double,
val sketchSize: Long,
val samplingIndicatorSize: Long
) : Methodology
data class WeightedReachMeasurementVarianceParams(
val binaryRepresentation: Int,
val weight: Int,
val measurementVarianceParams: ReachMeasurementVarianceParams,
val methodology: Methodology
)
data class WeightedFrequencyMeasurementVarianceParams(
val binaryRepresentation: Int,
val weight: Int,
val measurementVarianceParams: FrequencyMeasurementVarianceParams,
val methodology: Methodology
)
data class WeightedImpressionMeasurementVarianceParams(
val binaryRepresentation: Int,
val weight: Int,
val measurementVarianceParams: ImpressionMeasurementVarianceParams,
val methodology: Methodology
)
data class WeightedWatchDurationMeasurementVarianceParams(
val binaryRepresentation: Int,
val weight: Int,
val measurementVarianceParams: WatchDurationMeasurementVarianceParams,
val methodology: Methodology
)
/** The parameters used to compute the variance of a reach metric. */
data class ReachMetricVarianceParams(
val weightedMeasurementVarianceParamsList: List<WeightedReachMeasurementVarianceParams>
)
/** The parameters used to compute the variance of a reach-and-frequency metric. */
data class FrequencyMetricVarianceParams(
val weightedMeasurementVarianceParamsList: List<WeightedFrequencyMeasurementVarianceParams>
)
/** The parameters used to compute the variance of an impression metric. */
data class ImpressionMetricVarianceParams(
val weightedMeasurementVarianceParamsList: List<WeightedImpressionMeasurementVarianceParams>
)
/** The parameters used to compute the variance of a watch duration metric. */
data class WatchDurationMetricVarianceParams(
val weightedMeasurementVarianceParamsList: List<WeightedWatchDurationMeasurementVarianceParams>
)
| 88
| null |
11
| 36
|
ba2d2d8d3d4527d844e6d168273b1c2fabfd5d4e
| 2,938
|
cross-media-measurement
|
Apache License 2.0
|
app/src/main/java/com/sample/samples/screens/AudioTrack.kt
|
Ethan1983
| 861,518,075
| false
|
{"Kotlin": 28194}
|
package com.sample.samples.screens
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
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.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.arthenica.mobileffmpeg.FFprobe
import java.io.File
val File.isFlacFile: Boolean get() = isFlacFile(path)
private fun isFlacFile(filePath: String): Boolean {
val mediaInformation = FFprobe.getMediaInformation(filePath) ?: return false
val streams = mediaInformation.streams ?: return false
return streams
.filter { stream -> stream.type == "audio" }
.mapNotNull { stream -> stream.codec }
.any { codec -> codec.contains("flac") }
}
@Composable
fun AudioInfo(modifier: Modifier = Modifier) {
Column(
modifier.fillMaxSize(),
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
val context = LocalContext.current
var path by remember { mutableStateOf("${context.getExternalFilesDir(null)}") }
val onClickHandler = {
val file = File(path)
val validFile = file.isFile
val isFlacFile = validFile && file.isFlacFile
Toast.makeText(context, "Valid [$validFile] isFlac [$isFlacFile] Size [${file.length()}]", Toast.LENGTH_SHORT).show()
}
TextField(value = path, onValueChange = { newPath -> path = newPath })
Spacer(modifier = Modifier.height(16.dp))
Button(onClick = onClickHandler) {
Text("Check")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
dcfeb1395d8930b364f06c9675c395e9a64471ec
| 2,170
|
Sample
|
Apache License 2.0
|
intellij-idea/src/test/kotlin/com/itangcent/intellij/config/ConfigReaderDevEnvSupporterTest.kt
|
Earth-1610
| 178,314,657
| false
|
{"Kotlin": 1216447, "Java": 35079, "Shell": 3153}
|
package com.itangcent.intellij.config
import com.google.inject.Inject
import com.itangcent.intellij.context.ActionContext
import com.itangcent.intellij.extend.guice.with
import com.itangcent.intellij.jvm.dev.DevEnv
import com.itangcent.mock.AdvancedContextTest
import org.junit.jupiter.api.Test
import kotlin.test.assertTrue
/**
* Test case of [ConfigReaderDevEnvSupporter]
*/
internal class ConfigReaderDevEnvSupporterTest : AdvancedContextTest() {
@Inject
private lateinit var devEnv: DevEnv
override fun customConfig(): String {
return "dev=true"
}
override fun bind(builder: ActionContext.ActionContextBuilder) {
super.bind(builder)
builder.bind(DevEnv::class) { it.with(ConfigReaderDevEnvSupporter::class) }
}
@Test
fun testIsDev() {
assertTrue(devEnv.isDev())
}
@Test
fun testDev() {
var flag = false
devEnv.dev {
flag = true
}
assertTrue(flag)
}
}
| 0
|
Kotlin
|
5
| 8
|
af802e7ea26b233610c9d35af89365c93f48158b
| 987
|
intellij-kotlin
|
Apache License 2.0
|
src/controllers/UsersController.kt
|
Penguin-Dream-Team
| 312,890,302
| false
|
{"Kotlin": 68374, "Dockerfile": 1208}
|
package controllers
import application.UserList
import application.user
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.locations.*
import io.ktor.response.*
import io.ktor.routing.*
import models.User
import org.kodein.di.instance
import org.kodein.di.ktor.di
import responses.SuccessResponse
import services.UserService
@KtorExperimentalLocationsAPI
fun Route.users() {
val userService by di().instance<UserService>()
authenticate("password-2fauth", optional = true) {
get<UserList> {
val allUsers = userService.getAllUsers().map(User::toSimpleUserResponse)
println(call.user?.token)
println(call.user == null)
call.respond(SuccessResponse(data = allUsers, token = call.user?.token))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e6303704451ed5467dfa5c71ad95bc412ff2d00f
| 789
|
PenguBank-Server
|
MIT License
|
app/src/main/java/io/github/zwieback/familyfinance/business/preference/custom/filter/IncludeLastDaysOfPreviousMonthOnStartDatePreference.kt
|
zwieback
| 111,666,879
| false
| null |
package io.github.zwieback.familyfinance.business.preference.custom.filter
import android.content.Context
import android.util.AttributeSet
import androidx.core.content.res.TypedArrayUtils
import androidx.preference.Preference
import io.github.zwieback.familyfinance.R
import io.github.zwieback.familyfinance.core.preference.config.FilterPrefs
import io.github.zwieback.familyfinance.core.preference.custom.BooleanPreference
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
class IncludeLastDaysOfPreviousMonthOnStartDatePreference @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = TypedArrayUtils.getAttr(
context,
R.attr.checkBoxPreferenceStyle,
android.R.attr.checkBoxPreferenceStyle
),
defStyleRes: Int = 0
) : BooleanPreference(context, attrs, defStyleAttr, defStyleRes) {
private lateinit var filterPrefs: FilterPrefs
override fun onAttached() {
super.onAttached()
runBlocking(Dispatchers.IO) {
filterPrefs = FilterPrefs.with(context)
}
launch {
val includeLastDays = withContext(Dispatchers.IO) {
filterPrefs.includeLastDaysOfPreviousMonthOnStartDate
}
callChangeListener(includeLastDays)
}
}
override fun onPreferenceChange(preference: Preference, newValue: Any): Boolean {
if (newValue is Boolean) {
runBlocking(Dispatchers.IO) {
filterPrefs.includeLastDaysOfPreviousMonthOnStartDate = newValue
}
return true
}
return false
}
}
| 0
|
Kotlin
|
0
| 0
|
a640c6ce73ca195f2ee5e41ed71fbf6169d9bb3e
| 1,727
|
FamilyFinance
|
Apache License 2.0
|
src/main/kotlin/me/syari/ss/core/time/ScheduleTimeEveryWeek.kt
|
SecondStoryServer
| 247,193,075
| false
| null |
package me.syari.ss.core.time
import java.time.DayOfWeek
data class ScheduleTimeEveryWeek(
val dayOfWeek: DayOfWeek,
val hour: Int,
val minute: Int
) {
fun getNextMinute(): ScheduleTimeEveryWeek {
return create(dayOfWeek, hour, minute + 1)
}
val everyDay by lazy { ScheduleTimeEveryDay(hour, minute) }
companion object {
fun create(dayOfWeek: DayOfWeek, hour: Int, minute: Int): ScheduleTimeEveryWeek {
var nextHour = hour
val nextMinute = if (60 <= minute) {
nextHour += (minute / 60)
minute % 60
} else {
minute
}
val nextWeek = if (24 <= nextHour) {
nextHour %= 24
dayOfWeek.plus(nextHour / 24L)
} else {
dayOfWeek
}
return ScheduleTimeEveryWeek(nextWeek, nextHour, nextMinute)
}
}
}
| 0
| null |
1
| 1
|
ec274625b2287b23ae416b8d8aa35212e2fd2b71
| 938
|
SS-Core
|
Apache License 2.0
|
notifikasjon/src/test/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/notifikasjon/OpprettOppgaveServiceTest.kt
|
navikt
| 495,713,363
| false
|
{"Kotlin": 771119, "Dockerfile": 68}
|
package no.nav.helsearbeidsgiver.inntektsmelding.notifikasjon
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import no.nav.helsearbeidsgiver.felles.BehovType
import no.nav.helsearbeidsgiver.felles.DataFelt
import no.nav.helsearbeidsgiver.felles.EventName
import no.nav.helsearbeidsgiver.felles.Fail
import no.nav.helsearbeidsgiver.felles.Key
import no.nav.helsearbeidsgiver.felles.rapidsrivers.composite.Transaction
import no.nav.helsearbeidsgiver.felles.rapidsrivers.model.Behov
import no.nav.helsearbeidsgiver.felles.test.mock.MockRedisStore
import no.nav.helsearbeidsgiver.utils.json.toJson
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import java.util.UUID
class OpprettOppgaveServiceTest {
private val rapid = TestRapid()
private val redisStore = MockRedisStore()
private val service = OpprettOppgaveService(rapid, redisStore)
@BeforeEach
fun resetRapid() {
rapid.reset()
}
@Test
fun `erFeilMelding`() {
val fellesDeprecatedFail = Fail(
eventName = EventName.OPPGAVE_OPPRETT_REQUESTED,
behov = BehovType.OPPRETT_OPPGAVE,
feilmelding = "FEIL",
data = null,
uuid = UUID.randomUUID().toString(),
forespørselId = UUID.randomUUID().toString()
).toJsonMessage()
assertEquals(Transaction.TERMINATE, service.determineTransactionState(fellesDeprecatedFail))
assertTrue(service.isFailMelding(fellesDeprecatedFail))
}
@Disabled("Enable om vi begynner å bruke ny Fail-objekt sammen med CompositeEventListener")
@Test
fun `feil fra behov tolkes som feil av service`() {
val failFraBehov = Behov.create(
event = EventName.OPPGAVE_OPPRETT_REQUESTED,
behov = BehovType.OPPRETT_OPPGAVE,
forespoerselId = "987654321"
).createFail("Uff")
assertTrue(service.isFailMelding(failFraBehov.toJsonMessage()))
}
@Disabled("Enable om vi begynner å bruke ny Fail-objekt sammen med CompositeEventListener")
@Test
fun `feil fra rapid and rivers-model tolkes som feil av service`() {
val rapidAndRiverFail = no.nav.helsearbeidsgiver.felles.rapidsrivers.model.Fail.create(
behov = BehovType.OPPRETT_OPPGAVE,
event = EventName.OPPGAVE_OPPRETT_REQUESTED,
feilmelding = "OpprettOppgave feilet",
uuid = UUID.randomUUID().toString()
)
assertEquals(Transaction.TERMINATE, service.determineTransactionState(rapidAndRiverFail.toJsonMessage()))
assertTrue(service.isFailMelding(rapidAndRiverFail.toJsonMessage()))
}
@Test
fun `skal publisere to behov`() {
rapid.sendTestMessage(
JsonMessage.newMessage(
mapOf(
Key.EVENT_NAME.str to EventName.OPPGAVE_OPPRETT_REQUESTED,
Key.UUID.str to UUID.randomUUID(),
DataFelt.ORGNRUNDERENHET.str to "123456789",
Key.FORESPOERSEL_ID.str to "987654321"
)
).toJson()
)
val generertForespoerselId = redisStore.get("uuid")
rapid.sendTestMessage(
JsonMessage.newMessage(
mapOf(
Key.EVENT_NAME.str to EventName.OPPGAVE_OPPRETT_REQUESTED,
Key.DATA.str to "",
DataFelt.VIRKSOMHET.str to "TestBedrift A/S",
Key.FORESPOERSEL_ID.str to generertForespoerselId!!,
Key.UUID.str to generertForespoerselId
)
).toJson()
)
val behov = rapid.inspektør.message(0)
assertEquals(BehovType.VIRKSOMHET.name, behov.path(Key.BEHOV.str).asText())
val behov2 = rapid.inspektør.message(1)
assertEquals(BehovType.OPPRETT_OPPGAVE.name, behov2[Key.BEHOV.str].asText())
}
@Test
fun `skal fortsette selv om vi mottar feil fra hent virksomhetnavn`() {
rapid.sendTestMessage(
JsonMessage.newMessage(
mapOf(
Key.EVENT_NAME.str to EventName.OPPGAVE_OPPRETT_REQUESTED,
Key.UUID.str to UUID.randomUUID(),
DataFelt.ORGNRUNDERENHET.str to "123456789",
Key.FORESPOERSEL_ID.str to "987654321"
)
).toJson()
)
val generertForespoerselId = redisStore.get("uuid")
val feil = Fail(
EventName.OPPGAVE_OPPRETT_REQUESTED,
BehovType.VIRKSOMHET,
"Klarte ikke hente virksomhet",
mapOf(
DataFelt.ORGNRUNDERENHET to "123456789".toJson()
),
generertForespoerselId,
generertForespoerselId
).toJsonMessage().toJson()
rapid.sendTestMessage(feil)
val behov = rapid.inspektør.message(0)
assertEquals(BehovType.VIRKSOMHET.name, behov.path(Key.BEHOV.str).asText())
val behov2 = rapid.inspektør.message(1)
assertEquals(BehovType.OPPRETT_OPPGAVE.name, behov2[Key.BEHOV.str].asText())
assertEquals("Arbeidsgiver", behov2[DataFelt.VIRKSOMHET.str].asText())
}
}
| 13
|
Kotlin
|
0
| 2
|
11ec9e855b5ea4242bbef27746e728fe8890ed25
| 5,358
|
helsearbeidsgiver-inntektsmelding
|
MIT License
|
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/controlFlow/orderUtil.kt
|
androidports
| 115,100,208
| false
| null |
/*
* 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("OrderUtil")
package org.jetbrains.plugins.groovy.lang.psi.controlFlow
import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.InstructionImpl
import java.util.*
private val fakeRoot = InstructionImpl(null)
fun reversedPostOrder(flow: Array<Instruction>): IntArray = postOrder(flow).reversedArray()
fun postOrder(flow: Array<Instruction>): IntArray {
val N = flow.size
val result = IntArray(N)
var resultIndex = 0
val visited = BooleanArray(N)
val stack: Deque<Pair<Instruction, Iterator<Instruction>>> = LinkedList()
stack.push(fakeRoot to flow.iterator())
while (!stack.isEmpty()) {
val (instruction, iterator) = stack.peek()
val undiscovered = iterator.firstOrNull { !visited[it.num()] }
if (undiscovered != null) {
visited[undiscovered.num()] = true // discover successor
stack.push(undiscovered to undiscovered.allSuccessors().iterator())
}
else {
stack.pop()
if (instruction === fakeRoot) {
assert(stack.isEmpty())
}
else {
result[resultIndex++] = instruction.num() // mark black if all successors are discovered
}
}
}
assert(resultIndex == N)
return result
}
private inline fun <T> Iterator<T>.firstOrNull(predicate: (T) -> Boolean): T? {
while (hasNext()) {
val next = next()
if (predicate(next)) return next
}
return null
}
| 6
| null |
0
| 4
|
6e4f7135c5843ed93c15a9782f29e4400df8b068
| 1,987
|
intellij-community
|
Apache License 2.0
|
kotlin-samples/src/main/java/com/jetbrains/domain/Wheel.kt
|
trishagee
| 72,853,830
| true
|
{"Text": 3, "Ignore List": 4, "Markdown": 2, "Maven POM": 2, "Kotlin": 20, "Java": 179, "YAML": 2, "JSON": 3, "XML": 27, "HTML": 3, "HTTP": 1, "JavaScript": 3, "CSS": 1, "JSON with Comments": 1, "Batchfile": 1, "Shell": 1, "INI": 1, "SQL": 3, "SVG": 1, "Unity3D Asset": 5}
|
package com.jetbrains.domain
class Wheel
| 4
|
Java
|
5
| 4
|
f685e4842350321722dfe6018f2e4daabb0e7b39
| 42
|
intellij-samples
|
MIT License
|
app/src/main/java/com/dosti/scamfolio/ui/theme/Theme.kt
|
zeroParanoie
| 803,017,723
| false
|
{"Kotlin": 145065}
|
package com.dosti.scamfolio.ui.theme
import android.app.Activity
import androidx.compose.foundation.background
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.darkColorScheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalView
import androidx.core.view.WindowCompat
private val DarkColorScheme = darkColorScheme(
primary = DarkScam,
secondary = Aquamarine,
tertiary = Black,
background = Color(0xFFFFFBFE),
onBackground = Color(0xFFFFFFFF),
surface = DarkScam,
primaryContainer = DarkScam
)
private val LightColorScheme = lightColorScheme(
primary = Black,
secondary = AquamarineLight,
tertiary = Black,
background = Color(0xFFFFFBFE),
onBackground = Color(0xFF1C1B1F),
surface = DarkScam,
primaryContainer = DarkScam
/* Other default colors to override
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun ScamFolioTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
// Dynamic color is available on Android 12+
content: @Composable () -> Unit
) {
// BackgroundGradient()
val colorScheme = DarkColorScheme
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
val window = (view.context as Activity).window
window.statusBarColor = Color.Black.toArgb()
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = if (!darkTheme) darkTheme else !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
@Composable
fun BackgroundGradient() {
val brush = Brush.verticalGradient(listOf(Color(0xFF1E1E1E), Color.DarkGray))
Box(
modifier = Modifier
.fillMaxSize()
.background(brush)
)
}
| 0
|
Kotlin
|
2
| 0
|
7c289f15d0bde345ffad4322f31e95d0cda6e9a3
| 2,435
|
ScamFolio
|
Do What The F*ck You Want To Public License
|
app/src/main/java/com/mjpc13/sensorstreamer/ui/fragments/TrackingFragment.kt
|
mjpc13
| 553,780,688
| false
| null |
package com.mjpc13.sensorstreamer.ui.fragments
import android.content.Intent
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import com.mjpc13.sensorstreamer.R
import com.mjpc13.sensorstreamer.db.Run
import com.mjpc13.sensorstreamer.other.Constants.ACTION_PAUSE_SERVICE
import com.mjpc13.sensorstreamer.other.Constants.ACTION_START_OR_RESUME_SERVICE
import com.mjpc13.sensorstreamer.other.Constants.ACTION_STOP_SERVICE
import com.mjpc13.sensorstreamer.other.Constants.MAP_ZOOM
import com.mjpc13.sensorstreamer.other.Constants.POLYLINE_COLOR
import com.mjpc13.sensorstreamer.other.Constants.POLYLINE_WIDTH
import com.mjpc13.sensorstreamer.other.TrackingUtility
import com.mjpc13.sensorstreamer.services.PolyLine
import com.mjpc13.sensorstreamer.services.TrackingService
import com.mjpc13.sensorstreamer.ui.viewmodels.MainViewModel
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.model.LatLngBounds
import com.google.android.gms.maps.model.PolylineOptions
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.snackbar.Snackbar
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.android.synthetic.main.fragment_tracking.*
import java.util.*
import kotlin.math.round
@AndroidEntryPoint
class TrackingFragment: Fragment(R.layout.fragment_tracking) {
private val viewModel: MainViewModel by viewModels()
private var map: GoogleMap? = null
private var isTracking = false
private var pathPoints = mutableListOf<PolyLine>()
private var currentTimeMillis = 0L
private var menu: Menu? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
setHasOptionsMenu(true)
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
btnFinishRun.setOnClickListener{
zoomToSeeWholeTrack()
endRunAndSaveToDB()
}
mapView.onCreate(savedInstanceState)
btnToggleRun.setOnClickListener{
toggleRun()
}
mapView.getMapAsync {
map = it
addAllPolylines()
}
subscribeToService()
}
private fun subscribeToService(){
TrackingService.isTracking.observe(viewLifecycleOwner, Observer{
updateTracking(it)
})
TrackingService.pathPoints.observe(viewLifecycleOwner, Observer{
pathPoints = it
addLatestPolyline()
moveCameraToUser()
})
TrackingService.timeRunInMillis.observe(viewLifecycleOwner, Observer{
currentTimeMillis = it
val formattedTime = TrackingUtility.getFormattedStopWatchTime(currentTimeMillis,true)
tvTimer.text = formattedTime
})
}
private fun toggleRun(){
if(isTracking){
menu?.getItem(0)?.isVisible = true
sendCommandToService(ACTION_PAUSE_SERVICE)
} else{
sendCommandToService(ACTION_START_OR_RESUME_SERVICE)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.toolbar_tracking_menu, menu)
this.menu = menu
}
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
if (currentTimeMillis > 0L) {
this.menu?.getItem(0)?.isVisible = true
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId){
R.id.miCancelTracking -> {
showCancelTrackingDialog()
}
}
return super.onOptionsItemSelected(item)
}
private fun showCancelTrackingDialog(){
val dialog = MaterialAlertDialogBuilder(requireContext(), R.style.AlertDialogTheme)
.setTitle("Cancel the Run?")
.setMessage("Are you sure you want to spot streaming?")
.setIcon(R.drawable.ic_delete)
.setPositiveButton("Yes"){ _,_ ->
stopRun()
}
.setNegativeButton("No") { dialogInterface, _ ->
dialogInterface.cancel()
}
.create()
dialog.show()
}
private fun stopRun(){
sendCommandToService(ACTION_STOP_SERVICE)
findNavController().navigate(R.id.action_trackingFragment_to_runFragment)
}
private fun updateTracking(isTracking :Boolean){
this.isTracking = isTracking
if(!isTracking){
btnToggleRun.text = "Start"
btnFinishRun.visibility = View.VISIBLE
} else{
btnToggleRun.text = "Stop"
menu?.getItem(0)?.isVisible = true
btnFinishRun.visibility = View.GONE
}
}
private fun moveCameraToUser(){
if(pathPoints.isNotEmpty() && pathPoints.last().isNotEmpty()){
map?.animateCamera(
CameraUpdateFactory.newLatLngZoom(
pathPoints.last().last(),
MAP_ZOOM
)
)
}
}
private fun zoomToSeeWholeTrack(){
val bounds = LatLngBounds.Builder()
for (polyline in pathPoints){
for (pos in polyline){
bounds.include(pos)
}
}
map?.moveCamera(
CameraUpdateFactory.newLatLngBounds(
bounds.build(),
mapView.width,
mapView.height,
(mapView.height* 0.05f).toInt()))
}
private fun endRunAndSaveToDB(){
map?.snapshot { bmp ->
var distanceInMeters = 0
for (polyline in pathPoints){
distanceInMeters += TrackingUtility.calculatePolylineLength(polyline).toInt()
}
var avgSpeed = round(distanceInMeters/(currentTimeMillis/1000f)*10)/10f //in meter/sec
val dateTimestamp = Calendar.getInstance().timeInMillis
val run = Run(bmp, dateTimestamp, avgSpeed, distanceInMeters, currentTimeMillis)
viewModel.insertRun(run)
Snackbar.make(
requireActivity().findViewById(R.id.rootView),
"Run saved successfully",
Snackbar.LENGTH_LONG
).show()
stopRun()
}
}
//Draw every Polyline on the map. This needs to be here cause if the user rotates the screen every polyline is lost and needs to be re-draw
private fun addAllPolylines(){
for (polyline in pathPoints){
val polylineOptions = PolylineOptions()
.color(POLYLINE_COLOR)
.width(POLYLINE_WIDTH)
.addAll(polyline)
map?.addPolyline(polylineOptions)
}
}
private fun addLatestPolyline(){
if(pathPoints.isNotEmpty() && pathPoints.last().size > 1){
val preLastLatLong = pathPoints.last()[pathPoints.last().size-2]
val lastLatLong = pathPoints.last().last()
val polylineOptions = PolylineOptions()
.color(POLYLINE_COLOR)
.width(POLYLINE_WIDTH)
.add(preLastLatLong)
.add(lastLatLong)
map?.addPolyline(polylineOptions)
}
}
override fun onResume() {
super.onResume()
mapView?.onResume()
}
override fun onStart() {
super.onStart()
mapView?.onResume()
}
override fun onStop() {
super.onStop()
mapView?.onStop()
}
override fun onPause() {
super.onPause()
mapView?.onPause()
}
override fun onLowMemory() {
super.onLowMemory()
mapView?.onLowMemory()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
mapView?.onSaveInstanceState(outState)
}
private fun sendCommandToService(action: String) =
Intent(requireContext(), TrackingService::class.java).also {
it.action = action
requireContext().startService(it)
}
}
| 2
|
Kotlin
|
0
| 0
|
bc1a3d3cccf3fbca38f47edb4da3d2f472a6aa9b
| 8,475
|
SensorStreamer
|
MIT License
|
src/main/kotlin/com/cycode/plugin/settings/ApplicationSettingsConfigurable.kt
|
cycodehq
| 661,784,325
| false
|
{"Kotlin": 199124}
|
package com.cycode.plugin.settings
import com.cycode.plugin.Consts
import com.cycode.plugin.components.settingsWindow.SettingsWindow
import com.cycode.plugin.services.cycode
import com.cycode.plugin.services.pluginSettings
import com.intellij.openapi.options.SearchableConfigurable
import com.intellij.openapi.project.Project
import java.io.File
import java.net.MalformedURLException
import java.net.URISyntaxException
import java.net.URL
import javax.swing.JComponent
class ApplicationSettingsConfigurable(val project: Project) : SearchableConfigurable {
private val cycodeService = cycode(project)
private val pluginSettings = pluginSettings()
private val settingsWindows = SettingsWindow()
override fun createComponent(): JComponent {
return settingsWindows.getComponent()
}
override fun isModified(): Boolean {
return pluginSettings.getSettings() != settingsWindows.getSettings()
}
private fun isValidCliPath(cliPath: String): Boolean {
try {
val cliFile = File(cliPath)
if (!cliFile.isFile) return false
if (!cliFile.canExecute()) return false
} catch (e: Exception) {
return false
}
return true
}
private fun isValidUrl(url: String): Boolean {
return try {
// toURI() method is important here as it ensures that any URL string that complies with RFC 2396
URL(url).toURI()
true
} catch (e: MalformedURLException) {
false
} catch (e: URISyntaxException) {
false
}
}
override fun apply() {
val newSettings = settingsWindows.getSettings()
pluginSettings.cliAutoManaged = newSettings.cliAutoManaged
pluginSettings.cliAdditionalParams = newSettings.cliAdditionalParams
pluginSettings.scanOnSave = newSettings.scanOnSave
pluginSettings.scaSyncFlow = newSettings.scaSyncFlow
pluginSettings.sastSupport = newSettings.sastSupport
if (isValidCliPath(newSettings.cliPath)) {
pluginSettings.cliPath = newSettings.cliPath
} else {
pluginSettings.cliPath = Consts.DEFAULT_CLI_PATH
}
if (isValidUrl(newSettings.cliApiUrl)) {
pluginSettings.cliApiUrl = newSettings.cliApiUrl
}
if (isValidUrl(newSettings.cliAppUrl)) {
pluginSettings.cliAppUrl = newSettings.cliAppUrl
}
// run the same checks as on the plugin start after updating of settings
cycodeService.installCliIfNeededAndCheckAuthentication()
}
override fun getDisplayName(): String {
return "Cycode"
}
override fun getId(): String {
return "com.cycode.plugin.settings.ApplicationSettingsConfigurable"
}
}
| 1
|
Kotlin
|
0
| 1
|
e63cce021c1f58fbd023da971d4e401a04b6c90c
| 2,808
|
intellij-platform-plugin
|
MIT License
|
jvm/src/main/kotlin/com/jetbrains/infra/pgpVerifier/Sha256ChecksumSignatureVerifier.kt
|
JetBrains
| 383,109,473
| false
|
{"Kotlin": 28690, "C#": 22144}
|
package com.jetbrains.infra.pgpVerifier
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.Path
import java.security.MessageDigest
class Sha256ChecksumSignatureVerifier(private val pgpSignaturesVerifier: PgpSignaturesVerifier) {
private val sha256WithFileNameRegex = Regex("([0-9a-f]{64})[\t ]+\\*?([a-zA-Z0-9_\\-.*]+)\\s*")
private fun getHashFromChecksumFile(
detachedSignatureFile: Path,
checksumFile: Path,
expectedFileName: String,
untrustedPublicKeyRing: InputStream,
trustedMasterKey: InputStream,
): String {
Files.newInputStream(detachedSignatureFile).use { signatureStream ->
pgpSignaturesVerifier.verifySignature(
file = checksumFile,
detachedSignatureInputStream = signatureStream,
untrustedPublicKeyBundleInputStream = untrustedPublicKeyRing,
trustedMasterKeyInputStream = trustedMasterKey,
)
}
val text = Files.readString(checksumFile)
val match = sha256WithFileNameRegex.matchEntire(text) ?: error("Checksum file does not match regex '$sha256WithFileNameRegex': ~~~$text~~~")
val actualFileName = match.groupValues[2]
if (actualFileName != expectedFileName) {
error("Expected file name '$expectedFileName', but got '$actualFileName' in checksum file: ~~~$text~~~")
}
return match.groupValues[1]
}
fun verifyChecksumAndSignature(
file: Path,
detachedSignatureFile: Path,
checksumFile: Path,
expectedFileName: String,
untrustedPublicKeyRing: InputStream,
trustedMasterKey: InputStream,
) {
val expectedHash = getHashFromChecksumFile(
detachedSignatureFile = detachedSignatureFile,
checksumFile = checksumFile,
expectedFileName = expectedFileName,
untrustedPublicKeyRing = untrustedPublicKeyRing,
trustedMasterKey = trustedMasterKey,
)
val actualByteHash = getFileDigest(file, MessageDigest.getInstance("SHA-256"))
val actualHash = actualByteHash.toHexString()
if (expectedHash != actualHash) {
error(
"Failed to verify SHA-256 checksum for $file\n\n" +
"The actual value is $actualHash,\n" +
"but $expectedHash was expected"
)
}
}
private fun ByteArray.toHexString() = joinToString("") { "%02x".format(it) }
private fun getFileDigest(file: Path, digest: MessageDigest): ByteArray {
val buf = ByteArray(65536)
digest.reset()
Files.newInputStream(file).use {
while (true) {
val count = it.read(buf)
if (count <= 0) break
digest.update(buf, 0, count)
}
}
return digest.digest()
}
}
| 0
|
Kotlin
|
3
| 3
|
c33fc3ca9a58570a369b8e3b94411b0dd3b7925e
| 2,929
|
download-pgp-verifier
|
Apache License 2.0
|
src/main/kotlin/io/articulus/fhir/model/dstu3/Address.kt
|
Articulus-Tech
| 160,540,104
| false
| null |
//
// Generated from FHIR Version 3.0.1.11917 on 2018-12-05T09:46:12.461
//
// 2018, Articulus
//
package io.articulus.fhir.model.dstu3
import kotlin.collections.List
/**
* An address expressed using postal conventions (as opposed to GPS or other location definition formats)
*
* An address expressed using postal conventions (as opposed to GPS or other location definition formats). This data type may be used to convey addresses for use in delivering mail as well as for visiting locations which might not be valid for mail delivery. There are a variety of postal address formats defined around the world.
*/
open class Address() : Element() {
/**
* Name of city, town etc.
*/
var city: String? = null
/**
* Country (e.g. can be ISO 3166 2 or 3 letter code)
*/
var country: String? = null
/**
* District name (aka county)
*/
var district: String? = null
val line: List<String> = mutableListOf<String>()
/**
* Time period when address was/is in use
*/
var period: Period? = null
/**
* Postal code for area
*/
var postalCode: String? = null
/**
* Sub-unit of country (abbreviations ok)
*/
var state: String? = null
/**
* Text representation of the address
*/
var text: String? = null
/**
* postal | physical | both
*/
var type: String? = null
/**
* home | work | temp | old - purpose of this address
*/
var use: String? = null
}
| 0
|
Kotlin
|
0
| 3
|
90b7b912048fc61ad3696497d1ceaf76459852cb
| 1,518
|
kotlin-fhir-model
|
Apache License 2.0
|
feature-account-impl/src/main/java/jp/co/soramitsu/feature_account_impl/presentation/account/details/AccountDetailsFragment.kt
|
soramitsu
| 278,060,397
| false
| null |
package jp.co.soramitsu.feature_account_impl.presentation.account.details
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.lifecycleScope
import coil.ImageLoader
import jp.co.soramitsu.common.base.BaseFragment
import jp.co.soramitsu.common.di.FeatureUtils
import jp.co.soramitsu.common.utils.bindTo
import jp.co.soramitsu.common.utils.nameInputFilters
import jp.co.soramitsu.common.view.bottomSheet.list.dynamic.DynamicListBottomSheet
import jp.co.soramitsu.feature_account_api.di.AccountFeatureApi
import jp.co.soramitsu.feature_account_api.presenatation.actions.ExternalAccountActions
import jp.co.soramitsu.feature_account_api.presenatation.actions.copyAddressClicked
import jp.co.soramitsu.feature_account_impl.R
import jp.co.soramitsu.feature_account_impl.di.AccountFeatureComponent
import jp.co.soramitsu.feature_account_impl.presentation.account.model.ExportSourceChooserPayload
import jp.co.soramitsu.feature_account_impl.presentation.common.accountSource.SourceTypeChooserBottomSheetDialog
import kotlinx.android.synthetic.main.fragment_account_details.accountDetailsChainAccounts
import kotlinx.android.synthetic.main.fragment_account_details.accountDetailsNameField
import kotlinx.android.synthetic.main.fragment_account_details.accountDetailsToolbar
import javax.inject.Inject
private const val ACCOUNT_ID_KEY = "ACCOUNT_ADDRESS_KEY"
class AccountDetailsFragment : BaseFragment<AccountDetailsViewModel>(), ChainAccountsAdapter.Handler {
@Inject lateinit var imageLoader: ImageLoader
private val adapter by lazy(LazyThreadSafetyMode.NONE) {
ChainAccountsAdapter(this, imageLoader)
}
companion object {
fun getBundle(metaAccountId: Long): Bundle {
return Bundle().apply {
putLong(ACCOUNT_ID_KEY, metaAccountId)
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
) = layoutInflater.inflate(R.layout.fragment_account_details, container, false)
override fun initViews() {
accountDetailsToolbar.setHomeButtonListener {
viewModel.backClicked()
}
accountDetailsNameField.content.filters = nameInputFilters()
accountDetailsChainAccounts.setHasFixedSize(true)
accountDetailsChainAccounts.adapter = adapter
}
override fun inject() {
val metaId = argument<Long>(ACCOUNT_ID_KEY)
FeatureUtils.getFeature<AccountFeatureComponent>(
requireContext(),
AccountFeatureApi::class.java
)
.accountDetailsComponentFactory()
.create(this, metaId)
.inject(this)
}
override fun subscribe(viewModel: AccountDetailsViewModel) {
accountDetailsNameField.content.bindTo(viewModel.accountNameFlow, viewLifecycleOwner.lifecycleScope)
viewModel.chainAccountProjections.observe { adapter.submitList(it) }
viewModel.showExternalActionsEvent.observeEvent(::showAccountActions)
viewModel.showExportSourceChooser.observeEvent(::showExportSourceChooser)
}
override fun chainAccountClicked(item: AccountInChainUi) {
}
override fun chainAccountOptionsClicked(item: AccountInChainUi) {
viewModel.chainAccountOptionsClicked(item)
}
private fun showAccountActions(payload: ExternalAccountActions.Payload) {
WalletAccountActionsSheet(
context = requireContext(),
content = payload,
onCopy = viewModel::copyAddressClicked,
onExternalView = viewModel::viewExternalClicked,
onExportAccount = viewModel::exportClicked,
onSwitchNode = viewModel::switchNode
).show()
}
private fun showExportSourceChooser(payload: ExportSourceChooserPayload) {
SourceTypeChooserBottomSheetDialog(
context = requireActivity(),
payload = DynamicListBottomSheet.Payload(payload.sources),
onClicked = { viewModel.exportTypeSelected(it, payload.chainId) }
).show()
}
}
| 1
| null |
14
| 54
|
9d3659e4f142cc4e0270c149ddfb8bd0d6a9eefc
| 4,139
|
fearless-Android
|
Apache License 2.0
|
app/src/main/kotlin/dev/atick/safety/repository/auth/AuthRepositoryImpl.kt
|
atick-faisal
| 609,303,624
| false
|
{"Kotlin": 210519}
|
package dev.atick.safety.repository.auth
import dev.atick.storage.preferences.data.PreferencesDatastore
import javax.inject.Inject
class AuthRepositoryImpl @Inject constructor(
private val preferencesDatastore: PreferencesDatastore
) : AuthRepository {
override suspend fun saveUserId(userId: String): Result<Unit> {
return try {
preferencesDatastore.saveUserId(userId)
Result.success(Unit)
} catch (exception: Exception) {
Result.failure(exception)
}
}
}
| 2
|
Kotlin
|
1
| 1
|
4964d4350dab3670ffe9e8552427537f044d158c
| 529
|
Safety-Android
|
Apache License 2.0
|
kohii-core/src/main/java/kohii/v1/core/RecycledRendererProvider.kt
|
eneim
| 138,487,627
| false
|
{"Kotlin": 701013, "Java": 17388, "Shell": 1177}
|
/*
* Copyright (c) 2019 <NAME>, <EMAIL>
*
* 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 kohii.v1.core
import android.view.ViewGroup
import androidx.annotation.CallSuper
import androidx.collection.SparseArrayCompat
import androidx.collection.forEach
import androidx.core.util.Pools.SimplePool
import kohii.v1.media.Media
import kohii.v1.onEachAcquired
abstract class RecycledRendererProvider @JvmOverloads constructor(
private val poolSize: Int = 2
) : RendererProvider {
private val pools = SparseArrayCompat<SimplePool<Any>>(2)
@CallSuper
override fun acquireRenderer(
playback: Playback,
media: Media
): Any {
val rendererType = getRendererType(playback.container, media)
val pool = pools.get(rendererType)
return pool?.acquire() ?: createRenderer(playback, rendererType)
}
// Test: releaseRenderer(any(), any(), null) must return true.
@CallSuper
override fun releaseRenderer(
playback: Playback,
media: Media,
renderer: Any?
): Boolean {
if (renderer == null) return true
val rendererType = getRendererType(playback.container, media)
val pool = pools.get(rendererType) ?: SimplePool<Any>(poolSize).also {
pools.put(rendererType, it)
}
return pool.release(renderer)
}
@CallSuper
override fun clear() {
pools.forEach { _, value ->
value.onEachAcquired(::onClear)
}
}
protected open fun getRendererType(
container: ViewGroup,
media: Media
): Int = 0
// Must always create new Renderer.
protected abstract fun createRenderer(
playback: Playback,
rendererType: Int
): Any
protected open fun onClear(renderer: Any) = Unit
}
| 49
|
Kotlin
|
50
| 370
|
79f5ec327e3db627d88b089931b63d1e28e4e2ee
| 2,186
|
kohii
|
Apache License 2.0
|
app/src/main/java/com/disfluency/components/grid/TwoColumnGridItemSpan.kt
|
UTN-FRBA-Mobile
| 638,009,160
| false
| null |
package com.disfluency.components.grid
import androidx.compose.foundation.lazy.grid.GridItemSpan
/**
* Custom GridItemSpan to allow grids of two columns
* to have its last element occupy the width of both columns
*/
fun TwoColumnGridItemSpan(index: Int, listSize: Int): GridItemSpan{
val lineSpan = if(index == listSize - 1 && listSize % 2 == 1) 2 else 1
return GridItemSpan(lineSpan)
}
| 1
|
Kotlin
|
0
| 0
|
44142e38a9c5a6e4422767c439997e187f28f098
| 399
|
Disfluency
|
MIT License
|
library/src/main/kotlin/chat/tamtam/botsdk/model/response/SendMessage.kt
|
Litemn
| 175,861,105
| true
|
{"Kotlin": 109750}
|
package chat.tamtam.botsdk.model.response
import kotlinx.serialization.Optional
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* This message you will get as Response after sent message to chat
*
* @param chatId - identifier of chat where created message
* @param messageId - unique identifier of created message
* @param messageId - in most cases same as [chatId]
*/
@Serializable
class SendMessage(
@SerialName("chat_id") val chatId: Long,
@SerialName("message_id") val messageId: String,
@Optional @SerialName("recipient_id") val recipientId: Long = -1
)
| 0
|
Kotlin
|
0
| 0
|
fcfc679cf672d4402651e3ffbb0bfaa6f2b99c69
| 616
|
TamTamBotApiClientDsl
|
Apache License 2.0
|
minchat-cli/src/main/kotlin/io/minchat/cli/ui/ListView.kt
|
MinChat-official
| 604,238,971
| false
|
{"Kotlin": 394469}
|
package io.minchat.cli.ui
import androidx.compose.runtime.Composable
/**
* Displays [elements] by passing entries in it to the [display] function.
*/
@Composable
inline fun <T> ListView(
elements: Iterable<T>,
display: @Composable (T) -> Unit
) {
elements.forEach { display(it) }
}
/**
* Displays [elements] by passing entries in it to the [display] function.
* Includes element indices.
*/
@Composable
inline fun <T> ListView(
elements: Iterable<T>,
display: @Composable (Int, T) -> Unit
) {
elements.forEachIndexed { index, value -> display(index, value) }
}
| 0
|
Kotlin
|
0
| 3
|
8f70585146311efe9fc49e4e3b93eb8becb92cba
| 575
|
MinChat
|
Apache License 2.0
|
android/app/src/main/java/github/tornaco/android/thanos/start/chart/StartChartState.kt
|
Tornaco
| 228,014,878
| false
| null |
package github.tornaco.android.thanos.start.chart
import github.tornaco.android.thanos.widget.pie.ChartItem
data class StartChartState(
val isLoading: Boolean,
val totalTimes: Long,
val category: Category,
val entries: List<ChartItem<String>>,
)
| 239
|
Java
|
26
| 509
|
2c3531b7c2f23a1cabc7d0de2131257c57ff920b
| 264
|
Thanox
|
Apache License 2.0
|
event-sourcing/main/common/db/dao/module/ModuleDAO.kt
|
grifguitar
| 469,521,979
| false
|
{"Kotlin": 71873, "Java": 39627, "Dockerfile": 151}
|
package common.db.dao.module
import com.mongodb.rx.client.Success
import common.db.Event
import rx.Observable
interface ModuleDAO<E : Event> {
fun addEvent(event: E): Observable<Success>
fun getAllEventsForUser(userId: Long): Observable<E>
fun getAllEvents(): Observable<E>
fun getCount(): Observable<Long>
}
| 0
|
Kotlin
|
0
| 0
|
066d47162951d75b5697ea812bd6beadf8f201d1
| 332
|
soft-design
|
Apache License 2.0
|
app/src/androidTest/java/com/blinkist/easylibrary/features/library/LibraryPageObject.kt
|
tfcporciuncula
| 130,910,784
| false
| null |
package com.blinkist.easylibrary.features.library
import androidx.recyclerview.widget.RecyclerView
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.swipeDown
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.contrib.RecyclerViewActions
import androidx.test.espresso.matcher.ViewMatchers.hasDescendant
import androidx.test.espresso.matcher.ViewMatchers.isAssignableFrom
import androidx.test.espresso.matcher.ViewMatchers.isDisplayed
import androidx.test.espresso.matcher.ViewMatchers.withId
import androidx.test.espresso.matcher.ViewMatchers.withText
import com.blinkist.easylibrary.R
import com.blinkist.easylibrary.test.instrumentation.LazyActivityTestRule
import com.blinkist.easylibrary.test.instrumentation.RecyclerViewItemCountAssertion.Companion.withItemCount
import com.blinkist.easylibrary.test.instrumentation.atPosition
import com.blinkist.easylibrary.test.instrumentation.isRefreshing
import com.google.android.material.snackbar.Snackbar
import io.appflate.restmock.RESTMockServer
import io.appflate.restmock.utils.RequestMatchers.pathContains
import java.util.concurrent.TimeUnit
class LibraryPageObject(private val activityRule: LazyActivityTestRule<LibraryActivity>) {
private val recyclerView get() = onView(withId(R.id.recyclerView))
private val snackbar get() = onView(isAssignableFrom(Snackbar.SnackbarLayout::class.java))
private val progressBar get() = onView(withId(R.id.swipeRefreshLayout))
private val sortMenu get() = onView(withId(R.id.menu_sort))
private val ascendingOption get() = onView(withId(R.id.ascendingTextView))
private val descendingOption get() = onView(withId(R.id.descendingTextView))
private val ascendingCheck get() = onView(withId(R.id.ascendingCheckImageView))
private val descendingCheck get() = onView(withId(R.id.descendingCheckImageView))
val defaultBooksAmount = 22
fun launch() = activityRule.launchActivity()
fun pullToRefresh() {
recyclerView.perform(swipeDown())
}
fun scrollToTop() {
recyclerView.perform(RecyclerViewActions.scrollToPosition<RecyclerView.ViewHolder>(0))
}
fun clickOnSortMenu() {
sortMenu.perform(click())
}
fun clickOnAscending() {
ascendingOption.perform(click())
}
fun clickOnDescending() {
descendingOption.perform(click())
}
fun assertSortOptionsDialogIsVisible() {
ascendingOption.check(matches(isDisplayed()))
descendingOption.check(matches(isDisplayed()))
}
fun assertSortOptionDialogIsNotVisible() {
ascendingOption.check(doesNotExist())
descendingOption.check(doesNotExist())
}
fun assertAscendingIsSelected() {
ascendingCheck.check(matches(isDisplayed()))
}
fun assertDescendingIsSelected() {
descendingCheck.check(matches(isDisplayed()))
}
fun assertSnackbarIsVisible() {
snackbar.check(matches(isDisplayed()))
}
fun assertSnackbarIsNotVisible() {
snackbar.check(doesNotExist())
}
fun assertProgressBarIsVisible() {
progressBar.check(matches(isRefreshing()))
}
fun assertListItemCount(expectedCount: Int) {
recyclerView.check(withItemCount(expectedCount))
}
fun assertFirstBookIsMostRecent() {
recyclerView.check(matches(atPosition(1, hasDescendant(withText("Refactoring")))))
}
fun assertFirstBookIsLeastRecent() {
recyclerView.check(matches(atPosition(1, hasDescendant(withText("Design Patterns")))))
}
fun givenServiceFails() {
RESTMockServer.whenGET(pathContains("books")).thenReturnEmpty(500)
}
fun givenServiceReturnsDefaultBooks() {
RESTMockServer.whenGET(pathContains("books")).thenReturnFile(200, "books.json")
}
fun givenServiceReturnsDefaultBooksAndOneMoreBookOnRefresh() {
RESTMockServer.whenGET(pathContains("books"))
.thenReturnFile(200, "books.json")
.thenReturnFile(200, "onemorebook.json")
}
fun givenServiceReturnsDefaultBooksAndFailsOnRefresh() {
RESTMockServer.whenGET(pathContains("books"))
.thenReturnFile(200, "books.json")
.thenReturnEmpty(500)
}
fun givenServiceReturnsDefaultBooksAndDelaysOnRefresh() {
RESTMockServer.whenGET(pathContains("books"))
.thenReturnFile(200, "books.json")
.thenReturnFile(200, "books.json")
.delayBody(TimeUnit.SECONDS, 0, 5)
}
}
| 0
| null |
2
| 14
|
efac1f7e9c6f6b06ddc7e32e6d4263faa32dea6e
| 4,434
|
easy-library
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.