path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/plugin-saxon/main/uk/co/reecedunn/intellij/plugin/saxon/query/s9api/profiler/SaxonQueryProfiler.kt
rhdunn
62,201,764
false
null
/* * Copyright (C) 2019-2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.saxon.query.s9api.profiler import com.intellij.lang.Language import uk.co.reecedunn.intellij.plugin.intellij.lang.XPathSubset import uk.co.reecedunn.intellij.plugin.processor.profile.ProfileQueryResults import uk.co.reecedunn.intellij.plugin.processor.profile.ProfileableQuery import uk.co.reecedunn.intellij.plugin.processor.run.RunnableQuery import uk.co.reecedunn.intellij.plugin.processor.run.StoppableQuery import uk.co.reecedunn.intellij.plugin.saxon.query.s9api.runner.SaxonRunner internal class SaxonQueryProfiler(val runner: RunnableQuery) : ProfileableQuery, StoppableQuery { // region Query override var rdfOutputFormat: Language? get() = runner.rdfOutputFormat set(value) { runner.rdfOutputFormat = value } override var updating: Boolean get() = runner.updating set(value) { runner.updating = value } override var xpathSubset: XPathSubset get() = runner.xpathSubset set(value) { runner.xpathSubset = value } override var server: String get() = runner.server set(value) { runner.server = value } override var database: String get() = runner.database set(value) { runner.database = value } override var modulePath: String get() = runner.modulePath set(value) { runner.modulePath = value } override fun bindVariable(name: String, value: Any?, type: String?) { runner.bindVariable(name, value, type) } override fun bindContextItem(value: Any?, type: String?) { runner.bindContextItem(value, type) } // endregion // region ProfileableQuery override fun profile(): ProfileQueryResults { val results = (runner as SaxonRunner).asSequence().toList() val listener = (runner as SaxonRunner).traceListener as SaxonProfileTraceListener return ProfileQueryResults(results, listener.toProfileReport()) } // endregion // region StoppableQuery override fun stop() { (runner as SaxonRunner).traceListener?.stop() } // endregion // region Closeable override fun close() { runner.close() } // endregion }
47
Kotlin
4
25
d363dad28df1eb17c815a821c87b4f15d2b30343
2,917
xquery-intellij-plugin
Apache License 2.0
shared/src/commonMain/kotlin/model/data/formula/TopItem.kt
theodore-norvell
726,244,640
false
{"Kotlin": 49666, "Swift": 592, "Shell": 228}
package model.data.formula import model.data.Environment sealed class TopItem { abstract fun asNumberBuilder() : NumberBuilder? abstract fun negate() : TopItem abstract fun render( env : Environment) : String }
0
Kotlin
0
0
fba8c3a7456393f8fcdb1a868405483387be9d2e
227
compose-app
Apache License 2.0
app/src/main/java/com/hawesome/bleconnector/kit/ModbusKit.kt
hawesome512
325,215,146
false
{"Java": 136678, "Kotlin": 127590}
package com.hawesome.bleconfig.kit import com.hawesome.bleconfig.ext.toIntList //<editor-fold desc="定义数据类型"> /* * Modbus指令类型:读、写、错误 * */ enum class CMDType(val value: Int) { READ(0x03), WRITE(0x1A), ERROR(0x00) } /* * Modbus指令信息(指令类型,起始地址,数据长度) * */ data class CMDInfo(val type: CMDType = CMDType.ERROR, val location: Int = 0, val size: Int = 0) { /* * 修改参数后马上需要验证其结果 * */ fun toggle(): CMDInfo { val toggleType = when (type) { CMDType.WRITE -> CMDType.READ CMDType.READ -> CMDType.WRITE CMDType.ERROR -> CMDType.ERROR } return CMDInfo(toggleType, location, size) } } /* * Modbus返回数据结果:错误,写成功,读成功(有效数据) * */ enum class ReceivedResult(var data: List<Int> = listOf(), var cmdInfo: CMDInfo = CMDInfo()) { ERROR, WRITE_SUCCESS, READ_SUCCESS } //</editor-fold> /* * Modbus通信处理的工具类 * buildReadCMD(:CMDInfo):ByteArray 生成读指令 * buildWriteCMD(:CMDInfo:List<Int>):ByteArray 生成写指令 * varifyReceivedData(:ByteArray:ByteArray):ReceivedResult 验证返回数据 * */ object ModbusKit { //跟外设通信,统一采用Modbus通信地址:1,设备不检验通信地址与本机是否匹配 private const val FIXED_ADDRESS = 0x01 /* * Modbus读指令,location:起始地址,size:数据长度 * */ fun buildReadCMD(info: CMDInfo): ByteArray { val tmps = mutableListOf(FIXED_ADDRESS, CMDType.READ.value) tmps.addAll(seperateInt(info.location)) tmps.addAll(seperateInt(info.size)) tmps.addAll(buildCRC(tmps)) return ByteArray(tmps.size) { tmps[it].toByte() } } /* * Modbus写指令,location:起始地址,values:写数据,一个电量参数占一位 * */ fun buildWriteCMD(info: CMDInfo, values: List<Int>): ByteArray { val temps = mutableListOf(FIXED_ADDRESS, CMDType.WRITE.value) temps.addAll(seperateInt(info.location)) temps.addAll(seperateInt(info.size)) temps.add(values.size * 2) values.forEach { temps.addAll(seperateInt(it)) } temps.addAll(buildCRC(temps)) return ByteArray(temps.size) { temps[it].toByte() } } /* * 验证返回数据,判定通讯是否成功 * Read[HEX]: * snd→01,03,P1,P2,00,N,CRC1,CRC2【size=8】 * rcv→01,03,N*2,X0,X1……X2n-1,CRC1,CRC2【size≥7】 * Write[HEX]: * snd→01,10,P1,P2,00,N,2N,X0,X1……X2n-1,CRC1,CRC2【size≥11】 * rcv→01,10,P1,P2,00,N,CRC1,CRC2【size=8】 * */ fun varifyReceivedData(send: ByteArray, received: ByteArray): ReceivedResult { val snd = send.toIntList() val rcv = received.toIntList() val cmdInfo = extractCMDInfo(send) //读写功能指令(含crc)最小长度,防止数组长度溢出,功能码一致 if (snd.size >= 8 && rcv.size >= 7 && snd[1] == rcv[1]) { if (snd[1] == CMDType.WRITE.value && snd.subList(2, 3) == rcv.subList(2, 3)) { val result = ReceivedResult.WRITE_SUCCESS result.cmdInfo = cmdInfo return result } if (snd[1] == CMDType.READ.value && mergeInt(snd[4], snd[5]) * 2 == rcv[2]) { val data = mutableListOf<Int>() for (i in 0 until rcv[2] / 2) { data.add(mergeInt(rcv[2 * i + 3], rcv[2 * i + 4])) } val result = ReceivedResult.READ_SUCCESS result.data = data result.cmdInfo = cmdInfo return result } } return ReceivedResult.ERROR } /* * 验证指令是否完整 * */ fun checkCMDFull(cmd: ByteArray): Boolean { val cmds = cmd.toIntList() val sourceCRC = cmds.subList(cmds.size - 2, cmds.size) val targetCRC = buildCRC(cmds.subList(0, cmds.size - 2)) return sourceCRC == targetCRC } /* * 提取基本指令信息(读写通用) * */ private fun extractCMDInfo(cmd: ByteArray): CMDInfo { val temps = cmd.toIntList() if (temps.size < 6) return CMDInfo() val type = enumValues<CMDType>().firstOrNull { it.value == temps[1] } val location = mergeInt(temps[2], temps[3]) val size = mergeInt(temps[4], temps[5]) return CMDInfo(type ?: CMDType.ERROR, location, size) } /* * 整型数据分解为高低位数组:65535→【255,255】 * */ private fun seperateInt(source: Int): List<Int> { val tmps = mutableListOf(0xFF, 0XFF) tmps[0] = source / 0x100 tmps[1] = source % 0x100 return tmps } /* * 将高低位数据合并为整型数据:【255,255】→65535 * */ private fun mergeInt(vararg sources: Int) = if (sources.size != 2) 0 else (sources[0] * 0x100 + sources[1]) /* * 生成CRC校验码 * HEX:【01,03,00,00,00,01】→【84,0A】 * */ private fun buildCRC(sources: List<Int>): List<Int> { var temp = 0x0000FFFF val polynomial = 0x0000A001 sources.forEach { source -> temp = temp xor (source and 0x000000FF) (0 until 8).forEach { if (temp and 0x00000001 != 0) { temp = temp shr 1 temp = temp xor polynomial } else { temp = temp shr 1 } } } //高低位互换,符合士电CRC校验格式 return seperateInt(temp).reversed() } }
1
null
1
1
eea6f216dd64c70ac44d7b1d2826c9abea179e6e
5,127
BleConnector
Apache License 2.0
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/ec2/CfnVerifiedAccessEndpoint.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 142794926}
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package io.cloudshiftdev.awscdk.services.ec2 import io.cloudshiftdev.awscdk.CfnResource import io.cloudshiftdev.awscdk.CfnTag import io.cloudshiftdev.awscdk.IInspectable import io.cloudshiftdev.awscdk.IResolvable import io.cloudshiftdev.awscdk.ITaggable import io.cloudshiftdev.awscdk.TagManager import io.cloudshiftdev.awscdk.TreeInspector import io.cloudshiftdev.awscdk.common.CdkDslMarker import io.cloudshiftdev.awscdk.common.CdkObject import io.cloudshiftdev.awscdk.common.CdkObjectWrappers import kotlin.Any import kotlin.Boolean import kotlin.Number import kotlin.String import kotlin.Unit import kotlin.collections.List import kotlin.jvm.JvmName import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct import software.constructs.Construct as SoftwareConstructsConstruct /** * An AWS Verified Access endpoint specifies the application that AWS Verified Access provides * access to. * * It must be attached to an AWS Verified Access group. An AWS Verified Access endpoint must also * have an attached access policy before you attached it to a group. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.ec2.*; * CfnVerifiedAccessEndpoint cfnVerifiedAccessEndpoint = * CfnVerifiedAccessEndpoint.Builder.create(this, "MyCfnVerifiedAccessEndpoint") * .applicationDomain("applicationDomain") * .attachmentType("attachmentType") * .domainCertificateArn("domainCertificateArn") * .endpointDomainPrefix("endpointDomainPrefix") * .endpointType("endpointType") * .verifiedAccessGroupId("verifiedAccessGroupId") * // the properties below are optional * .description("description") * .loadBalancerOptions(LoadBalancerOptionsProperty.builder() * .loadBalancerArn("loadBalancerArn") * .port(123) * .protocol("protocol") * .subnetIds(List.of("subnetIds")) * .build()) * .networkInterfaceOptions(NetworkInterfaceOptionsProperty.builder() * .networkInterfaceId("networkInterfaceId") * .port(123) * .protocol("protocol") * .build()) * .policyDocument("policyDocument") * .policyEnabled(false) * .securityGroupIds(List.of("securityGroupIds")) * .sseSpecification(SseSpecificationProperty.builder() * .customerManagedKeyEnabled(false) * .kmsKeyArn("kmsKeyArn") * .build()) * .tags(List.of(CfnTag.builder() * .key("key") * .value("value") * .build())) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html) */ public open class CfnVerifiedAccessEndpoint( cdkObject: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint, ) : CfnResource(cdkObject), IInspectable, ITaggable { public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnVerifiedAccessEndpointProps, ) : this(software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap), id, props.let(CfnVerifiedAccessEndpointProps.Companion::unwrap)) ) public constructor( scope: CloudshiftdevConstructsConstruct, id: String, props: CfnVerifiedAccessEndpointProps.Builder.() -> Unit, ) : this(scope, id, CfnVerifiedAccessEndpointProps(props) ) /** * The DNS name for users to reach your application. */ public open fun applicationDomain(): String = unwrap(this).getApplicationDomain() /** * The DNS name for users to reach your application. */ public open fun applicationDomain(`value`: String) { unwrap(this).setApplicationDomain(`value`) } /** * The type of attachment used to provide connectivity between the AWS Verified Access endpoint * and the application. */ public open fun attachmentType(): String = unwrap(this).getAttachmentType() /** * The type of attachment used to provide connectivity between the AWS Verified Access endpoint * and the application. */ public open fun attachmentType(`value`: String) { unwrap(this).setAttachmentType(`value`) } /** * The creation time. */ public open fun attrCreationTime(): String = unwrap(this).getAttrCreationTime() /** * Use this to construct the redirect URI to add to your OIDC provider's allow list. */ public open fun attrDeviceValidationDomain(): String = unwrap(this).getAttrDeviceValidationDomain() /** * The DNS name generated for the endpoint. */ public open fun attrEndpointDomain(): String = unwrap(this).getAttrEndpointDomain() /** * The last updated time. */ public open fun attrLastUpdatedTime(): String = unwrap(this).getAttrLastUpdatedTime() /** * The endpoint status. */ public open fun attrStatus(): String = unwrap(this).getAttrStatus() /** * The ID of the Verified Access endpoint. */ public open fun attrVerifiedAccessEndpointId(): String = unwrap(this).getAttrVerifiedAccessEndpointId() /** * The instance identifier. */ public open fun attrVerifiedAccessInstanceId(): String = unwrap(this).getAttrVerifiedAccessInstanceId() /** * A description for the AWS Verified Access endpoint. */ public open fun description(): String? = unwrap(this).getDescription() /** * A description for the AWS Verified Access endpoint. */ public open fun description(`value`: String) { unwrap(this).setDescription(`value`) } /** * The ARN of a public TLS/SSL certificate imported into or created with ACM. */ public open fun domainCertificateArn(): String = unwrap(this).getDomainCertificateArn() /** * The ARN of a public TLS/SSL certificate imported into or created with ACM. */ public open fun domainCertificateArn(`value`: String) { unwrap(this).setDomainCertificateArn(`value`) } /** * A custom identifier that is prepended to the DNS name that is generated for the endpoint. */ public open fun endpointDomainPrefix(): String = unwrap(this).getEndpointDomainPrefix() /** * A custom identifier that is prepended to the DNS name that is generated for the endpoint. */ public open fun endpointDomainPrefix(`value`: String) { unwrap(this).setEndpointDomainPrefix(`value`) } /** * The type of AWS Verified Access endpoint. */ public open fun endpointType(): String = unwrap(this).getEndpointType() /** * The type of AWS Verified Access endpoint. */ public open fun endpointType(`value`: String) { unwrap(this).setEndpointType(`value`) } /** * Examines the CloudFormation resource and discloses attributes. * * @param inspector tree inspector to collect and process attributes. */ public override fun inspect(inspector: TreeInspector) { unwrap(this).inspect(inspector.let(TreeInspector.Companion::unwrap)) } /** * The load balancer details if creating the AWS Verified Access endpoint as `load-balancer` type. */ public open fun loadBalancerOptions(): Any? = unwrap(this).getLoadBalancerOptions() /** * The load balancer details if creating the AWS Verified Access endpoint as `load-balancer` type. */ public open fun loadBalancerOptions(`value`: IResolvable) { unwrap(this).setLoadBalancerOptions(`value`.let(IResolvable.Companion::unwrap)) } /** * The load balancer details if creating the AWS Verified Access endpoint as `load-balancer` type. */ public open fun loadBalancerOptions(`value`: LoadBalancerOptionsProperty) { unwrap(this).setLoadBalancerOptions(`value`.let(LoadBalancerOptionsProperty.Companion::unwrap)) } /** * The load balancer details if creating the AWS Verified Access endpoint as `load-balancer` type. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("4a124788efaf0789ac8ba6402764765993e15413edebaed50f0fd022ca6528b6") public open fun loadBalancerOptions(`value`: LoadBalancerOptionsProperty.Builder.() -> Unit): Unit = loadBalancerOptions(LoadBalancerOptionsProperty(`value`)) /** * The options for network-interface type endpoint. */ public open fun networkInterfaceOptions(): Any? = unwrap(this).getNetworkInterfaceOptions() /** * The options for network-interface type endpoint. */ public open fun networkInterfaceOptions(`value`: IResolvable) { unwrap(this).setNetworkInterfaceOptions(`value`.let(IResolvable.Companion::unwrap)) } /** * The options for network-interface type endpoint. */ public open fun networkInterfaceOptions(`value`: NetworkInterfaceOptionsProperty) { unwrap(this).setNetworkInterfaceOptions(`value`.let(NetworkInterfaceOptionsProperty.Companion::unwrap)) } /** * The options for network-interface type endpoint. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("b8337e634bb339ea7c0b6c5700f18e57880bbed9f22f8e02d7ce517292a2e577") public open fun networkInterfaceOptions(`value`: NetworkInterfaceOptionsProperty.Builder.() -> Unit): Unit = networkInterfaceOptions(NetworkInterfaceOptionsProperty(`value`)) /** * The Verified Access policy document. */ public open fun policyDocument(): String? = unwrap(this).getPolicyDocument() /** * The Verified Access policy document. */ public open fun policyDocument(`value`: String) { unwrap(this).setPolicyDocument(`value`) } /** * The status of the Verified Access policy. */ public open fun policyEnabled(): Any? = unwrap(this).getPolicyEnabled() /** * The status of the Verified Access policy. */ public open fun policyEnabled(`value`: Boolean) { unwrap(this).setPolicyEnabled(`value`) } /** * The status of the Verified Access policy. */ public open fun policyEnabled(`value`: IResolvable) { unwrap(this).setPolicyEnabled(`value`.let(IResolvable.Companion::unwrap)) } /** * The IDs of the security groups for the endpoint. */ public open fun securityGroupIds(): List<String> = unwrap(this).getSecurityGroupIds() ?: emptyList() /** * The IDs of the security groups for the endpoint. */ public open fun securityGroupIds(`value`: List<String>) { unwrap(this).setSecurityGroupIds(`value`) } /** * The IDs of the security groups for the endpoint. */ public open fun securityGroupIds(vararg `value`: String): Unit = securityGroupIds(`value`.toList()) /** * The options for additional server side encryption. */ public open fun sseSpecification(): Any? = unwrap(this).getSseSpecification() /** * The options for additional server side encryption. */ public open fun sseSpecification(`value`: IResolvable) { unwrap(this).setSseSpecification(`value`.let(IResolvable.Companion::unwrap)) } /** * The options for additional server side encryption. */ public open fun sseSpecification(`value`: SseSpecificationProperty) { unwrap(this).setSseSpecification(`value`.let(SseSpecificationProperty.Companion::unwrap)) } /** * The options for additional server side encryption. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("f32d85d924ae65480defb821300c1182d571b5d5dbd7911712e1ba2c787447ff") public open fun sseSpecification(`value`: SseSpecificationProperty.Builder.() -> Unit): Unit = sseSpecification(SseSpecificationProperty(`value`)) /** * Tag Manager which manages the tags for this resource. */ public override fun tags(): TagManager = unwrap(this).getTags().let(TagManager::wrap) /** * The tags. */ public open fun tagsRaw(): List<CfnTag> = unwrap(this).getTagsRaw()?.map(CfnTag::wrap) ?: emptyList() /** * The tags. */ public open fun tagsRaw(`value`: List<CfnTag>) { unwrap(this).setTagsRaw(`value`.map(CfnTag.Companion::unwrap)) } /** * The tags. */ public open fun tagsRaw(vararg `value`: CfnTag): Unit = tagsRaw(`value`.toList()) /** * The ID of the AWS Verified Access group. */ public open fun verifiedAccessGroupId(): String = unwrap(this).getVerifiedAccessGroupId() /** * The ID of the AWS Verified Access group. */ public open fun verifiedAccessGroupId(`value`: String) { unwrap(this).setVerifiedAccessGroupId(`value`) } /** * A fluent builder for [io.cloudshiftdev.awscdk.services.ec2.CfnVerifiedAccessEndpoint]. */ @CdkDslMarker public interface Builder { /** * The DNS name for users to reach your application. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-applicationdomain) * @param applicationDomain The DNS name for users to reach your application. */ public fun applicationDomain(applicationDomain: String) /** * The type of attachment used to provide connectivity between the AWS Verified Access endpoint * and the application. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-attachmenttype) * @param attachmentType The type of attachment used to provide connectivity between the AWS * Verified Access endpoint and the application. */ public fun attachmentType(attachmentType: String) /** * A description for the AWS Verified Access endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-description) * @param description A description for the AWS Verified Access endpoint. */ public fun description(description: String) /** * The ARN of a public TLS/SSL certificate imported into or created with ACM. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-domaincertificatearn) * @param domainCertificateArn The ARN of a public TLS/SSL certificate imported into or created * with ACM. */ public fun domainCertificateArn(domainCertificateArn: String) /** * A custom identifier that is prepended to the DNS name that is generated for the endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-endpointdomainprefix) * @param endpointDomainPrefix A custom identifier that is prepended to the DNS name that is * generated for the endpoint. */ public fun endpointDomainPrefix(endpointDomainPrefix: String) /** * The type of AWS Verified Access endpoint. * * Incoming application requests will be sent to an IP address, load balancer or a network * interface depending on the endpoint type specified. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-endpointtype) * @param endpointType The type of AWS Verified Access endpoint. */ public fun endpointType(endpointType: String) /** * The load balancer details if creating the AWS Verified Access endpoint as `load-balancer` * type. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions) * @param loadBalancerOptions The load balancer details if creating the AWS Verified Access * endpoint as `load-balancer` type. */ public fun loadBalancerOptions(loadBalancerOptions: IResolvable) /** * The load balancer details if creating the AWS Verified Access endpoint as `load-balancer` * type. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions) * @param loadBalancerOptions The load balancer details if creating the AWS Verified Access * endpoint as `load-balancer` type. */ public fun loadBalancerOptions(loadBalancerOptions: LoadBalancerOptionsProperty) /** * The load balancer details if creating the AWS Verified Access endpoint as `load-balancer` * type. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions) * @param loadBalancerOptions The load balancer details if creating the AWS Verified Access * endpoint as `load-balancer` type. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("143e30768e84ff117f0de95a9204553a81b007de64b519d78dda6c2e926011c5") public fun loadBalancerOptions(loadBalancerOptions: LoadBalancerOptionsProperty.Builder.() -> Unit) /** * The options for network-interface type endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions) * @param networkInterfaceOptions The options for network-interface type endpoint. */ public fun networkInterfaceOptions(networkInterfaceOptions: IResolvable) /** * The options for network-interface type endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions) * @param networkInterfaceOptions The options for network-interface type endpoint. */ public fun networkInterfaceOptions(networkInterfaceOptions: NetworkInterfaceOptionsProperty) /** * The options for network-interface type endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions) * @param networkInterfaceOptions The options for network-interface type endpoint. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("93b2625a3c0c0e0f890aae64cb437a3d456fd501658d5fff8b2c449e92f2d719") public fun networkInterfaceOptions(networkInterfaceOptions: NetworkInterfaceOptionsProperty.Builder.() -> Unit) /** * The Verified Access policy document. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-policydocument) * @param policyDocument The Verified Access policy document. */ public fun policyDocument(policyDocument: String) /** * The status of the Verified Access policy. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-policyenabled) * @param policyEnabled The status of the Verified Access policy. */ public fun policyEnabled(policyEnabled: Boolean) /** * The status of the Verified Access policy. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-policyenabled) * @param policyEnabled The status of the Verified Access policy. */ public fun policyEnabled(policyEnabled: IResolvable) /** * The IDs of the security groups for the endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-securitygroupids) * @param securityGroupIds The IDs of the security groups for the endpoint. */ public fun securityGroupIds(securityGroupIds: List<String>) /** * The IDs of the security groups for the endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-securitygroupids) * @param securityGroupIds The IDs of the security groups for the endpoint. */ public fun securityGroupIds(vararg securityGroupIds: String) /** * The options for additional server side encryption. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-ssespecification) * @param sseSpecification The options for additional server side encryption. */ public fun sseSpecification(sseSpecification: IResolvable) /** * The options for additional server side encryption. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-ssespecification) * @param sseSpecification The options for additional server side encryption. */ public fun sseSpecification(sseSpecification: SseSpecificationProperty) /** * The options for additional server side encryption. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-ssespecification) * @param sseSpecification The options for additional server side encryption. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("90791316987fd26f73cbd2cfebc78c4966a8f66169472336106115aafd42b831") public fun sseSpecification(sseSpecification: SseSpecificationProperty.Builder.() -> Unit) /** * The tags. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-tags) * @param tags The tags. */ public fun tags(tags: List<CfnTag>) /** * The tags. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-tags) * @param tags The tags. */ public fun tags(vararg tags: CfnTag) /** * The ID of the AWS Verified Access group. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-verifiedaccessgroupid) * @param verifiedAccessGroupId The ID of the AWS Verified Access group. */ public fun verifiedAccessGroupId(verifiedAccessGroupId: String) } private class BuilderImpl( scope: SoftwareConstructsConstruct, id: String, ) : Builder { private val cdkBuilder: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.Builder = software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.Builder.create(scope, id) /** * The DNS name for users to reach your application. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-applicationdomain) * @param applicationDomain The DNS name for users to reach your application. */ override fun applicationDomain(applicationDomain: String) { cdkBuilder.applicationDomain(applicationDomain) } /** * The type of attachment used to provide connectivity between the AWS Verified Access endpoint * and the application. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-attachmenttype) * @param attachmentType The type of attachment used to provide connectivity between the AWS * Verified Access endpoint and the application. */ override fun attachmentType(attachmentType: String) { cdkBuilder.attachmentType(attachmentType) } /** * A description for the AWS Verified Access endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-description) * @param description A description for the AWS Verified Access endpoint. */ override fun description(description: String) { cdkBuilder.description(description) } /** * The ARN of a public TLS/SSL certificate imported into or created with ACM. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-domaincertificatearn) * @param domainCertificateArn The ARN of a public TLS/SSL certificate imported into or created * with ACM. */ override fun domainCertificateArn(domainCertificateArn: String) { cdkBuilder.domainCertificateArn(domainCertificateArn) } /** * A custom identifier that is prepended to the DNS name that is generated for the endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-endpointdomainprefix) * @param endpointDomainPrefix A custom identifier that is prepended to the DNS name that is * generated for the endpoint. */ override fun endpointDomainPrefix(endpointDomainPrefix: String) { cdkBuilder.endpointDomainPrefix(endpointDomainPrefix) } /** * The type of AWS Verified Access endpoint. * * Incoming application requests will be sent to an IP address, load balancer or a network * interface depending on the endpoint type specified. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-endpointtype) * @param endpointType The type of AWS Verified Access endpoint. */ override fun endpointType(endpointType: String) { cdkBuilder.endpointType(endpointType) } /** * The load balancer details if creating the AWS Verified Access endpoint as `load-balancer` * type. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions) * @param loadBalancerOptions The load balancer details if creating the AWS Verified Access * endpoint as `load-balancer` type. */ override fun loadBalancerOptions(loadBalancerOptions: IResolvable) { cdkBuilder.loadBalancerOptions(loadBalancerOptions.let(IResolvable.Companion::unwrap)) } /** * The load balancer details if creating the AWS Verified Access endpoint as `load-balancer` * type. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions) * @param loadBalancerOptions The load balancer details if creating the AWS Verified Access * endpoint as `load-balancer` type. */ override fun loadBalancerOptions(loadBalancerOptions: LoadBalancerOptionsProperty) { cdkBuilder.loadBalancerOptions(loadBalancerOptions.let(LoadBalancerOptionsProperty.Companion::unwrap)) } /** * The load balancer details if creating the AWS Verified Access endpoint as `load-balancer` * type. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions) * @param loadBalancerOptions The load balancer details if creating the AWS Verified Access * endpoint as `load-balancer` type. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("143e30768e84ff117f0de95a9204553a81b007de64b519d78dda6c2e926011c5") override fun loadBalancerOptions(loadBalancerOptions: LoadBalancerOptionsProperty.Builder.() -> Unit): Unit = loadBalancerOptions(LoadBalancerOptionsProperty(loadBalancerOptions)) /** * The options for network-interface type endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions) * @param networkInterfaceOptions The options for network-interface type endpoint. */ override fun networkInterfaceOptions(networkInterfaceOptions: IResolvable) { cdkBuilder.networkInterfaceOptions(networkInterfaceOptions.let(IResolvable.Companion::unwrap)) } /** * The options for network-interface type endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions) * @param networkInterfaceOptions The options for network-interface type endpoint. */ override fun networkInterfaceOptions(networkInterfaceOptions: NetworkInterfaceOptionsProperty) { cdkBuilder.networkInterfaceOptions(networkInterfaceOptions.let(NetworkInterfaceOptionsProperty.Companion::unwrap)) } /** * The options for network-interface type endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions) * @param networkInterfaceOptions The options for network-interface type endpoint. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("93b2625a3c0c0e0f890aae64cb437a3d456fd501658d5fff8b2c449e92f2d719") override fun networkInterfaceOptions(networkInterfaceOptions: NetworkInterfaceOptionsProperty.Builder.() -> Unit): Unit = networkInterfaceOptions(NetworkInterfaceOptionsProperty(networkInterfaceOptions)) /** * The Verified Access policy document. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-policydocument) * @param policyDocument The Verified Access policy document. */ override fun policyDocument(policyDocument: String) { cdkBuilder.policyDocument(policyDocument) } /** * The status of the Verified Access policy. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-policyenabled) * @param policyEnabled The status of the Verified Access policy. */ override fun policyEnabled(policyEnabled: Boolean) { cdkBuilder.policyEnabled(policyEnabled) } /** * The status of the Verified Access policy. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-policyenabled) * @param policyEnabled The status of the Verified Access policy. */ override fun policyEnabled(policyEnabled: IResolvable) { cdkBuilder.policyEnabled(policyEnabled.let(IResolvable.Companion::unwrap)) } /** * The IDs of the security groups for the endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-securitygroupids) * @param securityGroupIds The IDs of the security groups for the endpoint. */ override fun securityGroupIds(securityGroupIds: List<String>) { cdkBuilder.securityGroupIds(securityGroupIds) } /** * The IDs of the security groups for the endpoint. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-securitygroupids) * @param securityGroupIds The IDs of the security groups for the endpoint. */ override fun securityGroupIds(vararg securityGroupIds: String): Unit = securityGroupIds(securityGroupIds.toList()) /** * The options for additional server side encryption. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-ssespecification) * @param sseSpecification The options for additional server side encryption. */ override fun sseSpecification(sseSpecification: IResolvable) { cdkBuilder.sseSpecification(sseSpecification.let(IResolvable.Companion::unwrap)) } /** * The options for additional server side encryption. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-ssespecification) * @param sseSpecification The options for additional server side encryption. */ override fun sseSpecification(sseSpecification: SseSpecificationProperty) { cdkBuilder.sseSpecification(sseSpecification.let(SseSpecificationProperty.Companion::unwrap)) } /** * The options for additional server side encryption. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-ssespecification) * @param sseSpecification The options for additional server side encryption. */ @kotlin.Suppress("INAPPLICABLE_JVM_NAME") @JvmName("90791316987fd26f73cbd2cfebc78c4966a8f66169472336106115aafd42b831") override fun sseSpecification(sseSpecification: SseSpecificationProperty.Builder.() -> Unit): Unit = sseSpecification(SseSpecificationProperty(sseSpecification)) /** * The tags. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-tags) * @param tags The tags. */ override fun tags(tags: List<CfnTag>) { cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap)) } /** * The tags. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-tags) * @param tags The tags. */ override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList()) /** * The ID of the AWS Verified Access group. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-verifiedaccessendpoint.html#cfn-ec2-verifiedaccessendpoint-verifiedaccessgroupid) * @param verifiedAccessGroupId The ID of the AWS Verified Access group. */ override fun verifiedAccessGroupId(verifiedAccessGroupId: String) { cdkBuilder.verifiedAccessGroupId(verifiedAccessGroupId) } public fun build(): software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint = cdkBuilder.build() } public companion object { public val CFN_RESOURCE_TYPE_NAME: String = software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.CFN_RESOURCE_TYPE_NAME public operator fun invoke( scope: CloudshiftdevConstructsConstruct, id: String, block: Builder.() -> Unit = {}, ): CfnVerifiedAccessEndpoint { val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id) return CfnVerifiedAccessEndpoint(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint): CfnVerifiedAccessEndpoint = CfnVerifiedAccessEndpoint(cdkObject) internal fun unwrap(wrapped: CfnVerifiedAccessEndpoint): software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint = wrapped.cdkObject as software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint } /** * Describes the load balancer options when creating an AWS Verified Access endpoint using the * `load-balancer` type. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.ec2.*; * LoadBalancerOptionsProperty loadBalancerOptionsProperty = LoadBalancerOptionsProperty.builder() * .loadBalancerArn("loadBalancerArn") * .port(123) * .protocol("protocol") * .subnetIds(List.of("subnetIds")) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-loadbalanceroptions.html) */ public interface LoadBalancerOptionsProperty { /** * The ARN of the load balancer. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-loadbalanceroptions.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions-loadbalancerarn) */ public fun loadBalancerArn(): String? = unwrap(this).getLoadBalancerArn() /** * The IP port number. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-loadbalanceroptions.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions-port) */ public fun port(): Number? = unwrap(this).getPort() /** * The IP protocol. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-loadbalanceroptions.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions-protocol) */ public fun protocol(): String? = unwrap(this).getProtocol() /** * The IDs of the subnets. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-loadbalanceroptions.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions-subnetids) */ public fun subnetIds(): List<String> = unwrap(this).getSubnetIds() ?: emptyList() /** * A builder for [LoadBalancerOptionsProperty] */ @CdkDslMarker public interface Builder { /** * @param loadBalancerArn The ARN of the load balancer. */ public fun loadBalancerArn(loadBalancerArn: String) /** * @param port The IP port number. */ public fun port(port: Number) /** * @param protocol The IP protocol. */ public fun protocol(protocol: String) /** * @param subnetIds The IDs of the subnets. */ public fun subnetIds(subnetIds: List<String>) /** * @param subnetIds The IDs of the subnets. */ public fun subnetIds(vararg subnetIds: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.LoadBalancerOptionsProperty.Builder = software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.LoadBalancerOptionsProperty.builder() /** * @param loadBalancerArn The ARN of the load balancer. */ override fun loadBalancerArn(loadBalancerArn: String) { cdkBuilder.loadBalancerArn(loadBalancerArn) } /** * @param port The IP port number. */ override fun port(port: Number) { cdkBuilder.port(port) } /** * @param protocol The IP protocol. */ override fun protocol(protocol: String) { cdkBuilder.protocol(protocol) } /** * @param subnetIds The IDs of the subnets. */ override fun subnetIds(subnetIds: List<String>) { cdkBuilder.subnetIds(subnetIds) } /** * @param subnetIds The IDs of the subnets. */ override fun subnetIds(vararg subnetIds: String): Unit = subnetIds(subnetIds.toList()) public fun build(): software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.LoadBalancerOptionsProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.LoadBalancerOptionsProperty, ) : CdkObject(cdkObject), LoadBalancerOptionsProperty { /** * The ARN of the load balancer. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-loadbalanceroptions.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions-loadbalancerarn) */ override fun loadBalancerArn(): String? = unwrap(this).getLoadBalancerArn() /** * The IP port number. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-loadbalanceroptions.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions-port) */ override fun port(): Number? = unwrap(this).getPort() /** * The IP protocol. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-loadbalanceroptions.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions-protocol) */ override fun protocol(): String? = unwrap(this).getProtocol() /** * The IDs of the subnets. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-loadbalanceroptions.html#cfn-ec2-verifiedaccessendpoint-loadbalanceroptions-subnetids) */ override fun subnetIds(): List<String> = unwrap(this).getSubnetIds() ?: emptyList() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): LoadBalancerOptionsProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.LoadBalancerOptionsProperty): LoadBalancerOptionsProperty = CdkObjectWrappers.wrap(cdkObject) as? LoadBalancerOptionsProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: LoadBalancerOptionsProperty): software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.LoadBalancerOptionsProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.LoadBalancerOptionsProperty } } /** * Describes the network interface options when creating an AWS Verified Access endpoint using the * `network-interface` type. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.ec2.*; * NetworkInterfaceOptionsProperty networkInterfaceOptionsProperty = * NetworkInterfaceOptionsProperty.builder() * .networkInterfaceId("networkInterfaceId") * .port(123) * .protocol("protocol") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-networkinterfaceoptions.html) */ public interface NetworkInterfaceOptionsProperty { /** * The ID of the network interface. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-networkinterfaceoptions.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions-networkinterfaceid) */ public fun networkInterfaceId(): String? = unwrap(this).getNetworkInterfaceId() /** * The IP port number. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-networkinterfaceoptions.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions-port) */ public fun port(): Number? = unwrap(this).getPort() /** * The IP protocol. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-networkinterfaceoptions.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions-protocol) */ public fun protocol(): String? = unwrap(this).getProtocol() /** * A builder for [NetworkInterfaceOptionsProperty] */ @CdkDslMarker public interface Builder { /** * @param networkInterfaceId The ID of the network interface. */ public fun networkInterfaceId(networkInterfaceId: String) /** * @param port The IP port number. */ public fun port(port: Number) /** * @param protocol The IP protocol. */ public fun protocol(protocol: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.NetworkInterfaceOptionsProperty.Builder = software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.NetworkInterfaceOptionsProperty.builder() /** * @param networkInterfaceId The ID of the network interface. */ override fun networkInterfaceId(networkInterfaceId: String) { cdkBuilder.networkInterfaceId(networkInterfaceId) } /** * @param port The IP port number. */ override fun port(port: Number) { cdkBuilder.port(port) } /** * @param protocol The IP protocol. */ override fun protocol(protocol: String) { cdkBuilder.protocol(protocol) } public fun build(): software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.NetworkInterfaceOptionsProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.NetworkInterfaceOptionsProperty, ) : CdkObject(cdkObject), NetworkInterfaceOptionsProperty { /** * The ID of the network interface. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-networkinterfaceoptions.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions-networkinterfaceid) */ override fun networkInterfaceId(): String? = unwrap(this).getNetworkInterfaceId() /** * The IP port number. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-networkinterfaceoptions.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions-port) */ override fun port(): Number? = unwrap(this).getPort() /** * The IP protocol. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-networkinterfaceoptions.html#cfn-ec2-verifiedaccessendpoint-networkinterfaceoptions-protocol) */ override fun protocol(): String? = unwrap(this).getProtocol() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): NetworkInterfaceOptionsProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.NetworkInterfaceOptionsProperty): NetworkInterfaceOptionsProperty = CdkObjectWrappers.wrap(cdkObject) as? NetworkInterfaceOptionsProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: NetworkInterfaceOptionsProperty): software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.NetworkInterfaceOptionsProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.NetworkInterfaceOptionsProperty } } /** * AWS Verified Access provides server side encryption by default to data at rest using AWS -owned * KMS keys. * * You also have the option of using customer managed KMS keys, which can be specified using the * options below. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import io.cloudshiftdev.awscdk.services.ec2.*; * SseSpecificationProperty sseSpecificationProperty = SseSpecificationProperty.builder() * .customerManagedKeyEnabled(false) * .kmsKeyArn("kmsKeyArn") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-ssespecification.html) */ public interface SseSpecificationProperty { /** * Enable or disable the use of customer managed KMS keys for server side encryption. * * Valid values: `True` | `False` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-ssespecification.html#cfn-ec2-verifiedaccessendpoint-ssespecification-customermanagedkeyenabled) */ public fun customerManagedKeyEnabled(): Any? = unwrap(this).getCustomerManagedKeyEnabled() /** * The ARN of the KMS key. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-ssespecification.html#cfn-ec2-verifiedaccessendpoint-ssespecification-kmskeyarn) */ public fun kmsKeyArn(): String? = unwrap(this).getKmsKeyArn() /** * A builder for [SseSpecificationProperty] */ @CdkDslMarker public interface Builder { /** * @param customerManagedKeyEnabled Enable or disable the use of customer managed KMS keys for * server side encryption. * Valid values: `True` | `False` */ public fun customerManagedKeyEnabled(customerManagedKeyEnabled: Boolean) /** * @param customerManagedKeyEnabled Enable or disable the use of customer managed KMS keys for * server side encryption. * Valid values: `True` | `False` */ public fun customerManagedKeyEnabled(customerManagedKeyEnabled: IResolvable) /** * @param kmsKeyArn The ARN of the KMS key. */ public fun kmsKeyArn(kmsKeyArn: String) } private class BuilderImpl : Builder { private val cdkBuilder: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.SseSpecificationProperty.Builder = software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.SseSpecificationProperty.builder() /** * @param customerManagedKeyEnabled Enable or disable the use of customer managed KMS keys for * server side encryption. * Valid values: `True` | `False` */ override fun customerManagedKeyEnabled(customerManagedKeyEnabled: Boolean) { cdkBuilder.customerManagedKeyEnabled(customerManagedKeyEnabled) } /** * @param customerManagedKeyEnabled Enable or disable the use of customer managed KMS keys for * server side encryption. * Valid values: `True` | `False` */ override fun customerManagedKeyEnabled(customerManagedKeyEnabled: IResolvable) { cdkBuilder.customerManagedKeyEnabled(customerManagedKeyEnabled.let(IResolvable.Companion::unwrap)) } /** * @param kmsKeyArn The ARN of the KMS key. */ override fun kmsKeyArn(kmsKeyArn: String) { cdkBuilder.kmsKeyArn(kmsKeyArn) } public fun build(): software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.SseSpecificationProperty = cdkBuilder.build() } private class Wrapper( cdkObject: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.SseSpecificationProperty, ) : CdkObject(cdkObject), SseSpecificationProperty { /** * Enable or disable the use of customer managed KMS keys for server side encryption. * * Valid values: `True` | `False` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-ssespecification.html#cfn-ec2-verifiedaccessendpoint-ssespecification-customermanagedkeyenabled) */ override fun customerManagedKeyEnabled(): Any? = unwrap(this).getCustomerManagedKeyEnabled() /** * The ARN of the KMS key. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-verifiedaccessendpoint-ssespecification.html#cfn-ec2-verifiedaccessendpoint-ssespecification-kmskeyarn) */ override fun kmsKeyArn(): String? = unwrap(this).getKmsKeyArn() } public companion object { public operator fun invoke(block: Builder.() -> Unit = {}): SseSpecificationProperty { val builderImpl = BuilderImpl() return Wrapper(builderImpl.apply(block).build()) } internal fun wrap(cdkObject: software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.SseSpecificationProperty): SseSpecificationProperty = CdkObjectWrappers.wrap(cdkObject) as? SseSpecificationProperty ?: Wrapper(cdkObject) internal fun unwrap(wrapped: SseSpecificationProperty): software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.SseSpecificationProperty = (wrapped as CdkObject).cdkObject as software.amazon.awscdk.services.ec2.CfnVerifiedAccessEndpoint.SseSpecificationProperty } } }
1
Kotlin
0
4
ddf2bfd2275b50bb86a667c4298dd92f59d7e342
54,083
kotlin-cdk-wrapper
Apache License 2.0
src/jvmMain/kotlin/layouts/ui/sections/GroupSection.kt
N7ghtm4r3
710,292,647
false
{"Kotlin": 279232}
package layouts.ui.sections import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.tecknobit.pandoro.helpers.ui.SingleItemManager import com.tecknobit.pandoro.records.Group import com.tecknobit.pandoro.records.users.GroupMember import com.tecknobit.pandoro.records.users.GroupMember.InvitationStatus.PENDING import com.tecknobit.pandoro.records.users.GroupMember.Role import com.tecknobit.pandoro.records.users.GroupMember.Role.ADMIN import helpers.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import layouts.components.LeaveGroup import layouts.components.RemoveUser import layouts.ui.screens.Home.Companion.activeScreen import layouts.ui.screens.Home.Companion.currentGroup import layouts.ui.screens.Home.Companion.showEditProjectGroupPopup import layouts.ui.screens.SplashScreen.Companion.requester import layouts.ui.screens.SplashScreen.Companion.user import layouts.ui.sections.ProfileSection.Companion.hideLeaveGroup import org.json.JSONException import kotlin.math.ceil /** * This is the layout for the group section * * @author Tecknobit - N7ghtm4r3 * @see Section * @see SingleItemManager */ class GroupSection : Section(), SingleItemManager { /** * Function to show the content of the [GroupSection] * * No-any params required */ @OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class) @Composable override fun showSection() { val isCurrentUserAnAdmin = currentGroup.value.isUserAdmin(user) val authorId = currentGroup.value.author.id val isCurrentUserAMaintainer = currentGroup.value.isUserMaintainer(user) refreshItem() showSection { LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(10.dp), verticalArrangement = Arrangement.spacedBy(12.dp) ) { stickyHeader { Row( modifier = Modifier.fillParentMaxWidth().background(BACKGROUND_COLOR), verticalAlignment = Alignment.CenterVertically ) { IconButton( onClick = { navBack() } ) { Icon( modifier = Modifier.size(22.dp), imageVector = Icons.Default.ArrowBack, contentDescription = null ) } Text( text = currentGroup.value.name, fontSize = 25.sp ) } } item { Column( modifier = Modifier.padding(start = 20.dp, end = 20.dp) ) { Text( modifier = Modifier.padding(top = 5.dp), text = "Author: ${currentGroup.value.author.completeName}", textAlign = TextAlign.Justify, fontSize = 20.sp ) Text( modifier = Modifier.padding(top = 5.dp), text = currentGroup.value.description, textAlign = TextAlign.Justify, fontSize = 14.sp ) spaceContent() var showMembersSection by remember { mutableStateOf(true) } var showMembersIcon by remember { mutableStateOf(Icons.Default.VisibilityOff) } Row( modifier = Modifier.fillMaxWidth().padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = "Members", fontSize = 20.sp ) IconButton( onClick = { showMembersSection = !showMembersSection showMembersIcon = if (showMembersSection) Icons.Default.VisibilityOff else Icons.Default.Visibility } ) { Icon( imageVector = showMembersIcon, contentDescription = null ) } } if (showMembersSection) { val members = mutableListOf<GroupMember>() members.addAll(currentGroup.value.members) if (!isCurrentUserAMaintainer) { val membersToHide = mutableListOf<GroupMember>() members.forEach { member -> if (member.invitationStatus == PENDING) membersToHide.add(member) } members.removeAll(membersToHide) } val totalMembers = members.size Text( modifier = Modifier.padding(top = 10.dp), text = "Total members: $totalMembers", fontSize = 14.sp ) if (members.isNotEmpty()) { spaceContent() LazyVerticalGrid( columns = GridCells.Fixed(3), modifier = Modifier.height( if (totalMembers < 3) 90.dp else if (totalMembers <= 15) (ceil(totalMembers / 3.toFloat()) * 90).dp else 400.dp ), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), contentPadding = PaddingValues( top = 20.dp, start = 10.dp, bottom = 10.dp, end = 10.dp ) ) { items( items = members, key = { member -> member.id } ) { member -> val isMemberPending = member.invitationStatus == PENDING if ((isCurrentUserAMaintainer && isMemberPending) || !isMemberPending) { Card( modifier = Modifier.fillMaxWidth().height(65.dp), backgroundColor = Color.White, shape = RoundedCornerShape(10.dp), elevation = 2.dp ) { Row( modifier = Modifier.padding( start = 20.dp, top = 10.dp, end = 20.dp, bottom = 10.dp ), verticalAlignment = Alignment.CenterVertically ) { Image( modifier = Modifier.size(45.dp).clip(CircleShape), bitmap = loadImageBitmap(member.profilePic), contentDescription = null, contentScale = ContentScale.Crop ) Text( modifier = Modifier.padding(start = 20.dp), text = member.completeName, fontSize = 18.sp ) var modifier = Modifier.padding(start = 20.dp) if (!member.isLoggedUser(user) && isCurrentUserAMaintainer && !isMemberPending && member.id != authorId ) { var showRoleMenu by remember { mutableStateOf(false) } if (isCurrentUserAnAdmin || !member.isAdmin) { modifier = modifier.clickable { showRoleMenu = true } } DropdownMenu( modifier = Modifier.background(BACKGROUND_COLOR), expanded = showRoleMenu, onDismissRequest = { showRoleMenu = false }, offset = DpOffset(150.dp, 0.dp) ) { Role.values().forEach { role -> DropdownMenuItem( onClick = { requester!!.execChangeMemberRole( currentGroup.value.id, member.id, role ) if (requester!!.successResponse()) showRoleMenu = false else showSnack(requester!!.errorMessage()) } ) { Text( text = role.toString(), color = if (role == ADMIN) RED_COLOR else PRIMARY_COLOR ) } } } } Text( modifier = modifier, text = if (isMemberPending) PENDING.toString() else member.role.toString(), textAlign = TextAlign.Center, color = if (member.role == ADMIN) RED_COLOR else { if (isMemberPending) YELLOW_COLOR else PRIMARY_COLOR } ) if (!member.isLoggedUser(user) && isCurrentUserAMaintainer && member.id != authorId ) { val showRemoveDialog = mutableStateOf(false) if (isCurrentUserAnAdmin || !member.isAdmin) { Column( modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.End ) { IconButton( onClick = { showRemoveDialog.value = true } ) { Icon( imageVector = Icons.Default.GroupRemove, contentDescription = null ) } } } RemoveUser( show = showRemoveDialog, group = currentGroup.value, memberId = member.id ) } } } } } } } } spaceContent() val projects = currentGroup.value.projects val areProjectsEmpty = projects.isEmpty() if (!areProjectsEmpty || isCurrentUserAnAdmin) { var showProjectsSection by remember { mutableStateOf(true) } var showProjectsIcon by remember { mutableStateOf(Icons.Default.VisibilityOff) } Row( modifier = Modifier.fillMaxWidth().padding(top = 10.dp), verticalAlignment = Alignment.CenterVertically ) { Text( text = "Projects", fontSize = 20.sp ) IconButton( onClick = { showProjectsSection = !showProjectsSection showProjectsIcon = if (showProjectsSection) Icons.Default.VisibilityOff else Icons.Default.Visibility } ) { Icon( imageVector = showProjectsIcon, contentDescription = null ) } if (showProjectsSection && isCurrentUserAnAdmin && user.projects.isNotEmpty()) { IconButton( onClick = { showEditProjectGroupPopup.value = true } ) { Icon( imageVector = Icons.Default.ModeEditOutline, contentDescription = null ) } } } if (showProjectsSection) { Text( modifier = Modifier.padding(top = 10.dp), text = "Projects number: ${projects.size}", fontSize = 14.sp ) spaceContent() if (!areProjectsEmpty) { LazyVerticalGrid( modifier = Modifier .padding(top = 20.dp) .height(50.dp), columns = GridCells.Adaptive(100.dp), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), contentPadding = PaddingValues(start = 10.dp, end = 10.dp) ) { items( items = projects, key = { project -> project.id } ) { project -> Card( modifier = Modifier.fillMaxWidth().height(40.dp), shape = RoundedCornerShape(15), backgroundColor = Color.White, elevation = 2.dp, onClick = { navToProject(Sections.Group, project) }, ) { Column( modifier = Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = project.name, fontSize = 14.sp ) } Column( modifier = Modifier.weight(1f).fillMaxHeight(), horizontalAlignment = Alignment.End, verticalArrangement = Arrangement.Center ) { Box( modifier = Modifier.background(PRIMARY_COLOR).fillMaxHeight() .width(3.dp) ) } } } } spaceContent() } } } } } if (!hideLeaveGroup) { item { val showLeaveDialog = mutableStateOf(false) Column( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.CenterHorizontally ) { TextButton( modifier = Modifier.fillMaxSize(), onClick = { showLeaveDialog.value = true } ) { Text( modifier = Modifier.wrapContentSize(), text = "Leave group", color = RED_COLOR, textAlign = TextAlign.Center ) } } LeaveGroup( show = showLeaveDialog, group = currentGroup.value, ) } } } } } /** * Function to refresh an item to display in the UI * * No-any params required */ override fun refreshItem() { CoroutineScope(Dispatchers.Default).launch { while (user.id != null && activeScreen.value == Sections.Group) { try { val response = requester!!.execGetSingleGroup(currentGroup.value.id) if (requester!!.successResponse()) { val tmpGroup = Group(response) if (needToRefresh(currentGroup.value, tmpGroup)) currentGroup.value = tmpGroup } } catch (_: JSONException) { } delay(1000) } } } }
0
Kotlin
0
0
a308833f42d6b795ea0787d05188e1b6a685cedf
24,991
Pandoro-Desktop
MIT License
src/main/kotlin/TEMP.kt
TeamVoided
737,359,498
false
{"Kotlin": 871908, "Java": 13546}
//// //// Source code recreated from a .class file by IntelliJ IDEA //// (powered by FernFlower decompiler) //// //package net.minecraft.entity.projectile // //import net.minecraft.enchantment.EnchantmentHelper //import net.minecraft.entity.EntityType //import net.minecraft.entity.EquipmentSlot //import net.minecraft.entity.LivingEntity //import net.minecraft.entity.data.DataTracker //import net.minecraft.entity.data.TrackedData //import net.minecraft.entity.data.TrackedDataHandlerRegistry //import net.minecraft.entity.player.PlayerEntity //import net.minecraft.item.Item //import net.minecraft.item.ItemStack //import net.minecraft.item.Items //import net.minecraft.nbt.NbtCompound //import net.minecraft.server.network.ServerPlayerEntity //import net.minecraft.server.world.ServerWorld //import net.minecraft.sound.SoundEvent //import net.minecraft.sound.SoundEvents //import net.minecraft.util.hit.BlockHitResult //import net.minecraft.util.hit.EntityHitResult //import net.minecraft.util.math.MathHelper //import net.minecraft.util.math.Vec3d //import net.minecraft.world.World // //class TridentEntity : PersistentProjectileEntity { // private var dealtDamage = false // var returnTimer: Int = 0 // // constructor(entityType: EntityType<out TridentEntity?>?, world: World?) : super(entityType, world) // // constructor(world: World?, owner: LivingEntity?, stack: ItemStack) : super( // EntityType.TRIDENT, // owner, // world, // stack, // null as ItemStack? // ) { // dataTracker.set(LOYALTY, this.method_59960(stack)) // dataTracker.set(ENCHANTED, stack.hasGlint()) // } // // constructor(world: World?, d: Double, e: Double, f: Double, stack: ItemStack) : super( // EntityType.TRIDENT, // d, // e, // f, // world, // stack, // stack // ) { // dataTracker.set(LOYALTY, this.method_59960(stack)) // dataTracker.set(ENCHANTED, stack.hasGlint()) // } // // override fun initDataTracker(builder: DataTracker.Builder) { // super.initDataTracker(builder) // builder.add(LOYALTY, 0.toByte()) // builder.add(ENCHANTED, false) // } // // override fun tick() { // if (this.inGroundTime > 4) { // this.dealtDamage = true // } // // val entity = this.owner // val i = (dataTracker.get(LOYALTY) as Byte).toInt() // if (i > 0 && (this.dealtDamage || this.isNoClip) && entity != null) { // if (!this.isOwnerAlive) { // if (!world.isClient && this.pickupType == PickupPermission.ALLOWED) { // this.dropStack(this.asItemStack(), 0.1f) // } // // this.discard() // } else { // this.isNoClip = true // val vec3d = entity.eyePos.subtract(this.pos) // this.setPos(this.x, this.y + vec3d.y * 0.015 * (i.toDouble()), this.z) // if (world.isClient) { // this.lastRenderY = this.y // } // // val d = 0.05 * i.toDouble() // this.velocity = velocity.multiply(0.95).add(vec3d.normalize().multiply(d)) // if (this.returnTimer == 0) { // this.playSound(SoundEvents.ITEM_TRIDENT_RETURN, 10.0f, 1.0f) // } // // ++this.returnTimer // } // } // // super.tick() // } // // private val isOwnerAlive: Boolean // get() { // val entity = this.owner // return if (entity != null && entity.isAlive) { // entity !is ServerPlayerEntity || !entity.isSpectator() // } else { // false // } // } // // val isEnchanted: Boolean // get() = dataTracker.get(ENCHANTED) as Boolean // // override fun getEntityCollision(currentPosition: Vec3d, nextPosition: Vec3d): EntityHitResult? { // return if (this.dealtDamage) null else super.getEntityCollision(currentPosition, nextPosition) // } // // override fun onEntityHit(entityHitResult: EntityHitResult) { // val entity = entityHitResult.entity // var f = 8.0f // val entity2 = this.owner // val damageSource = this.damageSources.trident( // this, (entity2 // ?: this) // ) // var var7 = this.world // if (var7 is ServerWorld) { // f = EnchantmentHelper.getDamage(var7, this.method_59958(), entity, damageSource, f) // } // // this.dealtDamage = true // if (entity.damage(damageSource, f)) { // if (entity.type === EntityType.ENDERMAN) { // return // } // // var7 = this.world // if (var7 is ServerWorld) { // serverWorld = var7 // EnchantmentHelper.onEntityHitWithItem(serverWorld, entity, damageSource, this.method_59958()) // } // // if (entity is LivingEntity) { // val livingEntity = entity // this.method_59957(livingEntity, damageSource) // this.onHit(livingEntity) // } // } // // this.velocity = velocity.multiply(-0.01, -0.1, -0.01) // this.playSound(SoundEvents.ITEM_TRIDENT_HIT, 1.0f, 1.0f) // } // // override fun method_59956(world: ServerWorld, result: BlockHitResult, stack: ItemStack) { // val vec3d = result.blockPos.method_60913(result.pos) // val var6 = this.owner // val var10002 = if (var6 is LivingEntity) { // var6 // } else { // null // } // // EnchantmentHelper.onHitBlock( // world, stack, var10002, this, null as EquipmentSlot?, vec3d, world.getBlockState(result.blockPos) // ) { item: Item? -> // this.kill() // } // } // // override fun method_59958(): ItemStack? { // return this.stack // } // // override fun tryPickup(player: PlayerEntity): Boolean { // return super.tryPickup(player) || this.isNoClip && this.isOwner(player) && player.inventory.insertStack(this.asItemStack()) // } // // override fun getDefaultItemStack(): ItemStack { // return ItemStack(Items.TRIDENT) // } // // override fun getHitSound(): SoundEvent { // return SoundEvents.ITEM_TRIDENT_HIT_GROUND // } // // override fun onPlayerCollision(player: PlayerEntity) { // if (this.isOwner(player) || this.owner == null) { // super.onPlayerCollision(player) // } // } // // override fun readCustomDataFromNbt(nbt: NbtCompound) { // super.readCustomDataFromNbt(nbt) // this.dealtDamage = nbt.getBoolean("DealtDamage") // dataTracker.set(LOYALTY, this.method_59960(this.stack)) // } // // override fun writeCustomDataToNbt(nbt: NbtCompound) { // super.writeCustomDataToNbt(nbt) // nbt.putBoolean("DealtDamage", this.dealtDamage) // } // // private fun method_59960(stack: ItemStack): Byte { // val var3 = this.world // return if (var3 is ServerWorld) { // MathHelper.clamp(EnchantmentHelper.getTridentReturnAcceleration(var3, stack, this), 0, 127).toByte() // } else { // 0 // } // } // // public override fun age() { // val i = (dataTracker.get(LOYALTY) as Byte).toInt() // if (this.pickupType != PickupPermission.ALLOWED || i <= 0) { // super.age() // } // } // // override fun getDragInWater(): Float { // return 0.99f // } // // override fun shouldRender(cameraX: Double, cameraY: Double, cameraZ: Double): Boolean { // return true // } // // companion object { // private val LOYALTY: TrackedData<Byte> = // DataTracker.registerData(TridentEntity::class.java, TrackedDataHandlerRegistry.BYTE) // private val ENCHANTED: TrackedData<Boolean> = DataTracker.registerData( // TridentEntity::class.java, TrackedDataHandlerRegistry.BOOLEAN // ) // } //}
0
Kotlin
0
0
1c5e4407343aabc6ed97548ff127111bd4a9b028
8,094
DusksAndDungeons
MIT License
domain/news/src/main/java/ir/kaaveh/domain/model/Resource.kt
Kaaveh
576,928,671
false
null
package ir.composenews.domain.model sealed class Resource<T>( val data: T? = null, val exception: Exception? = null, ) { class Success<T>(data: T) : Resource<T>(data) class Error<T>(exception: Exception, data: T? = null) : Resource<T>(data, exception) }
4
Kotlin
5
32
21f26e68421560767f48d3825cc3dcbbe432787f
271
ComposeNews
Apache License 2.0
client_end_user/shared/src/commonMain/kotlin/presentation/pickLanguage/PickLanguageScreen.kt
TheChance101
671,967,732
false
{"Kotlin": 2473455, "Ruby": 8872, "HTML": 6083, "Swift": 4726, "JavaScript": 3082, "CSS": 1436, "Dockerfile": 1407, "Shell": 1140}
package presentation.pickLanguage import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp import cafe.adriel.voyager.navigator.Navigator import com.angus.designSystem.ui.theme.Theme import org.jetbrains.compose.resources.ExperimentalResourceApi import org.jetbrains.compose.resources.painterResource import presentation.base.BaseScreen import presentation.composable.LanguageCard import presentation.composable.HeadFirstCard import presentation.main.MainContainer import resources.Resources object PickLanguageScreen : BaseScreen<PickLanguageScreenModel, PickLanguageUIState, PickLanguageUIEffect, PickLanguageInteractionListener>() { @Composable override fun Content() { initScreen(getScreenModel()) } override fun onEffect(effect: PickLanguageUIEffect, navigator: Navigator) { when (effect) { is PickLanguageUIEffect.onGoToPreferredLanguage -> navigator.replaceAll(MainContainer) } } @OptIn(ExperimentalResourceApi::class) @Composable override fun onRender(state: PickLanguageUIState, listener: PickLanguageInteractionListener) { Box( modifier = Modifier.fillMaxSize().background(Theme.colors.background), contentAlignment = Alignment.Center ) { Image( modifier = Modifier.fillMaxSize(), painter = painterResource(Resources.images.backgroundPattern), contentDescription = Resources.strings.backgroundDescription, contentScale = ContentScale.Crop ) HeadFirstCard( textHeader = Resources.strings.languageAskAboutLanguage, textSubHeader = Resources.strings.selectLanguage ) { LazyVerticalGrid( contentPadding = PaddingValues(top = 16.dp), columns = GridCells.Adaptive(140.dp), horizontalArrangement = Arrangement.spacedBy(16.dp), verticalArrangement = Arrangement.spacedBy(16.dp), ) { items(state.languages.size) { index -> LanguageCard( state = state.languages[index], onClick = { listener.onLanguageSelected(state.languages[index]) } ) } } } } } }
4
Kotlin
55
572
1d2e72ba7def605529213ac771cd85cbab832241
2,966
beep-beep
Apache License 2.0
src/app/api/src/main/kotlin/yapp/be/apiapplication/system/security/resolver/ShelterUserAuthenticationInfoArgumentResolver.kt
YAPP-Github
634,126,325
false
null
package yapp.be.apiapplication.system.security.resolver import org.springframework.context.annotation.Configuration import org.springframework.core.MethodParameter import org.springframework.security.core.context.SecurityContextHolder import org.springframework.web.bind.support.WebDataBinderFactory import org.springframework.web.context.request.NativeWebRequest import org.springframework.web.method.support.HandlerMethodArgumentResolver import org.springframework.web.method.support.ModelAndViewContainer import yapp.be.apiapplication.system.security.CustomUserDetails import yapp.be.model.vo.Email @Configuration class ShelterUserAuthenticationInfoArgumentResolver : HandlerMethodArgumentResolver { override fun supportsParameter(parameter: MethodParameter): Boolean { return parameter.getParameterAnnotation(ShelterUserAuthentication::class.java) != null && parameter.parameterType == ShelterUserAuthenticationInfo::class.java } override fun resolveArgument( parameter: MethodParameter, mavContainer: ModelAndViewContainer?, webRequest: NativeWebRequest, binderFactory: WebDataBinderFactory? ): Any { val authenticationToken = SecurityContextHolder.getContext().authentication val principal = authenticationToken.principal as CustomUserDetails return ShelterUserAuthenticationInfo( shelterUserId = principal.id!!, email = Email(principal.username) ) } }
2
null
1
7
ebee64b31bfe77106c0212605ba5e0f9b9957879
1,491
DangleDangle-server
Apache License 2.0
idea/src/org/jetbrains/kotlin/idea/refactoring/cutPaste/MoveDeclarationsIntentionAction.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.refactoring.cutPaste import com.intellij.codeInsight.hint.HintManager import com.intellij.codeInspection.HintAction import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.IdeActions import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.RangeMarker import com.intellij.openapi.keymap.KeymapUtil import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.util.PsiModificationTracker import com.intellij.refactoring.BaseRefactoringIntentionAction import org.jetbrains.kotlin.idea.conversion.copy.range class MoveDeclarationsIntentionAction( private val processor: MoveDeclarationsProcessor, private val bounds: RangeMarker, private val modificationCount: Long ) : BaseRefactoringIntentionAction(), HintAction { override fun startInWriteAction() = false override fun getText() = "Update usages to reflect package name change" override fun getFamilyName() = "Update usages on declarations cut/paste" override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean { return PsiModificationTracker.SERVICE.getInstance(processor.project).modificationCount == modificationCount } override fun invoke(project: Project, editor: Editor, element: PsiElement) { processor.performRefactoring() } override fun showHint(editor: Editor): Boolean { val range = bounds.range ?: return false if (editor.caretModel.offset != range.endOffset) return false if (PsiModificationTracker.SERVICE.getInstance(processor.project).modificationCount != modificationCount) return false val hintText = "$text? ${KeymapUtil.getFirstKeyboardShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS))}" HintManager.getInstance().showQuestionHint(editor, hintText, range.endOffset, range.endOffset) { processor.performRefactoring() true } return true } }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
2,684
kotlin
Apache License 2.0
app/src/main/java/com/android/musicplayer/presentation/songplayer/SongPlayerActivity.kt
mousavi007
242,477,306
false
null
package com.android.musicplayer.presentation.songplayer import android.content.Context import android.content.Intent import android.os.Bundle import android.util.Log import android.widget.SeekBar import androidx.core.content.ContextCompat import androidx.lifecycle.Observer import coil.api.load import com.android.musicplayer.R import com.android.musicplayer.data.model.Song import com.android.player.BaseSongPlayerActivity import com.android.player.model.ASong import com.android.player.utils.OnSwipeTouchListener import kotlinx.android.synthetic.main.activity_song_player.* import java.io.File class SongPlayerActivity : BaseSongPlayerActivity() { private var mSong: Song? = null private var mSongList: MutableList<ASong>? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_song_player) if (intent?.extras?.containsKey(SONG_LIST_KEY) == true) { mSongList = intent?.extras?.getParcelableArrayList(SONG_LIST_KEY) Log.i(TAG, "song list: $mSongList") } if (intent?.extras?.containsKey(ASong::class.java.name) == true) { mSong = intent?.extras?.get(ASong::class.java.name) as Song } mSong?.let { play(mSongList, it) } loadInitialData(mSong?.title, mSong?.artist, mSong?.clipArt) playerViewModel.songDurationTextData.observe(this, Observer<String> { t -> song_player_total_time_text_view.text = t }) playerViewModel.songDurationData.observe(this, Observer { song_player_progress_seek_bar.max = it }) playerViewModel.songPositionTextData.observe(this, Observer<String> { t -> song_player_passed_time_text_view.text = t }) playerViewModel.songPositionData.observe(this, Observer { song_player_progress_seek_bar.progress = it }) playerViewModel.isRepeatData.observe(this, Observer { song_player_repeat_image_view.setImageResource( if (it) R.drawable.ic_repeat_one_color_primary_vector else R.drawable.ic_repeat_one_black_vector ) }) playerViewModel.isShuffleData.observe(this, Observer { song_player_shuffle_image_view.setImageResource( if (it) R.drawable.ic_shuffle_color_primary_vector else R.drawable.ic_shuffle_black_vector ) }) playerViewModel.isPlayData.observe(this, Observer { song_player_toggle_image_view.setImageResource(if (it) R.drawable.ic_pause_vector else R.drawable.ic_play_vector) }) playerViewModel.playerData.observe(this, Observer { loadInitialData(it?.title, it?.artist, it?.clipArt) }) song_player_skip_next_image_view.setOnClickListener { playerViewModel.next() } song_player_skip_back_image_view.setOnClickListener { playerViewModel.previous() } song_player_toggle_image_view.setOnClickListener { playerViewModel.play() } song_player_shuffle_image_view.setOnClickListener { playerViewModel.shuffle() } song_player_repeat_image_view.setOnClickListener { playerViewModel.repeat() } song_player_progress_seek_bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) { Log.i(TAG, "onProgressChanged: p0: $p0 p1: $p1, p2: $p2") } override fun onStartTrackingTouch(p0: SeekBar?) { Log.i(TAG, "onStartTrackingTouch: p0: $p0") } override fun onStopTrackingTouch(p0: SeekBar?) { Log.i(TAG, "onStopTrackingTouch: p0: $p0") playerViewModel.seekTo(song_player_progress_seek_bar.progress.toLong()) } }) song_player_container.setOnTouchListener(object : OnSwipeTouchListener(this@SongPlayerActivity) { override fun onSwipeRight() { if (mSongList?.size ?: 0 > 1) skipToPrevious() } override fun onSwipeLeft() { if (mSongList?.size ?: 0 > 1) skipToNext() } }) } private fun loadInitialData(title: String?, singerName: String?, image: String?) { song_player_title_text_view.text = title song_player_singer_name_text_view.text = singerName image?.let { song_player_image_view.load(File(it)) { crossfade(true) placeholder(ContextCompat.getDrawable(this@SongPlayerActivity, R.drawable.placeholder)) error(ContextCompat.getDrawable(this@SongPlayerActivity, R.drawable.placeholder)) //transformations(CircleCropTransformation()) } } } companion object { private val TAG = SongPlayerActivity::class.java.name fun start(context: Context, song: Song, songList: ArrayList<Song>) { val intent = Intent(context, SongPlayerActivity::class.java) intent.putExtra(ASong::class.java.name, song) intent.putExtra(SONG_LIST_KEY, songList) context.startActivity(intent) } } }
0
null
0
1
7662328f2d2dc643976c15e001b5bbcbf2524843
5,415
MusicPlayer
Apache License 2.0
vector/src/test/java/im/vector/app/features/poll/create/CreatePollViewModelTest.kt
tchapgouv
340,329,238
false
null
/* * Copyright (c) 2022 New Vector Ltd * * 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 im.vector.app.features.poll.create import com.airbnb.mvrx.test.MavericksTestRule import im.vector.app.features.poll.PollMode import im.vector.app.test.fakes.FakeCreatePollViewStates.A_FAKE_OPTIONS import im.vector.app.test.fakes.FakeCreatePollViewStates.A_FAKE_QUESTION import im.vector.app.test.fakes.FakeCreatePollViewStates.A_FAKE_ROOM_ID import im.vector.app.test.fakes.FakeCreatePollViewStates.A_POLL_START_TIMELINE_EVENT import im.vector.app.test.fakes.FakeCreatePollViewStates.createPollArgs import im.vector.app.test.fakes.FakeCreatePollViewStates.editPollArgs import im.vector.app.test.fakes.FakeCreatePollViewStates.editedPollViewState import im.vector.app.test.fakes.FakeCreatePollViewStates.initialCreatePollViewState import im.vector.app.test.fakes.FakeCreatePollViewStates.pollViewStateWithOnlyQuestion import im.vector.app.test.fakes.FakeCreatePollViewStates.pollViewStateWithQuestionAndEnoughOptions import im.vector.app.test.fakes.FakeCreatePollViewStates.pollViewStateWithQuestionAndEnoughOptionsButDeletedLastOption import im.vector.app.test.fakes.FakeCreatePollViewStates.pollViewStateWithQuestionAndMaxOptions import im.vector.app.test.fakes.FakeCreatePollViewStates.pollViewStateWithQuestionAndNotEnoughOptions import im.vector.app.test.fakes.FakeCreatePollViewStates.pollViewStateWithoutQuestionAndEnoughOptions import im.vector.app.test.fakes.FakeSession import im.vector.app.test.test import io.mockk.unmockkAll import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.After import org.junit.Before import org.junit.Rule import org.junit.Test import org.matrix.android.sdk.api.session.room.model.message.PollType class CreatePollViewModelTest { private val testDispatcher = UnconfinedTestDispatcher() @get:Rule val mavericksTestRule = MavericksTestRule( testDispatcher = testDispatcher // See https://github.com/airbnb/mavericks/issues/599 ) private val fakeSession = FakeSession() private fun createPollViewModel(pollMode: PollMode): CreatePollViewModel { return if (pollMode == PollMode.EDIT) { CreatePollViewModel(CreatePollViewState(editPollArgs), fakeSession) } else { CreatePollViewModel(CreatePollViewState(createPollArgs), fakeSession) } } @Before fun setup() { fakeSession .roomService() .getRoom(A_FAKE_ROOM_ID) .timelineService() .givenTimelineEvent(A_POLL_START_TIMELINE_EVENT) } @After fun tearDown() { unmockkAll() } @Test fun `given the view model is initialized then poll cannot be created and more options can be added`() = runTest { val createPollViewModel = createPollViewModel(PollMode.CREATE) val test = createPollViewModel.test() test .assertLatestState(initialCreatePollViewState) .finish() } @Test fun `given there is not any options when the question is added then poll cannot be created and more options can be added`() = runTest { val createPollViewModel = createPollViewModel(PollMode.CREATE) val test = createPollViewModel.test() createPollViewModel.handle(CreatePollAction.OnQuestionChanged(A_FAKE_QUESTION)) test .assertLatestState(pollViewStateWithOnlyQuestion) .finish() } @Test fun `given there is not enough options when the question is added then poll cannot be created and more options can be added`() = runTest { val createPollViewModel = createPollViewModel(PollMode.CREATE) val test = createPollViewModel.test() createPollViewModel.handle(CreatePollAction.OnQuestionChanged(A_FAKE_QUESTION)) repeat(CreatePollViewModel.MIN_OPTIONS_COUNT - 1) { createPollViewModel.handle(CreatePollAction.OnOptionChanged(it, A_FAKE_OPTIONS[it])) } test .assertLatestState(pollViewStateWithQuestionAndNotEnoughOptions) .finish() } @Test fun `given there is not a question when enough options are added then poll cannot be created and more options can be added`() = runTest { val createPollViewModel = createPollViewModel(PollMode.CREATE) val test = createPollViewModel.test() repeat(CreatePollViewModel.MIN_OPTIONS_COUNT) { createPollViewModel.handle(CreatePollAction.OnOptionChanged(it, A_FAKE_OPTIONS[it])) } test .assertLatestState(pollViewStateWithoutQuestionAndEnoughOptions) .finish() } @Test fun `given there is a question when enough options are added then poll can be created and more options can be added`() = runTest { val createPollViewModel = createPollViewModel(PollMode.CREATE) val test = createPollViewModel.test() createPollViewModel.handle(CreatePollAction.OnQuestionChanged(A_FAKE_QUESTION)) repeat(CreatePollViewModel.MIN_OPTIONS_COUNT) { createPollViewModel.handle(CreatePollAction.OnOptionChanged(it, A_FAKE_OPTIONS[it])) } test .assertLatestState(pollViewStateWithQuestionAndEnoughOptions) .finish() } @Test fun `given there is a question when max number of options are added then poll can be created and more options cannot be added`() = runTest { val createPollViewModel = createPollViewModel(PollMode.CREATE) val test = createPollViewModel.test() createPollViewModel.handle(CreatePollAction.OnQuestionChanged(A_FAKE_QUESTION)) repeat(CreatePollViewModel.MAX_OPTIONS_COUNT) { if (it >= CreatePollViewModel.MIN_OPTIONS_COUNT) { createPollViewModel.handle(CreatePollAction.OnAddOption) } createPollViewModel.handle(CreatePollAction.OnOptionChanged(it, A_FAKE_OPTIONS[it])) } test .assertLatestState(pollViewStateWithQuestionAndMaxOptions) .finish() } @Test fun `given an initial poll state when poll type is changed then view state is updated accordingly`() = runTest { val createPollViewModel = createPollViewModel(PollMode.CREATE) val test = createPollViewModel.test() createPollViewModel.handle(CreatePollAction.OnPollTypeChanged(PollType.UNDISCLOSED)) createPollViewModel.handle(CreatePollAction.OnPollTypeChanged(PollType.DISCLOSED)) test .assertStatesChanges( initialCreatePollViewState, { copy(pollType = PollType.UNDISCLOSED) }, { copy(pollType = PollType.DISCLOSED) }, ) .finish() } @Test fun `given there is not a question and enough options when create poll is requested then error view events are post`() = runTest { val createPollViewModel = createPollViewModel(PollMode.CREATE) val test = createPollViewModel.test() createPollViewModel.handle(CreatePollAction.OnCreatePoll) createPollViewModel.handle(CreatePollAction.OnQuestionChanged(A_FAKE_QUESTION)) createPollViewModel.handle(CreatePollAction.OnCreatePoll) createPollViewModel.handle(CreatePollAction.OnOptionChanged(0, A_FAKE_OPTIONS[0])) createPollViewModel.handle(CreatePollAction.OnCreatePoll) test .assertEvents( CreatePollViewEvents.EmptyQuestionError, CreatePollViewEvents.NotEnoughOptionsError(requiredOptionsCount = CreatePollViewModel.MIN_OPTIONS_COUNT), CreatePollViewEvents.NotEnoughOptionsError(requiredOptionsCount = CreatePollViewModel.MIN_OPTIONS_COUNT), ) } @Test fun `given there is a question and enough options when create poll is requested then success view event is post`() = runTest { val createPollViewModel = createPollViewModel(PollMode.CREATE) val test = createPollViewModel.test() createPollViewModel.handle(CreatePollAction.OnQuestionChanged(A_FAKE_QUESTION)) createPollViewModel.handle(CreatePollAction.OnOptionChanged(0, A_FAKE_OPTIONS[0])) createPollViewModel.handle(CreatePollAction.OnOptionChanged(1, A_FAKE_OPTIONS[1])) createPollViewModel.handle(CreatePollAction.OnCreatePoll) test .assertEvents( CreatePollViewEvents.Success, ) } @Test fun `given there is a question and enough options when the last option is deleted then view state should be updated accordingly`() = runTest { val createPollViewModel = createPollViewModel(PollMode.CREATE) val test = createPollViewModel.test() createPollViewModel.handle(CreatePollAction.OnQuestionChanged(A_FAKE_QUESTION)) createPollViewModel.handle(CreatePollAction.OnOptionChanged(0, A_FAKE_OPTIONS[0])) createPollViewModel.handle(CreatePollAction.OnOptionChanged(1, A_FAKE_OPTIONS[1])) createPollViewModel.handle(CreatePollAction.OnDeleteOption(1)) test.assertLatestState(pollViewStateWithQuestionAndEnoughOptionsButDeletedLastOption) } @Test fun `given an edited poll event when question and options are changed then view state is updated accordingly`() = runTest { val createPollViewModel = createPollViewModel(PollMode.EDIT) val test = createPollViewModel.test() test .assertState(editedPollViewState) .finish() } @Test fun `given an edited poll event then able to be edited`() = runTest { val createPollViewModel = createPollViewModel(PollMode.EDIT) val test = createPollViewModel.test() createPollViewModel.handle(CreatePollAction.OnCreatePoll) test .assertEvents( CreatePollViewEvents.Success, ) } }
91
null
6
9
f088d7c2be9d4546057e90215c5171c04d227267
10,628
tchap-android
Apache License 2.0
challenge/flutter/all_samples/material_rawscrollbar_1/android/app/src/main/kotlin/com/example/material_rawscrollbar_1/MainActivity.kt
davidzou
5,868,257
false
null
package com.example.material_rawscrollbar_1 import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
1
null
1
4
1060f6501c432510e164578d4af60a49cd5ed681
140
WonderingWall
Apache License 2.0
kotlin.iot/core/common/src/main/java/NetworkWorker.kt
YuriZhuravlev
651,845,683
false
null
package ru.zhuravlev.yuri.core import ru.zhuravlev.yuri.core.model.* interface NetworkWorker { fun subscribe(onMessage: MessageHandler) fun unsubscribe() fun publish(configurationTemperature: ConfigurationTemperature) fun publish(signal: UserSignal) interface MessageHandler { fun onTemperature(temperature: Temperature) fun onPassiveInfraredSensor(pir: PassiveInfraredSensor) fun onWaterLevel(waterLevel: WaterLevel) fun onError(error: Throwable) } }
0
Kotlin
0
0
38bad20ca219ced244f89c0d792583d1a28e8473
511
IoT-System
MIT License
ktlint-ruleset-standard/src/main/kotlin/com/pinterest/ktlint/ruleset/standard/rules/TrailingCommaOnDeclarationSiteRule.kt
pinterest
64,293,719
false
null
package com.pinterest.ktlint.ruleset.standard.rules import com.pinterest.ktlint.rule.engine.core.api.ElementType import com.pinterest.ktlint.rule.engine.core.api.ElementType.ARROW import com.pinterest.ktlint.rule.engine.core.api.ElementType.CLASS import com.pinterest.ktlint.rule.engine.core.api.ElementType.COMMA import com.pinterest.ktlint.rule.engine.core.api.ElementType.DESTRUCTURING_DECLARATION import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUNCTION_LITERAL import com.pinterest.ktlint.rule.engine.core.api.ElementType.FUNCTION_TYPE import com.pinterest.ktlint.rule.engine.core.api.ElementType.RBRACE import com.pinterest.ktlint.rule.engine.core.api.ElementType.SEMICOLON import com.pinterest.ktlint.rule.engine.core.api.ElementType.TYPE_PARAMETER_LIST import com.pinterest.ktlint.rule.engine.core.api.ElementType.VALUE_PARAMETER_LIST import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHEN_ENTRY import com.pinterest.ktlint.rule.engine.core.api.ElementType.WHITE_SPACE import com.pinterest.ktlint.rule.engine.core.api.Rule.VisitorModifier.RunAfterRule.Mode.ONLY_WHEN_RUN_AFTER_RULE_IS_LOADED_AND_ENABLED import com.pinterest.ktlint.rule.engine.core.api.RuleId import com.pinterest.ktlint.rule.engine.core.api.SinceKtlint import com.pinterest.ktlint.rule.engine.core.api.SinceKtlint.Status.EXPERIMENTAL import com.pinterest.ktlint.rule.engine.core.api.SinceKtlint.Status.STABLE import com.pinterest.ktlint.rule.engine.core.api.children import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfig import com.pinterest.ktlint.rule.engine.core.api.editorconfig.EditorConfigProperty import com.pinterest.ktlint.rule.engine.core.api.indent import com.pinterest.ktlint.rule.engine.core.api.isCodeLeaf import com.pinterest.ktlint.rule.engine.core.api.nextLeaf import com.pinterest.ktlint.rule.engine.core.api.noNewLineInClosedRange import com.pinterest.ktlint.rule.engine.core.api.prevCodeLeaf import com.pinterest.ktlint.rule.engine.core.api.prevLeaf import com.pinterest.ktlint.rule.engine.core.api.upsertWhitespaceAfterMe import com.pinterest.ktlint.rule.engine.core.util.cast import com.pinterest.ktlint.ruleset.standard.StandardRule import org.ec4j.core.model.PropertyType import org.ec4j.core.model.PropertyType.PropertyValueParser import org.jetbrains.kotlin.com.intellij.lang.ASTNode import org.jetbrains.kotlin.com.intellij.psi.PsiElement import org.jetbrains.kotlin.com.intellij.psi.PsiWhiteSpace import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.kotlin.com.intellij.psi.impl.source.tree.PsiWhiteSpaceImpl import org.jetbrains.kotlin.com.intellij.psi.tree.TokenSet import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression import org.jetbrains.kotlin.psi.KtDestructuringDeclaration import org.jetbrains.kotlin.psi.KtEnumEntry import org.jetbrains.kotlin.psi.KtFunctionLiteral import org.jetbrains.kotlin.psi.KtParameterList import org.jetbrains.kotlin.psi.KtValueArgumentList import org.jetbrains.kotlin.psi.KtWhenEntry import org.jetbrains.kotlin.psi.KtWhenExpression import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType import org.jetbrains.kotlin.psi.psiUtil.collectDescendantsOfType import org.jetbrains.kotlin.psi.psiUtil.nextLeaf import org.jetbrains.kotlin.psi.psiUtil.prevLeaf /** * Linting trailing comma for declaration site. * * @see [Kotlin Style Guide](https://kotlinlang.org/docs/coding-conventions.html#trailing-commas) */ @SinceKtlint("0.43", EXPERIMENTAL) @SinceKtlint("0.46", STABLE) public class TrailingCommaOnDeclarationSiteRule : StandardRule( id = "trailing-comma-on-declaration-site", visitorModifiers = setOf( VisitorModifier.RunAfterRule( ruleId = WRAPPING_RULE_ID, mode = ONLY_WHEN_RUN_AFTER_RULE_IS_LOADED_AND_ENABLED, ), VisitorModifier.RunAsLateAsPossible, ), usesEditorConfigProperties = setOf(TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY), ) { private var allowTrailingComma = TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY.defaultValue override fun beforeFirstNode(editorConfig: EditorConfig) { allowTrailingComma = editorConfig[TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY] } override fun beforeVisitChildNodes( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, ) { // Keep processing of element types in sync with Intellij Kotlin formatting settings. // https://github.com/JetBrains/intellij-kotlin/blob/master/formatter/src/org/jetbrains/kotlin/idea/formatter/trailingComma/util.kt when (node.elementType) { CLASS -> visitClass(node, emit, autoCorrect) DESTRUCTURING_DECLARATION -> visitDestructuringDeclaration(node, autoCorrect, emit) FUNCTION_LITERAL -> visitFunctionLiteral(node, autoCorrect, emit) TYPE_PARAMETER_LIST -> visitTypeList(node, autoCorrect, emit) VALUE_PARAMETER_LIST -> visitValueList(node, autoCorrect, emit) WHEN_ENTRY -> visitWhenEntry(node, autoCorrect, emit) else -> Unit } } private fun visitDestructuringDeclaration( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, ) { val inspectNode = node .children() .last { it.elementType == ElementType.RPAR } node.reportAndCorrectTrailingCommaNodeBefore( inspectNode = inspectNode, isTrailingCommaAllowed = node.isTrailingCommaAllowed(), autoCorrect = autoCorrect, emit = emit, ) } private fun ASTNode.isTrailingCommaAllowed() = elementType in TYPES_ON_DECLARATION_SITE && allowTrailingComma private fun visitFunctionLiteral( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, ) { val inspectNode = node .children() .lastOrNull { it.elementType == ARROW } ?: // lambda w/o an arrow -> no arguments -> no commas return node.reportAndCorrectTrailingCommaNodeBefore( inspectNode = inspectNode, isTrailingCommaAllowed = node.isTrailingCommaAllowed(), autoCorrect = autoCorrect, emit = emit, ) } private fun visitValueList( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, ) { if (node.treeParent.elementType != FUNCTION_LITERAL) { node .children() .lastOrNull { it.elementType == ElementType.RPAR } ?.let { inspectNode -> node.reportAndCorrectTrailingCommaNodeBefore( inspectNode = inspectNode, isTrailingCommaAllowed = node.isTrailingCommaAllowed(), autoCorrect = autoCorrect, emit = emit, ) } } } private fun visitTypeList( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, ) { val inspectNode = node .children() .first { it.elementType == ElementType.GT } node.reportAndCorrectTrailingCommaNodeBefore( inspectNode = inspectNode, isTrailingCommaAllowed = node.isTrailingCommaAllowed(), autoCorrect = autoCorrect, emit = emit, ) } private fun visitWhenEntry( node: ASTNode, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, ) { val psi = node.psi require(psi is KtWhenEntry) if (psi.isElse || psi.parent.cast<KtWhenExpression>().leftParenthesis == null) { // no commas for "else" or when there are no opening parenthesis for the when-expression return } val inspectNode = node .children() .first { it.elementType == ARROW } node.reportAndCorrectTrailingCommaNodeBefore( inspectNode = inspectNode, isTrailingCommaAllowed = node.isTrailingCommaAllowed(), autoCorrect = autoCorrect, emit = emit, ) } private fun visitClass( node: ASTNode, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, autoCorrect: Boolean, ) { val psi = node.psi require(psi is KtClass) node .takeIf { psi.isEnum() } ?.findChildByType(ElementType.CLASS_BODY) ?.takeUnless { it.noEnumEntries() } ?.let { classBody -> classBody .findNodeAfterLastEnumEntry() ?.let { nodeAfterLastEnumEntry -> when { !node.isTrailingCommaAllowed() && nodeAfterLastEnumEntry.elementType == RBRACE -> { node.reportAndCorrectTrailingCommaNodeBefore( inspectNode = nodeAfterLastEnumEntry, isTrailingCommaAllowed = false, autoCorrect = autoCorrect, emit = emit, ) } !classBody.lastTwoEnumEntriesAreOnSameLine() -> { node.reportAndCorrectTrailingCommaNodeBefore( inspectNode = nodeAfterLastEnumEntry, isTrailingCommaAllowed = node.isTrailingCommaAllowed(), autoCorrect = autoCorrect, emit = emit, ) } } } } } private fun ASTNode.noEnumEntries() = children().none { it.psi is KtEnumEntry } private fun ASTNode.lastTwoEnumEntriesAreOnSameLine(): Boolean { val lastTwoEnumEntries = children() .filter { it.psi is KtEnumEntry } .toList() .takeLast(2) return lastTwoEnumEntries.count() == 2 && noNewLineInClosedRange(lastTwoEnumEntries[0], lastTwoEnumEntries[1]) } /** * Determines the [ASTNode] before which the trailing comma is allowed. * * If the list of enumeration entries is terminated by a semicolon, that semicolon will be returned. Otherwise, the * last element of the class. */ private fun ASTNode.findNodeAfterLastEnumEntry() = children() .lastOrNull { it.psi is KtEnumEntry } ?.children() ?.singleOrNull { it.elementType == SEMICOLON } ?: lastChildNode private fun ASTNode.reportAndCorrectTrailingCommaNodeBefore( inspectNode: ASTNode, isTrailingCommaAllowed: Boolean, autoCorrect: Boolean, emit: (offset: Int, errorMessage: String, canBeAutoCorrected: Boolean) -> Unit, ) { val prevLeaf = inspectNode.prevLeaf() val trailingCommaNode = prevLeaf?.findPreviousTrailingCommaNodeOrNull() val trailingCommaState = when { isMultiline(psi) -> if (trailingCommaNode != null) TrailingCommaState.EXISTS else TrailingCommaState.MISSING else -> if (trailingCommaNode != null) TrailingCommaState.REDUNDANT else TrailingCommaState.NOT_EXISTS } when (trailingCommaState) { TrailingCommaState.EXISTS -> if (isTrailingCommaAllowed) { inspectNode .treeParent .takeIf { it.elementType == WHEN_ENTRY } ?.findChildByType(ARROW) ?.prevLeaf() ?.let { lastNodeBeforeArrow -> if (lastNodeBeforeArrow.elementType != WHITE_SPACE || !lastNodeBeforeArrow.textContains('\n')) { emit( trailingCommaNode!!.startOffset, "Expected a newline between the trailing comma and \"${inspectNode.text}\"", true, ) if (autoCorrect) { lastNodeBeforeArrow.upsertWhitespaceAfterMe(inspectNode.treeParent.indent()) } } } } else { emit( trailingCommaNode!!.startOffset, "Unnecessary trailing comma before \"${inspectNode.text}\"", true, ) if (autoCorrect) { this.removeChild(trailingCommaNode) } } TrailingCommaState.MISSING -> if (isTrailingCommaAllowed) { val leafBeforeArrowOrNull = leafBeforeArrowOrNull() val addNewLine = leafBeforeArrowOrNull ?.let { !(leafBeforeArrowOrNull is PsiWhiteSpace && leafBeforeArrowOrNull.textContains('\n')) } ?: false val prevNode = inspectNode.prevCodeLeaf()!! if (addNewLine) { emit( prevNode.startOffset + prevNode.textLength, "Missing trailing comma and newline before \"${inspectNode.text}\"", true, ) } else { emit( prevNode.startOffset + prevNode.textLength, "Missing trailing comma before \"${inspectNode.text}\"", true, ) } if (autoCorrect) { if (addNewLine) { val indent = prevNode .treeParent .indent() if (leafBeforeArrowOrNull is PsiWhiteSpace) { (leafBeforeArrowOrNull as LeafPsiElement).rawReplaceWithText(indent) } else { inspectNode .prevCodeLeaf() ?.nextLeaf() ?.let { before -> before.treeParent.addChild(PsiWhiteSpaceImpl(indent), before) } } } if (inspectNode.treeParent.elementType == ElementType.ENUM_ENTRY) { val parentIndent = (prevNode.psi.parent.prevLeaf() as? PsiWhiteSpace)?.text ?: prevNode.indent() (inspectNode as LeafPsiElement).apply { this.treeParent.addChild(LeafPsiElement(COMMA, ","), this) this.treeParent.addChild(PsiWhiteSpaceImpl(parentIndent), null) this.treeParent.addChild(LeafPsiElement(SEMICOLON, ";"), null) } inspectNode.treeParent.removeChild(inspectNode) } else { inspectNode .prevCodeLeaf() ?.nextLeaf() ?.let { before -> before.treeParent.addChild(LeafPsiElement(COMMA, ","), before) } } } } TrailingCommaState.REDUNDANT -> { emit( trailingCommaNode!!.startOffset, "Unnecessary trailing comma before \"${inspectNode.text}\"", true, ) if (autoCorrect) { this.removeChild(trailingCommaNode) } } TrailingCommaState.NOT_EXISTS -> Unit } } private fun isMultiline(element: PsiElement): Boolean = when { element.parent is KtFunctionLiteral -> { isMultiline(element.parent) } element is KtFunctionLiteral -> { containsLineBreakInLeavesRange(element.valueParameterList!!, element.arrow!!) } element is KtWhenEntry -> { containsLineBreakInLeavesRange(element.firstChild, element.arrow!!) } element is KtDestructuringDeclaration -> { containsLineBreakInLeavesRange(element.lPar!!, element.rPar!!) } element is KtValueArgumentList && element.children.size == 1 && element.anyDescendantOfType<KtCollectionLiteralExpression>() -> { // special handling for collection literal // @Annotation([ // "something", // ]) val lastChild = element.collectDescendantsOfType<KtCollectionLiteralExpression>().last() containsLineBreakInLeavesRange(lastChild.rightBracket!!, element.rightParenthesis!!) } element is KtParameterList && element.parameters.isEmpty() -> { false } else -> { element.textContains('\n') } } private fun ASTNode.leafBeforeArrowOrNull() = when (psi) { is KtWhenEntry -> (psi as KtWhenEntry) .arrow ?.prevLeaf() is KtFunctionLiteral -> (psi as KtFunctionLiteral) .arrow ?.prevLeaf() else -> null } private fun ASTNode.findPreviousTrailingCommaNodeOrNull(): ASTNode? { val codeLeaf = if (isCodeLeaf()) { this } else { prevCodeLeaf() } return codeLeaf?.takeIf { it.elementType == COMMA } } private fun containsLineBreakInLeavesRange( from: PsiElement, to: PsiElement, ): Boolean { var leaf: PsiElement? = from while (leaf != null && !leaf.isEquivalentTo(to)) { if (leaf.textContains('\n')) { return true } leaf = leaf.nextLeaf(skipEmptyElements = false) } return leaf?.textContains('\n') ?: false } private enum class TrailingCommaState { /** * The trailing comma is needed and exists */ EXISTS, /** * The trailing comma is needed and doesn't exist */ MISSING, /** * The trailing comma isn't needed and doesn't exist */ NOT_EXISTS, /** * The trailing comma isn't needed, but exists */ REDUNDANT, } public companion object { private val BOOLEAN_VALUES_SET = setOf("true", "false") public val TRAILING_COMMA_ON_DECLARATION_SITE_PROPERTY: EditorConfigProperty<Boolean> = EditorConfigProperty( type = PropertyType.LowerCasingPropertyType( "ij_kotlin_allow_trailing_comma", "Defines whether a trailing comma (or no trailing comma) should be enforced on the defining " + "side, e.g. parameter-list, type-argument-list, lambda-value-parameters, enum-entries, etc." + "When set, IntelliJ IDEA uses this property to allow usage of a trailing comma by discretion " + "of the developer. KtLint however uses this setting to enforce consistent usage of the " + "trailing comma when set.", PropertyValueParser.BOOLEAN_VALUE_PARSER, BOOLEAN_VALUES_SET, ), defaultValue = true, androidStudioCodeStyleDefaultValue = false, ) private val TYPES_ON_DECLARATION_SITE = TokenSet.create( CLASS, DESTRUCTURING_DECLARATION, FUNCTION_LITERAL, FUNCTION_TYPE, TYPE_PARAMETER_LIST, VALUE_PARAMETER_LIST, WHEN_ENTRY, ) } } public val TRAILING_COMMA_ON_DECLARATION_SITE_RULE_ID: RuleId = TrailingCommaOnDeclarationSiteRule().ruleId
7
null
509
6,205
80c4d5d822d47bb7077a874ebb9105097f2eb1c2
21,492
ktlint
MIT License
app/src/main/java/com/example/bvm/ui/book/BookChangeActivity.kt
Liuwq-bit
431,728,147
false
null
package com.example.bvm.ui.book import android.icu.text.SimpleDateFormat import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.view.MenuItem import android.widget.Toast import androidx.annotation.RequiresApi import androidx.lifecycle.ViewModelProviders import com.example.bvm.BVMApplication import com.example.bvm.R import com.example.bvm.logic.model.Author import com.example.bvm.logic.model.Book import com.example.bvm.ui.book.ViewModel.BookViewModel import kotlinx.android.synthetic.main.activity_book_change.* import kotlinx.android.synthetic.main.book_add.* import java.util.* class BookChangeActivity : AppCompatActivity() { val viewModel by lazy { ViewModelProviders.of(this).get(BookViewModel::class.java) } @RequiresApi(Build.VERSION_CODES.N) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_book_change) setSupportActionBar(changeBookToolbar) supportActionBar?.let { it.setDisplayHomeAsUpEnabled(true) } val bookId = intent.getStringExtra(BookInfoActivity.BOOK_ID) ?: "" val bookTitle = intent.getStringExtra(BookInfoActivity.BOOK_TITLE) ?: "" val bookInfo = intent.getStringExtra(BookInfoActivity.BOOK_INFO) ?: "" val bookPic = intent.getStringExtra(BookInfoActivity.BOOK_PIC) ?: "" val bookAuthor = intent.getStringExtra(BookInfoActivity.BOOK_AUTHOR) ?: "" val bookAuthorInfo = intent.getStringExtra(BookInfoActivity.BOOK_AUTHOR_INFO) ?: "" val bookLabel = intent.getStringExtra(BookInfoActivity.BOOK_LABEL) ?: "" val bookPublishTime = intent.getStringExtra(BookInfoActivity.BOOK_PUBLISH_TIME) ?: "" changeBookNameText.editText?.setText(bookTitle) changeBookAuthorText.editText?.setText(bookAuthor) changeBookAuthorInfoText.editText?.setText(bookAuthorInfo) changeBookLabelText.editText?.setText(bookLabel) changeBookInfoText.editText?.setText(bookInfo) changeBookPublishTimeText.editText?.setText(bookPublishTime) changeBookPicText.editText?.setText(bookPic) changeBookCommitFab.setOnClickListener { val bookName = changeBookNameText.editText?.text.toString() val bookAuthor = changeBookAuthorText.editText?.text.toString() val bookAuthorInfo = changeBookAuthorInfoText.editText?.text.toString() val bookLabel = changeBookLabelText.editText?.text.toString() val bookInfo = changeBookInfoText.editText?.text.toString() val bookPublishTime = changeBookPublishTimeText.editText?.text.toString() val bookPic = changeBookPicText.editText?.text.toString() val date = Date() val dateFormat = SimpleDateFormat("yyyy-MM-dd") val book = Book(bookId?.toLong(), bookName, bookLabel, bookInfo, bookAuthor, bookAuthorInfo, dateFormat.format(date), bookPublishTime, bookPic) val author = Author(bookAuthor, bookAuthorInfo) viewModel.insertBooks(book, author) Toast.makeText(BVMApplication.context, "修改成功", Toast.LENGTH_SHORT).show() finish() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() return true } } return super.onOptionsItemSelected(item) } }
0
Kotlin
0
1
aed83fcabe475d01faed5ed35e7a4892ffde05f1
3,550
BVM
Apache License 2.0
cform-macro/src/test/kotlin/test/pl/wrzasq/cform/macro/pipeline/types/S3SourceTest.kt
rafalwrzeszcz-wrzasqpl
308,744,180
false
{"Kotlin": 252955}
/** * This file is part of the pl.wrzasq.cform. * * @license http://mit-license.org/ The MIT license * @copyright 2021 © by <NAME> - Wrzasq.pl. */ package test.pl.wrzasq.cform.macro.pipeline.types import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import pl.wrzasq.cform.macro.pipeline.types.S3Source class S3SourceTest { @Test fun noBucket() { assertThrows<IllegalStateException> { S3Source( "NoBucket", mapOf("ObjectKey" to "test.json"), null ) } } @Test fun noObjectKey() { assertThrows<IllegalStateException> { S3Source( "NoObjectKey", mapOf("Bucket" to "s3name"), null ) } } }
5
Kotlin
0
1
6d6ae1abe6d44126944ff090c010ca8d01dd794d
816
pl.wrzasq.cform
MIT License
app/src/main/java/com/graduation/mawruth/ui/signup/SignupActivity.kt
MohamedElattar22
753,310,964
false
{"Kotlin": 193180}
package com.graduation.mawruth.ui.signup import android.app.Dialog import android.content.Intent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowCompat import androidx.lifecycle.ViewModelProvider import com.graduation.mawruth.R import com.graduation.mawruth.databinding.ActivitySignupBinding import com.graduation.mawruth.ui.confirmEmail.ConfirmEmailActivity import com.graduation.mawruth.utils.RegexConstants import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class SignupActivity : AppCompatActivity() { private lateinit var viewBinding: ActivitySignupBinding private lateinit var viewModel: SignUpViewModel private lateinit var dialog: Dialog private var txtWatcher: TextWatcher? = null var email: String = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewBinding = ActivitySignupBinding.inflate(layoutInflater) setContentView(viewBinding.root) viewModel = ViewModelProvider(this)[SignUpViewModel::class.java] viewBinding.lifecycleOwner = this viewBinding.vm = viewModel initViews() } private fun initViews() { WindowCompat.setDecorFitsSystemWindows(window, false) dialog = Dialog(this) dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) dialog.setCancelable(false) val dialogView = LayoutInflater.from(this).inflate(R.layout.loading_dialog, null) dialog.setContentView(dialogView) textChanger() viewBinding.registerBtn.setOnClickListener { viewModel.registerUser() dialog.show() } subscribeToLiveData() } private fun textChanger() { txtWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { val userName = viewBinding.userInput.text.toString() email = viewBinding.emailTxt.text.toString() val password = viewBinding.passwordInput.text.toString() val passwordConf = viewBinding.passwordConf.text.toString() if (password.isNullOrBlank()) { viewBinding.emailContainer.error = "Password is required" } else { viewBinding.emailContainer.error = "" } if (userName.isNullOrBlank()) { viewBinding.userInputLayout.error = "User name is required" } else { viewBinding.userInputLayout.error = "" } if (email.isNullOrBlank()) { viewBinding.emailContainer.error = "Enter valid email" } else { viewBinding.emailContainer.error = "" } if (passwordConf.isNullOrBlank()) { viewBinding.passConfLayout.error = "Password confirmation is required" } else { viewBinding.passConfLayout.error = "" } if (!validateEmail(email)) { viewBinding.emailContainer.error = "Enter valid email" } else { viewBinding.emailContainer.error = "" } if (userName.isNotBlank() && password.isNotBlank() && email.isNotBlank() && password.isNotBlank() && passwordConf.isNotBlank() ) { if (password == passwordConf) { viewBinding.registerBtn.isEnabled = true viewBinding.passConfLayout.error = "" } else { viewBinding.passConfLayout.error = "password is not match" } } if (userName.isBlank() || password.isBlank() || email.isBlank() && password.isBlank() || passwordConf.isBlank() || passwordConf != password ) { viewBinding.registerBtn.isEnabled = false } } override fun afterTextChanged(s: Editable?) { } } viewBinding.emailTxt.addTextChangedListener(txtWatcher) viewBinding.passwordConf.addTextChangedListener(txtWatcher) viewBinding.userInput.addTextChangedListener(txtWatcher) viewBinding.passwordConf.addTextChangedListener(txtWatcher) } private fun validateEmail(email: String): Boolean { return RegexConstants.emailPattern.matches(email) } // private fun createDialog() { // val loadingDialogBinding = layoutInflater.inflate(R.layout.loading_dialog, null) // val dialog = MaterialAlertDialogBuilder(this) // .setView(loadingDialogBinding) // dialog.setBackground(ColorDrawable(Color.TRANSPARENT)) // dialog.show() // } private fun subscribeToLiveData() { viewModel.errorMessage.observe(this) { Toast.makeText(this, "Invalid email or username", Toast.LENGTH_SHORT).show() dialog.dismiss() } viewModel.openActivity.observe(this) { if (it) { navigateToVerifyOTP() dialog.dismiss() } } } private fun navigateToVerifyOTP() { val intent = Intent(this, ConfirmEmailActivity::class.java) intent.putExtra("email", email) startActivity(intent) finish() } }
0
Kotlin
0
4
d9cb7e523edbfd0eb17d7ce0f8c70c6e77820d03
5,878
Mawruth
Apache License 2.0
jetbrains-core/src/software/aws/toolkits/jetbrains/ui/feedback/Constants.kt
JetBrains
223,485,227
false
null
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.ui.feedback const val FEEDBACK_SOURCE = "source" const val ENABLED_EXPERIMENTS = "experimentsEnabled"
6
null
4
9
ccee3307fe58ad48f93cd780d4378c336ee20548
258
aws-toolkit-jetbrains
Apache License 2.0
src/main/kotlin/com/github/burkclik/asplugin/actions/ModuleLevelDynamicActionGroup.kt
Trendyol
535,543,930
false
null
package com.github.burkclik.asplugin.actions import com.github.burkclik.asplugin.util.ConfigFileReader import com.github.burkclik.asplugin.util.getModuleName import com.github.burkclik.asplugin.util.getModuleTerminalCommand import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.project.Project import com.intellij.util.containers.map2Array class ModuleLevelDynamicActionGroup : ActionGroup() { override fun getChildren(e: AnActionEvent?): Array<AnAction> { val event = e ?: return emptyArray() val project = e.project ?: return emptyArray() return runCatching { readActions(project) } .onFailure { it.printStackTrace() } .getOrNull() .orEmpty() .map2Array { createModuleLevelGradleTaskAction(event, it) } } private fun readActions(project: Project): List<String> { return ConfigFileReader() .readConfigFile(project, "config/Commander/module-tasks.txt") } private fun createModuleLevelGradleTaskAction(event: AnActionEvent, task: String): GradleTaskAction { val path: String = event.getData(CommonDataKeys.VIRTUAL_FILE)?.path.orEmpty() val rootPath: String = event.getData(CommonDataKeys.PROJECT)?.basePath.orEmpty().split("/").last() val gradleTerminalCommand = getModuleTerminalCommand(rootPath = rootPath, modulePath = path, gradleTaskName = task) val moduleName = getModuleName(rootPath, path) return GradleTaskAction( tabName = moduleName, taskName = task, gradleTerminalCommand = gradleTerminalCommand ) } }
0
Kotlin
0
2
037f7bf5edc57221072a134a3f8b935bc40ac3b3
1,805
Commander-AS-Plugin
MIT License
modules/tak/compose/icons/src/main/kotlin/dev/jonpoulton/alakazam/tak/compose/icons/raptorx/Note.kt
jonapoul
375,762,483
false
{"Kotlin": 2898393, "Shell": 670}
package dev.jonpoulton.alakazam.tak.compose.icons.raptorx import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd 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.group import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import dev.jonpoulton.alakazam.android.ui.compose.PreviewDark import dev.jonpoulton.alakazam.tak.compose.icons.PreviewIcon import dev.jonpoulton.alakazam.tak.compose.icons.RaptorXTakIcons public val RaptorXTakIcons.Note: ImageVector get() { if (nullableIcon != null) { return nullableIcon!! } nullableIcon = Builder( name = "Note", defaultWidth = 30.0.dp, defaultHeight = 31.0.dp, viewportWidth = 30.0f, viewportHeight = 31.0f, ).apply { group { path( fill = SolidColor(Color.Transparent), stroke = SolidColor(Color.White), strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd, ) { moveTo(17.5392f, 25.6537f) verticalLineTo(18.0386f) horizontalLineTo(25.1543f) lineTo(17.5392f, 25.6537f) close() } path( fill = SolidColor(Color.White), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd, ) { moveTo(12.0593f, 19.0381f) horizontalLineTo(7.9712f) curveTo(7.4182f, 19.0381f, 6.9712f, 18.5911f, 6.9712f, 18.0381f) curveTo(6.9712f, 17.4861f, 7.4182f, 17.0381f, 7.9712f, 17.0381f) horizontalLineTo(12.0593f) curveTo(12.6113f, 17.0381f, 13.0593f, 17.4861f, 13.0593f, 18.0381f) curveTo(13.0593f, 18.5911f, 12.6113f, 19.0381f, 12.0593f, 19.0381f) close() } path( fill = SolidColor(Color.White), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd, ) { moveTo(7.9712f, 12.4058f) horizontalLineTo(21.5125f) curveTo(22.0635f, 12.4058f, 22.5125f, 12.8528f, 22.5125f, 13.4058f) curveTo(22.5125f, 13.9578f, 22.0635f, 14.4058f, 21.5125f, 14.4058f) horizontalLineTo(7.9712f) curveTo(7.4182f, 14.4058f, 6.9712f, 13.9578f, 6.9712f, 13.4058f) curveTo(6.9712f, 12.8528f, 7.4182f, 12.4058f, 7.9712f, 12.4058f) close() } path( fill = SolidColor(Color.White), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd, ) { moveTo(7.9712f, 7.8618f) horizontalLineTo(19.2064f) curveTo(19.7584f, 7.8618f, 20.2064f, 8.3088f, 20.2064f, 8.8618f) curveTo(20.2064f, 9.4138f, 19.7584f, 9.8618f, 19.2064f, 9.8618f) horizontalLineTo(7.9712f) curveTo(7.4182f, 9.8618f, 6.9712f, 9.4138f, 6.9712f, 8.8618f) curveTo(6.9712f, 8.3088f, 7.4182f, 7.8618f, 7.9712f, 7.8618f) close() } path( fill = SolidColor(Color.Transparent), stroke = SolidColor(Color.White), strokeLineWidth = 1.5f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero, ) { moveTo(4.75f, 5.25f) horizontalLineTo(25.2504f) verticalLineTo(18.9126f) lineTo(18.4126f, 25.7504f) horizontalLineTo(4.75f) verticalLineTo(5.25f) close() } } } .build() return nullableIcon!! } private var nullableIcon: ImageVector? = null @Composable @PreviewDark private fun Preview() = PreviewIcon(icon = RaptorXTakIcons.Note)
0
Kotlin
0
0
7769263ac0c6f0976facff732cf533dfd7ec44a3
4,483
alakazam
Apache License 2.0
winter/src/main/kotlin/io/jentz/winter/WinterInjection.kt
andreycooper
215,816,411
true
{"Kotlin": 378817, "Java": 11491, "Ruby": 1282}
package io.jentz.winter import io.jentz.winter.adapter.ApplicationGraphOnlyAdapter /** * Abstraction to create, get and dispose a dependency graph from a class that can't make use of * constructor injection. * * For applications it is recommended to use the object version [Injection] directly and for * libraries it is recommended to create a object version from [WinterInjection] instead. * * @see Injection */ open class WinterInjection { /** * Adapter interface to provide application specific graph creation and retrieval strategy. */ interface Adapter { /** * Get dependency graph for [instance]. * * @param instance The instance to get the graph for. * @return The graph for [instance]. * @throws [io.jentz.winter.WinterException] if no graph for [instance] exists. * */ fun getGraph(instance: Any): Graph /** * Create dependency graph for [instance]. * * The adapter implementation is responsible for storing the created graph. * * @param instance The instance to create a dependency graph for. * @param block An optional builder block to pass to the component init method. * @return The newly created graph * @throws [io.jentz.winter.WinterException] if given [instance] type is not supported. * */ fun createGraph(instance: Any, block: ComponentBuilderBlock?): Graph /** * Dispose the dependency graph of the given [instance]. * * @param instance The instance to dispose the graph for. * @throws [io.jentz.winter.WinterException] if no graph for this [instance] type exists. */ fun disposeGraph(instance: Any) } /** * Set the application specific [adapter][Adapter]. * * Default adapter is [ApplicationGraphOnlyAdapter] that operates on [GraphRegistry]. */ var adapter: Adapter = ApplicationGraphOnlyAdapter(GraphRegistry) /** * Create and return dependency graph for [instance]. * * @param instance The instance for which a graph should be created. * @param block An optional builder block to pass to the component init method. * @return The newly created graph. * @throws [io.jentz.winter.WinterException] if given [instance] type is not supported. */ fun createGraph(instance: Any, block: ComponentBuilderBlock? = null): Graph = adapter.createGraph(instance, block) /** * Create and return dependency graph for [instance] and also pass the graph to the given * [injector]. * * @param instance The instance for which a graph should be created. * @param injector The injector to inject into. * @param block An optional builder block to pass to the component init method. * @return The created dependency graph. * @throws [io.jentz.winter.WinterException] if given [instance] type is not supported. */ fun createGraphAndInject( instance: Any, injector: Injector, block: ComponentBuilderBlock? = null ): Graph = createGraph(instance, block).also(injector::inject) /** * Create and return dependency graph for [instance] and inject all members into instance. * * This is useful in conjunction with JSR330 `Inject` annotations. * * @param instance The instance to create a graph for and to inject into. * @param injectSuperClasses If true this will look for members injectors for super classes too. * @param block An optional builder block to pass to the component init method. * @return The created dependency graph. * @throws [io.jentz.winter.WinterException] if given [instance] type is not supported. */ fun <T : Any> createGraphAndInject( instance: T, injectSuperClasses: Boolean = false, block: ComponentBuilderBlock? = null ): Graph = createGraph(instance, block).also { graph -> graph.inject(instance, injectSuperClasses) } /** * Get dependency graph for [instance]. * * @param instance The instance to retrieve the dependency graph for. * @throws [io.jentz.winter.WinterException] if given [instance] type is not supported. * */ fun getGraph(instance: Any): Graph = adapter.getGraph(instance) /** * Dispose the dependency graph of the given [instance]. * * @param instance The instance to dispose the graph for. * @throws [io.jentz.winter.WinterException] if given [instance] type is not supported. */ fun disposeGraph(instance: Any) { adapter.disposeGraph(instance) } /** * Get dependency graph for given [instance] and inject dependencies into injector. * * @param instance The instance to retrieve the dependency graph for. * @param injector The injector to inject into. * @throws [io.jentz.winter.WinterException] if given [instance] type is not supported. */ fun inject(instance: Any, injector: Injector) { injector.inject(getGraph(instance)) } /** * Inject into [instance] by using the dependency graph of the [instance]. * This uses [MembersInjector] and is useful in conjunction with Winters JSR330 annotation * processor. * * @param instance The instance to retrieve the dependency graph for and inject dependencies * into. * @param injectSuperClasses If true this will look for members injectors for super classes too. * @throws [io.jentz.winter.WinterException] If given [instance] type is not supported. */ fun <T : Any> inject(instance: T, injectSuperClasses: Boolean = false) { getGraph(instance).inject(instance, injectSuperClasses) } }
0
null
0
0
4fd5ca4e9547198860719ce2a23f47d8141335f4
5,831
winter
Apache License 2.0
app/src/main/java/com/debanshu777/compose_github/network/model/userStats/Watching.kt
Debanshu777
467,621,052
false
{"Kotlin": 390827}
package com.debanshu777.compose_github.network.model.userStats import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Organizations( @SerialName("totalCount") val totalCount: Int = 0 // 1 )
1
Kotlin
2
57
422904eb5e71737e7f527932bfe84253740ed35c
252
Github-Compose
MIT License
kohii-sample/src/main/java/kohii/v1/sample/ui/fbook/vh/VideoViewHolder.kt
eneim
138,487,627
false
null
/* * 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.sample.ui.fbook.vh import android.view.ViewGroup import android.widget.Button import android.widget.ImageButton import android.widget.ImageView import androidx.core.view.isVisible import com.bumptech.glide.Glide import com.google.android.exoplayer2.Player import kohii.v1.core.Binder.Options import kohii.v1.core.Playback import kohii.v1.core.Playback.Controller import kohii.v1.core.Rebinder import kohii.v1.exoplayer.Kohii import kohii.v1.sample.DemoApp.Companion.VIDEO_URI_ASSET import kohii.v1.sample.R import kohii.v1.sample.data.Sources import kohii.v1.sample.data.Video internal class VideoViewHolder( parent: ViewGroup, val kohii: Kohii, val shouldBind: (Rebinder?) -> Boolean, ) : FbookItemHolder(parent), Playback.StateListener, Playback.ArtworkHintListener { init { videoContainer.isVisible = true } internal val playerView = itemView.findViewById(R.id.playerView) as ViewGroup internal val volume = itemView.findViewById(R.id.volumeSwitch) as ImageButton internal val thumbnail = itemView.findViewById(R.id.thumbnail) as ImageView internal val playAgain = itemView.findViewById(R.id.playerAgain) as Button internal var playback: Playback? = null private var video: Video? = null private var videoImage: String? = null private var videoSources: Sources? = null private val videoTag: String? get() = this.videoSources?.let { "FB::${it.file}::$absoluteAdapterPosition" } private val params: Options.() -> Unit get() = { tag = requireNotNull(videoTag) artworkHintListener = this@VideoViewHolder controller = object : Controller { override fun kohiiCanStart(): Boolean = true } } // Trick here: we do not rely on the actual binding to have the Rebinder. This instance will // be useful in some verifications. internal val rebinder: Rebinder? get() = this.videoTag?.let { Rebinder(it) } override fun bind(item: Any?) { super.bind(item) (item as? Video)?.also { this.video = it this.videoSources = it.playlist.first() .also { pl -> videoImage = pl.image Glide.with(itemView) .load(pl.image) .into(thumbnail) } .sources.first() if (shouldBind(this.rebinder)) { kohii.setUp(VIDEO_URI_ASSET, params) .bind(playerView) { pk -> volume.isSelected = !pk.volumeInfo.mute pk.addStateListener(this@VideoViewHolder) playback = pk } } } } override fun onArtworkHint( playback: Playback, shouldShow: Boolean, position: Long, state: Int, ) { thumbnail.isVisible = shouldShow playAgain.isVisible = shouldShow && state == Player.STATE_ENDED } override fun onRecycled(success: Boolean) { video = null videoSources = null videoImage = null playback = null } }
49
null
50
370
79f5ec327e3db627d88b089931b63d1e28e4e2ee
3,531
kohii
Apache License 2.0
app/src/test/java/org/simple/clinic/drugs/DrugSummaryUpdateTest.kt
simpledotorg
132,515,649
false
null
package org.simple.clinic.drugs; import com.spotify.mobius.test.NextMatchers.hasEffects import com.spotify.mobius.test.NextMatchers.hasNoModel import com.spotify.mobius.test.UpdateSpec import com.spotify.mobius.test.UpdateSpec.assertThatNext import org.junit.Test import org.simple.clinic.TestData import org.simple.clinic.summary.prescribeddrugs.CurrentFacilityLoaded import org.simple.clinic.summary.prescribeddrugs.DrugSummaryEffect import org.simple.clinic.summary.prescribeddrugs.DrugSummaryEvent import org.simple.clinic.summary.prescribeddrugs.DrugSummaryModel import org.simple.clinic.summary.prescribeddrugs.DrugSummaryUpdate import org.simple.clinic.summary.prescribeddrugs.OpenUpdatePrescribedDrugScreen import java.util.UUID class DrugSummaryUpdateTest { private val patientUuid = UUID.fromString("871a2f40-2bda-488c-9443-7dc708c3743a") private val updateSpec = UpdateSpec<DrugSummaryModel, DrugSummaryEvent, DrugSummaryEffect>(DrugSummaryUpdate()) private val defaultModel = DrugSummaryModel.create(patientUuid) private val facility = TestData.facility( uuid = UUID.fromString("de250445-0ec9-43e4-be33-2a49ca334535"), name = "CHC Buchho", ) @Test fun `when current facility is loaded with prescribed drugs, then open prescribed drug screen`() { val prescribedDrugRecords = listOf( TestData.prescription(uuid = UUID.fromString("4aec376e-1a8f-11eb-adc1-0242ac120002"), name = "Amlodipine1"), TestData.prescription(uuid = UUID.fromString("537a119e-1a8f-11eb-adc1-0242ac120002"), name = "Amlodipine2"), TestData.prescription(uuid = UUID.fromString("5ac2a678-1a8f-11eb-adc1-0242ac120002"), name = "Amlodipine3"), TestData.prescription(uuid = UUID.fromString("5f9f0fe2-1a8f-11eb-adc1-0242ac120002"), name = "Amlodipine4"), ) updateSpec .given(defaultModel.prescribedDrugsLoaded(prescribedDrugRecords)) .whenEvent(CurrentFacilityLoaded(facility)) .then(assertThatNext( hasNoModel(), hasEffects(OpenUpdatePrescribedDrugScreen(patientUuid, facility)), )) } }
3
null
73
236
ff699800fbe1bea2ed0492df484777e583c53714
2,095
simple-android
MIT License
Backpack/src/main/java/net/skyscanner/backpack/util/ColorStateList.kt
Skyscanner
117,813,847
false
null
/** * Backpack for Android - Skyscanner's Design System * * Copyright 2018-2021 Skyscanner Ltd * * 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.skyscanner.backpack.util import android.content.res.ColorStateList import androidx.annotation.ColorInt internal fun ColorStateList.getColorForState(state: IntArray) = getColorForState(state, defaultColor) internal inline fun colorStateList( @ColorInt color: Int, @ColorInt pressedColor: Int = color, @ColorInt focusedColor: Int = pressedColor, @ColorInt activatedColor: Int = pressedColor, @ColorInt disabledColor: Int ) = ColorStateList( arrayOf( intArrayOf(-android.R.attr.state_enabled), intArrayOf(android.R.attr.state_pressed), intArrayOf(android.R.attr.state_focused), intArrayOf(android.R.attr.state_activated), intArrayOf() ), intArrayOf(disabledColor, pressedColor, focusedColor, activatedColor, color) )
8
null
32
94
9b5448b446c7bc46560e430595829e5f4f090e6b
1,426
backpack-android
Apache License 2.0
integration-tests/src/test/kotlin/com/google/devtools/ksp/test/KMPImplementedIT.kt
google
297,744,725
false
{"Kotlin": 2173589, "Shell": 5321, "Java": 3893}
package com.google.devtools.ksp.test import org.gradle.testkit.runner.BuildResult import org.gradle.testkit.runner.GradleRunner import org.gradle.testkit.runner.TaskOutcome import org.junit.Assert import org.junit.Assume import org.junit.Ignore import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.io.File import java.util.jar.* @RunWith(Parameterized::class) class KMPImplementedIT(useKSP2: Boolean) { @Rule @JvmField val project: TemporaryTestProject = TemporaryTestProject("kmp", useKSP2 = useKSP2) private fun verify(jarName: String, contents: List<String>) { val artifact = File(project.root, jarName) Assert.assertTrue(artifact.exists()) JarFile(artifact).use { jarFile -> contents.forEach { Assert.assertTrue(jarFile.getEntry(it).size > 0) } } } private fun verifyKexe(path: String) { val artifact = File(project.root, path) Assert.assertTrue(artifact.exists()) Assert.assertTrue(artifact.readBytes().size > 0) } private fun checkExecutionOptimizations(log: String) { Assert.assertFalse( "Execution optimizations have been disabled", log.contains("Execution optimizations have been disabled") ) } @Test fun testJvm() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) val gradleRunner = GradleRunner.create().withProjectDir(project.root) gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload-jvm:build" ).build().let { Assert.assertEquals(TaskOutcome.SUCCESS, it.task(":workload-jvm:build")?.outcome) verify( "workload-jvm/build/libs/workload-jvm-jvm-1.0-SNAPSHOT.jar", listOf( "com/example/Foo.class" ) ) Assert.assertFalse(it.output.contains("kotlin scripting plugin:")) Assert.assertTrue(it.output.contains("w: [ksp] platforms: [JVM")) Assert.assertTrue(it.output.contains("w: [ksp] List has superTypes: true")) checkExecutionOptimizations(it.output) } } @Test fun testJvmErrorLog() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) val gradleRunner = GradleRunner.create().withProjectDir(project.root) File(project.root, "workload-jvm/build.gradle.kts").appendText("\nksp { arg(\"exception\", \"process\") }\n") gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload-jvm:build" ).buildAndFail().let { val errors = it.output.lines().filter { it.startsWith("e: [ksp]") } Assert.assertEquals("e: [ksp] java.lang.Exception: Test Exception in process", errors.first()) } project.restore("workload-jvm/build.gradle.kts") } @Test fun testJs() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) val gradleRunner = GradleRunner.create().withProjectDir(project.root) gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload-js:build" ).build().let { Assert.assertEquals(TaskOutcome.SUCCESS, it.task(":workload-js:build")?.outcome) verify( "workload-js/build/libs/workload-js-js-1.0-SNAPSHOT.klib", listOf( "default/ir/types.knt" ) ) Assert.assertFalse(it.output.contains("kotlin scripting plugin:")) Assert.assertTrue(it.output.contains("w: [ksp] platforms: [JS")) Assert.assertTrue(it.output.contains("w: [ksp] List has superTypes: true")) checkExecutionOptimizations(it.output) } } @Test fun testWasm() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) val gradleRunner = GradleRunner.create().withProjectDir(project.root) gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload-wasm:build" ).build().let { Assert.assertEquals(TaskOutcome.SUCCESS, it.task(":workload-wasm:build")?.outcome) verify( "workload-wasm/build/libs/workload-wasm-wasm-js-1.0-SNAPSHOT.klib", listOf( "default/ir/types.knt" ) ) Assert.assertFalse(it.output.contains("kotlin scripting plugin:")) Assert.assertTrue(it.output.contains("w: [ksp] platforms: [wasm-js")) Assert.assertTrue(it.output.contains("w: [ksp] List has superTypes: true")) checkExecutionOptimizations(it.output) } } @Test fun testJsErrorLog() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) val gradleRunner = GradleRunner.create().withProjectDir(project.root) File(project.root, "workload-js/build.gradle.kts").appendText("\nksp { arg(\"exception\", \"process\") }\n") gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload-js:build" ).buildAndFail().let { val errors = it.output.lines().filter { it.startsWith("e: [ksp]") } Assert.assertEquals("e: [ksp] java.lang.Exception: Test Exception in process", errors.first()) } project.restore("workload-js/build.gradle.kts") } @Test fun testJsFailWarning() { File(project.root, "workload-js/build.gradle.kts") .appendText("\nksp {\n allWarningsAsErrors = true\n}\n") val gradleRunner = GradleRunner.create().withProjectDir(project.root) gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload-js:build" ).buildAndFail() } @Test fun testAndroidNative() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) val gradleRunner = GradleRunner.create().withProjectDir(project.root) gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload-androidNative:build" ).build().let { Assert.assertEquals(TaskOutcome.SUCCESS, it.task(":workload-androidNative:build")?.outcome) verifyKexe( "workload-androidNative/build/bin/androidNativeX64/debugExecutable/workload-androidNative.kexe" ) verifyKexe( "workload-androidNative/build/bin/androidNativeX64/releaseExecutable/workload-androidNative.kexe" ) verifyKexe( "workload-androidNative/build/bin/androidNativeArm64/debugExecutable/workload-androidNative.kexe" ) verifyKexe( "workload-androidNative/build/bin/androidNativeArm64/releaseExecutable/workload-androidNative.kexe" ) Assert.assertFalse(it.output.contains("kotlin scripting plugin:")) Assert.assertTrue(it.output.contains("w: [ksp] platforms: [Native")) checkExecutionOptimizations(it.output) } } @Test fun testLinuxX64() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) val gradleRunner = GradleRunner.create().withProjectDir(project.root) val genDir = File(project.root, "workload-linuxX64/build/generated/ksp/linuxX64/linuxX64Main/kotlin") gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload-linuxX64:build" ).build().let { Assert.assertEquals(TaskOutcome.SUCCESS, it.task(":workload-linuxX64:build")?.outcome) Assert.assertEquals(TaskOutcome.SUCCESS, it.task(":workload-linuxX64:kspTestKotlinLinuxX64")?.outcome) verifyKexe("workload-linuxX64/build/bin/linuxX64/debugExecutable/workload-linuxX64.kexe") verifyKexe("workload-linuxX64/build/bin/linuxX64/releaseExecutable/workload-linuxX64.kexe") // TODO: Enable after CI's Xcode version catches up. // Assert.assertTrue( // result.task(":workload-linuxX64:kspKotlinIosArm64")?.outcome == TaskOutcome.SUCCESS || // result.task(":workload-linuxX64:kspKotlinIosArm64")?.outcome == TaskOutcome.SKIPPED // ) // Assert.assertTrue( // result.task(":workload-linuxX64:kspKotlinMacosX64")?.outcome == TaskOutcome.SUCCESS || // result.task(":workload-linuxX64:kspKotlinMacosX64")?.outcome == TaskOutcome.SKIPPED // ) Assert.assertTrue( it.task(":workload-linuxX64:kspKotlinMingwX64")?.outcome == TaskOutcome.SUCCESS || it.task(":workload-linuxX64:kspKotlinMingwX64")?.outcome == TaskOutcome.SKIPPED ) Assert.assertFalse(it.output.contains("kotlin scripting plugin:")) Assert.assertTrue(it.output.contains("w: [ksp] platforms: [Native")) Assert.assertTrue(it.output.contains("w: [ksp] List has superTypes: true")) Assert.assertTrue(File(genDir, "Main_dot_kt.kt").exists()) Assert.assertTrue(File(genDir, "ToBeRemoved_dot_kt.kt").exists()) checkExecutionOptimizations(it.output) } File(project.root, "workload-linuxX64/src/linuxX64Main/kotlin/ToBeRemoved.kt").delete() gradleRunner.withArguments( "--configuration-cache-problems=warn", ":workload-linuxX64:build" ).build().let { Assert.assertEquals(TaskOutcome.SUCCESS, it.task(":workload-linuxX64:build")?.outcome) Assert.assertEquals(TaskOutcome.SUCCESS, it.task(":workload-linuxX64:kspTestKotlinLinuxX64")?.outcome) verifyKexe("workload-linuxX64/build/bin/linuxX64/debugExecutable/workload-linuxX64.kexe") verifyKexe("workload-linuxX64/build/bin/linuxX64/releaseExecutable/workload-linuxX64.kexe") Assert.assertTrue(File(genDir, "Main_dot_kt.kt").exists()) Assert.assertFalse(File(genDir, "ToBeRemoved_dot_kt.kt").exists()) checkExecutionOptimizations(it.output) } } @Ignore @Test fun testNonEmbeddableArtifact() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) val gradleRunner = GradleRunner.create().withProjectDir(project.root) gradleRunner.withArguments( "--configuration-cache-problems=warn", "-Pkotlin.native.useEmbeddableCompilerJar=false", ":workload-linuxX64:kspTestKotlinLinuxX64" ).build() gradleRunner.withArguments( "--configuration-cache-problems=warn", "-Pkotlin.native.useEmbeddableCompilerJar=true", ":workload-linuxX64:kspTestKotlinLinuxX64" ).build() gradleRunner.withArguments( "--configuration-cache-problems=warn", ":workload-linuxX64:kspTestKotlinLinuxX64" ).build() } @Test fun testLinuxX64ErrorLog() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) val gradleRunner = GradleRunner.create().withProjectDir(project.root) File(project.root, "workload-linuxX64/build.gradle.kts") .appendText("\nksp { arg(\"exception\", \"process\") }\n") gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload-linuxX64:build" ).buildAndFail().let { val errors = it.output.lines().filter { it.startsWith("e: [ksp]") } Assert.assertEquals("e: [ksp] java.lang.Exception: Test Exception in process", errors.first()) } project.restore("workload-js/build.gradle.kts") } private fun verifyAll(result: BuildResult) { Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":workload:build")?.outcome) Assert.assertEquals(TaskOutcome.SUCCESS, result.task(":workload:kspTestKotlinLinuxX64")?.outcome) verify( "workload/build/libs/workload-jvm-1.0-SNAPSHOT.jar", listOf( "com/example/Foo.class" ) ) verify( "workload/build/libs/workload-js-1.0-SNAPSHOT.klib", listOf( "default/ir/types.knt" ) ) verifyKexe("workload/build/bin/linuxX64/debugExecutable/workload.kexe") verifyKexe("workload/build/bin/linuxX64/releaseExecutable/workload.kexe") verifyKexe("workload/build/bin/androidNativeX64/debugExecutable/workload.kexe") verifyKexe("workload/build/bin/androidNativeX64/releaseExecutable/workload.kexe") verifyKexe("workload/build/bin/androidNativeArm64/debugExecutable/workload.kexe") verifyKexe("workload/build/bin/androidNativeArm64/releaseExecutable/workload.kexe") // TODO: Enable after CI's Xcode version catches up. // Assert.assertTrue( // result.task(":workload:kspKotlinIosArm64")?.outcome == TaskOutcome.SUCCESS || // result.task(":workload:kspKotlinIosArm64")?.outcome == TaskOutcome.SKIPPED // ) // Assert.assertTrue( // result.task(":workload:kspKotlinMacosX64")?.outcome == TaskOutcome.SUCCESS || // result.task(":workload:kspKotlinMacosX64")?.outcome == TaskOutcome.SKIPPED // ) Assert.assertTrue( result.task(":workload:kspKotlinMingwX64")?.outcome == TaskOutcome.SUCCESS || result.task(":workload:kspKotlinMingwX64")?.outcome == TaskOutcome.SKIPPED ) Assert.assertFalse(result.output.contains("kotlin scripting plugin:")) Assert.assertTrue(result.output.contains("w: [ksp] platforms: [JVM")) Assert.assertTrue(result.output.contains("w: [ksp] platforms: [JS")) Assert.assertTrue(result.output.contains("w: [ksp] platforms: [Native")) } @Test fun testMainConfiguration() { Assume.assumeFalse(System.getProperty("os.name").startsWith("Windows", ignoreCase = true)) val gradleRunner = GradleRunner.create().withProjectDir(project.root) val buildScript = File(project.root, "workload/build.gradle.kts") val lines = buildScript.readLines().takeWhile { it.trimEnd() != "dependencies {" } buildScript.writeText(lines.joinToString(System.lineSeparator())) buildScript.appendText(System.lineSeparator()) buildScript.appendText("dependencies {") buildScript.appendText(System.lineSeparator()) buildScript.appendText(" add(\"ksp\", project(\":test-processor\"))") buildScript.appendText(System.lineSeparator()) buildScript.appendText("}") val messages = listOf( "The 'ksp' configuration is deprecated in Kotlin Multiplatform projects. ", "Please use target-specific configurations like 'kspJvm' instead." ) // KotlinNative doesn't support configuration cache yet. gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload:build", "-Pksp.allow.all.target.configuration=false" ).buildAndFail().apply { Assert.assertTrue( messages.all { output.contains(it) } ) checkExecutionOptimizations(output) } // KotlinNative doesn't support configuration cache yet. gradleRunner.withArguments( "--configuration-cache-problems=warn", "clean", ":workload:build", ).build().apply { Assert.assertTrue( messages.all { output.contains(it) } ) verifyAll(this) checkExecutionOptimizations(output) } } companion object { @JvmStatic @Parameterized.Parameters(name = "KSP2={0}") fun params() = listOf(arrayOf(true), arrayOf(false)) } }
379
Kotlin
268
2,854
a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3
16,616
ksp
Apache License 2.0
autofill/autofill-impl/src/main/java/com/duckduckgo/autofill/impl/InternalAutofillCapabilityChecker.kt
duckduckgo
78,869,127
false
null
/* * Copyright (c) 2023 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.autofill.impl import com.duckduckgo.autofill.api.AutofillCapabilityChecker import com.duckduckgo.autofill.api.AutofillFeature import com.duckduckgo.autofill.api.InternalTestUserChecker import com.duckduckgo.autofill.impl.configuration.integration.JavascriptCommunicationSupport import com.duckduckgo.common.utils.DispatcherProvider import com.duckduckgo.di.scopes.AppScope import com.squareup.anvil.annotations.ContributesBinding import javax.inject.Inject import kotlinx.coroutines.withContext /** * Used to check the status of various Autofill features. * * Whether autofill features are enabled depends on a variety of inputs. This class provides a single way to query the status of all of them. */ interface InternalAutofillCapabilityChecker : AutofillCapabilityChecker { /** * Whether autofill is supported in the current environment. */ fun webViewSupportsAutofill(): Boolean /** * Whether autofill can inject credentials into a WebView for the given page. * @param url The URL of the webpage to check. */ suspend fun canInjectCredentialsToWebView(url: String): Boolean /** * Whether autofill can save credentials from a WebView for the given page. * @param url The URL of the webpage to check. */ suspend fun canSaveCredentialsFromWebView(url: String): Boolean /** * Whether autofill can generate a password into a WebView for the given page. * @param url The URL of the webpage to check. */ suspend fun canGeneratePasswordFromWebView(url: String): Boolean /** * Whether autofill is configured to be enabled. This is a configuration value, not a user preference. */ suspend fun isAutofillEnabledByConfiguration(url: String): Boolean } @ContributesBinding(AppScope::class) class AutofillCapabilityCheckerImpl @Inject constructor( private val autofillFeature: AutofillFeature, private val internalTestUserChecker: InternalTestUserChecker, private val autofillGlobalCapabilityChecker: AutofillGlobalCapabilityChecker, private val javascriptCommunicationSupport: JavascriptCommunicationSupport, private val dispatcherProvider: DispatcherProvider, ) : InternalAutofillCapabilityChecker { override suspend fun canInjectCredentialsToWebView(url: String): Boolean = withContext(dispatcherProvider.io()) { if (!isSecureAutofillAvailable()) return@withContext false if (!isAutofillEnabledByConfiguration(url)) return@withContext false if (!isAutofillEnabledByUser()) return@withContext false if (isInternalTester()) return@withContext true return@withContext autofillFeature.canInjectCredentials().isEnabled() } override suspend fun canSaveCredentialsFromWebView(url: String): Boolean = withContext(dispatcherProvider.io()) { if (!isSecureAutofillAvailable()) return@withContext false if (!isAutofillEnabledByConfiguration(url)) return@withContext false if (!isAutofillEnabledByUser()) return@withContext false if (isInternalTester()) return@withContext true return@withContext autofillFeature.canSaveCredentials().isEnabled() } override suspend fun canGeneratePasswordFromWebView(url: String): Boolean = withContext(dispatcherProvider.io()) { if (!isSecureAutofillAvailable()) return@withContext false if (!isAutofillEnabledByConfiguration(url)) return@withContext false if (!isAutofillEnabledByUser()) return@withContext false if (isInternalTester()) return@withContext true return@withContext autofillFeature.canGeneratePasswords().isEnabled() } /** * Because the credential management screen handles the states where the user has toggled autofill off, or the device can't support it, * this feature is not dependent those checks. * * We purposely don't couple this check against [isSecureAutofillAvailable] or [isAutofillEnabledByUser]. */ override suspend fun canAccessCredentialManagementScreen(): Boolean = withContext(dispatcherProvider.io()) { if (isInternalTester()) return@withContext true if (!isGlobalFeatureEnabled()) return@withContext false return@withContext autofillFeature.canAccessCredentialManagement().isEnabled() } override fun webViewSupportsAutofill(): Boolean { return javascriptCommunicationSupport.supportsModernIntegration() } private suspend fun isInternalTester(): Boolean { return withContext(dispatcherProvider.io()) { internalTestUserChecker.isInternalTestUser } } private suspend fun isGlobalFeatureEnabled(): Boolean { return withContext(dispatcherProvider.io()) { autofillFeature.self().isEnabled() } } override suspend fun isAutofillEnabledByConfiguration(url: String) = autofillGlobalCapabilityChecker.isAutofillEnabledByConfiguration(url) private suspend fun isSecureAutofillAvailable() = autofillGlobalCapabilityChecker.isSecureAutofillAvailable() private suspend fun isAutofillEnabledByUser() = autofillGlobalCapabilityChecker.isAutofillEnabledByUser() } @ContributesBinding(AppScope::class) class DefaultCapabilityChecker @Inject constructor( private val capabilityChecker: InternalAutofillCapabilityChecker, ) : AutofillCapabilityChecker by capabilityChecker
83
null
894
3,781
587ad2cfe861e69f9407f8abf90b859e151ca367
5,985
Android
Apache License 2.0
autofill/autofill-impl/src/main/java/com/duckduckgo/autofill/impl/AutofillJavascriptInterface.kt
duckduckgo
78,869,127
false
null
/* * Copyright (c) 2022 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.autofill.impl import android.webkit.JavascriptInterface import android.webkit.WebView import com.duckduckgo.app.di.AppCoroutineScope import com.duckduckgo.autofill.api.AutofillCapabilityChecker import com.duckduckgo.autofill.api.Callback import com.duckduckgo.autofill.api.EmailProtectionInContextSignupFlowListener import com.duckduckgo.autofill.api.EmailProtectionUserPromptListener import com.duckduckgo.autofill.api.domain.app.LoginCredentials import com.duckduckgo.autofill.api.domain.app.LoginTriggerType import com.duckduckgo.autofill.api.email.EmailManager import com.duckduckgo.autofill.api.passwordgeneration.AutomaticSavedLoginsMonitor import com.duckduckgo.autofill.impl.deduper.AutofillLoginDeduplicator import com.duckduckgo.autofill.impl.domain.javascript.JavascriptCredentials import com.duckduckgo.autofill.impl.email.incontext.availability.EmailProtectionInContextRecentInstallChecker import com.duckduckgo.autofill.impl.email.incontext.store.EmailProtectionInContextDataStore import com.duckduckgo.autofill.impl.jsbridge.AutofillMessagePoster import com.duckduckgo.autofill.impl.jsbridge.request.AutofillDataRequest import com.duckduckgo.autofill.impl.jsbridge.request.AutofillRequestParser import com.duckduckgo.autofill.impl.jsbridge.request.AutofillStoreFormDataRequest import com.duckduckgo.autofill.impl.jsbridge.request.SupportedAutofillInputMainType.CREDENTIALS import com.duckduckgo.autofill.impl.jsbridge.request.SupportedAutofillInputSubType.PASSWORD import com.duckduckgo.autofill.impl.jsbridge.request.SupportedAutofillInputSubType.USERNAME import com.duckduckgo.autofill.impl.jsbridge.request.SupportedAutofillTriggerType import com.duckduckgo.autofill.impl.jsbridge.request.SupportedAutofillTriggerType.AUTOPROMPT import com.duckduckgo.autofill.impl.jsbridge.request.SupportedAutofillTriggerType.USER_INITIATED import com.duckduckgo.autofill.impl.jsbridge.response.AutofillResponseWriter import com.duckduckgo.autofill.impl.sharedcreds.ShareableCredentials import com.duckduckgo.autofill.impl.store.InternalAutofillStore import com.duckduckgo.autofill.impl.store.NeverSavedSiteRepository import com.duckduckgo.autofill.impl.systemautofill.SystemAutofillServiceSuppressor import com.duckduckgo.autofill.impl.ui.credential.passwordgeneration.Actions import com.duckduckgo.autofill.impl.ui.credential.passwordgeneration.Actions.DeleteAutoLogin import com.duckduckgo.autofill.impl.ui.credential.passwordgeneration.Actions.DiscardAutoLoginId import com.duckduckgo.autofill.impl.ui.credential.passwordgeneration.Actions.PromptToSave import com.duckduckgo.autofill.impl.ui.credential.passwordgeneration.Actions.UpdateSavedAutoLogin import com.duckduckgo.autofill.impl.ui.credential.passwordgeneration.AutogeneratedPasswordEventResolver import com.duckduckgo.common.utils.ConflatedJob import com.duckduckgo.common.utils.DefaultDispatcherProvider import com.duckduckgo.common.utils.DispatcherProvider import com.duckduckgo.di.scopes.AppScope import com.squareup.anvil.annotations.ContributesBinding import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import timber.log.Timber interface AutofillJavascriptInterface { @JavascriptInterface fun getAutofillData(requestString: String) @JavascriptInterface fun getIncontextSignupDismissedAt(data: String) fun injectCredentials(credentials: LoginCredentials) fun injectNoCredentials() fun cancelRetrievingStoredLogins() fun acceptGeneratedPassword() fun rejectGeneratedPassword() fun inContextEmailProtectionFlowFinished() var callback: Callback? var emailProtectionInContextCallback: EmailProtectionUserPromptListener? var emailProtectionInContextSignupFlowCallback: EmailProtectionInContextSignupFlowListener? var webView: WebView? var autoSavedLoginsMonitor: AutomaticSavedLoginsMonitor? var tabId: String? companion object { const val INTERFACE_NAME = "BrowserAutofill" } @JavascriptInterface fun closeEmailProtectionTab(data: String) } @ContributesBinding(AppScope::class) class AutofillStoredBackJavascriptInterface @Inject constructor( private val requestParser: AutofillRequestParser, private val autofillStore: InternalAutofillStore, private val shareableCredentials: ShareableCredentials, private val autofillMessagePoster: AutofillMessagePoster, private val autofillResponseWriter: AutofillResponseWriter, @AppCoroutineScope private val coroutineScope: CoroutineScope, private val dispatcherProvider: DispatcherProvider = DefaultDispatcherProvider(), private val currentUrlProvider: UrlProvider = WebViewUrlProvider(dispatcherProvider), private val autofillCapabilityChecker: AutofillCapabilityChecker, private val passwordEventResolver: AutogeneratedPasswordEventResolver, private val emailManager: EmailManager, private val inContextDataStore: EmailProtectionInContextDataStore, private val recentInstallChecker: EmailProtectionInContextRecentInstallChecker, private val loginDeduplicator: AutofillLoginDeduplicator, private val systemAutofillServiceSuppressor: SystemAutofillServiceSuppressor, private val neverSavedSiteRepository: NeverSavedSiteRepository, ) : AutofillJavascriptInterface { override var callback: Callback? = null override var emailProtectionInContextCallback: EmailProtectionUserPromptListener? = null override var emailProtectionInContextSignupFlowCallback: EmailProtectionInContextSignupFlowListener? = null override var webView: WebView? = null override var autoSavedLoginsMonitor: AutomaticSavedLoginsMonitor? = null override var tabId: String? = null // coroutine jobs tracked for supporting cancellation private val getAutofillDataJob = ConflatedJob() private val storeFormDataJob = ConflatedJob() private val injectCredentialsJob = ConflatedJob() private val emailProtectionInContextSignupJob = ConflatedJob() @JavascriptInterface override fun getAutofillData(requestString: String) { Timber.v("BrowserAutofill: getAutofillData called:\n%s", requestString) getAutofillDataJob += coroutineScope.launch(dispatcherProvider.io()) { val url = currentUrlProvider.currentUrl(webView) if (url == null) { Timber.w("Can't autofill as can't retrieve current URL") return@launch } if (!autofillCapabilityChecker.canInjectCredentialsToWebView(url)) { Timber.v("BrowserAutofill: getAutofillData called but feature is disabled") return@launch } val parseResult = requestParser.parseAutofillDataRequest(requestString) val request = parseResult.getOrElse { Timber.w(it, "Unable to parse getAutofillData request") return@launch } val triggerType = convertTriggerType(request.trigger) if (request.mainType != CREDENTIALS) { handleUnknownRequestMainType(request, url) return@launch } if (request.isGeneratedPasswordAvailable()) { handleRequestForPasswordGeneration(url, request) } else if (request.isAutofillCredentialsRequest()) { handleRequestForAutofillingCredentials(url, request, triggerType) } else { Timber.w("Unable to process request; don't know how to handle request %s", requestString) } } } @JavascriptInterface override fun getIncontextSignupDismissedAt(data: String) { emailProtectionInContextSignupJob += coroutineScope.launch(dispatcherProvider.io()) { val permanentDismissalTime = inContextDataStore.timestampUserChoseNeverAskAgain() val installedRecently = recentInstallChecker.isRecentInstall() val jsonResponse = autofillResponseWriter.generateResponseForEmailProtectionInContextSignup(installedRecently, permanentDismissalTime) autofillMessagePoster.postMessage(webView, jsonResponse) } } @JavascriptInterface override fun closeEmailProtectionTab(data: String) { emailProtectionInContextSignupFlowCallback?.closeInContextSignup() } @JavascriptInterface fun showInContextEmailProtectionSignupPrompt(data: String) { coroutineScope.launch(dispatcherProvider.io()) { currentUrlProvider.currentUrl(webView)?.let { val isSignedIn = emailManager.isSignedIn() withContext(dispatcherProvider.main()) { if (isSignedIn) { emailProtectionInContextCallback?.showNativeChooseEmailAddressPrompt() } else { emailProtectionInContextCallback?.showNativeInContextEmailProtectionSignupPrompt() } } } } } private suspend fun handleRequestForPasswordGeneration( url: String, request: AutofillDataRequest, ) { callback?.onGeneratedPasswordAvailableToUse(url, request.generatedPassword?.username, request.generatedPassword?.value!!) } private suspend fun handleRequestForAutofillingCredentials( url: String, request: AutofillDataRequest, triggerType: LoginTriggerType, ) { val matches = mutableListOf<LoginCredentials>() val directMatches = autofillStore.getCredentials(url) val shareableMatches = shareableCredentials.shareableCredentials(url) Timber.v("Direct matches: %d, shareable matches: %d for %s", directMatches.size, shareableMatches.size, url) matches.addAll(directMatches) matches.addAll(shareableMatches) val credentials = filterRequestedSubtypes(request, matches) val dedupedCredentials = loginDeduplicator.deduplicate(url, credentials) Timber.v("Original autofill credentials list size: %d, after de-duping: %d", credentials.size, dedupedCredentials.size) if (dedupedCredentials.isEmpty()) { callback?.noCredentialsAvailable(url) } else { callback?.onCredentialsAvailableToInject(url, dedupedCredentials, triggerType) } } private fun convertTriggerType(trigger: SupportedAutofillTriggerType): LoginTriggerType { return when (trigger) { USER_INITIATED -> LoginTriggerType.USER_INITIATED AUTOPROMPT -> LoginTriggerType.AUTOPROMPT } } private fun filterRequestedSubtypes( request: AutofillDataRequest, credentials: List<LoginCredentials>, ): List<LoginCredentials> { return when (request.subType) { USERNAME -> credentials.filterNot { it.username.isNullOrBlank() } PASSWORD -> credentials.filterNot { it.password.isNullOrBlank() } } } private fun handleUnknownRequestMainType( request: AutofillDataRequest, url: String, ) { Timber.w("Autofill type %s unsupported", request.mainType) callback?.noCredentialsAvailable(url) } @JavascriptInterface fun storeFormData(data: String) { // important to call suppressor as soon as possible systemAutofillServiceSuppressor.suppressAutofill(webView) Timber.i("storeFormData called, credentials provided to be persisted") storeFormDataJob += coroutineScope.launch(dispatcherProvider.io()) { val currentUrl = currentUrlProvider.currentUrl(webView) ?: return@launch if (!autofillCapabilityChecker.canSaveCredentialsFromWebView(currentUrl)) { Timber.v("BrowserAutofill: storeFormData called but feature is disabled") return@launch } if (neverSavedSiteRepository.isInNeverSaveList(currentUrl)) { Timber.v("BrowserAutofill: storeFormData called but site is in never save list") return@launch } val parseResult = requestParser.parseStoreFormDataRequest(data) val request = parseResult.getOrElse { Timber.w(it, "Unable to parse storeFormData request") return@launch } if (!request.isValid()) { Timber.w("Invalid data from storeFormData") return@launch } val jsCredentials = JavascriptCredentials(request.credentials!!.username, request.credentials.password) val credentials = jsCredentials.asLoginCredentials(currentUrl) val autologinId = autoSavedLoginsMonitor?.getAutoSavedLoginId(tabId) Timber.i("Autogenerated? %s, Previous autostored login ID: %s", request.credentials.autogenerated, autologinId) val autosavedLogin = autologinId?.let { autofillStore.getCredentialsWithId(it) } val autogenerated = request.credentials.autogenerated val actions = passwordEventResolver.decideActions(autosavedLogin, autogenerated) processStoreFormDataActions(actions, currentUrl, credentials) } } private suspend fun processStoreFormDataActions( actions: List<Actions>, currentUrl: String, credentials: LoginCredentials, ) { Timber.d("%d actions to take: %s", actions.size, actions.joinToString()) actions.forEach { when (it) { is DeleteAutoLogin -> { autofillStore.deleteCredentials(it.autologinId) } is DiscardAutoLoginId -> { autoSavedLoginsMonitor?.clearAutoSavedLoginId(tabId) } is PromptToSave -> { callback?.onCredentialsAvailableToSave(currentUrl, credentials) } is UpdateSavedAutoLogin -> { autofillStore.getCredentialsWithId(it.autologinId)?.let { existingCredentials -> if (isUpdateRequired(existingCredentials, credentials)) { Timber.v("Update required as not identical to what is already stored. id=%s", it.autologinId) val toSave = existingCredentials.copy(username = credentials.username, password = <PASSWORD>) autofillStore.updateCredentials(toSave)?.let { savedCredentials -> callback?.onCredentialsSaved(savedCredentials) } } else { Timber.v("Update not required as identical to what is already stored. id=%s", it.autologinId) callback?.onCredentialsSaved(existingCredentials) } } } } } } private fun isUpdateRequired( existingCredentials: LoginCredentials, credentials: LoginCredentials, ): Boolean { return existingCredentials.username != credentials.username || existingCredentials.password != credentials.password } private fun AutofillStoreFormDataRequest?.isValid(): Boolean { if (this == null || credentials == null) return false return !(credentials.username.isNullOrBlank() && credentials.password.isNullOrBlank()) } override fun injectCredentials(credentials: LoginCredentials) { Timber.v("Informing JS layer with credentials selected") injectCredentialsJob += coroutineScope.launch(dispatcherProvider.io()) { val jsCredentials = credentials.asJsCredentials() val jsonResponse = autofillResponseWriter.generateResponseGetAutofillData(jsCredentials) Timber.i("Injecting credentials: %s", jsonResponse) autofillMessagePoster.postMessage(webView, jsonResponse) } } override fun injectNoCredentials() { Timber.v("No credentials selected; informing JS layer") injectCredentialsJob += coroutineScope.launch(dispatcherProvider.io()) { autofillMessagePoster.postMessage(webView, autofillResponseWriter.generateEmptyResponseGetAutofillData()) } } private fun LoginCredentials.asJsCredentials(): JavascriptCredentials { return JavascriptCredentials( username = username, password = <PASSWORD>, ) } override fun cancelRetrievingStoredLogins() { getAutofillDataJob.cancel() } override fun acceptGeneratedPassword() { Timber.v("Accepting generated password") injectCredentialsJob += coroutineScope.launch(dispatcherProvider.io()) { autofillMessagePoster.postMessage(webView, autofillResponseWriter.generateResponseForAcceptingGeneratedPassword()) } } override fun rejectGeneratedPassword() { Timber.v("Rejecting generated password") injectCredentialsJob += coroutineScope.launch(dispatcherProvider.io()) { autofillMessagePoster.postMessage(webView, autofillResponseWriter.generateResponseForRejectingGeneratedPassword()) } } override fun inContextEmailProtectionFlowFinished() { emailProtectionInContextSignupJob += coroutineScope.launch(dispatcherProvider.io()) { val json = autofillResponseWriter.generateResponseForEmailProtectionEndOfFlow(emailManager.isSignedIn()) autofillMessagePoster.postMessage(webView, json) } } private fun JavascriptCredentials.asLoginCredentials( url: String, ): LoginCredentials { return LoginCredentials( id = null, domain = url, username = username, password = <PASSWORD>, domainTitle = null, ) } interface UrlProvider { suspend fun currentUrl(webView: WebView?): String? } @ContributesBinding(AppScope::class) class WebViewUrlProvider @Inject constructor(val dispatcherProvider: DispatcherProvider) : UrlProvider { override suspend fun currentUrl(webView: WebView?): String? { return withContext(dispatcherProvider.main()) { webView?.url } } } }
68
null
901
3,823
6415f0f087a11a51c0a0f15faad5cce9c790417c
18,863
Android
Apache License 2.0
app/src/main/java/com/tomclaw/drawa/share/ShareItem.kt
solkin
62,579,229
false
{"Kotlin": 201724, "Java": 39209}
package com.tomclaw.drawa.share import android.os.Parcel import android.os.Parcelable import androidx.annotation.DrawableRes import androidx.annotation.StringRes class ShareItem( val id: Int, @DrawableRes val image: Int, @StringRes val title: Int, @StringRes val description: Int ) : Parcelable { override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) { writeInt(id) writeInt(image) writeInt(title) writeInt(description) } override fun describeContents(): Int = 0 companion object CREATOR : Parcelable.Creator<ShareItem> { override fun createFromParcel(parcel: Parcel): ShareItem { val id = parcel.readInt() val image = parcel.readInt() val title = parcel.readInt() val description = parcel.readInt() return ShareItem(id, image, title, description) } override fun newArray(size: Int): Array<ShareItem?> { return arrayOfNulls(size) } } }
1
Kotlin
6
22
131f0ef2a9ea88854f18ecef2250d5396da225e2
1,043
drawa-android
Apache License 2.0
data/src/main/java/com/ribsky/data/model/UserApiModel.kt
nexy791
607,748,138
false
null
package com.ribsky.data.model import com.ribsky.domain.model.user.BaseUserModel import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class UserApiModel( override val name: String = "", override val email: String = "", override val image: String = "", override var score: Int = 0, override var lessons: Map<String, String> = HashMap(), override var lessonsCount: Int = 0, override var saved: Map<String, String> = HashMap(), override var version: Long = 0, override var hasPrem: Boolean = false, override var hasDiscount: Boolean = false, override var botTotalCount: Long = 0, override var streak: Int = 0, override var streakLastDay: Long = 0, override var bioLevel: Int = -1, override var bioGoal: Int = -1, ) : BaseUserModel { @JsonClass(generateAdapter = true) data class UserApiModelRequest( val name: String = "", val email: String = "", val image: String = "", var score: Int = 0, var lessons: Map<String, String> = HashMap(), var lessonsCount: Int = 0, var saved: Map<String, String> = HashMap(), var version: Long = 0, var hasPrem: Boolean = false, var botTotalCount: Long = 0, var streak: Int = 0, var streakLastDay: Long = 0, var bioLevel: Int = -1, var bioGoal: Int = -1, ) { constructor(user: BaseUserModel) : this( name = user.name, email = user.email, image = user.image, score = user.score, lessons = user.lessons, lessonsCount = user.lessonsCount, saved = user.saved, version = user.version, hasPrem = user.hasPrem, botTotalCount = user.botTotalCount, streak = user.streak, streakLastDay = user.streakLastDay, bioLevel = user.bioLevel, bioGoal = user.bioGoal, ) fun toMap(): Map<String, Any?> { return mapOf( "name" to name, "email" to email, "image" to image, "score" to score, "lessons" to lessons, "lessonsCount" to lessonsCount, "saved" to saved, "version" to version, "hasPrem" to hasPrem, "botTotalCount" to botTotalCount, "streak" to streak, "streakLastDay" to streakLastDay, "bioLevel" to bioLevel, "bioGoal" to bioGoal, ) } } constructor(user: BaseUserModel) : this( name = user.name, email = user.email, image = user.image, score = user.score, lessons = user.lessons, lessonsCount = user.lessonsCount, saved = user.saved, version = user.version, hasDiscount = user.hasDiscount, hasPrem = user.hasPrem, streak = user.streak, streakLastDay = user.streakLastDay, bioLevel = user.bioLevel, bioGoal = user.bioGoal, ) }
0
null
0
17
ff6543fd2b738b6861f03b7509c80534dd56f417
3,131
dymka
Apache License 2.0
src/main/kotlin/io/github/sulion/jared/processing/Classificator.kt
Sulion
220,689,115
false
null
package io.github.sulion.jared.processing import io.github.sulion.jared.config.DSL_CONFIG import io.github.sulion.jared.data.ExpenseCategory import io.github.sulion.jared.models.Tables.CLASSIFICATOR import org.apache.commons.codec.digest.DigestUtils import org.jooq.SQLDialect import org.jooq.impl.DSL import java.util.* import javax.sql.DataSource class Classificator(private val dataSource: DataSource) { fun classify(term: String): ExpenseCategory? = dataSource.connection.use { DSL.using(it, SQLDialect.POSTGRES_10, DSL_CONFIG.settings) .selectFrom(CLASSIFICATOR) .where(CLASSIFICATOR.KEYWORD.startsWith(term)) .fetch(CLASSIFICATOR.CATEGORY) .firstOrNull() ?.toUpperCase() ?.toCategory() } fun extendClassification(term: String, category: ExpenseCategory) { val preparedTerm = term.toLowerCase().trim() dataSource.connection.use { DSL.using(it, SQLDialect.POSTGRES_10, DSL_CONFIG.settings).transaction { c -> DSL.using(c) .insertInto(CLASSIFICATOR, CLASSIFICATOR.HASH, CLASSIFICATOR.KEYWORD, CLASSIFICATOR.CATEGORY) .values(preparedTerm.digest(), preparedTerm, category.name.toLowerCase()) .execute() } } } private fun String.toCategory() = ExpenseCategory.valueOf(this) private fun String.digest() = String(Base64.getEncoder().encode(DigestUtils.sha256(this))) }
0
Kotlin
0
0
4a1137a88bc5269841f2db6fbfb3a380506074c5
1,558
jared-the-manager
Apache License 2.0
providers/aws/src/main/kotlin/cloudspec/aws/sns/SNSResourceLoader.kt
efoncubierta
259,448,965
false
null
/*- * #%L * CloudSpec AWS Provider * %% * Copyright (C) 2020 <NAME> * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package cloudspec.aws.sns import arrow.core.Option import arrow.core.extensions.list.traverse.sequence import arrow.core.extensions.listk.functorFilter.filter import arrow.core.firstOrNone import arrow.fx.IO import arrow.fx.extensions.fx import arrow.fx.extensions.io.applicative.applicative import arrow.syntax.collections.flatten import cloudspec.aws.AWSConfig import cloudspec.aws.AWSResourceLoader import cloudspec.aws.IAWSClientsProvider import cloudspec.aws.sns.nested.toKeyValues import cloudspec.model.KeyValue import cloudspec.model.SetValues import cloudspec.model.getStrings import software.amazon.awssdk.arns.Arn import software.amazon.awssdk.regions.Region import software.amazon.awssdk.services.sns.SnsClient abstract class SNSResourceLoader<T : SNSResource>(protected val clientsProvider: IAWSClientsProvider) : AWSResourceLoader<T> { override fun byId(sets: SetValues, id: String): IO<Option<T>> { return IO.fx { val (resources) = resources(sets, listOf(id)) resources.firstOrNone() } } override fun all(sets: SetValues): IO<List<T>> = resources(sets, emptyList()) protected fun resources(sets: SetValues, ids: List<String>): IO<List<T>> { return if (ids.isNotEmpty()) { // TODO filter out ARNs not in AWSConfig.REGIONS_REF resourcesByArns(ids.map { Arn.fromString(it) }) } else { allResources(sets) } } private fun resourcesByArns(arns: List<Arn>): IO<List<T>> { return IO.fx { val (tables) = arns.map { resourceByArn(it) }.sequence(IO.applicative()) tables.filter { it.isDefined() }.flatten() } } abstract fun resourceByArn(arn: Arn): IO<Option<T>> private fun allResources(sets: SetValues): IO<List<T>> { return IO.fx { val (tables) = sets.getStrings(AWSConfig.REGIONS_REF) .let { regions -> if (regions.isEmpty()) Region.regions() else regions.map { Region.of(it) } } .map { resourcesByRegion(it) } .parSequence() tables.flatten() } } abstract fun resourcesByRegion(region: Region): IO<List<T>> protected fun <V> requestGlobal(handler: (client: SnsClient) -> V): IO<V> { return IO.effect { clientsProvider.snsClient.use { client -> handler(client) } } } protected fun <V> requestInRegion(region: Region, handler: (client: SnsClient) -> V): IO<V> { return IO.effect { clientsProvider.snsClientForRegion(region).use { client -> handler(client) } } } protected fun listTags(region: Region, arn: String): IO<List<KeyValue>> { return requestInRegion(region) { client -> // https://docs.aws.amazon.com/sns/latest/api/API_ListTagsForResource.html client.listTagsForResource { builder -> builder.resourceArn(arn) } .tags() .toKeyValues() } } }
3
Kotlin
2
26
edabff96392cdb1f0d55b3a9c57ae5c433c7be69
3,761
cloudspec
Apache License 2.0
sdk/src/main/kotlin/GetApp/Client/models/UploadArtifactDto.kt
getappsh
735,551,269
false
{"Kotlin": 788107, "Java": 8139, "Python": 589}
/** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package GetApp.Client.models import com.squareup.moshi.Json import com.squareup.moshi.JsonClass /** * * * @param platform * @param component * @param formation * @param OS * @param version * @param releaseNotes * @param propertySize * @param url * @param artifactType * @param uploadToken */ data class UploadArtifactDto ( @Json(name = "platform") val platform: kotlin.String? = null, @Json(name = "component") val component: kotlin.String? = null, @Json(name = "formation") val formation: kotlin.String? = null, @Json(name = "OS") val OS: kotlin.String? = null, @Json(name = "version") val version: kotlin.String? = null, @Json(name = "releaseNotes") val releaseNotes: kotlin.String? = null, @Json(name = "size") val propertySize: kotlin.String? = null, @Json(name = "url") val url: kotlin.String? = null, @Json(name = "artifactType") val artifactType: kotlin.String? = null, @Json(name = "uploadToken") val uploadToken: kotlin.String? = null )
2
Kotlin
1
1
423a49aea8abd2f6b85cc00bf7ecd46dd742db9e
1,339
getmap-android-sdk
Apache License 2.0
app/src/test/java/app/odapplications/bitstashwallet/modules/pin/unlock/UnlockPinPresenterTest.kt
bitstashco
220,133,996
false
null
package app.odapplications.bitstashwallet.modules.pin.unlock import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.never import com.nhaarman.mockito_kotlin.verify import app.odapplications.bitstashwallet.entities.LockoutState import app.odapplications.bitstashwallet.modules.RxBaseTest import app.odapplications.bitstashwallet.modules.pin.PinModule import org.junit.Before import org.junit.Test import org.mockito.Mockito.mock import org.mockito.Mockito.reset import java.util.* class UnlockPinPresenterTest { private val interactor = mock(UnlockPinModule.IInteractor::class.java) private val router = mock(UnlockPinModule.IRouter::class.java) private val view = mock(PinModule.IView::class.java) private lateinit var presenter: UnlockPinPresenter @Before fun setUp() { RxBaseTest.setup() presenter = UnlockPinPresenter(view, router, interactor, false) } @Test fun testAddPages() { presenter.viewDidLoad() verify(view).addPages(any()) } @Test fun viewDidLoad() { presenter.viewDidLoad() verify(view).hideToolbar() verify(interactor).updateLockoutState() } @Test fun viewDidLoad_showCancelButton() { presenter = UnlockPinPresenter(view, router, interactor, true) presenter.viewDidLoad() verify(view).showBackButton() verify(interactor).updateLockoutState() } @Test fun onUnlockEnter() { val pin = "000000" presenter.onEnter(pin, 0) verify(view).fillCircles(pin.length, 0) verify(interactor).unlock(pin) } @Test fun onUnlockEnter_notEnough() { val pin = "00000" presenter.onEnter(pin, 0) verify(interactor, never()).unlock(pin) } @Test fun onDelete() { val pin = "12345" presenter.onEnter(pin, 0) verify(view).fillCircles(5, 0) reset(view) presenter.onDelete(0) verify(view).fillCircles(4, 0) } @Test fun wrongPinSubmitted() { val pin = "12345" presenter.onEnter(pin, 0) verify(view).fillCircles(5, 0) reset(view) presenter.wrongPinSubmitted() verify(view).showPinWrong(0) } @Test fun onUnlock_onAppStart() { presenter = UnlockPinPresenter(view, router, interactor, false) presenter.unlock() verify(router).dismissModuleWithSuccess() } @Test fun onViewDidLoad_UpdateLockoutState() { presenter.viewDidLoad() verify(interactor).updateLockoutState() } @Test fun updateLockoutState_Unlocked() { val hasFailedAttempts = false val state = LockoutState.Unlocked(hasFailedAttempts) presenter.updateLockoutState(state) verify(view).showPinInput() verify(view, never()).showLockView(any()) } @Test fun updateLockoutState_UnlockedWithFewAttempts() { val hasFailedAttempts = true val state = LockoutState.Unlocked(hasFailedAttempts) presenter.updateLockoutState(state) verify(view).showPinInput() verify(view, never()).showLockView(any()) } @Test fun updateLockoutState_Locked() { val date = Date() val state = LockoutState.Locked(date) presenter.updateLockoutState(state) verify(view).showLockView(any()) verify(view, never()).showPinInput() } }
4
Java
3
11
64c242dbbcb6b4df475a608b1edb43f87e5091fd
3,451
BitStash-Android-Wallet
MIT License
squash-mysql/test/org/jetbrains/squash/dialects/mysql/tests/MySqlModificationTests.kt
orangy
59,228,714
false
null
package org.jetbrains.squash.dialects.mysql.tests import org.jetbrains.squash.tests.* class MySqlModificationTests : ModificationTests(), DatabaseTests by MySqlDatabaseTests()
27
Kotlin
17
258
dc025481b7104a5e234d6df370d715b6b37c81eb
177
squash
Apache License 2.0
app/src/main/java/com/lxh/cookcommunity/ui/fragment/fooddetail/FoodDetailViewModel.kt
wyuange
330,105,416
true
{"Kotlin": 272162, "Java": 20875, "FreeMarker": 1691}
package com.lxh.cookcommunity.ui.fragment.fooddetail import android.app.Application import androidx.lifecycle.MutableLiveData import com.lxh.cookcommunity.manager.api.ApiService import com.lxh.cookcommunity.model.api.home.Food import com.lxh.cookcommunity.ui.base.BaseViewModel import org.kodein.di.generic.instance class FoodDetailViewModel(application: Application) : BaseViewModel(application) { val apiService by instance<ApiService>() val bannerListMutableLiveData = MutableLiveData<List<String>>() val foodMutableLiveData = MutableLiveData<Food>() //拉取Banner fun fetchBannerList() { bannerListMutableLiveData.postValue( listOf( "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1607513279220&di=2369ecf649d5b2008b8bed9ad0c9b407&imgtype=0&src=http%3A%2F%2Fi2.chuimg.com%2F50d835d3dde44c83969debae054163f9_1280w_1280h.jpg%3FimageView2%2F2%2Fw%2F600%2Finterlace%2F1%2Fq%2F90", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1607513279220&di=2369ecf649d5b2008b8bed9ad0c9b407&imgtype=0&src=http%3A%2F%2Fi2.chuimg.com%2F50d835d3dde44c83969debae054163f9_1280w_1280h.jpg%3FimageView2%2F2%2Fw%2F600%2Finterlace%2F1%2Fq%2F90", "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1607513279220&di=2369ecf649d5b2008b8bed9ad0c9b407&imgtype=0&src=http%3A%2F%2Fi2.chuimg.com%2F50d835d3dde44c83969debae054163f9_1280w_1280h.jpg%3FimageView2%2F2%2Fw%2F600%2Finterlace%2F1%2Fq%2F90" ) ) } }
0
null
0
0
3b9bbc73569cef6c735ab288b5087739135b9557
1,553
CookCommunity
Apache License 2.0
security/src/main/java/pm/gnosis/svalinn/security/FingerprintHelper.kt
vanderian
171,901,954
false
null
package pm.gnosis.svalinn.security import io.reactivex.Completable import io.reactivex.Observable import io.reactivex.Single import javax.crypto.Cipher interface FingerprintHelper { fun removeKey(): Completable fun systemHasFingerprintsEnrolled(): Boolean fun isKeySet(): Single<Boolean> fun authenticate(iv: ByteArray? = null): Observable<AuthenticationResult> } sealed class AuthenticationResult class AuthenticationFailed : AuthenticationResult() data class AuthenticationError(val errMsgId: Int, val errString: CharSequence?) : IllegalArgumentException() data class AuthenticationHelp(val helpMsgId: Int, val helpString: CharSequence?) : AuthenticationResult() data class AuthenticationResultSuccess(val cipher: Cipher) : AuthenticationResult() class FingerprintNotAvailable(message: String? = null) : Exception(message)
1
null
1
1
68371db16857c7420697ed1a54d1f074c7fd4f8e
844
svalinn-kotlin
MIT License
app/src/main/java/tech/danielwaiguru/notebook/presentation/viewmodels/AddNoteViewModel.kt
DanielWaiguru91
272,407,309
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package tech.danielwaiguru.notebook.presentation.viewmodels import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.launch import tech.danielwaiguru.notebook.domain.model.Note import tech.danielwaiguru.notebook.domain.repository.NoteRepository class AddNoteViewModel(private val noteRepository: NoteRepository) : ViewModel() { fun saveNote(note: Note) = viewModelScope.launch { noteRepository.insertNote(note) } }
0
Kotlin
1
2
652e0c9e86c9bc1b4826b04a1ec8e23385f1dee5
1,098
Notebook
Apache License 2.0
app/src/main/java/com/jeanbarrossilva/realism/data/RealismPreference.kt
jeanbarrossilva
315,365,931
false
null
package com.jeanbarrossilva.realism.data import android.content.Context import android.util.Log import androidx.compose.runtime.Composable import androidx.compose.ui.platform.ContextAmbient import androidx.compose.ui.res.stringResource import androidx.core.content.edit import com.jeanbarrossilva.realism.extension.ContextX.preferences import com.jeanbarrossilva.realism.R import com.jeanbarrossilva.realism.extension.SharedPreferencesEditorX.put import java.time.LocalTime @Suppress("UNCHECKED_CAST") class RealismPreference<T>( private val context: Context, val key: String, val defaultValue: T, val name: String? = null, val dependency: RealismPreference<Boolean>? = null ) { private val preferences = context.preferences private val doesSharedPreferenceExist = preferences.contains(key) /** Gets the value from [context]'s [android.content.SharedPreferences]. **/ fun value() = preferences.all[key] as T fun setValue(context: Context, value: T) = context.preferences.edit(commit = true) { put(key, value) } @Composable fun setValue(value: T) { setValue(ContextAmbient.current, value) with(onChangeListeners) { forEach { (key, function) -> if (key == [email protected]) function(value) } lastOrNull { (key, _) -> key == key }?.let { (key, _) -> Log.d("RealismPreference.setValueOf", "$key changed to $value.") } } } @Composable fun onChange(block: @Composable (T) -> Unit) { block(value()) onChangeListeners.add(key to block as @Composable (Any?) -> Unit) } fun isAvailable() = dependency?.value() ?: true init { if (!doesSharedPreferenceExist) { preferences.edit { put(key, defaultValue) } Log.d("RealismPreference", "Tried to access nonexistent $key SharedPreference. It has been added with the value of ${value()}.") } } companion object { private val onChangeListeners = mutableListOf<Pair<String, @Composable (Any?) -> Unit>>() @Composable fun allowQuoteNotifications() = RealismPreference( ContextAmbient.current, key = "allowQuoteNotifications", defaultValue = true, name = stringResource(R.string.RealismPreference_name_allowQuoteNotifications) ) @Composable fun quoteNotificationTime() = RealismPreference( ContextAmbient.current, key = "quoteNotificationTime", defaultValue = LocalTime.of(9, 0).toString(), name = stringResource(R.string.RealismPreference_name_quoteNotificationTime), dependency = allowQuoteNotifications() ) } }
0
Kotlin
0
0
6727d0603e1bad83388988c322830604719267bc
2,715
EDQ
MIT License
kakao/src/main/kotlin/io/github/kakaocup/kakao/swiperefresh/SwipeRefreshLayoutActions.kt
KakaoCup
370,697,938
false
{"Kotlin": 325884, "Ruby": 148}
@file:Suppress("unused") package com.agoda.kakao.swiperefresh import android.view.View import androidx.swiperefreshlayout.widget.SwipeRefreshLayout import androidx.test.espresso.UiController import androidx.test.espresso.ViewAction import androidx.test.espresso.matcher.ViewMatchers import com.agoda.kakao.common.actions.SwipeableActions /** * Provides actions for SwipeRefreshLayout */ interface SwipeRefreshLayoutActions : SwipeableActions { /** * Sets the refreshing state of SwipeRefreshLayout * * @param refreshing state to be set */ fun setRefreshing(refreshing: Boolean) { view.perform(object : ViewAction { override fun getDescription() = "Sets the refreshing state to $refreshing" override fun getConstraints() = ViewMatchers.isAssignableFrom(SwipeRefreshLayout::class.java) override fun perform(uiController: UiController, view: View) { if (view is SwipeRefreshLayout) { view.isRefreshing = refreshing } } }) } }
13
Kotlin
28
330
578e2c729541e51cd584159404417234f0cbbce1
1,078
Kakao
Apache License 2.0
src/day01/Day01.kt
mherda64
512,106,270
false
{"Kotlin": 10058}
package day01 import readInputAsInts fun main() { fun part1(input: List<Int>): Int { return input.windowed(2).count { (a, b) -> a < b } } fun part2(input: List<Int>): Int { return input .windowed(3) .windowed(2) .count { (a,b) -> a.sum() < b.sum() } } // test if implementation meets criteria from the description, like: val testInput = readInputAsInts("Day01_test") check(part1(testInput) == 7) val input = readInputAsInts("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
d04e179f30ad6468b489d2f094d6973b3556de1d
577
AoC2021_kotlin
Apache License 2.0
app/src/main/java/pl/lightmobile/design01transitions/CustomTransitionFragment.kt
obiwanzenobi
180,178,805
false
null
package pl.lightmobile.design01transitions import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.transition.TransitionInflater class CustomTransitionFragment : Fragment() { override fun onAttach(context: Context?) { super.onAttach(context) enterTransition = TransitionInflater.from(context).inflateTransition(R.transition.custom_transition) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater.inflate(R.layout.fragment_custom_transition, container, false) } }
0
Kotlin
0
0
2b4a5407d48df2fb569ae75c1bcb1b13f003ac55
729
android-design01-transitions
MIT License
app/src/main/java/com/erkindilekci/rickandmorty/data/remote/dto/Location.kt
erkindilekci
656,549,599
false
null
package com.erkindilekci.rickandmorty.data.remote.dto data class Location( val name: String, val url: String )
0
Kotlin
0
0
f2ecc9e1f4936b2d1e0a272efb0c827619ff8a08
120
RickAndMorty
Apache License 2.0
onactivityresult/src/main/java/org/legobyte/onactivityresult/Proxy.kt
legobyte
213,495,273
false
null
package org.legobyte.onactivityresult import android.app.Activity import android.content.Context import android.content.ContextWrapper import android.content.Intent import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.ResultReceiver import androidx.annotation.CheckResult object Proxy { @JvmStatic val mainThreadHandler by lazy { Handler(Looper.getMainLooper()) } const val KEY_INTENT = "legobyte:intent" const val KEY_REQUEST_CODE = "legobyte:request-code" const val KEY_RESULT_RECEIVER = "legobyte:result-receiver" const val DEFAULT_REQUEST_CODE = 10 const val RESULT_INTENT_UNHANDLED = -10 fun with(context: Context): ContextBucket { return ContextBucket(context) } } data class ContextBucket(internal val context: Context) { @CheckResult fun listener(resultReceiver: (requestCode: Int, resultCode: Int, data: Intent?) -> Unit) = Launcher(this, resultReceiver) } data class Launcher(private val contextBucket: ContextBucket, private val resultReceiver: (requestCode: Int, resultCode: Int, data: Intent?) -> Unit){ fun launch(intent: Intent, requestCode: Int= Proxy.DEFAULT_REQUEST_CODE){ val receiver = object: ResultReceiver(Proxy.mainThreadHandler){ override fun onReceiveResult(resultCode: Int, resultData: Bundle?) { val resultIntent = resultData?.getParcelable<Intent>(Proxy.KEY_INTENT) resultReceiver(requestCode, resultCode, resultIntent) } } val context = when { contextBucket.context is Activity -> contextBucket.context contextBucket.context is ContextWrapper -> contextBucket.context.baseContext ?: contextBucket.context else -> contextBucket.context } context.startActivity(Intent(context, ProxyActivity::class.java).apply { if(context !is Activity){ // this is not an activity context addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) } putExtra(Proxy.KEY_INTENT, intent) putExtra(Proxy.KEY_REQUEST_CODE, requestCode) putExtra(Proxy.KEY_RESULT_RECEIVER, receiver) }) } }
0
Kotlin
1
9
43cd606783e7b63e32f55d9b9b27c951d61e2c78
2,227
OnActivityResult
Apache License 2.0
RetenoSdkPush/src/main/java/com/reteno/push/receiver/PushPermissionChangedReceiver.kt
reteno-com
545,381,514
false
{"Kotlin": 1163777, "Java": 164545, "HTML": 17807, "Shell": 379}
package com.reteno.push.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.reteno.core.util.Logger import com.reteno.core.util.isOsVersionSupported class PushPermissionChangedReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (!isOsVersionSupported()) { return } /*@formatter:off*/ Logger.i(TAG, "onReceive(): ", "context = [" , context , "], intent = [" , intent , "]") /*@formatter:on*/ try { context?.let(NotificationsEnabledManager::onCheckState) } catch (ex: Throwable) { /*@formatter:off*/ Logger.e(TAG, "onReceive(): ", ex) /*@formatter:on*/ } } companion object { private val TAG: String = PushPermissionChangedReceiver::class.java.simpleName } }
1
Kotlin
1
1
665fff618bff763e27c2aa8c2b46e8f122ba07d5
903
reteno-mobile-android-sdk
MIT License
ground/src/main/java/com/google/android/ground/persistence/local/room/dao/JobDao.kt
google
127,777,820
false
{"Kotlin": 1403201}
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.persistence.local.room.dao import androidx.room.Dao import androidx.room.Query import com.google.android.ground.persistence.local.room.entity.JobEntity import io.reactivex.Completable @Dao interface JobDao : BaseDao<JobEntity> { @Query("DELETE FROM job WHERE survey_id = :surveyId") fun deleteBySurveyId(surveyId: String): Completable }
224
Kotlin
116
245
502a3bcafa4d65ba62868036cf5287a4219aaf5c
972
ground-android
Apache License 2.0
app/src/main/java/com/koleff/kare_android/ui/compose/screen/WorkoutDetailsScreen.kt
MartinKoleff
741,013,199
false
{"Kotlin": 1413112}
package com.koleff.kare_android.ui.compose.screen import android.util.Log import androidx.compose.animation.core.animateDpAsState import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.calculateEndPadding import androidx.compose.foundation.layout.calculateStartPadding import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.pullrefresh.PullRefreshIndicator import androidx.compose.material.pullrefresh.pullRefresh import androidx.compose.material.pullrefresh.rememberPullRefreshState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalConfiguration import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.koleff.kare_android.data.model.dto.ExerciseDto import com.koleff.kare_android.data.model.dto.MuscleGroup import com.koleff.kare_android.data.model.dto.WorkoutConfigurationDto import com.koleff.kare_android.data.model.response.base_response.KareError import com.koleff.kare_android.ui.compose.banners.AddExerciseToWorkoutBanner import com.koleff.kare_android.ui.compose.banners.SwipeableExerciseBanner import com.koleff.kare_android.ui.compose.components.DeleteExercisesRow import com.koleff.kare_android.ui.compose.components.LoadingWheel import com.koleff.kare_android.ui.compose.components.SelectedExercisesRow import com.koleff.kare_android.ui.compose.components.StartWorkoutHeader import com.koleff.kare_android.ui.compose.components.StartWorkoutToolbar import com.koleff.kare_android.ui.compose.components.SubmitExercisesRow import com.koleff.kare_android.ui.compose.components.navigation_components.scaffolds.MainScreenScaffold import com.koleff.kare_android.ui.compose.dialogs.DeleteExerciseDialog import com.koleff.kare_android.ui.compose.dialogs.DeleteMultipleExercisesDialog import com.koleff.kare_android.ui.compose.dialogs.EditWorkoutDialog import com.koleff.kare_android.ui.compose.dialogs.ErrorDialog import com.koleff.kare_android.ui.compose.dialogs.FavoriteWorkoutDialog import com.koleff.kare_android.ui.compose.dialogs.WarningDialog import com.koleff.kare_android.ui.compose.dialogs.WorkoutConfigurationDialog import com.koleff.kare_android.ui.event.OnMultipleExercisesUpdateEvent import com.koleff.kare_android.ui.state.AnimatedToolbarState import com.koleff.kare_android.ui.state.BaseState import com.koleff.kare_android.ui.view_model.WorkoutDetailsViewModel import kotlinx.coroutines.flow.collectLatest @OptIn(ExperimentalMaterialApi::class) @Composable fun WorkoutDetailsScreen( workoutDetailsViewModel: WorkoutDetailsViewModel = hiltViewModel() ) { val workoutDetailsState by workoutDetailsViewModel.getWorkoutDetailsState.collectAsState() val updateWorkoutDetailsState by workoutDetailsViewModel.updateWorkoutDetailsState.collectAsState() val deleteWorkoutDetailsState by workoutDetailsViewModel.deleteWorkoutState.collectAsState() val deleteExerciseState by workoutDetailsViewModel.deleteExerciseState.collectAsState() val startWorkoutState by workoutDetailsViewModel.startWorkoutState.collectAsState() val createWorkoutState by workoutDetailsViewModel.createWorkoutState.collectAsState() val favoriteWorkoutState by workoutDetailsViewModel.favoriteWorkoutState.collectAsState() val unfavoriteWorkoutState by workoutDetailsViewModel.unfavoriteWorkoutState.collectAsState() val workoutTitle = if (workoutDetailsState.workoutDetails.name == "" || updateWorkoutDetailsState.isLoading) "Loading..." else workoutDetailsState.workoutDetails.name var selectedWorkout by remember { mutableStateOf(workoutDetailsState.workoutDetails) } var exercises by remember { mutableStateOf(selectedWorkout.exercises) } var selectedExercise by remember { mutableStateOf<ExerciseDto?>(null) } var showAddExerciseBanner by remember { mutableStateOf(workoutDetailsState.isSuccessful) } //Update workout on initial load LaunchedEffect(workoutDetailsState) { if (workoutDetailsState.isSuccessful) { Log.d("WorkoutDetailsScreen", "Initial load completed.") selectedWorkout = workoutDetailsState.workoutDetails exercises = selectedWorkout.exercises showAddExerciseBanner = true } } //When exercise is deleted -> update workout exercise list LaunchedEffect(deleteExerciseState) { if (deleteExerciseState.isSuccessful) { Log.d("WorkoutDetailsScreen", "Exercise successfully deleted.") selectedWorkout = deleteExerciseState.workoutDetails exercises = selectedWorkout.exercises } } //Dialog visibility var showDeleteExerciseDialog by remember { mutableStateOf(false) } var showDeleteMultipleExercisesDialog by remember { mutableStateOf(false) } var showEditWorkoutNameDialog by remember { mutableStateOf(false) } var showFavoriteDialog by remember { mutableStateOf(false) } var showUnfavoriteDialog by remember { mutableStateOf(false) } var showDeleteWorkoutDialog by remember { mutableStateOf(false) } var showWorkoutConfigureDialog by remember { mutableStateOf(false) } var showErrorDialog by remember { mutableStateOf(false) } var showLoadingDialog by remember { mutableStateOf(false) } //Dialog callbacks val onDeleteWorkout: () -> Unit = { workoutDetailsViewModel.deleteWorkout() showDeleteWorkoutDialog = false } val onFavoriteWorkout: () -> Unit = { workoutDetailsViewModel.favoriteWorkout(selectedWorkout.workoutId) showFavoriteDialog = false } val onUnfavoriteWorkout: () -> Unit = { workoutDetailsViewModel.unfavoriteWorkout(selectedWorkout.workoutId) showUnfavoriteDialog = false } val onEditWorkoutName: (String) -> Unit = { newName -> val updatedWorkout = selectedWorkout.copy(name = newName) //Update workout workoutDetailsViewModel.updateWorkout(updatedWorkout) showEditWorkoutNameDialog = false } val onUpdateWorkoutConfiguration: (WorkoutConfigurationDto) -> Unit = { configuration -> workoutDetailsViewModel.updateWorkoutConfiguration( configuration ) showWorkoutConfigureDialog = false } var isDeleteMode by remember { mutableStateOf(false) } val onDeleteModeEnabled = { isDeleteMode = !isDeleteMode } val selectedExercises = remember { mutableStateListOf<ExerciseDto>() } val onDeleteMultipleExercises: () -> Unit = { //(List<ExerciseDto>) -> Unit workoutDetailsViewModel.onMultipleExercisesUpdateEvent( OnMultipleExercisesUpdateEvent.OnMultipleExercisesDelete(selectedExercises) ) selectedExercises.clear() isDeleteMode = false showDeleteMultipleExercisesDialog = false } val onDeleteExercise = { selectedExercise?.let { workoutDetailsViewModel.deleteExercise( workoutDetailsState.workoutDetails.workoutId, selectedExercise!!.exerciseId ) } showDeleteExerciseDialog = false } val onExerciseSelected: (ExerciseDto) -> Unit = { selectedExercise -> if (isDeleteMode) { val isNewExercise = !selectedExercises.map { it.exerciseId } .contains(selectedExercise.exerciseId) if (isNewExercise) { selectedExercises.add( selectedExercise.copy(workoutId = workoutDetailsState.workoutDetails.workoutId) ) } else { selectedExercises.removeAll { it.exerciseId == selectedExercise.exerciseId } isDeleteMode = selectedExercises.isNotEmpty() } } else { workoutDetailsViewModel.navigateToExerciseDetailsConfigurator(selectedExercise) } } //Error handling var error by remember { mutableStateOf<KareError?>(null) } val onErrorDialogDismiss = { showErrorDialog = false workoutDetailsViewModel.clearError() //Enters launched effect to update showErrorDialog... } LaunchedEffect( workoutDetailsState, deleteExerciseState, deleteWorkoutDetailsState, updateWorkoutDetailsState, startWorkoutState, createWorkoutState, favoriteWorkoutState, unfavoriteWorkoutState ) { val states = listOf( workoutDetailsState, deleteExerciseState, deleteWorkoutDetailsState, updateWorkoutDetailsState, startWorkoutState, createWorkoutState, favoriteWorkoutState, unfavoriteWorkoutState ) val errorState: BaseState = states.firstOrNull { it.isError } ?: BaseState() error = errorState.error showErrorDialog = errorState.isError Log.d("WorkoutDetailsScreen", "Error detected -> $showErrorDialog") val loadingState = states.firstOrNull { it.isLoading } ?: BaseState() showLoadingDialog = loadingState.isLoading } //Dialogs if (showErrorDialog) { Log.d("WorkoutDetailsScreen", "Error: $error") error?.let { ErrorDialog(it, onErrorDialogDismiss) } } if (showDeleteExerciseDialog) { DeleteExerciseDialog( onClick = onDeleteExercise, onDismiss = { showDeleteExerciseDialog = false } ) } if (showDeleteMultipleExercisesDialog) { DeleteMultipleExercisesDialog( totalExercises = selectedExercises.size, onClick = onDeleteMultipleExercises, onDismiss = { showDeleteMultipleExercisesDialog = false } ) } if (showEditWorkoutNameDialog) { EditWorkoutDialog( currentName = selectedWorkout.name, onDismiss = { showEditWorkoutNameDialog = false }, onConfirm = onEditWorkoutName ) } if (showDeleteWorkoutDialog) { WarningDialog( title = "Delete Workout", description = "Are you sure you want to delete this workout? This action cannot be undone.", positiveButtonTitle = "Delete", onClick = onDeleteWorkout, onDismiss = { showDeleteWorkoutDialog = false } ) } if (showWorkoutConfigureDialog) { WorkoutConfigurationDialog( workoutConfiguration = workoutDetailsState.workoutDetails.configuration, onSave = onUpdateWorkoutConfiguration, onDismiss = { showWorkoutConfigureDialog = false } ) } if (showFavoriteDialog) { FavoriteWorkoutDialog(actionTitle = "Favorite Workout", onClick = onFavoriteWorkout, onDismiss = { showFavoriteDialog = false } ) } if (showUnfavoriteDialog) { FavoriteWorkoutDialog(actionTitle = "Unfavorite Workout", onClick = onUnfavoriteWorkout, onDismiss = { showUnfavoriteDialog = false } ) } //Pull to refresh val pullRefreshState = rememberPullRefreshState( refreshing = workoutDetailsViewModel.isRefreshing, onRefresh = { workoutDetailsViewModel.getWorkoutDetails(workoutDetailsState.workoutDetails.workoutId) } ) //Collapsable header state val configuration = LocalConfiguration.current val screenHeight = configuration.screenHeightDp.dp val lazyListState = rememberLazyListState() val scrollThreshold = screenHeight / 2 //firstVisibleItemIndex -> How many elements are scrolled from the screen. //First element is collapsable header. Second is workout banner and etc... //------------------------------------------------------------------------ //firstVisibleItemScrollOffset -> current scroll session offset. //Resets once you stop scrolling. val showToolbar = remember { derivedStateOf { lazyListState.firstVisibleItemIndex > 0 || lazyListState.firstVisibleItemScrollOffset >= scrollThreshold.value } } val toolbarSize = 65.dp val toolbarHeight = animateDpAsState( targetValue = if (showToolbar.value) toolbarSize else 0.dp, label = "Main screen toolbar height" ) val textAlpha by animateFloatAsState( targetValue = if (toolbarHeight.value > 40.dp) 1f else 0f, label = "Text alpha animation" ) //Recompositions when scroll state changes val isLogging = false LaunchedEffect(lazyListState) { snapshotFlow { lazyListState.firstVisibleItemIndex } .collectLatest { index -> if (isLogging) Log.d("WorkoutDetailsScreen", "First visible item index: $index") } snapshotFlow { lazyListState.firstVisibleItemScrollOffset } .collectLatest { offset -> if (isLogging) Log.d( "WorkoutDetailsScreen", "First visible item scroll offset: $offset" ) } } MainScreenScaffold( screenTitle = workoutTitle, onNavigateToDashboard = { workoutDetailsViewModel.onNavigateToDashboard() }, onNavigateToWorkouts = { workoutDetailsViewModel.onNavigateToWorkouts() }, onNavigateBackAction = { workoutDetailsViewModel.onNavigateBack() }, onNavigateToSettings = { workoutDetailsViewModel.onNavigateToSettings() }, animatedToolbarState = AnimatedToolbarState( showToolbar = showToolbar.value, toolbarHeight = toolbarHeight.value, textAlpha = textAlpha ) ) { innerPadding -> val loadingWheelPadding = PaddingValues( top = toolbarSize + innerPadding.calculateTopPadding(), //Top toolbar padding start = innerPadding.calculateStartPadding(LayoutDirection.Rtl), end = innerPadding.calculateEndPadding(LayoutDirection.Rtl), bottom = innerPadding.calculateBottomPadding() ) Box( Modifier .fillMaxSize() .pullRefresh(pullRefreshState) ) { if (showLoadingDialog) { LoadingWheel(innerPadding = loadingWheelPadding) } else { //Exercises LazyColumn( state = lazyListState, modifier = Modifier .fillMaxSize() .padding(innerPadding), verticalArrangement = Arrangement.Top, horizontalAlignment = Alignment.CenterHorizontally ) { //Collapsable header with toolbar item { StartWorkoutHeader( modifier = Modifier.fillParentMaxHeight(), title = workoutTitle, subtitle = MuscleGroup.toDescription(selectedWorkout.muscleGroup), isWorkoutFavorited = selectedWorkout.isFavorite, onStartWorkoutAction = { workoutDetailsViewModel.startWorkout() }, onConfigureAction = { showWorkoutConfigureDialog = true }, onAddExerciseAction = { workoutDetailsViewModel.addExercise() }, onDeleteWorkoutAction = { showDeleteWorkoutDialog = true }, onEditWorkoutNameAction = { showEditWorkoutNameDialog = true }, onFavoriteWorkoutAction = { showFavoriteDialog = true }, onUnfavoriteWorkoutAction = { showUnfavoriteDialog = true }, onNavigateBackAction = { workoutDetailsViewModel.onNavigateBack() }, onNavigateToSettings = { workoutDetailsViewModel.onNavigateToSettings() } ) } Log.d("WorkoutDetailsScreen", "Exercises: $exercises") items(exercises.size) { currentExerciseId -> val currentExercise = exercises[currentExerciseId] SwipeableExerciseBanner( modifier = Modifier .fillParentMaxWidth() .height(200.dp), exercise = currentExercise, onClick = onExerciseSelected, onLongPress = { onDeleteModeEnabled() selectedExercise = currentExercise onExerciseSelected(currentExercise) }, onDelete = { selectedExercise = currentExercise showDeleteExerciseDialog = true }, isSelected = selectedExercises.contains(currentExercise) ) } item { if (showAddExerciseBanner) { //Show only after data is fetched AddExerciseToWorkoutBanner { //Open search exercise screen workoutDetailsViewModel.addExercise() } } } } //Footer if (selectedExercises.isNotEmpty()) { Column( modifier = Modifier .fillMaxSize() .padding(innerPadding), verticalArrangement = Arrangement.Bottom, horizontalAlignment = Alignment.CenterHorizontally, ) { SelectedExercisesRow(selectedExercises = selectedExercises) DeleteExercisesRow( modifier = Modifier.padding( top = 8.dp, start = 16.dp, end = 16.dp, bottom = 8.dp ), onDelete = { showDeleteMultipleExercisesDialog = true } ) } } } PullRefreshIndicator( modifier = Modifier.align(Alignment.TopCenter), refreshing = workoutDetailsViewModel.isRefreshing, state = pullRefreshState ) //If put as first content -> hides behind the screen... } //Fixed place WorkoutDetails custom toolbar Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.TopCenter ) { StartWorkoutToolbar( onNavigateBackAction = { workoutDetailsViewModel.onNavigateBack() }, onNavigateToSettings = { workoutDetailsViewModel.onNavigateToSettings() } ) } } }
23
Kotlin
0
4
4ad6b9f320ff60e05b453375b9b855bd3e4a3483
20,376
KareFitnessApp
MIT License
app/src/main/java/jp/osdn/gokigen/thetaview/operation/imagefile/ImageStoreLocal.kt
MRSa
747,976,113
false
{"Kotlin": 424651}
package jp.osdn.gokigen.thetaview.operation.imagefile import android.net.Uri import android.os.Environment import android.util.Log import androidx.camera.core.ImageCapture import androidx.camera.core.ImageCaptureException import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.content.ContextCompat import androidx.fragment.app.FragmentActivity import com.google.android.material.snackbar.Snackbar import jp.osdn.gokigen.thetaview.R import java.io.File import java.text.SimpleDateFormat import java.util.* class ImageStoreLocal(private val context: FragmentActivity) { /** * 保存用ディレクトリを準備する(ダメな場合はアプリ領域のディレクトリを確保する) * */ private fun prepareLocalOutputDirectory(): File { val mediaDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES) mediaDir?.mkdirs() return (if (mediaDir != null && mediaDir.exists()) mediaDir else context.filesDir) } fun takePhoto(imageCapture : ImageCapture?) { if (imageCapture == null) { Log.v(TAG, " takePhotoLocal() : ImageCapture is null.") return } Log.v(TAG, " takePhotoLocal()") try { val photoFile = File(prepareLocalOutputDirectory(), "P" + SimpleDateFormat(FILENAME_FORMAT, Locale.US).format(System.currentTimeMillis()) + ".jpg") val outputOptions = ImageCapture.OutputFileOptions.Builder(photoFile).build() imageCapture.takePicture( outputOptions, ContextCompat.getMainExecutor(context), object : ImageCapture.OnImageSavedCallback { override fun onError(exc: ImageCaptureException) { Log.e(TAG, "Photo capture failed: ${exc.message}", exc) } override fun onImageSaved(output: ImageCapture.OutputFileResults) { val savedUri = Uri.fromFile(photoFile) val msg = context.getString(R.string.capture_success) + " $savedUri" Snackbar.make(context.findViewById<ConstraintLayout>(R.id.main_layout), msg, Snackbar.LENGTH_SHORT).show() Log.v(TAG, msg) } } ) } catch (e : Exception) { e.printStackTrace() } } companion object { private val TAG = this.toString() private const val FILENAME_FORMAT = "yyyyMMdd_HHmmss" } }
0
Kotlin
0
0
a4ecad82ba955919de2bb16e18da2a2b6c2c7cfc
2,562
ThetaView
Apache License 2.0
src/AndroidODataOfflineSample/app/src/main/java/com/flexberry/androidodataofflinesample/data/local/datasource/room/RoomDataBaseEntityInfo.kt
Flexberry
632,280,538
false
null
package com.flexberry.androidodataofflinesample.data.local.datasource.room import androidx.sqlite.db.SimpleSQLiteQuery import com.flexberry.androidodataofflinesample.data.local.dao.BaseDao import kotlin.reflect.KClass /** * Информация о базе данных сущности. * * @param T Тип сущности. * @param kotlinClass Класс сущности. * @param dao [BaseDao] интерфейс. * @param tableName Имя таблицы. * @param details Список детейлов. */ class RoomDataBaseEntityInfo<T : Any> ( val kotlinClass: KClass<T>, val dao: BaseDao<T>, val tableName: String, val details: List<RoomDataBaseRelation<*>>? = null, val masters: List<RoomDataBaseRelation<*>>? = null ) { /** * Имя типа сущности. */ val typeName = kotlinClass.simpleName!! /** * Вставить сущности в текущий [BaseDao]. * * @param appData Список сущностей. * @return Количество вставленных сущностей. */ fun insertObjectsToDataBase(appData: List<Any>): Int { return dao.insertObjects(appData as List<T>).size } /** * Получить сущности из текущего [BaseDao]. * * @param query Запрос. * @return Список сущностей. */ fun getObjectsFromDataBase(query: SimpleSQLiteQuery): List<T> { return dao.getObjects(query) } /** * Обновить сущности в текущем [BaseDao]. * * @param appData Список сущностей. * @return Количество обновленных сущностей. */ fun updateObjectsInDataBase(appData: List<Any>): Int { return dao.updateObjects(appData as List<T>) } /** * Удалить сущности из текущего [BaseDao]. * * @param appData Список сущностей. * @return Количество удаленных сущностей. */ fun deleteObjectsFromDataBase(appData: List<Any>): Int { return dao.deleteObjects(appData as List<T>) } /** * Содержит ли тип указанный детейл. * * @param detailName Имя детейла. * @return True если содержит, иначе False. */ fun hasDetail(detailName: String?): Boolean { return details?.any { it.entityProperty == detailName } ?: false } /** * Получить информацию о детейле по его имени. * * @param detailName Имя детейла. * @return Описание связи [RoomDataBaseRelation]. */ fun getDetailInfo(detailName: String?): RoomDataBaseRelation<*>? { return details?.firstOrNull { it.entityProperty == detailName } } /** * Получить информацию о мастере по его имени. * * @param detailName Имя мастера. * @return Описание связи [RoomDataBaseRelation]. */ fun getMasterInfo(detailName: String?): RoomDataBaseRelation<*>? { return masters?.firstOrNull { it.entityProperty == detailName } } }
1
Kotlin
1
1
1f55387800a8cbf722016cbf5e0f6b1f5cc995a8
2,755
Flexberry.AndroidODataOffline.Sample
MIT License
examples/ktor-example/src/main/kotlin/stove/ktor/example/application/ProductService.kt
Trendyol
590,452,775
false
{"Kotlin": 267198}
package stove.ktor.example.application import stove.ktor.example.domain.ProductRepository import java.time.Duration class ProductService( private val repository: ProductRepository, private val lockProvider: LockProvider ) { companion object { private const val DURATION = 30L } suspend fun update(id: Long, request: UpdateProductRequest) { val acquireLock = lockProvider.acquireLock(::ProductService.name, Duration.ofSeconds(DURATION)) if (!acquireLock) { print("lock could not be acquired") return } try { repository.transaction { val jedi = it.findById(id) jedi.name = request.name it.update(jedi) } } finally { lockProvider.releaseLock(::ProductService.name) } } }
5
Kotlin
8
96
fbd1cf5e64ad27cfde947ac9f9e4326e8051fe68
767
stove
Apache License 2.0
app/src/main/java/org/fossasia/susi/ai/skills/skilllisting/contract/ISkillListingPresenter.kt
fossasia
68,798,776
false
null
package org.fossasia.susi.ai.skills.skilllisting.contract /** * * Created by chiragw15 on 15/8/17. */ interface ISkillListingPresenter { fun onAttach(skillListingView: ISkillListingView) fun getGroups(swipeToRefreshActive: Boolean) fun getMetrics(swipeToRefreshActive: Boolean) fun onDetach() }
81
null
1131
2,391
a3409051185d4624e65f7df7847e2fca0910cebe
315
susi_android
Apache License 2.0
app/src/main/java/com/example/pulsa/activities/SubActivity.kt
BridgeTheMasterBuilder
588,133,993
false
null
package com.example.pulsa.activities import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.GestureDetector import android.view.MotionEvent import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.view.GestureDetectorCompat import com.example.pulsa.R import com.example.pulsa.adapters.GenericRecyclerAdapter import com.example.pulsa.databinding.ActivitySubBinding import com.example.pulsa.networking.NetworkManager import com.example.pulsa.objects.Post import com.example.pulsa.objects.Sub import com.example.pulsa.utils.MediaUtils import com.google.android.material.button.MaterialButton import com.google.gson.reflect.TypeToken private const val MEDIA_PLAY = R.drawable.icons8_play_96 private const val MEDIA_STOPPED = "stopped" class SubActivity : BaseLayoutActivity(), GestureDetector.OnGestureListener, ActivityRing<Post> { private lateinit var binding: ActivitySubBinding private lateinit var adapter: GenericRecyclerAdapter<Post> private lateinit var posts: MutableList<Post> private lateinit var mDetector: GestureDetectorCompat private var mediaUtilsArray = arrayOf<Pair<MediaUtils, MaterialButton?>>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val sub: Sub = intent.getParcelableExtra("sub")!! val slug = sub.slug var map: HashMap<String, Any> = HashMap() map["type"] = object : TypeToken<List<Post>>() {} map["url"] = "p/${slug}/" runOnUiThread { NetworkManager().get(this, map) } binding = ActivitySubBinding.inflate(layoutInflater) setContentView(binding.root) /* binding.recyclerView.setOnTouchListener(View.OnTouchListener { v, event -> v.performClick() onTouchEvent(event) })*/ binding.newpostbtn.setOnClickListener { val intent = Intent(this, NewPostActivity::class.java) intent.putExtra("sub", sub) resultLauncher.launch(intent) } mDetector = GestureDetectorCompat(this, this) } val resultLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> if (result.resultCode == Activity.RESULT_OK) { val data = result.data?.extras val pos = data?.getInt("pos")!! if (handle(data, posts, pos)) { return@registerForActivityResult } else { val post: Post = result.data?.getParcelableExtra("post")!! adapter.addItem(post) } } } override fun resolveGet(content: Any) { posts = content as MutableList<Post> adapter = GenericRecyclerAdapter( posts, { post, position -> adapterOnClick(post, position) }, R.layout.post_item ) audioOnClickSetup() binding.recyclerView.adapter = adapter userOnClickSetup() subOnClickSetup() } private fun audioOnClickSetup() { adapter.playAudioOnClick { button, mediaUtils -> val containsTuple = mediaUtilsArray.any { (util, _) -> util == mediaUtils } if (!containsTuple) mediaUtilsArray = mediaUtilsArray.plusElement(mediaUtils to button) mediaUtils.playMedia(button) } adapter.playRecordingOnClick { button, mediaUtils -> val containsTuple = mediaUtilsArray.any { (util, _) -> util == mediaUtils } if (!containsTuple) mediaUtilsArray = mediaUtilsArray.plusElement(mediaUtils to button) mediaUtils.playMedia(button) } } private fun adapterOnClick(post: Post, position: Int) { val intent = Intent(this, PostActivity::class.java) intent.putExtra("post", post) intent.putExtra("pos", position) resultLauncher.launch(intent) } private fun userOnClickSetup() { adapter.userOnClick { user, position -> val intent = Intent(this, UserPageActivity::class.java) intent.putExtra("user", user) intent.putExtra("pos", position) startActivity(intent) } } private fun subOnClickSetup() { adapter.subOnClick { sub, position -> val intent = Intent(this, SubActivity::class.java) intent.putExtra("sub", sub) intent.putExtra("pos", position) startActivity(intent) } } public fun failure() { // TODO: Display failed to load posts xml // TODO: Rename function println("Failed to load posts") } override fun onTouchEvent(event: MotionEvent): Boolean { mDetector.onTouchEvent(event) return super.onTouchEvent(event) } override fun onFling( event1: MotionEvent, event2: MotionEvent, velocityX: Float, velocityY: Float ): Boolean { return false } override fun onDown(p0: MotionEvent): Boolean { return true } override fun onShowPress(p0: MotionEvent) { } override fun onLongPress(p0: MotionEvent) { } override fun onScroll( event1: MotionEvent, event2: MotionEvent, velocityX: Float, velocityY: Float ): Boolean { Toast.makeText(this, "jjjj", Toast.LENGTH_SHORT).show() if (velocityX > 0.0) { intent.putExtra("nextContent", true) setResult(Activity.RESULT_OK, intent) finish() } else if (velocityX < 0.0) { intent.putExtra("prevContent", true) setResult(Activity.RESULT_OK, intent) finish() } return true } override fun onSingleTapUp(p0: MotionEvent): Boolean { return false } override fun dispatch(content: Post, position: Int) { adapterOnClick(content, position) } override fun onStop() { super.onStop() mediaUtilsArray.forEach { pair -> pair.first.medPlayer?.stop() pair.second?.tag = MEDIA_STOPPED pair.second?.setIconResource(MEDIA_PLAY) } } }
0
Kotlin
1
2
9ed68b624407d67b24d6db4abae158e6e24e37a7
6,263
pulsa-mobile
The Unlicense
app/src/main/java/com/packt/tellastory/activities/MainActivity.kt
mikerworks
108,963,811
false
null
package com.packt.tellastory.activities import android.app.Fragment; import android.content.Intent import android.os.Bundle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.AppCompatActivity; import android.view.Menu; import android.view.MenuItem; import com.packt.tellastory.R import com.packt.tellastory.data.Repository import com.packt.tellastory.fragments.StoriesFragment import com.packt.tellastory.fragments.StoryContributeFragment import com.packt.tellastory.fragments.StoryDetailFragment import com.packt.tellastory.models.Story import android.app.Activity import com.packt.tellastory.AuthenticationHelper class MainActivity : AppCompatActivity() { val REQUEST_LATE_ONBOARDING = 100 val repository: Repository get() = Repository(this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } override fun onResume() { super.onResume() onList() } override fun onBackPressed() { val drawer = findViewById(R.id.drawer_layout) as DrawerLayout if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawer(GravityCompat.START) } else { super.onBackPressed() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return super.onOptionsItemSelected(item) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) { if (requestCode == REQUEST_LATE_ONBOARDING) { if (resultCode == Activity.RESULT_OK) { val story = data.getParcelableExtra<Story>(OnboardingActivity.ARG_STORY) val lastContribution = story.contributions.last() lastContribution.contributor = AuthenticationHelper.userName repository.updateContributions(story) onList() } } } fun onList() { val fragment = StoriesFragment.newInstance() showFragment(fragment) } fun onCreateStory() { val newStory = Story() newStory.lastUpdate = "today" val fragment = StoryContributeFragment.newInstance(newStory) showFragment(fragment) } fun onContribute(story: Story) { val fragment = StoryContributeFragment.newInstance(story) showFragment(fragment) } fun onReadStory(story: Story) { val fragment = StoryDetailFragment.newInstance(story) showFragment(fragment) } fun onLateOnboarding(story: Story) { val intent = Intent(this, OnboardingActivity::class.java) intent.putExtra(OnboardingActivity.ARG_LATE, true) intent.putExtra(OnboardingActivity.ARG_STORY, story) startActivityForResult(intent, REQUEST_LATE_ONBOARDING) } private fun showFragment(fragment: Fragment) { val ft = fragmentManager.beginTransaction() ft.replace(R.id.main_fragment_container, fragment, fragment.javaClass.toString()) ft.commit() } }
0
Kotlin
0
0
c229be54e703c327767e1e7ce3af98353ec94a58
3,242
packt-lean-onboarding
MIT License
common/src/main/kotlin/com/yod/common/widget/StableViewPager.kt
luketang3
117,669,049
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Kotlin": 34, "XML": 21, "Java": 4}
package com.yod.common.widget import android.content.Context import android.support.v4.view.ViewPager import android.util.AttributeSet import android.view.MotionEvent import timber.log.Timber /** * stable * Created by tangJ on 2017/9/5 */ class StableViewPager @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ViewPager(context, attrs) { override fun onTouchEvent(ev: MotionEvent): Boolean { try { return super.onTouchEvent(ev) } catch (ex: IllegalArgumentException) { ex.printStackTrace() Timber.d("==>crash: onTouchEvent") } return false } override fun onInterceptTouchEvent(ev: MotionEvent): Boolean { try { return super.onInterceptTouchEvent(ev) } catch (ex: IllegalArgumentException) { ex.printStackTrace() Timber.d("==>crash: onInterceptTouchEvent") } return false } }
1
null
1
1
1cb0ad9aac66107163484c31bf9745b2617eb468
912
yodLib
Apache License 2.0
app/src/main/kotlin/com/pnuema/bible/android/database/ChapterCountOffline.kt
barnhill
98,140,541
false
null
package com.pnuema.bible.android.database import androidx.room.Entity import com.pnuema.bible.android.data.firefly.ChapterCount @Entity(tableName = "offlineChapterCount", primaryKeys = ["book_id","version"]) data class ChapterCountOffline ( var book_id: Int, var version: String, val chapterCount: Int = 0 ) { fun convertToChapterCount(): ChapterCount = ChapterCount(chapterCount) }
0
Kotlin
2
13
ca2ddcf6d29e78df59a835b4076605a919cdf957
402
Bible
Apache License 2.0
src/test/kotlin/CohortProperties.kt
ykhandelwal913
322,276,158
true
{"Kotlin": 93670}
import java.io.File import java.net.URI import java.util.Properties class CohortProperties( val jira: URI, val userName: String, val userPassword: String, val cohort: String ) { companion object { fun load(secretsName: String): CohortProperties { val secrets = File("cohort-secrets/").resolve(secretsName) val properties = Properties() secrets.bufferedReader().use { properties.load(it) } return CohortProperties( jira = URI(properties.getProperty("jira.uri")!!), userName = properties.getProperty("user.name")!!, userPassword = properties.getProperty("user.password")!!, cohort = properties.getProperty("cohort")!! ) } } }
0
null
0
0
e613cbf383e4076958cae488f21f755bf8775f9c
789
jces-1209
Apache License 2.0
app/src/main/java/com/pedro/streamer/screen/ScreenService.kt
pedroSG94
79,667,969
false
{"Kotlin": 1116814, "Java": 618860, "GLSL": 34672}
/* * Copyright (C) 2024 pedroSG94. * * 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.pedro.streamer.screen import android.app.NotificationChannel import android.app.NotificationManager import android.app.Service import android.content.Context import android.content.Intent import android.media.projection.MediaProjection import android.media.projection.MediaProjectionManager import android.os.Build import android.os.IBinder import android.util.Log import androidx.annotation.RequiresApi import androidx.core.app.NotificationCompat import com.pedro.common.ConnectChecker import com.pedro.library.base.recording.RecordController import com.pedro.library.generic.GenericStream import com.pedro.library.util.sources.audio.MixAudioSource import com.pedro.library.util.sources.audio.AudioSource import com.pedro.library.util.sources.audio.InternalAudioSource import com.pedro.library.util.sources.audio.MicrophoneSource import com.pedro.library.util.sources.video.NoVideoSource import com.pedro.library.util.sources.video.ScreenSource import com.pedro.streamer.R import com.pedro.streamer.utils.PathUtils import com.pedro.streamer.utils.toast import java.text.SimpleDateFormat import java.util.Date import java.util.Locale /** * Basic Screen service streaming implementation */ @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP) class ScreenService: Service(), ConnectChecker { companion object { private const val TAG = "DisplayService" private const val CHANNEL_ID = "DisplayStreamChannel" const val NOTIFY_ID = 123456 var INSTANCE: ScreenService? = null } private var notificationManager: NotificationManager? = null private lateinit var genericStream: GenericStream private var mediaProjection: MediaProjection? = null private val mediaProjectionManager: MediaProjectionManager by lazy { applicationContext.getSystemService(MEDIA_PROJECTION_SERVICE) as MediaProjectionManager } private var callback: ConnectChecker? = null private val width = 640 private val height = 480 private val vBitrate = 1200 * 1000 private var rotation = 0 //0 for landscape or 90 for portrait private val sampleRate = 32000 private val isStereo = true private val aBitrate = 128 * 1000 private var prepared = false private var recordPath = "" private var selectedAudioSource: Int = R.id.audio_source_microphone override fun onCreate() { super.onCreate() Log.i(TAG, "RTP Display service create") notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val channel = NotificationChannel(CHANNEL_ID, CHANNEL_ID, NotificationManager.IMPORTANCE_HIGH) notificationManager?.createNotificationChannel(channel) } genericStream = GenericStream(baseContext, this, NoVideoSource(), MicrophoneSource()).apply { //This is important to keep a constant fps because media projection only produce fps if the screen change getGlInterface().setForceRender(true, 15) } prepared = try { genericStream.prepareVideo(width, height, vBitrate, rotation = rotation) && genericStream.prepareAudio(sampleRate, isStereo, aBitrate, echoCanceler = true, noiseSuppressor = true ) } catch (e: IllegalArgumentException) { false } if (prepared) INSTANCE = this else toast("Invalid audio or video parameters, prepare failed") } private fun keepAliveTrick() { val notification = NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setSilent(true) .setOngoing(false) .build() startForeground(1, notification) } override fun onBind(p0: Intent?): IBinder? { return null } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { Log.i(TAG, "RTP Display service started") return START_STICKY } fun sendIntent(): Intent { return mediaProjectionManager.createScreenCaptureIntent() } fun isStreaming(): Boolean { return genericStream.isStreaming } fun isRecording(): Boolean { return genericStream.isRecording } fun stopStream() { if (genericStream.isStreaming) { genericStream.stopStream() notificationManager?.cancel(NOTIFY_ID) } } fun setCallback(connectChecker: ConnectChecker?) { callback = connectChecker } override fun onDestroy() { super.onDestroy() Log.i(TAG, "RTP Display service destroy") stopStream() INSTANCE = null //release stream and media projection properly genericStream.release() mediaProjection?.stop() mediaProjection = null } fun prepareStream(resultCode: Int, data: Intent): Boolean { keepAliveTrick() stopStream() mediaProjection?.stop() val mediaProjection = mediaProjectionManager.getMediaProjection(resultCode, data) this.mediaProjection = mediaProjection val screenSource = ScreenSource(applicationContext, mediaProjection) return try { //ScreenSource need use always setCameraOrientation(0) because the MediaProjection handle orientation. //You also need remove autoHandleOrientation if you are using it. //You need to call it after prepareVideo to override the default value. genericStream.getGlInterface().setCameraOrientation(0) genericStream.changeVideoSource(screenSource) toggleAudioSource(selectedAudioSource) true } catch (ignored: IllegalArgumentException) { false } } fun getCurrentAudioSource(): AudioSource = genericStream.audioSource fun toggleAudioSource(itemId: Int) { when (itemId) { R.id.audio_source_microphone -> { selectedAudioSource = R.id.audio_source_microphone if (genericStream.audioSource is MicrophoneSource) return genericStream.changeAudioSource(MicrophoneSource()) } R.id.audio_source_internal -> { selectedAudioSource = R.id.audio_source_internal if (genericStream.audioSource is InternalAudioSource) return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { mediaProjection?.let { genericStream.changeAudioSource(InternalAudioSource(it)) } } else { throw IllegalArgumentException("You need min API 29+") } } R.id.audio_source_mix -> { selectedAudioSource = R.id.audio_source_mix if (genericStream.audioSource is MixAudioSource) return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { mediaProjection?.let { genericStream.changeAudioSource(MixAudioSource(it).apply { //Using audio mix the internal audio volume is higher than microphone. Increase microphone fix it. microphoneVolume = 2f }) } } else { throw IllegalArgumentException("You need min API 29+") } } } } fun toggleRecord(state: (RecordController.Status) -> Unit) { if (!genericStream.isRecording) { val folder = PathUtils.getRecordPath() if (!folder.exists()) folder.mkdir() val sdf = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()) recordPath = "${folder.absolutePath}/${sdf.format(Date())}.mp4" genericStream.startRecord(recordPath) { status -> if (status == RecordController.Status.RECORDING) { state(RecordController.Status.RECORDING) } } state(RecordController.Status.STARTED) } else { genericStream.stopRecord() state(RecordController.Status.STOPPED) PathUtils.updateGallery(this, recordPath) } } fun startStream(endpoint: String) { if (!genericStream.isStreaming) genericStream.startStream(endpoint) } override fun onConnectionStarted(url: String) { callback?.onConnectionStarted(url) } override fun onConnectionSuccess() { callback?.onConnectionSuccess() } override fun onNewBitrate(bitrate: Long) { callback?.onNewBitrate(bitrate) } override fun onConnectionFailed(reason: String) { callback?.onConnectionFailed(reason) } override fun onDisconnect() { callback?.onDisconnect() } override fun onAuthError() { callback?.onAuthError() } override fun onAuthSuccess() { callback?.onAuthSuccess() } }
87
Kotlin
772
2,545
eca59948009d5a7b564f9a838c149b850898d089
8,788
RootEncoder
Apache License 2.0
client/rpc/src/main/kotlin/net/corda/client/rpc/CordaRPCClient.kt
desertfund
113,458,422
false
null
package net.corda.client.rpc import net.corda.client.rpc.internal.KryoClientSerializationScheme import net.corda.client.rpc.internal.RPCClient import net.corda.client.rpc.internal.RPCClientConfiguration import net.corda.core.context.Actor import net.corda.core.context.Trace import net.corda.core.messaging.CordaRPCOps import net.corda.core.serialization.internal.effectiveSerializationEnv import net.corda.core.utilities.NetworkHostAndPort import net.corda.nodeapi.ArtemisTcpTransport.Companion.tcpTransport import net.corda.nodeapi.ConnectionDirection import net.corda.nodeapi.internal.serialization.KRYO_RPC_CLIENT_CONTEXT import java.time.Duration /** * This class is essentially just a wrapper for an RPCConnection<CordaRPCOps> and can be treated identically. * * @see RPCConnection */ class CordaRPCConnection internal constructor(connection: RPCConnection<CordaRPCOps>) : RPCConnection<CordaRPCOps> by connection /** * Can be used to configure the RPC client connection. * * @property connectionMaxRetryInterval How much time to wait between connection retries if the server goes down. This * time will be reached via exponential backoff. */ data class CordaRPCClientConfiguration(val connectionMaxRetryInterval: Duration) { internal fun toRpcClientConfiguration(): RPCClientConfiguration { return RPCClientConfiguration.default.copy( connectionMaxRetryInterval = connectionMaxRetryInterval ) } companion object { /** * Returns the default configuration we recommend you use. */ @JvmField val DEFAULT = CordaRPCClientConfiguration(connectionMaxRetryInterval = RPCClientConfiguration.default.connectionMaxRetryInterval) } } /** * An RPC client connects to the specified server and allows you to make calls to the server that perform various * useful tasks. Please see the Client RPC section of docs.corda.net to learn more about how this API works. A brief * description is provided here. * * Calling [start] returns an [RPCConnection] containing a proxy that lets you invoke RPCs on the server. Calls on * it block, and if the server throws an exception then it will be rethrown on the client. Proxies are thread safe and * may be used to invoke multiple RPCs in parallel. * * RPC sends and receives are logged on the net.corda.rpc logger. * * The [CordaRPCOps] defines what client RPCs are available. If an RPC returns an [rx.Observable] anywhere in the object * graph returned then the server-side observable is transparently forwarded to the client side here. * *You are expected to use it*. The server will begin sending messages immediately that will be buffered on the * client, you are expected to drain by subscribing to the returned observer. You can opt-out of this by simply * calling the [net.corda.client.rpc.notUsed] method on it. * * You don't have to explicitly close the observable if you actually subscribe to it: it will close itself and free up * the server-side resources either when the client or JVM itself is shutdown, or when there are no more subscribers to * it. Once all the subscribers to a returned observable are unsubscribed or the observable completes successfully or * with an error, the observable is closed and you can't then re-subscribe again: you'll have to re-request a fresh * observable with another RPC. * * @param hostAndPort The network address to connect to. * @param configuration An optional configuration used to tweak client behaviour. */ class CordaRPCClient @JvmOverloads constructor( hostAndPort: NetworkHostAndPort, configuration: CordaRPCClientConfiguration = CordaRPCClientConfiguration.DEFAULT ) { init { try { effectiveSerializationEnv } catch (e: IllegalStateException) { try { KryoClientSerializationScheme.initialiseSerialization() } catch (e: IllegalStateException) { // Race e.g. two of these constructed in parallel, ignore. } } } private val rpcClient = RPCClient<CordaRPCOps>( tcpTransport(ConnectionDirection.Outbound(), hostAndPort, config = null), configuration.toRpcClientConfiguration(), KRYO_RPC_CLIENT_CONTEXT ) /** * Logs in to the target server and returns an active connection. The returned connection is a [java.io.Closeable] * and can be used with a try-with-resources statement. If you don't use that, you should use the * [RPCConnection.notifyServerAndClose] or [RPCConnection.forceClose] methods to dispose of the connection object * when done. * * @param username The username to authenticate with. * @param password The password to authenticate with. * @throws RPCException if the server version is too low or if the server isn't reachable within a reasonable timeout. */ fun start(username: String, password: String): CordaRPCConnection { return start(username, password, null, null) } /** * Logs in to the target server and returns an active connection. The returned connection is a [java.io.Closeable] * and can be used with a try-with-resources statement. If you don't use that, you should use the * [RPCConnection.notifyServerAndClose] or [RPCConnection.forceClose] methods to dispose of the connection object * when done. * * @param username The username to authenticate with. * @param password The password to authenticate with. * @param externalTrace external [Trace] for correlation. * @throws RPCException if the server version is too low or if the server isn't reachable within a reasonable timeout. */ fun start(username: String, password: String, externalTrace: Trace?, impersonatedActor: Actor?): CordaRPCConnection { return CordaRPCConnection(rpcClient.start(CordaRPCOps::class.java, username, password, externalTrace, impersonatedActor)) } /** * A helper for Kotlin users that simply closes the connection after the block has executed. Be careful not to * over-use this, as setting up and closing connections takes time. */ inline fun <A> use(username: String, password: String, block: (CordaRPCConnection) -> A): A { return start(username, password).use(block) } }
1
null
1
1
f9614123968035cb325c6de0b84cf2718643f399
6,356
corda
Apache License 2.0
base/src/test/java/de/whitefrog/frogr/test/model/Person.kt
joewhite86
118,778,368
false
null
package de.whitefrog.frogr.test.model import com.fasterxml.jackson.annotation.JsonView import de.whitefrog.frogr.model.Entity import de.whitefrog.frogr.model.annotation.* import de.whitefrog.frogr.rest.Views import org.neo4j.graphdb.Direction import java.util.* class Person(@Indexed var field: String? = null, @Indexed var number: Long? = null) : Entity(), PersonInterface { enum class Age { Old, Mature, Child} @Unique var uniqueField: String? = null @Indexed(type = IndexType.LowerCase) var lowerCaseIndex: String? = null var age: Age? = null var dateField: Date? = null @Fetch var autoFetch: String? = null @Fetch(group = "testGroup") var fetchGroupField1: String? = null @Fetch(group = "testGroup") var fetchGroupField2: String? = null @JsonView(Views.Secure::class) var secureField: String? = null @NullRemove var nullRemoveField: String? = null @Lazy @RelatedTo(direction = Direction.OUTGOING, type = "Likes") var likes: ArrayList<Person> = ArrayList() @Lazy @RelatedTo(direction = Direction.INCOMING, type = "Likes") var likedBy: ArrayList<Person> = ArrayList() @Lazy @RelatedTo(direction = Direction.OUTGOING, type = "Likes") var likesRelationships: ArrayList<Likes> = ArrayList() @Lazy @RelatedTo(direction = Direction.INCOMING, type = "Likes") var likedByRelationships: ArrayList<Likes> = ArrayList() @RelationshipCount(direction = Direction.OUTGOING, type = "Likes") var likesCount: Long? = null @RelatedTo(direction = Direction.BOTH, type = "MarriedWith") var marriedWith: Person? = null @RelatedTo(direction = Direction.BOTH, type = "MarriedWith") var marriedWithRelationship: MarriedWith? = null @RelatedTo(direction = Direction.OUTGOING, type = "Wears") var wears: ArrayList<Clothing> = ArrayList() @RelatedTo(direction = Direction.OUTGOING, type = "HasInventory") var inventory: ArrayList<InventoryItem> = ArrayList() override fun equals(other: Any?): Boolean { if(other !is Person) return false val eq = super.equals(other) if(!eq && id < 0 && other.id < 0 && field != null) { return field == other.field } return eq } override fun toString(): String { val sField = if(field != null) " ($field)" else "" return "Person$sField" } }
1
Kotlin
1
2
396ac4243acb7b75f624431e61d691e3fb6c9103
2,273
frogr
MIT License
app/src/main/java/com/bernaferrari/changedetection/detailsvisual/VisualViewModel.kt
bernaferrari
135,081,469
false
{"Kotlin": 423918, "Java": 60461}
package com.bernaferrari.changedetection.detailsImage import android.app.Application import android.arch.lifecycle.AndroidViewModel import android.arch.lifecycle.LiveData import android.arch.paging.LivePagedListBuilder import android.arch.paging.PagedList import com.bernaferrari.changedetection.data.Snap import com.bernaferrari.changedetection.data.source.SnapsRepository import kotlin.coroutines.experimental.suspendCoroutine /** * Exposes the data to be used in the site diff screen. */ class ImageViewModel( context: Application, private val mSnapsRepository: SnapsRepository ) : AndroidViewModel(context) { /** * Called to remove a diff * * @param id The diff url to be removed. */ fun removeSnap(id: String) { mSnapsRepository.deleteSnap(id) } fun getAllSnapsPagedForId(id: String, filter: String): LiveData<PagedList<Snap>> { return LivePagedListBuilder( mSnapsRepository.getSnapForPaging(id, filter), PagedList.Config.Builder() .setPageSize(PAGE_SIZE) .setEnablePlaceholders(ENABLE_PLACEHOLDERS) .build() ).build() } suspend fun getSnapsFiltered(id: String, filter: String): LiveData<List<Snap>> = suspendCoroutine { cont -> mSnapsRepository.getSnapsFiltered(id, filter) { cont.resume(it) } } companion object { /** * A good page size is a value that fills at least a screen worth of content on a large * device so the User is unlikely to see a null item. * You can play with this constant to observe the paging behavior. * <p> * It's possible to vary this with list device size, but often unnecessary, unless a user * scrolling on a large device is expected to scroll through items more quickly than a small * device, such as when the large device uses a grid layout of items. */ private const val PAGE_SIZE = 3 /** * If placeholders are enabled, PagedList will report the full size but some items might * be null in onBind method (PagedListAdapter triggers a rebind when data is loaded). * <p> * If placeholders are disabled, onBind will never receive null but as more pages are * loaded, the scrollbars will jitter as new pages are loaded. You should probably disable * scrollbars if you disable placeholders. */ private const val ENABLE_PLACEHOLDERS = true } }
22
Kotlin
97
696
4cb31aab20c321421347b3aad4ad86f516f136f0
2,539
ChangeDetection
Apache License 2.0
compiler/fir/providers/src/org/jetbrains/kotlin/fir/types/InferenceUtils.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.types import org.jetbrains.kotlin.builtins.functions.FunctionClassKind import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.declarations.FirAnonymousFunction import org.jetbrains.kotlin.fir.declarations.FirClass import org.jetbrains.kotlin.fir.originalForSubstitutionOverride import org.jetbrains.kotlin.fir.resolve.ScopeSession import org.jetbrains.kotlin.fir.resolve.fullyExpandedType import org.jetbrains.kotlin.fir.resolve.scope import org.jetbrains.kotlin.fir.resolve.toSymbol import org.jetbrains.kotlin.fir.scopes.FakeOverrideTypeCalculator import org.jetbrains.kotlin.fir.scopes.ProcessorAction import org.jetbrains.kotlin.fir.scopes.processOverriddenFunctions import org.jetbrains.kotlin.fir.scopes.unsubstitutedScope import org.jetbrains.kotlin.fir.symbols.ConeClassLikeLookupTag import org.jetbrains.kotlin.fir.symbols.impl.ConeClassLikeLookupTagImpl import org.jetbrains.kotlin.fir.symbols.impl.FirFunctionSymbol import org.jetbrains.kotlin.fir.symbols.impl.FirNamedFunctionSymbol import org.jetbrains.kotlin.fir.types.impl.ConeClassLikeTypeImpl import org.jetbrains.kotlin.name.ClassId import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.types.AbstractTypeChecker import org.jetbrains.kotlin.util.OperatorNameConventions import kotlin.contracts.ExperimentalContracts import kotlin.contracts.contract @OptIn(ExperimentalContracts::class) private fun ConeKotlinType.classId(session: FirSession): ClassId? { contract { returns(true) implies (this@classId is ConeClassLikeType) } if (this !is ConeClassLikeType) return null return fullyExpandedType(session).lookupTag.classId } fun ConeKotlinType.isKProperty(session: FirSession): Boolean { val classId = classId(session) ?: return false return classId.packageFqName == StandardClassIds.BASE_REFLECT_PACKAGE && classId.shortClassName.identifier.startsWith("KProperty") } fun ConeKotlinType.isKMutableProperty(session: FirSession): Boolean { val classId = classId(session) ?: return false return classId.packageFqName == StandardClassIds.BASE_REFLECT_PACKAGE && classId.shortClassName.identifier.startsWith("KMutableProperty") } fun ConeKotlinType.functionClassKind(session: FirSession): FunctionClassKind? { return classId(session)?.toFunctionClassKind() } private fun ClassId.toFunctionClassKind(): FunctionClassKind? { return FunctionClassKind.byClassNamePrefix(packageFqName, relativeClassName.asString()) } // Function, SuspendFunction, KFunction, KSuspendFunction fun ConeKotlinType.isBuiltinFunctionalType(session: FirSession): Boolean { return functionClassKind(session) != null } // Function, SuspendFunction, KFunction, KSuspendFunction fun ConeClassLikeLookupTag.isBuiltinFunctionalType(): Boolean { return classId.toFunctionClassKind() != null } inline fun ConeKotlinType.isFunctionalType(session: FirSession, predicate: (FunctionClassKind) -> Boolean): Boolean { val kind = functionClassKind(session) ?: return false return predicate(kind) } // Function fun ConeKotlinType.isFunctionalType(session: FirSession): Boolean { return isFunctionalType(session) { it == FunctionClassKind.Function } } // SuspendFunction, KSuspendFunction fun ConeKotlinType.isSuspendFunctionType(session: FirSession): Boolean { return isFunctionalType(session) { it.isSuspendType } } // KFunction, KSuspendFunction fun ConeKotlinType.isKFunctionType(session: FirSession): Boolean { return isFunctionalType(session) { it.isReflectType } } fun ConeKotlinType.kFunctionTypeToFunctionType(session: FirSession): ConeClassLikeType { require(this.isKFunctionType(session)) val kind = if (isSuspendFunctionType(session)) FunctionClassKind.SuspendFunction else FunctionClassKind.Function val functionalTypeId = ClassId(kind.packageFqName, kind.numberedClassName(typeArguments.size - 1)) return ConeClassLikeTypeImpl(ConeClassLikeLookupTagImpl(functionalTypeId), typeArguments, isNullable = false) } fun ConeKotlinType.suspendFunctionTypeToFunctionType(session: FirSession): ConeClassLikeType { require(this.isSuspendFunctionType(session)) val kind = if (isKFunctionType(session)) FunctionClassKind.KFunction else FunctionClassKind.Function val functionalTypeId = ClassId(kind.packageFqName, kind.numberedClassName(typeArguments.size - 1)) return ConeClassLikeTypeImpl(ConeClassLikeLookupTagImpl(functionalTypeId), typeArguments, isNullable = false, attributes = attributes) } fun ConeKotlinType.suspendFunctionTypeToFunctionTypeWithContinuation(session: FirSession, continuationClassId: ClassId): ConeClassLikeType { require(this.isSuspendFunctionType(session)) val kind = if (isKFunctionType(session)) FunctionClassKind.KFunction else FunctionClassKind.Function val functionalTypeId = ClassId(kind.packageFqName, kind.numberedClassName(typeArguments.size)) val fullyExpandedType = type.fullyExpandedType(session) val typeArguments = fullyExpandedType.typeArguments val lastTypeArgument = typeArguments.last() return ConeClassLikeTypeImpl( ConeClassLikeLookupTagImpl(functionalTypeId), typeArguments = (typeArguments.dropLast(1) + ConeClassLikeLookupTagImpl(continuationClassId).constructClassType( arrayOf(lastTypeArgument), isNullable = false ) + lastTypeArgument).toTypedArray(), isNullable = false, attributes = attributes ) } fun ConeKotlinType.isSubtypeOfFunctionalType(session: FirSession, expectedFunctionalType: ConeClassLikeType): Boolean { require(expectedFunctionalType.isBuiltinFunctionalType(session)) return AbstractTypeChecker.isSubtypeOf(session.typeContext, this, expectedFunctionalType.replaceArgumentsWithStarProjections()) } fun ConeKotlinType.findSubtypeOfNonSuspendFunctionalType(session: FirSession, expectedFunctionalType: ConeClassLikeType): ConeKotlinType? { require(expectedFunctionalType.isBuiltinFunctionalType(session) && !expectedFunctionalType.isSuspendFunctionType(session)) return when (this) { is ConeClassLikeType -> { // Expect the argument type is not a suspend functional type. if (isSuspendFunctionType(session) || !isSubtypeOfFunctionalType(session, expectedFunctionalType)) null else this } is ConeIntersectionType -> { if (intersectedTypes.any { it.isSuspendFunctionType(session) }) null else intersectedTypes.find { it.findSubtypeOfNonSuspendFunctionalType(session, expectedFunctionalType) != null } } is ConeTypeParameterType -> { val bounds = lookupTag.typeParameterSymbol.resolvedBounds.map { it.coneType } if (bounds.any { it.isSuspendFunctionType(session) }) null else bounds.find { it.findSubtypeOfNonSuspendFunctionalType(session, expectedFunctionalType) != null } } else -> null } } fun ConeClassLikeType.findBaseInvokeSymbol(session: FirSession, scopeSession: ScopeSession): FirNamedFunctionSymbol? { require(this.isBuiltinFunctionalType(session)) val functionN = (lookupTag.toSymbol(session)?.fir as? FirClass) ?: return null var baseInvokeSymbol: FirNamedFunctionSymbol? = null functionN.unsubstitutedScope( session, scopeSession, withForcedTypeCalculator = false ).processFunctionsByName(OperatorNameConventions.INVOKE) { functionSymbol -> baseInvokeSymbol = functionSymbol return@processFunctionsByName } return baseInvokeSymbol } fun ConeKotlinType.findContributedInvokeSymbol( session: FirSession, scopeSession: ScopeSession, expectedFunctionalType: ConeClassLikeType, shouldCalculateReturnTypesOfFakeOverrides: Boolean ): FirFunctionSymbol<*>? { val baseInvokeSymbol = expectedFunctionalType.findBaseInvokeSymbol(session, scopeSession) ?: return null val fakeOverrideTypeCalculator = if (shouldCalculateReturnTypesOfFakeOverrides) { FakeOverrideTypeCalculator.Forced } else { FakeOverrideTypeCalculator.DoNothing } val scope = scope(session, scopeSession, fakeOverrideTypeCalculator) ?: return null var declaredInvoke: FirNamedFunctionSymbol? = null scope.processFunctionsByName(OperatorNameConventions.INVOKE) { functionSymbol -> if (functionSymbol.fir.valueParameters.size == baseInvokeSymbol.fir.valueParameters.size) { declaredInvoke = functionSymbol return@processFunctionsByName } } var overriddenInvoke: FirFunctionSymbol<*>? = null if (declaredInvoke != null) { // Make sure the user-contributed or type-substituted invoke we just found above is an override of base invoke. scope.processOverriddenFunctions(declaredInvoke!!) { functionSymbol -> if (functionSymbol == baseInvokeSymbol || functionSymbol.originalForSubstitutionOverride == baseInvokeSymbol) { overriddenInvoke = functionSymbol ProcessorAction.STOP } else { ProcessorAction.NEXT } } } return if (overriddenInvoke != null) declaredInvoke else null } fun ConeKotlinType.isKClassType(): Boolean { return classId == StandardClassIds.KClass } private fun ConeTypeProjection.typeOrDefault(default: ConeKotlinType): ConeKotlinType = when (this) { is ConeKotlinTypeProjection -> type is ConeStarProjection -> default } fun ConeKotlinType.receiverType(session: FirSession): ConeKotlinType? { if (!isBuiltinFunctionalType(session) || !isExtensionFunctionType(session)) return null return fullyExpandedType(session).let { expanded -> expanded.typeArguments[expanded.contextReceiversNumberForFunctionType].typeOrDefault(session.builtinTypes.nothingType.type) } } fun ConeKotlinType.returnType(session: FirSession): ConeKotlinType { require(this is ConeClassLikeType) return fullyExpandedType(session).typeArguments.last().typeOrDefault(session.builtinTypes.nullableAnyType.type) } fun ConeKotlinType.valueParameterTypesIncludingReceiver(session: FirSession): List<ConeKotlinType> { require(this is ConeClassLikeType) return fullyExpandedType(session).typeArguments.dropLast(1).map { it.typeOrDefault(session.builtinTypes.nothingType.type) } } val FirAnonymousFunction.returnType: ConeKotlinType? get() = returnTypeRef.coneTypeSafe() val FirAnonymousFunction.receiverType: ConeKotlinType? get() = receiverTypeRef?.coneTypeSafe() fun ConeTypeContext.isTypeMismatchDueToNullability( actualType: ConeKotlinType, expectedType: ConeKotlinType ): Boolean { return actualType.isNullableType() && !expectedType.isNullableType() && AbstractTypeChecker.isSubtypeOf( this, actualType, expectedType.withNullability(ConeNullability.NULLABLE, this) ) }
7
null
5411
43,797
a8f547d080724fae3a45d675a16c5b3fc2f13b17
11,260
kotlin
Apache License 2.0
src/main/java/uk/gov/justice/digital/hmpps/cmd/api/domain/NotificationType.kt
nickmcmahon01
310,653,680
false
{"Kotlin": 337402, "Dockerfile": 1319, "Java": 1075, "Shell": 181}
package uk.gov.justice.digital.hmpps.cmd.api.domain enum class NotificationType(val value: String) { EMAIL_SUMMARY("bef26932-5284-4c0b-8df9-54202b790a9e"), SMS_SUMMARY("37f1724b-3843-4a57-b3ea-7120aa01d8f6"), }
0
Kotlin
2
0
b29b5a7161ce28c925f3b08dceb524c4ee2e96df
216
cmd-api
MIT License
app/src/main/java/com/echomu/github/AndroidGenericFrameworkAppGlideModule.kt
echoMu
507,586,352
false
null
package com.echomu.github import android.content.Context import com.bumptech.glide.GlideBuilder import com.bumptech.glide.annotation.GlideModule import com.bumptech.glide.load.DecodeFormat import com.bumptech.glide.module.AppGlideModule import com.bumptech.glide.request.RequestOptions /** * Created by echoMu. */ @GlideModule class AndroidGenericFrameworkAppGlideModule : AppGlideModule() { override fun applyOptions(context: Context, builder: GlideBuilder) { super.applyOptions(context, builder) builder.setDefaultRequestOptions(RequestOptions().format(DecodeFormat.PREFER_RGB_565)) } }
0
Kotlin
0
0
96907920eec4e7d56e930b3d57b1d2de60dc9194
618
IGitHub
Apache License 2.0
Capstone Project/app/src/main/java/com/sum/capstoneproject/response/CRUDResponse.kt
sumeyraozugur
502,581,500
false
{"Kotlin": 55266}
package com.sum.capstoneproject.response import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class CRUDResponse (@SerializedName("status") @Expose var status:Int, @SerializedName("message") @Expose var message:String)
0
Kotlin
0
1
c2dc877db09f6904398c9f1d2a97ee81269369d7
389
UpSchool-Capstone-Project
Apache License 2.0
jetbrains-core/it/software/aws/toolkits/jetbrains/services/ecr/EcrPullIntegrationTest.kt
JetBrains
223,485,227
true
{"Gradle Kotlin DSL": 21, "Markdown": 16, "Java Properties": 2, "Shell": 1, "Text": 12, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "EditorConfig": 3, "YAML": 28, "XML": 96, "Kotlin": 1102, "JSON": 54, "Java": 9, "SVG": 64, "TOML": 1, "INI": 1, "CODEOWNERS": 1, "Maven POM": 4, "Dockerfile": 14, "JavaScript": 3, "Python": 5, "Go": 1, "Go Module": 1, "Microsoft Visual Studio Solution": 6, "C#": 79}
// Copyright 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.ecr import com.intellij.testFramework.ProjectRule import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import software.amazon.awssdk.regions.Region import software.amazon.awssdk.services.ecr.EcrClient import software.aws.toolkits.core.rules.EcrTemporaryRepositoryRule import software.aws.toolkits.jetbrains.core.docker.ToolkitDockerAdapter import software.aws.toolkits.jetbrains.services.ecr.resources.Repository import java.util.UUID class EcrPullIntegrationTest { private val ecrClient = EcrClient.builder() .region(Region.US_WEST_2) .build() @Rule @JvmField val projectRule = ProjectRule() @Rule @JvmField val folder = TemporaryFolder() @Rule @JvmField val ecrRule = EcrTemporaryRepositoryRule(ecrClient) private lateinit var remoteRepo: Repository @Before fun setUp() { remoteRepo = ecrRule.createRepository().toToolkitEcrRepository()!! } @Test fun testPullImage() { val remoteTag = UUID.randomUUID().toString() val dockerfile = folder.newFile() dockerfile.writeText( """ # arbitrary base image with a shell FROM public.ecr.aws/lambda/provided:latest RUN touch $(date +%s) """.trimIndent() ) val project = projectRule.project runBlocking { val serverInstance = EcrUtils.getDockerServerRuntimeInstance().runtimeInstance val ecrLogin = ecrClient.authorizationToken.authorizationData().first().getDockerLogin() val dockerAdapter = ToolkitDockerAdapter(project, serverInstance) val imageId = dockerAdapter.buildLocalImage(dockerfile)!! // gross transform because we only have the short SHA right now val localImage = serverInstance.agent.getImages(null).first { it.imageId.startsWith(EcrIntegrationTestUtils.getImagePrefix(imageId)) } val localImageId = localImage.imageId val config = EcrUtils.buildDockerRepositoryModel(ecrLogin, remoteRepo, remoteTag) val pushRequest = ImageEcrPushRequest( serverInstance, localImageId, remoteRepo, remoteTag ) // push up and image and then delete the local tag EcrUtils.pushImage(projectRule.project, ecrLogin, pushRequest) localImage.deleteImage() assertThat(serverInstance.agent.getImages(null).firstOrNull { it.imageId == localImageId }).isNull() // pull it from the remote dockerAdapter.pullImage(config).await() assertThat(serverInstance.agent.getImages(null).firstOrNull { it.imageId == localImageId }).isNotNull() } } }
6
Kotlin
4
9
ccee3307fe58ad48f93cd780d4378c336ee20548
3,071
aws-toolkit-jetbrains
Apache License 2.0
src/main/kotlin/arraysandstrings/RotateImage.kt
e-freiman
471,473,372
false
null
package arraysandstrings class RotateImage { private fun swap(i1: Int, j1: Int, i2: Int, j2: Int, matrix: Array<IntArray>) { val temp = matrix[i1][j1] matrix[i1][j1] = matrix[i2][j2] matrix[i2][j2] = temp } fun rotate(matrix: Array<IntArray>): Unit { // transpose the matrix for(i in matrix.indices) { for (j in i..matrix.lastIndex) { swap(i, j, j, i, matrix) } } //mirror vertically for(i in matrix.indices) { for (j in 0..matrix.lastIndex / 2) { swap(i, j, i, matrix.size - j - 1, matrix) } } } } fun main() { val matrix = arrayOf( intArrayOf(5,1,9,11), intArrayOf(2,4,8,10), intArrayOf(13,3,6,7), intArrayOf(15,14,12,16)) RotateImage().rotate(matrix) println(matrix.contentDeepToString()) }
0
Kotlin
0
0
fab7f275fbbafeeb79c520622995216f6c7d8642
914
LeetcodeGoogleInterview
Apache License 2.0
src/main/kotlin/arraysandstrings/RotateImage.kt
e-freiman
471,473,372
false
null
package arraysandstrings class RotateImage { private fun swap(i1: Int, j1: Int, i2: Int, j2: Int, matrix: Array<IntArray>) { val temp = matrix[i1][j1] matrix[i1][j1] = matrix[i2][j2] matrix[i2][j2] = temp } fun rotate(matrix: Array<IntArray>): Unit { // transpose the matrix for(i in matrix.indices) { for (j in i..matrix.lastIndex) { swap(i, j, j, i, matrix) } } //mirror vertically for(i in matrix.indices) { for (j in 0..matrix.lastIndex / 2) { swap(i, j, i, matrix.size - j - 1, matrix) } } } } fun main() { val matrix = arrayOf( intArrayOf(5,1,9,11), intArrayOf(2,4,8,10), intArrayOf(13,3,6,7), intArrayOf(15,14,12,16)) RotateImage().rotate(matrix) println(matrix.contentDeepToString()) }
0
Kotlin
0
0
fab7f275fbbafeeb79c520622995216f6c7d8642
914
LeetcodeGoogleInterview
Apache License 2.0
nebulosa-indi-client/src/main/kotlin/nebulosa/indi/client/device/wheels/INDIFilterWheel.kt
tiagohm
568,578,345
false
{"Kotlin": 2467740, "TypeScript": 451309, "HTML": 225848, "SCSS": 13625, "Python": 2817, "JavaScript": 1198, "Makefile": 160}
package nebulosa.indi.client.device.wheels import nebulosa.indi.client.INDIClient import nebulosa.indi.client.device.INDIDevice import nebulosa.indi.device.filterwheel.* import nebulosa.indi.protocol.* // https://github.com/indilib/indi/blob/master/libs/indibase/indifilterwheel.cpp internal open class INDIFilterWheel( override val sender: INDIClient, override val name: String, ) : INDIDevice(), FilterWheel { @Volatile final override var count = 0 @Volatile final override var position = 0 @Volatile final override var moving = false final override val names = ArrayList<String>(12) override fun handleMessage(message: INDIProtocol) { when (message) { is NumberVector<*> -> { when (message.name) { "FILTER_SLOT" -> { val slot = message["FILTER_SLOT_VALUE"]!! if (message is DefNumberVector) { count = slot.max.toInt() - slot.min.toInt() + 1 sender.fireOnEventReceived(FilterWheelCountChanged(this)) } if (message.state == PropertyState.ALERT) { sender.fireOnEventReceived(FilterWheelMoveFailed(this)) } val prevPosition = position position = slot.value.toInt() if (prevPosition != position) { sender.fireOnEventReceived(FilterWheelPositionChanged(this)) } val prevIsMoving = moving moving = message.isBusy if (prevIsMoving != moving) { sender.fireOnEventReceived(FilterWheelMovingChanged(this)) } } } } is TextVector<*> -> { when (message.name) { "FILTER_NAME" -> { names.clear() repeat(16) { val key = "FILTER_SLOT_NAME_${it + 1}" if (key in message) { names.add(message[key]!!.value) } } sender.fireOnEventReceived(FilterWheelNamesChanged(this)) } } } else -> Unit } super.handleMessage(message) } override fun moveTo(position: Int) { if (position in 1..count) { sendNewNumber("FILTER_SLOT", "FILTER_SLOT_VALUE" to position.toDouble()) } } override fun names(names: Iterable<String>) { sendNewText("FILTER_NAME", names.mapIndexed { i, name -> "FILTER_SLOT_NAME_${i + 1}" to name }) } override fun close() = Unit override fun toString() = "FilterWheel(name=$name, slotCount=$count, position=$position, moving=$moving)" }
4
Kotlin
2
4
bc81dd82c3c7dce1cf55bd03d0a69a8a1818f9ce
3,029
nebulosa
MIT License
library/src/main/java/cloud/pace/sdk/appkit/communication/generated/model/request/DisableRequest.kt
pace
303,641,261
false
null
// // Generated by KotlinPoet: // https://github.com/square/kotlinpoet // // Please do not edit! // package cloud.pace.sdk.appkit.communication.generated.model.request import kotlin.Double public data class DisableRequest( /** * The date when the app should be enabled again, in seconds since epoch */ public val until: Double )
0
Kotlin
0
3
09f36aa0344d3482e86715ad7c47d7f1a4aa4fe4
345
cloud-sdk-android
MIT License
src/main/kotlin/net/rentalhost/plugins/php/hammer/inspections/codeError/OverrideIllegalInspection.kt
hammer-tools
509,864,102
false
null
package net.rentalhost.plugins.php.hammer.inspections.codeError import com.intellij.codeInspection.ProblemsHolder import com.intellij.codeInspection.options.OptCheckbox import com.intellij.codeInspection.options.OptPane import com.intellij.codeInspection.options.PlainMessage import com.intellij.icons.AllIcons import com.intellij.openapi.util.text.HtmlChunk import com.intellij.util.xmlb.annotations.OptionTag import com.jetbrains.php.PhpIndex import com.jetbrains.php.lang.inspections.PhpInspection import com.jetbrains.php.lang.inspections.attributes.PhpRemoveAttributeQuickFix import com.jetbrains.php.lang.psi.elements.Method import com.jetbrains.php.lang.psi.elements.PhpAttribute import com.jetbrains.php.lang.psi.visitors.PhpElementVisitor import net.rentalhost.plugins.php.hammer.extensions.psi.getEntire import net.rentalhost.plugins.php.hammer.extensions.psi.isOverridable import net.rentalhost.plugins.php.hammer.services.FindUsageService import net.rentalhost.plugins.php.hammer.services.ProblemsHolderService import net.rentalhost.plugins.php.hammer.services.QuickFixService class OverrideIllegalInspection : PhpInspection() { @OptionTag var considerUnusedTraits = false override fun buildVisitor(problemsHolder: ProblemsHolder, isOnTheFly: Boolean): PhpElementVisitor = object : PhpElementVisitor() { override fun visitPhpAttribute(attribute: PhpAttribute) { if (attribute.fqn != "\\Override") return val method = attribute.owner as? Method ?: return val methodClass = method.containingClass ?: return val attributeBase = attribute.getEntire() if (methodClass.isTrait) { // Traits should be considered here as well. // But to be considered an override, it needs to be an override for all methods that use the trait. with(PhpIndex.getInstance(method.project).getTraitUsages(methodClass)) { if (!considerUnusedTraits && isEmpty()) return if (isNotEmpty() && all { method.isOverridable(it) }) return if (any { method.isOverridable(it) }) { val methodCall = "${methodClass.name}::${method.name}()" ProblemsHolderService.instance.registerProblem( problemsHolder, attributeBase, "this method has an #[Override] on at least one method, but this method is not present in all classes that use this trait", listOf( QuickFixService.instance.simpleAction( "Show incompatible classes...", AllIcons.Actions.Search ) { FindUsageService.showUsages( method.project, filterNot { method.isOverridable(it) }, "Incompatible classes for $methodCall" ) }, QuickFixService.instance.simpleAction( "Show overrided methods...", AllIcons.Actions.Search ) { FindUsageService.showUsages( method.project, filter { method.isOverridable(it) }.mapNotNull { it.superClass?.findMethodByName(method.name) }, "Overrided methods for $methodCall", ) } ) ) return } } } // Considers only methods that do not perform overrides. else if (method.isOverridable()) { return } // Otherwise, we have found a problem compatible with this inspection. ProblemsHolderService.instance.registerProblem( problemsHolder, attributeBase, "this method doesn't actually perform an override; remove this illegal #[Override] attribute", QuickFixService.instance.simpleInline("Remove illegal attribute") { PhpRemoveAttributeQuickFix.removeAttribute(attribute) } ) } } override fun getOptionsPane(): OptPane { return OptPane.pane( OptCheckbox( "considerUnusedTraits", PlainMessage("Consider unused traits"), emptyList(), HtmlChunk.raw( "When this option is enabled, <code>trait</code> that haven't been used (via the <code>use</code> keyword) " + "in any class will not trigger issues until they are actually used somewhere." ) ), ) } }
9
null
2
96
eb07d4f34bdd4a588251db854e6c60ca6584886a
4,415
php-hammer
Apache License 2.0
multi-theme-core/src/main/java/com/magic/multi/theme/core/base/BaseAttr.kt
mistletoe5215
389,977,624
false
{"Kotlin": 64510}
package com.magic.multi.theme.core.base import android.view.View /** * Created by mistletoe * on 7/23/21 **/ abstract class BaseAttr { /** * xml里某个属性的名称 */ var attrName: String? = null /** * xml里某个属性的值 */ var attrValue: Int = 0 /** * xml里某个属性值的名称 */ var entryName: String? = null /** * xml里某个属性值的类型 */ var entryType: String? = null /** * file name * assets 里的资源名称 */ var attrAssetsValue: String? = null /** * 是否在解析时立即apply */ open var applyImmediate: Boolean = false /** * 刷新该控件的该属性 */ abstract fun apply(view: View?) }
0
Kotlin
2
20
adf7b3a0b9842af987e3cf834b374b4c32bbadbb
661
MagicMistletoe
Apache License 2.0
jvm/src/test/kotlin/dev/paulshields/assistantview/lang/JavaSourceFileInterpreterTest.kt
Pkshields
445,326,540
false
{"Kotlin": 113569}
package dev.paulshields.assistantview.lang import assertk.assertThat import assertk.assertions.isEqualTo import assertk.assertions.isNotNull import assertk.assertions.isNull import com.intellij.openapi.project.Project import com.intellij.psi.PsiFile import com.intellij.psi.PsiJavaFile import dev.paulshields.assistantview.testcommon.mock import org.junit.jupiter.api.Test class JavaSourceFileInterpreterTest { private val project = mock<Project>() private val target = JavaSourceFileInterpreter() @Test fun `should parse java file`() { val javaFile = mock<PsiJavaFile>() val result = target.parseFile(javaFile, project) assertThat(result).isNotNull() assertThat(result?.psiFile).isEqualTo(javaFile) assertThat(result?.project).isEqualTo(project) } @Test fun `should gracefully fail to parse unsupported file`() { val unsupportedFile = mock<PsiFile>() val result = target.parseFile(unsupportedFile, project) assertThat(result).isNull() } }
0
Kotlin
0
1
d4a9cb5ec8877522b007649898e5bfc071ba8055
1,045
AssistantView
MIT License
template-xml/app/src/main/java/co/nimblehq/template/xml/model/UiModel.kt
nimblehq
101,353,301
false
null
package co.nimblehq.template.xml.model import co.nimblehq.template.xml.domain.model.Model data class UiModel( val id: Int ) private fun Model.toUiModel() = UiModel(id = id ?: -1) fun List<Model>.toUiModels() = this.map { it.toUiModel() }
23
Kotlin
21
63
f5288193d83de72333461b1e7d0495b9ed3943d7
246
android-templates
MIT License
PluginsAndFeatures/azure-toolkit-for-intellij/rider/src/com/microsoft/intellij/runner/functionapp/config/FunctionAppRunState.kt
JetBrains
137,064,201
true
{"Java": 6822615, "Kotlin": 2384238, "C#": 198892, "Scala": 151332, "Gherkin": 108427, "JavaScript": 98350, "HTML": 23518, "CSS": 21770, "Groovy": 21447, "Shell": 21354, "XSLT": 7141, "Dockerfile": 3518, "Batchfile": 2155}
/** * Copyright (c) 2019-2023 JetBrains s.r.o. * * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated * documentation files (the "Software"), to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and * to permit persons to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial portions of * the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.microsoft.intellij.runner.functionapp.config import com.intellij.execution.process.ProcessOutputTypes import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.notification.Notifications import com.intellij.openapi.project.Project import com.intellij.util.application import com.microsoft.azure.management.appservice.FunctionApp import com.microsoft.azure.management.appservice.FunctionRuntimeStack import com.microsoft.azure.management.appservice.OperatingSystem import com.microsoft.azure.management.appservice.WebAppBase import com.microsoft.azure.management.sql.SqlDatabase import com.microsoft.azure.toolkit.intellij.common.AzureRunProfileState import com.microsoft.azuretools.core.mvp.model.AzureMvpModel import com.microsoft.azuretools.core.mvp.model.appserviceplan.AzureAppServicePlanMvpModel import com.microsoft.azuretools.core.mvp.model.database.AzureSqlDatabaseMvpModel import com.microsoft.azuretools.core.mvp.model.functionapp.AzureFunctionAppMvpModel import com.microsoft.azuretools.core.mvp.model.storage.AzureStorageAccountMvpModel import com.microsoft.intellij.RunProcessHandler import com.microsoft.intellij.runner.appbase.config.runstate.AppDeployStateUtil.getAppUrl import com.microsoft.intellij.runner.appbase.config.runstate.AppDeployStateUtil.openAppInBrowser import com.microsoft.intellij.runner.appbase.config.runstate.AppDeployStateUtil.refreshAzureExplorer import com.microsoft.intellij.runner.database.config.deploy.DatabaseDeployUtil.getOrCreateSqlDatabaseFromConfig import com.microsoft.intellij.runner.database.model.DatabasePublishModel import com.microsoft.intellij.runner.functionapp.config.runstate.FunctionAppDeployStateUtil.addConnectionString import com.microsoft.intellij.runner.functionapp.config.runstate.FunctionAppDeployStateUtil.deployToAzureFunctionApp import com.microsoft.intellij.runner.functionapp.config.runstate.FunctionAppDeployStateUtil.functionAppStart import com.microsoft.intellij.runner.functionapp.config.runstate.FunctionAppDeployStateUtil.getOrCreateFunctionAppFromConfiguration import org.jetbrains.plugins.azure.util.FrameworkUtil import com.microsoft.intellij.runner.functionapp.model.FunctionAppPublishModel import com.microsoft.intellij.runner.functionapp.model.FunctionAppSettingModel import org.jetbrains.plugins.azure.RiderAzureBundle.message import org.jetbrains.plugins.azure.functions.coreTools.FunctionsCoreToolsMsBuild import org.jetbrains.plugins.azure.functions.run.localsettings.FunctionLocalSettingsUtil import org.jetbrains.plugins.azure.functions.run.localsettings.FunctionsWorkerRuntime import java.io.File data class FunctionAppDeployResult(val app: WebAppBase, val sqlDatabase: SqlDatabase?) class FunctionAppRunState(project: Project, private val myModel: FunctionAppSettingModel) : AzureRunProfileState<FunctionAppDeployResult>(project) { private var isFunctionAppCreated = false private var isDatabaseCreated = false companion object { private const val TARGET_FUNCTION_NAME = "FunctionApp" private const val TARGET_FUNCTION_DEPLOYMENT_SLOT_NAME = "FunctionDeploymentSlot" } override fun getDeployTarget(): String = if (myModel.functionAppModel.isDeployToSlot) TARGET_FUNCTION_DEPLOYMENT_SLOT_NAME else TARGET_FUNCTION_NAME override fun executeSteps(processHandler: RunProcessHandler, telemetryMap: MutableMap<String, String>): FunctionAppDeployResult { val publishableProject = myModel.functionAppModel.publishableProject ?: throw RuntimeException(message("process_event.publish.project.not_defined")) val subscriptionId = myModel.functionAppModel.subscription?.subscriptionId() ?: throw RuntimeException(message("process_event.publish.subscription.not_defined")) val app = getOrCreateFunctionAppFromConfiguration(myModel.functionAppModel, processHandler) tryConfigureAzureFunctionRuntimeStack(app, subscriptionId, processHandler) deployToAzureFunctionApp( project = project, publishableProject = publishableProject, configuration = myModel.functionAppModel.configuration, platform = myModel.functionAppModel.platform, app = app, processHandler = processHandler) isFunctionAppCreated = true var database: SqlDatabase? = null if (myModel.databaseModel.isDatabaseConnectionEnabled) { database = getOrCreateSqlDatabaseFromConfig(myModel.databaseModel, processHandler) val databaseUri = AzureMvpModel.getInstance().getResourceUri(subscriptionId, database.id()) if (databaseUri != null) processHandler.setText(message("process_event.publish.sql_db.url", databaseUri)) if (myModel.databaseModel.connectionStringName.isEmpty()) throw RuntimeException(message("process_event.publish.connection_string.not_defined")) if (myModel.databaseModel.sqlServerAdminLogin.isEmpty()) throw RuntimeException(message("process_event.publish.sql_server.admin_login_not_defined")) if (myModel.databaseModel.sqlServerAdminPassword.isEmpty()) throw RuntimeException(message("process_event.publish.sql_server.admin_password_not_defined")) addConnectionString( subscriptionId, app, database, myModel.databaseModel.connectionStringName, myModel.databaseModel.sqlServerAdminLogin, myModel.databaseModel.sqlServerAdminPassword, processHandler) } isDatabaseCreated = true functionAppStart(app, processHandler) val url = getAppUrl(app) processHandler.setText(message("process_event.publish.url", url)) processHandler.setText(message("process_event.publish.done")) return FunctionAppDeployResult(app, database) } private fun tryConfigureAzureFunctionRuntimeStack(app: WebAppBase, subscriptionId: String, processHandler: RunProcessHandler) { if (app !is FunctionApp) return // Set runtime stack based on project config val publishableProject = myModel.functionAppModel.publishableProject if (publishableProject != null && publishableProject.isDotNetCore) { application.invokeAndWait { val functionLocalSettings = FunctionLocalSettingsUtil.readFunctionLocalSettings(project, File(publishableProject.projectFilePath).parent) val workerRuntime = functionLocalSettings?.values?.workerRuntime ?: FunctionsWorkerRuntime.DotNetDefault val coreToolsVersion = FunctionsCoreToolsMsBuild.requestAzureFunctionsVersion(project, publishableProject.projectFilePath) ?: "V4" val netCoreVersion = FrameworkUtil.getProjectNetCoreFrameworkVersion(project, publishableProject) myModel.functionAppModel.functionRuntimeStack = FunctionRuntimeStack( workerRuntime.value, "~" + coreToolsVersion.trimStart('v', 'V'), "${workerRuntime.value}|$netCoreVersion", "${workerRuntime.value}|$netCoreVersion") } } val functionRuntimeStack = myModel.functionAppModel.functionRuntimeStack processHandler.setText(message("process_event.publish.updating_runtime", functionRuntimeStack.runtime(), functionRuntimeStack.version())) if (myModel.functionAppModel.operatingSystem == OperatingSystem.LINUX) { val appServicePlan = AzureAppServicePlanMvpModel .getAppServicePlanById(subscriptionId, app.appServicePlanId()) processHandler.setText(message("process_event.publish.updating_runtime.linux", functionRuntimeStack.linuxFxVersionForDedicatedPlan)) // For Linux, we have to set the correct FunctionRuntimeStack app.update() .withExistingLinuxAppServicePlan(appServicePlan) .withBuiltInImage(functionRuntimeStack) .apply() // For Linux dynamic (consumption) plan, we have to set SCM_DO_BUILD_DURING_DEPLOYMENT=false if (appServicePlan.pricingTier() == FunctionAppPublishModel.dynamicPricingTier) { processHandler.setText(message("process_event.publish.updating_appsettings.scm_build")) app.update() .withAppSetting("SCM_DO_BUILD_DURING_DEPLOYMENT", "false") .apply() } } else { // For Windows, we have to set the correct runtime and version app.update() .withRuntime(functionRuntimeStack.runtime()) .withRuntimeVersion(functionRuntimeStack.version()) .apply() } } override fun onSuccess(result: FunctionAppDeployResult, processHandler: RunProcessHandler) { processHandler.notifyComplete() // Refresh for both cases (when create new function app and publish into existing one) // to make sure separate functions are updated as well refreshAzureExplorer(listenerId = "FunctionModule") val app = result.app val sqlDatabase = result.sqlDatabase refreshAppsAfterPublish(app, myModel.functionAppModel) if (sqlDatabase != null) { refreshDatabaseAfterPublish(sqlDatabase, myModel.databaseModel) } showPublishNotification(message("notification.publish.publish_complete"), NotificationType.INFORMATION) if (myModel.functionAppModel.openInBrowserAfterPublish) { openAppInBrowser(app, processHandler) } } override fun onFail(error: Throwable, processHandler: RunProcessHandler) { if (processHandler.isProcessTerminated || processHandler.isProcessTerminating) return if (isFunctionAppCreated) { AzureFunctionAppMvpModel.refreshSubscriptionToFunctionAppMap() AzureStorageAccountMvpModel.refreshStorageAccountsMap() } if (isDatabaseCreated) AzureSqlDatabaseMvpModel.refreshSqlServerToSqlDatabaseMap() showPublishNotification(message("notification.publish.publish_failed"), NotificationType.ERROR) processHandler.println(error.message, ProcessOutputTypes.STDERR) processHandler.notifyComplete() } private fun refreshAppsAfterPublish(app: WebAppBase, model: FunctionAppPublishModel) { model.resetOnPublish(app) AzureFunctionAppMvpModel.refreshSubscriptionToFunctionAppMap() AzureStorageAccountMvpModel.refreshStorageAccountsMap() } private fun refreshDatabaseAfterPublish(sqlDatabase: SqlDatabase, model: DatabasePublishModel) { model.resetOnPublish(sqlDatabase) AzureSqlDatabaseMvpModel.refreshSqlServerToSqlDatabaseMap() } private fun showPublishNotification(text: String, type: NotificationType) { val notification = NotificationGroupManager.getInstance() .getNotificationGroup("Azure Web App Publish Message") .createNotification(text, type) Notifications.Bus.notify(notification, project) } }
73
Java
10
41
a8b64627376a5144a71725853ba4217b97044722
12,579
azure-tools-for-intellij
MIT License
client/src/test/java/nl/altindag/client/service/Http4kApache4AsyncHttpClientServiceShould.kt
skarzhevskyy
326,338,610
true
{"Java": 186080, "Kotlin": 33594, "Scala": 20975, "Shell": 13761, "Gherkin": 2228}
package nl.altindag.client.service import com.nhaarman.mockitokotlin2.times import com.nhaarman.mockitokotlin2.verify import nl.altindag.client.ClientType.HTTP4K_APACHE4_ASYNC_HTTP_CLIENT import nl.altindag.client.TestConstants import nl.altindag.client.util.MockServerTestHelper import nl.altindag.client.util.SSLFactoryTestHelper import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class Http4kApache4AsyncHttpClientServiceShould { @Test fun executeRequest() { MockServerTestHelper.mockResponseForClient(HTTP4K_APACHE4_ASYNC_HTTP_CLIENT) val client = Http4kApache4AsyncHttpClientService(null) val response = client.executeRequest(TestConstants.HTTP_URL) assertThat(response.responseBody).isEqualTo("Hello") assertThat(response.statusCode).isEqualTo(200) } @Test fun createClientWithSslMaterial() { val sslFactory = SSLFactoryTestHelper.createSSLFactory(false, true) Http4kApache4AsyncHttpClientService(sslFactory) verify(sslFactory, times(1)).sslContext verify(sslFactory, times(1)).hostnameVerifier } }
0
null
0
0
383b05ee866c394f83b6371622b712ef8fad3c8d
1,142
mutual-tls-ssl
Apache License 2.0
telegramit-autoconfigure/src/main/kotlin/org/botlaxy/telegramit/autoconfigure/TelegramitAutoConfiguration.kt
vitaxa
258,866,097
false
null
package org.botlaxy.telegramit.autoconfigure import org.botlaxy.telegramit.autoconfigure.property.TelegramPropertiesValidator import org.botlaxy.telegramit.autoconfigure.property.TelegramitProperties import org.botlaxy.telegramit.core.bot import org.botlaxy.telegramit.core.client.TelegramClientType import org.botlaxy.telegramit.core.conversation.persistence.ConversationPersistence import org.botlaxy.telegramit.core.handler.filter.TelegramUpdateFilter import org.botlaxy.telegramit.core.handler.loader.DefaultHandlerScriptManager import org.botlaxy.telegramit.core.handler.loader.HandlerScriptManager import org.botlaxy.telegramit.core.handler.loader.collect.ClassPathScriptCollector import org.botlaxy.telegramit.core.handler.loader.collect.ScriptCollector import org.botlaxy.telegramit.core.handler.loader.compile.HandlerScriptCompiler import org.botlaxy.telegramit.spring.client.SpringTelegramBot import org.botlaxy.telegramit.spring.handler.loader.compile.SpringScriptCompiler import org.springframework.boot.autoconfigure.condition.ConditionalOnClass import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.support.GenericApplicationContext import org.springframework.validation.Validator @Configuration @ConditionalOnClass(SpringTelegramBot::class) @EnableConfigurationProperties(TelegramitProperties::class) class TelegramitAutoConfiguration(val telegramProperties: TelegramitProperties) { companion object { @Bean fun configurationPropertiesValidator(): Validator { return TelegramPropertiesValidator() } } @Bean @ConditionalOnMissingBean(name = ["telegramProperties"]) fun telegramProperties(): TelegramitProperties = telegramProperties @Bean @ConditionalOnMissingBean(HandlerScriptCompiler::class) fun handlerScriptCompiler(context: GenericApplicationContext): HandlerScriptCompiler { return SpringScriptCompiler(context) } @Bean @ConditionalOnMissingBean(ScriptCollector::class) fun scriptCollector(): ScriptCollector { return ClassPathScriptCollector() } @Bean @ConditionalOnMissingBean(HandlerScriptManager::class) fun handlerScriptManager( handlerScriptCompiler: HandlerScriptCompiler, scriptCollector: ScriptCollector ): HandlerScriptManager { return DefaultHandlerScriptManager(handlerScriptCompiler, scriptCollector) } @Bean @ConditionalOnMissingBean(SpringTelegramBot::class) fun telegramBot( telegramProperties: TelegramitProperties, handlerScriptManager: HandlerScriptManager, persistence: ConversationPersistence?, filters: List<TelegramUpdateFilter>? ): SpringTelegramBot { val telegramBot = bot { name = telegramProperties.name token = telegramProperties.token updateFilters = filters if (telegramProperties.mode == TelegramClientType.WEBHOOK) { client { type = telegramProperties.mode host = telegramProperties.webhookHost port = telegramProperties.webHookPort } } proxy { telegramProperties.proxyHost?.let { host = it } telegramProperties.proxyPort?.let { port = it } telegramProperties.proxyLogin?.let { login = it } telegramProperties.proxyPassword?.let { password = it } telegramProperties.proxyType?.let { type = it } } persistence?.let { persistenceConfig { conversationPersistence = persistence } } handlerScriptConfig { this.handlerScriptManager = handlerScriptManager } } return SpringTelegramBot(telegramBot) } }
0
Kotlin
2
9
2e7fdb9e1e3edf2638d7dbb0895b4f8a10fbaa43
4,108
telegramit
Apache License 2.0
app/src/main/java/com/ramitsuri/notificationjournal/ui/editjournal/EditJournalEntryViewModel.kt
ramitsuri
667,037,607
false
{"Kotlin": 224720, "Shell": 9028, "Python": 2413, "HTML": 577}
package com.ramitsuri.notificationjournal.ui.editjournal import androidx.lifecycle.AbstractSavedStateViewModelFactory import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.NavBackStackEntry import com.ramitsuri.notificationjournal.core.data.TagsDao import com.ramitsuri.notificationjournal.core.model.entry.JournalEntry import com.ramitsuri.notificationjournal.core.model.Tag import com.ramitsuri.notificationjournal.core.repository.JournalRepository import com.ramitsuri.notificationjournal.di.ServiceLocator import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class EditJournalEntryViewModel( savedStateHandle: SavedStateHandle, private val repository: JournalRepository, private val tagsDao: TagsDao, ) : ViewModel() { private val _saved = MutableStateFlow(false) val saved: StateFlow<Boolean> = _saved private val _state: MutableStateFlow<EditJournalEntryViewState> = MutableStateFlow(EditJournalEntryViewState.default()) val state: StateFlow<EditJournalEntryViewState> = _state private lateinit var entry: JournalEntry init { viewModelScope.launch { entry = repository.get(checkNotNull(savedStateHandle[ENTRY_ID_ARG])) _state.update { it.copy(isLoading = false, text = entry.text, selectedTag = entry.tag) } } loadTags() } fun textUpdated(text: String) { _state.update { it.copy(text = text) } } fun tagClicked(tag: String) { _state.update { it.copy(selectedTag = tag) } } fun save() { if (!::entry.isInitialized) { return } val currentState = _state.value val text = currentState.text if (text.isEmpty()) { return } _state.update { it.copy(isLoading = true) } val tag = currentState.selectedTag viewModelScope.launch { repository.editText( id = entry.id, text = text ) repository.editTag( id = entry.id, tag = tag ) _saved.update { true } } } private fun loadTags() { viewModelScope.launch { _state.update { it.copy(tags = tagsDao.getAll()) } } } companion object { const val ENTRY_ID_ARG = "entry_id" fun factory(navBackStackEntry: NavBackStackEntry) = object : AbstractSavedStateViewModelFactory( owner = navBackStackEntry, defaultArgs = navBackStackEntry.arguments, ) { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create( key: String, modelClass: Class<T>, handle: SavedStateHandle ): T { return EditJournalEntryViewModel( savedStateHandle = handle, repository = ServiceLocator.repository, tagsDao = ServiceLocator.tagsDao, ) as T } } } } data class EditJournalEntryViewState( val isLoading: Boolean, val text: String, val tags: List<Tag>, val selectedTag: String?, ) { companion object { fun default() = EditJournalEntryViewState( isLoading = true, text = "", tags = listOf(), selectedTag = null, ) } }
0
Kotlin
0
0
d886f31940f887103955ab71d180260ff445b80d
3,779
notification-journal
MIT License
quartz/src/androidTest/java/com/vitorpamplona/quartz/NIP19EmbedTests.kt
retrnull
827,005,629
false
null
/** * Copyright (c) 2024 Vitor Pamplona * * Permission is hereby granted, free of charge, to any person obtaining a copy of * this software and associated documentation files (the "Software"), to deal in * the Software without restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.vitorpamplona.quartz import androidx.test.ext.junit.runners.AndroidJUnit4 import com.vitorpamplona.quartz.crypto.KeyPair import com.vitorpamplona.quartz.encoders.Hex import com.vitorpamplona.quartz.encoders.Nip19Bech32 import com.vitorpamplona.quartz.encoders.decodePrivateKeyAsHexOrNull import com.vitorpamplona.quartz.encoders.hexToByteArray import com.vitorpamplona.quartz.events.Event import com.vitorpamplona.quartz.events.FhirResourceEvent import com.vitorpamplona.quartz.events.TextNoteEvent import com.vitorpamplona.quartz.signers.NostrSignerInternal import junit.framework.TestCase.assertEquals import junit.framework.TestCase.assertNotNull import junit.framework.TestCase.assertTrue import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @RunWith(AndroidJUnit4::class) class NIP19EmbedTests { @Test fun testEmbedKind1Event() { val signer = NostrSignerInternal( KeyPair(Hex.decode("e8e7197ccc53c9ed4cf9b1c8dce085475fa1ffdd71f2c14e44fe23d0bdf77598")), ) var textNote: Event? = null val countDownLatch = CountDownLatch(1) TextNoteEvent.create("I like this. It could solve the ninvite problem in #1062, and it seems like it could be applied very broadly to limit the spread of events that shouldn't stand on their own or need to be private. The one question I have is how long are these embeds? If it's 50 lines of text, that breaks the human readable (or at least parseable) requirement of kind 1s. Also, encoding json in a tlv is silly, we should at least use the tlv to reduce the payload size.", isDraft = false, signer = signer) { textNote = it countDownLatch.countDown() } Assert.assertTrue(countDownLatch.await(1, TimeUnit.SECONDS)) assertNotNull(textNote) val bech32 = Nip19Bech32.createNEmbed(textNote!!) println(bech32) val decodedNote = (Nip19Bech32.uriToRoute(bech32)?.entity as Nip19Bech32.NEmbed).event assertTrue(decodedNote.hasValidSignature()) assertEquals(textNote!!.toJson(), decodedNote.toJson()) } @Test fun testVisionPrescriptionEmbedEvent() { val signer = NostrSignerInternal( KeyPair(Hex.decode("e8e7197ccc53c9ed4cf9b1c8dce085475fa1ffdd71f2c14e44fe23d0bdf77598")), ) var eyeglassesPrescriptionEvent: Event? = null val countDownLatch = CountDownLatch(1) FhirResourceEvent.create(fhirPayload = visionPrescriptionFhir, signer = signer) { eyeglassesPrescriptionEvent = it countDownLatch.countDown() } Assert.assertTrue(countDownLatch.await(1, TimeUnit.SECONDS)) assertNotNull(eyeglassesPrescriptionEvent) val bech32 = Nip19Bech32.createNEmbed(eyeglassesPrescriptionEvent!!) println(eyeglassesPrescriptionEvent!!.toJson()) println(bech32) val decodedNote = (Nip19Bech32.uriToRoute(bech32)?.entity as Nip19Bech32.NEmbed).event assertTrue(decodedNote.hasValidSignature()) assertEquals(eyeglassesPrescriptionEvent!!.toJson(), decodedNote.toJson()) } @Test fun testVisionPrescriptionBundleEmbedEvent() { val signer = NostrSignerInternal( KeyPair(Hex.decode("e8e7197ccc53c9ed4cf9b1c8dce085475fa1ffdd71f2c14e44fe23d0bdf77598")), ) var eyeglassesPrescriptionEvent: Event? = null val countDownLatch = CountDownLatch(1) FhirResourceEvent.create(fhirPayload = visionPrescriptionBundle, signer = signer) { eyeglassesPrescriptionEvent = it countDownLatch.countDown() } Assert.assertTrue(countDownLatch.await(1, TimeUnit.SECONDS)) assertNotNull(eyeglassesPrescriptionEvent) val bech32 = Nip19Bech32.createNEmbed(eyeglassesPrescriptionEvent!!) println(eyeglassesPrescriptionEvent!!.toJson()) println(bech32) val decodedNote = (Nip19Bech32.uriToRoute(bech32)?.entity as Nip19Bech32.NEmbed).event assertTrue(decodedNote.hasValidSignature()) assertEquals(eyeglassesPrescriptionEvent!!.toJson(), decodedNote.toJson()) } @Test fun testVisionPrescriptionBundle2EmbedEvent() { val signer = NostrSignerInternal( KeyPair(decodePrivateKeyAsHexOrNull("nsec1arn3jlxv20y76n8ek8ydecy9ga06rl7aw8evznjylc3ap00hwkvqx4vvy6")!!.hexToByteArray()), ) var eyeglassesPrescriptionEvent: Event? = null val countDownLatch = CountDownLatch(1) FhirResourceEvent.create(fhirPayload = visionPrescriptionBundle2, signer = signer) { eyeglassesPrescriptionEvent = it countDownLatch.countDown() } Assert.assertTrue(countDownLatch.await(1, TimeUnit.SECONDS)) assertNotNull(eyeglassesPrescriptionEvent) val bech32 = Nip19Bech32.createNEmbed(eyeglassesPrescriptionEvent!!) println(eyeglassesPrescriptionEvent!!.toJson()) println(bech32) val decodedNote = (Nip19Bech32.uriToRoute(bech32)?.entity as Nip19Bech32.NEmbed).event assertTrue(decodedNote.hasValidSignature()) assertEquals(eyeglassesPrescriptionEvent!!.toJson(), decodedNote.toJson()) } val visionPrescriptionFhir = "{\"resourceType\":\"VisionPrescription\",\"status\":\"active\",\"created\":\"2014-06-15\",\"patient\":{\"reference\":\"Patient/Donald Duck\"},\"dateWritten\":\"2014-06-15\",\"prescriber\":{\"reference\":\"Practitioner/Adam Careful\"},\"lensSpecification\":[{\"eye\":\"right\",\"sphere\":-2,\"prism\":[{\"amount\":0.5,\"base\":\"down\"}],\"add\":2},{\"eye\":\"left\",\"sphere\":-1,\"cylinder\":-0.5,\"axis\":180,\"prism\":[{\"amount\":0.5,\"base\":\"up\"}],\"add\":2}]}" val visionPrescriptionBundle = "{\"resourceType\":\"Bundle\",\"id\":\"bundle-vision-test\",\"type\":\"document\",\"entry\":[{\"resourceType\":\"Practitioner\",\"id\":\"2\",\"active\":true,\"name\":[{\"use\":\"official\",\"family\":\"Careful\",\"given\":[\"Adam\"]}],\"gender\":\"male\"},{\"resourceType\":\"Patient\",\"id\":\"1\",\"active\":true,\"name\":[{\"use\":\"official\",\"family\":\"Duck\",\"given\":[\"Donald\"]}],\"gender\":\"male\"},{\"resourceType\":\"VisionPrescription\",\"status\":\"active\",\"created\":\"2014-06-15\",\"patient\":{\"reference\":\"#1\"},\"dateWritten\":\"2014-06-15\",\"prescriber\":{\"reference\":\"#2\"},\"lensSpecification\":[{\"eye\":\"right\",\"sphere\":-2,\"prism\":[{\"amount\":0.5,\"base\":\"down\"}],\"add\":2},{\"eye\":\"left\",\"sphere\":-1,\"cylinder\":-0.5,\"axis\":180,\"prism\":[{\"amount\":0.5,\"base\":\"up\"}],\"add\":2}]}]}" val visionPrescriptionBundle2 = "{\"resourceType\":\"Bundle\",\"id\":\"bundle-vision-test\",\"type\":\"document\",\"entry\":[{\"resourceType\":\"Practitioner\",\"id\":\"2\",\"active\":true,\"name\":[{\"use\":\"official\",\"family\":\"Smith\",\"given\":[\"Dr. Joe\"]}],\"gender\":\"male\"},{\"resourceType\":\"Patient\",\"id\":\"1\",\"active\":true,\"name\":[{\"use\":\"official\",\"family\":\"Doe\",\"given\":[\"Jane\"]}],\"gender\":\"male\"},{\"resourceType\":\"VisionPrescription\",\"status\":\"active\",\"created\":\"2014-06-15\",\"patient\":{\"reference\":\"#1\"},\"dateWritten\":\"2014-06-15\",\"lensSpecification\":[{\"eye\":\"right\",\"sphere\":-2,\"prism\":[{\"amount\":0.5,\"base\":\"down\"}],\"add\":2},{\"eye\":\"left\",\"sphere\":-1,\"cylinder\":-0.5,\"axis\":180,\"prism\":[{\"amount\":0.5,\"base\":\"up\"}],\"add\":2}]}]}" }
5
null
3
34
d33428614279300c503770c10a4305ca2a4d5ab6
8,737
garnet
MIT License
src/main/kotlin/org/jaqpot/api/auth/UserService.kt
ntua-unit-of-control-and-informatics
790,773,279
false
{"Kotlin": 28985}
package org.jaqpot.api.auth import org.jaqpot.api.model.UserDto interface UserService { fun getUserById(id: String): UserDto fun getUserByUsername(username: String): UserDto fun getUserByEmail(email: String): UserDto }
0
Kotlin
0
0
ce3afeb1684b43e6857759402989565d5b93d9f9
233
jaqpot-api-v2
MIT License
common/data/src/main/java/app/common/data/work/ContactSyncWorker.kt
ShabanKamell
377,910,641
false
null
package app.common.data.work import android.content.Context import androidx.work.CoroutineWorker import androidx.work.WorkerParameters import app.common.data.domain.contacts.ContactsRepo import app.common.data.domain.contacts.ContactsRepoInterface import org.koin.java.KoinJavaComponent.inject class ContactSyncWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) { private val contactsRepo: ContactsRepoInterface by inject(ContactsRepo::class.java) override suspend fun doWork(): Result { syncContacts() return Result.success() } private suspend fun syncContacts() { contactsRepo.sync() } }
0
Kotlin
0
1
86af3d676d887ba4b5953289e3dca9c947551513
684
Contacts
Apache License 2.0
app/src/main/java/dev/spikeysanju/einsen/ui/theme/dimensions/AppDimensions.kt
Spikeysanju
367,818,611
false
null
/* * Copyright 2020-2021 Photos.network developers * * 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 network.photos.android.theme import androidx.compose.runtime.staticCompositionLocalOf import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp data class AppDimensions( val paddingSmall: Dp = 4.dp, val paddingMedium: Dp = 8.dp, val paddingLarge: Dp = 24.dp ) internal val LocalDimensions = staticCompositionLocalOf { AppDimensions() }
5
null
74
858
e9e9e4277883ab91611e8699bb93da3dc51fc9d4
986
Einsen
Apache License 2.0
app/src/main/java/siarhei/luskanau/managed/virtual/device/ui/theme/Color.kt
siarhei-luskanau
427,449,267
false
{"Kotlin": 6070}
@file:Suppress("MagicNumber") package siarhei.luskanau.managed.virtual.device.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260)
0
Kotlin
2
2
b02151e659c60a8c015f705a4e71f4689a4cb6e2
335
android-managed-virtual-device
MIT License
scientific/src/commonMain/kotlin/converter/time/convertToElectricCharge.kt
splendo
191,371,940
false
null
/* Copyright 2021 Splendo Consulting B.V. The Netherlands 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.splendo.kaluga.scientific.converter.time import com.splendo.kaluga.scientific.PhysicalQuantity import com.splendo.kaluga.scientific.ScientificValue import com.splendo.kaluga.scientific.converter.electricCurrent.times import com.splendo.kaluga.scientific.unit.Abampere import com.splendo.kaluga.scientific.unit.Biot import com.splendo.kaluga.scientific.unit.ElectricCurrent import com.splendo.kaluga.scientific.unit.Time import kotlin.jvm.JvmName @JvmName("timeTimesAbampere") infix operator fun <TimeUnit : Time> ScientificValue<PhysicalQuantity.Time, TimeUnit>.times(current: ScientificValue<PhysicalQuantity.ElectricCurrent, Abampere>) = current * this @JvmName("timeTimesBiot") infix operator fun <TimeUnit : Time> ScientificValue<PhysicalQuantity.Time, TimeUnit>.times(current: ScientificValue<PhysicalQuantity.ElectricCurrent, Biot>) = current * this @JvmName("timeTimesCurrent") infix operator fun <CurrentUnit : ElectricCurrent, TimeUnit : Time> ScientificValue<PhysicalQuantity.Time, TimeUnit>.times( current: ScientificValue<PhysicalQuantity.ElectricCurrent, CurrentUnit> ) = current * this
89
null
7
93
6d2d2ff964d13ccb2768aa336fa7ef9941959e96
1,752
kaluga
Apache License 2.0
orb-kotlin-core/src/main/kotlin/com/withorb/api/models/SubscriptionFetchCostsParams.kt
orbcorp
797,931,036
false
{"Kotlin": 11071096, "Shell": 3618, "Dockerfile": 366}
// File generated from our OpenAPI spec by Stainless. package com.withorb.api.models import com.fasterxml.jackson.annotation.JsonCreator import com.withorb.api.core.Enum import com.withorb.api.core.JsonField import com.withorb.api.core.JsonValue import com.withorb.api.core.NoAutoDetect import com.withorb.api.core.toUnmodifiable import com.withorb.api.errors.OrbInvalidDataException import com.withorb.api.models.* import java.time.OffsetDateTime import java.time.format.DateTimeFormatter import java.util.Objects class SubscriptionFetchCostsParams constructor( private val subscriptionId: String, private val timeframeEnd: OffsetDateTime?, private val timeframeStart: OffsetDateTime?, private val viewMode: ViewMode?, private val additionalQueryParams: Map<String, List<String>>, private val additionalHeaders: Map<String, List<String>>, private val additionalBodyProperties: Map<String, JsonValue>, ) { fun subscriptionId(): String = subscriptionId fun timeframeEnd(): OffsetDateTime? = timeframeEnd fun timeframeStart(): OffsetDateTime? = timeframeStart fun viewMode(): ViewMode? = viewMode internal fun getQueryParams(): Map<String, List<String>> { val params = mutableMapOf<String, List<String>>() this.timeframeEnd?.let { params.put("timeframe_end", listOf(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(it))) } this.timeframeStart?.let { params.put("timeframe_start", listOf(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(it))) } this.viewMode?.let { params.put("view_mode", listOf(it.toString())) } params.putAll(additionalQueryParams) return params.toUnmodifiable() } internal fun getHeaders(): Map<String, List<String>> = additionalHeaders fun getPathParam(index: Int): String { return when (index) { 0 -> subscriptionId else -> "" } } fun _additionalQueryParams(): Map<String, List<String>> = additionalQueryParams fun _additionalHeaders(): Map<String, List<String>> = additionalHeaders fun _additionalBodyProperties(): Map<String, JsonValue> = additionalBodyProperties override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is SubscriptionFetchCostsParams && this.subscriptionId == other.subscriptionId && this.timeframeEnd == other.timeframeEnd && this.timeframeStart == other.timeframeStart && this.viewMode == other.viewMode && this.additionalQueryParams == other.additionalQueryParams && this.additionalHeaders == other.additionalHeaders && this.additionalBodyProperties == other.additionalBodyProperties } override fun hashCode(): Int { return Objects.hash( subscriptionId, timeframeEnd, timeframeStart, viewMode, additionalQueryParams, additionalHeaders, additionalBodyProperties, ) } override fun toString() = "SubscriptionFetchCostsParams{subscriptionId=$subscriptionId, timeframeEnd=$timeframeEnd, timeframeStart=$timeframeStart, viewMode=$viewMode, additionalQueryParams=$additionalQueryParams, additionalHeaders=$additionalHeaders, additionalBodyProperties=$additionalBodyProperties}" fun toBuilder() = Builder().from(this) companion object { fun builder() = Builder() } @NoAutoDetect class Builder { private var subscriptionId: String? = null private var timeframeEnd: OffsetDateTime? = null private var timeframeStart: OffsetDateTime? = null private var viewMode: ViewMode? = null private var additionalQueryParams: MutableMap<String, MutableList<String>> = mutableMapOf() private var additionalHeaders: MutableMap<String, MutableList<String>> = mutableMapOf() private var additionalBodyProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(subscriptionFetchCostsParams: SubscriptionFetchCostsParams) = apply { this.subscriptionId = subscriptionFetchCostsParams.subscriptionId this.timeframeEnd = subscriptionFetchCostsParams.timeframeEnd this.timeframeStart = subscriptionFetchCostsParams.timeframeStart this.viewMode = subscriptionFetchCostsParams.viewMode additionalQueryParams(subscriptionFetchCostsParams.additionalQueryParams) additionalHeaders(subscriptionFetchCostsParams.additionalHeaders) additionalBodyProperties(subscriptionFetchCostsParams.additionalBodyProperties) } fun subscriptionId(subscriptionId: String) = apply { this.subscriptionId = subscriptionId } /** Costs returned are exclusive of `timeframe_end`. */ fun timeframeEnd(timeframeEnd: OffsetDateTime) = apply { this.timeframeEnd = timeframeEnd } /** Costs returned are inclusive of `timeframe_start`. */ fun timeframeStart(timeframeStart: OffsetDateTime) = apply { this.timeframeStart = timeframeStart } /** * Controls whether Orb returns cumulative costs since the start of the billing period, or * incremental day-by-day costs. If your customer has minimums or discounts, it's strongly * recommended that you use the default cumulative behavior. */ fun viewMode(viewMode: ViewMode) = apply { this.viewMode = viewMode } fun additionalQueryParams(additionalQueryParams: Map<String, List<String>>) = apply { this.additionalQueryParams.clear() putAllQueryParams(additionalQueryParams) } fun putQueryParam(name: String, value: String) = apply { this.additionalQueryParams.getOrPut(name) { mutableListOf() }.add(value) } fun putQueryParams(name: String, values: Iterable<String>) = apply { this.additionalQueryParams.getOrPut(name) { mutableListOf() }.addAll(values) } fun putAllQueryParams(additionalQueryParams: Map<String, Iterable<String>>) = apply { additionalQueryParams.forEach(this::putQueryParams) } fun removeQueryParam(name: String) = apply { this.additionalQueryParams.put(name, mutableListOf()) } fun additionalHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply { this.additionalHeaders.clear() putAllHeaders(additionalHeaders) } fun putHeader(name: String, value: String) = apply { this.additionalHeaders.getOrPut(name) { mutableListOf() }.add(value) } fun putHeaders(name: String, values: Iterable<String>) = apply { this.additionalHeaders.getOrPut(name) { mutableListOf() }.addAll(values) } fun putAllHeaders(additionalHeaders: Map<String, Iterable<String>>) = apply { additionalHeaders.forEach(this::putHeaders) } fun removeHeader(name: String) = apply { this.additionalHeaders.put(name, mutableListOf()) } fun additionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply { this.additionalBodyProperties.clear() this.additionalBodyProperties.putAll(additionalBodyProperties) } fun putAdditionalBodyProperty(key: String, value: JsonValue) = apply { this.additionalBodyProperties.put(key, value) } fun putAllAdditionalBodyProperties(additionalBodyProperties: Map<String, JsonValue>) = apply { this.additionalBodyProperties.putAll(additionalBodyProperties) } fun build(): SubscriptionFetchCostsParams = SubscriptionFetchCostsParams( checkNotNull(subscriptionId) { "`subscriptionId` is required but was not set" }, timeframeEnd, timeframeStart, viewMode, additionalQueryParams.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), additionalHeaders.mapValues { it.value.toUnmodifiable() }.toUnmodifiable(), additionalBodyProperties.toUnmodifiable(), ) } class ViewMode @JsonCreator private constructor( private val value: JsonField<String>, ) : Enum { @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value override fun equals(other: Any?): Boolean { if (this === other) { return true } return other is ViewMode && this.value == other.value } override fun hashCode() = value.hashCode() override fun toString() = value.toString() companion object { val PERIODIC = ViewMode(JsonField.of("periodic")) val CUMULATIVE = ViewMode(JsonField.of("cumulative")) fun of(value: String) = ViewMode(JsonField.of(value)) } enum class Known { PERIODIC, CUMULATIVE, } enum class Value { PERIODIC, CUMULATIVE, _UNKNOWN, } fun value(): Value = when (this) { PERIODIC -> Value.PERIODIC CUMULATIVE -> Value.CUMULATIVE else -> Value._UNKNOWN } fun known(): Known = when (this) { PERIODIC -> Known.PERIODIC CUMULATIVE -> Known.CUMULATIVE else -> throw OrbInvalidDataException("Unknown ViewMode: $value") } fun asString(): String = _value().asStringOrThrow() } }
2
Kotlin
0
0
5fa11559694c0162e2794c1cb71618027195ff9b
9,762
orb-kotlin
Apache License 2.0
src/main/kotlin/org/radarbase/redcap/config/ManagementPortalConfig.kt
RADAR-base
101,426,351
false
{"Kotlin": 113490, "Python": 5049, "Dockerfile": 1408}
package org.radarbase.redcap.config import com.fasterxml.jackson.annotation.JsonCreator import com.fasterxml.jackson.annotation.JsonProperty import java.net.URL data class ManagementPortalConfig /** * Constructor. * @param oauthClientId [String] representing OAuth2 client identifier * @param oauthClientSecret [String] representing OAuth2 client identifier * @param managementPortalUrl [URL] pointing a Management Portal instane * @param tokenEndpoint [String] representing Management Portal web root to renew tokens * @param projectEndpoint [String] representing Management Portal web root to access * project data * @param subjectEndpoint [String] representing Management Portal web root to manage * subject **/ @JsonCreator constructor( @JsonProperty("oauth_client_id") val oauthClientId: String, @JsonProperty("oauth_client_secret") val oauthClientSecret: String, @JsonProperty("base_url") val managementPortalUrl: URL, @JsonProperty("token_endpoint") val tokenEndpoint: String = "oauth/token", @JsonProperty("project_endpoint") val projectEndpoint: String = "api/projects/", @JsonProperty("subject_endpoint") val subjectEndpoint: String = "api/subjects/" )
14
Kotlin
1
1
0f3a7fa983c4e675c5fa4b8c6141e678e6838e4b
1,198
RADAR-RedcapIntegration
Apache License 2.0
app/src/main/java/com/vishalgaur/shoppingapp/data/Result.kt
i-vishi
358,205,394
false
null
package com.pj109.xkorey.share.result /** * A generic class that holds a value with its loading status. * @param <T> */ sealed class Result<out R> { data class Success<out T>(val data: T) : Result<T>() data class Error(val exception: Exception) : Result<Nothing>() object Loading : Result<Nothing>() override fun toString(): String { return when (this) { is Success<*> -> "Success[data=$data]" is Error -> "Error[exception=$exception]" Loading -> "Loading" } } } /** * `true` if [Result] is of type [Success] & holds non-null [Success.data]. */ val Result<*>.succeeded get() = this is Result.Success && data != null
9
null
6
97
1768ebf52bb9ae27fe7eca9e92b999cbcd7113f6
702
shopping-android-app
MIT License
ui-lib/src/main/java/co/electriccoin/zcash/ui/screen/contact/viewmodel/UpdateContactViewModel.kt
Electric-Coin-Company
390,808,594
false
{"Kotlin": 1834553}
package co.electriccoin.zcash.ui.screen.contact.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import cash.z.ecc.sdk.ANDROID_STATE_FLOW_TIMEOUT import co.electriccoin.zcash.ui.R import co.electriccoin.zcash.ui.common.model.AddressBookContact import co.electriccoin.zcash.ui.common.usecase.DeleteContactUseCase import co.electriccoin.zcash.ui.common.usecase.GetContactUseCase import co.electriccoin.zcash.ui.common.usecase.UpdateContactUseCase import co.electriccoin.zcash.ui.common.usecase.ValidateContactAddressUseCase import co.electriccoin.zcash.ui.common.usecase.ValidateContactNameUseCase import co.electriccoin.zcash.ui.design.component.ButtonState import co.electriccoin.zcash.ui.design.component.TextFieldState import co.electriccoin.zcash.ui.design.util.stringRes import co.electriccoin.zcash.ui.screen.contact.model.ContactState import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.WhileSubscribed import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.mapLatest import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch class UpdateContactViewModel( private val contactId: String, private val validateContactAddress: ValidateContactAddressUseCase, private val validateContactName: ValidateContactNameUseCase, private val updateContact: UpdateContactUseCase, private val deleteContact: DeleteContactUseCase, private val getContact: GetContactUseCase ) : ViewModel() { private var contact: AddressBookContact? = null private val contactAddress = MutableStateFlow("") private val contactName = MutableStateFlow("") private val isUpdatingContact = MutableStateFlow(false) private val isDeletingContact = MutableStateFlow(false) private val isLoadingContact = MutableStateFlow(true) @OptIn(ExperimentalCoroutinesApi::class) private val contactAddressState = contactAddress.mapLatest { address -> TextFieldState( value = stringRes(address), error = if (address.isEmpty()) { null } else { when (validateContactAddress(address = address, exclude = contact)) { ValidateContactAddressUseCase.Result.Invalid -> stringRes("") ValidateContactAddressUseCase.Result.NotUnique -> stringRes(R.string.contact_address_error_not_unique) ValidateContactAddressUseCase.Result.Valid -> null } }, onValueChange = { newValue -> contactAddress.update { newValue } } ) } @OptIn(ExperimentalCoroutinesApi::class) private val contactNameState = contactName.mapLatest { name -> TextFieldState( value = stringRes(name), error = if (name.isEmpty()) { null } else { when (validateContactName(name = name, exclude = contact)) { ValidateContactNameUseCase.Result.TooLong -> stringRes(R.string.contact_name_error_too_long) ValidateContactNameUseCase.Result.NotUnique -> stringRes(R.string.contact_name_error_not_unique) ValidateContactNameUseCase.Result.Valid -> null } }, onValueChange = { newValue -> contactName.update { newValue } } ) } private val updateButtonState = combine(contactAddressState, contactNameState, isUpdatingContact) { address, name, isUpdatingContact -> ButtonState( text = stringRes(R.string.update_contact_primary_btn), isEnabled = address.error == null && name.error == null && contactAddress.value.isNotEmpty() && contactName.value.isNotEmpty() && (contactName.value.trim() != contact?.name || contactAddress.value.trim() != contact?.address), onClick = ::onUpdateButtonClick, isLoading = isUpdatingContact ) } private val deleteButtonState = isDeletingContact.map { isDeletingContact -> ButtonState( text = stringRes(R.string.update_contact_secondary_btn), onClick = ::onDeleteButtonClick, isLoading = isDeletingContact ) } val state = combine( contactAddressState, contactNameState, updateButtonState, deleteButtonState, isLoadingContact ) { address, name, saveButton, deleteButton, isLoadingContact -> ContactState( title = stringRes(R.string.update_contact_title), isLoading = isLoadingContact, walletAddress = address, contactName = name, negativeButton = deleteButton, positiveButton = saveButton, onBack = ::onBack, ) }.stateIn( scope = viewModelScope, started = SharingStarted.WhileSubscribed(ANDROID_STATE_FLOW_TIMEOUT), initialValue = null ) val navigationCommand = MutableSharedFlow<String>() val backNavigationCommand = MutableSharedFlow<Unit>() init { viewModelScope.launch { getContact(contactId).let { contact -> contactAddress.update { contact?.address.orEmpty() } contactName.update { contact?.name.orEmpty() } [email protected] = contact } isLoadingContact.update { false } } } private fun onBack() = viewModelScope.launch { backNavigationCommand.emit(Unit) } private fun onUpdateButtonClick() = viewModelScope.launch { contact?.let { isUpdatingContact.update { true } updateContact(contact = it, name = contactName.value, address = contactAddress.value) backNavigationCommand.emit(Unit) isUpdatingContact.update { false } } } private fun onDeleteButtonClick() = viewModelScope.launch { contact?.let { isDeletingContact.update { true } deleteContact(it) backNavigationCommand.emit(Unit) isDeletingContact.update { false } } } }
172
Kotlin
15
25
359d4a5eea03dfb3c1ffbc5df1baca1c6f7917a7
7,084
zashi-android
MIT License
aggregator/src/main/kotlin/nl/tudelft/hyperion/aggregator/workers/Expiry.kt
SERG-Delft
254,399,628
false
{"Gradle Kotlin DSL": 19, "Shell": 5, "Text": 2, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Markdown": 31, "INI": 1, "Ruby": 5, "AsciiDoc": 1, "YAML": 42, "Dockerfile": 15, "Kotlin": 153, "SQL": 1, "Dotenv": 2, "XML": 4, "Java": 5, "SVG": 2}
package nl.tudelft.hyperion.aggregator.workers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import nl.tudelft.hyperion.aggregator.Configuration import nl.tudelft.hyperion.aggregator.database.AggregationEntries import org.jetbrains.exposed.sql.transactions.transaction /** * Starts a new expiry worker that runs in the background and automatically removes * database entries that are older than the values specified in the configuration. */ @Suppress("TooGenericExceptionCaught") fun startExpiryWorker(configuration: Configuration) = GlobalScope.launch { val logger = mu.KotlinLogging.logger {} logger.debug { "Starting expiry worker..." } while (isActive) { logger.debug { "Running deletion..." } try { // Delete rows that are too old. transaction { // Cannot represent the interval syntax using exposed, unfortunately. // This is not vulnerable to sql injection as all the properties are hardcoded. exec( "DELETE FROM ${AggregationEntries.tableName} WHERE ${AggregationEntries.timestamp.name} <" + " now() - interval '${configuration.aggregationTtl} seconds'" ) } } catch (ex: Exception) { // Catch error, but keep loop running. logger.error(ex) { "Failed to delete expired rows." } } logger.debug { "Deleted expired rows." } // Wait for our granularity to process. If the granularity stayed constant, // we will have a new row to remove from the database. delay(configuration.granularity * 1000L) } // Never returns. }
0
Kotlin
1
13
a010d1b6e59592231a2ed29a6d11af38644f2834
1,777
hyperion
Apache License 2.0
src/main/kotlin/io/github/juuxel/polyester/item/PolyesterBaseItem.kt
Juuxel
178,036,245
false
null
package io.github.juuxel.polyester.item import net.minecraft.client.item.TooltipContext import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.text.Text import net.minecraft.world.World open class PolyesterBaseItem(override val name: String, settings: Settings) : Item(settings), PolyesterItem { override fun appendTooltip( stack: ItemStack?, world: World?, list: MutableList<Text>, context: TooltipContext? ) { super.appendTooltip(stack, world, list, context) PolyesterItem.appendTooltipToList(list, this) } }
1
null
1
1
21bfa057cd004e3037df2b99f3de8bfc5ee7316a
610
Polyester
MIT License
app/src/main/java/com/omerguzel/pokedex/data/remote/network/response/Other.kt
omerrguzel
720,436,407
false
{"Kotlin": 84274}
package com.omerguzel.pokedex.data.remote.network.response import com.google.gson.annotations.SerializedName data class Other( @SerializedName("dream_world") val dreamWorld: DreamWorld? = null, val home: Home? = null, @SerializedName("official-artwork") val officialArtwork: OfficialArtwork? = null )
0
Kotlin
0
0
e0a0c9061531a18a6159e1394a7638b6ccbbab95
323
Pokedex
The Unlicense
sw-ui/src/test/kotlin/org/luxons/sevenwonders/ui/utils/CoroutineUtilsTest.kt
joffrey-bion
75,569,445
false
null
package org.luxons.sevenwonders.ui.utils import kotlinx.coroutines.delay import org.luxons.sevenwonders.ui.test.runSuspendingTest import kotlin.test.Test import kotlin.test.assertEquals class CoroutineUtilsTest { @Test fun awaitFirstTest() = runSuspendingTest { val s = awaitFirst( { delay(100); "1" }, { delay(200); "2" }, ) assertEquals("1", s) val s2 = awaitFirst( { delay(150); "1" }, { delay(50); "2" }, ) assertEquals("2", s2) } }
35
Kotlin
6
35
d09c3e7128fbb8b9f1500153b12ef657dcb76694
548
seven-wonders
MIT License
app/src/main/java/com/kcteam/features/dashboard/presentation/RouteActivityDashboardAdapter.kt
DebashisINT
558,234,039
false
null
package com.breezepowell.features.dashboard.presentation import android.content.Context import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.breezepowell.R import com.breezepowell.features.location.UserLocationDataEntity import kotlinx.android.synthetic.main.inflate_route_activity_item.view.* /** * Created by Kinsuk on 01-11-2017. */ class RouteActivityDashboardAdapter(context: Context, userLocationDataEntity: List<UserLocationDataEntity>) : RecyclerView.Adapter<RouteActivityDashboardAdapter.MyViewHolder>() { private val layoutInflater: LayoutInflater private var context: Context var userLocationDataEntity: List<UserLocationDataEntity> = userLocationDataEntity init { layoutInflater = LayoutInflater.from(context) this.context = context } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bindItems(context, userLocationDataEntity) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val v = layoutInflater.inflate(R.layout.inflate_route_activity_item, parent, false) return MyViewHolder(v) } override fun getItemCount(): Int { return userLocationDataEntity.size } class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bindItems(context: Context, userLocationDataEntity: List<UserLocationDataEntity>) { if (adapterPosition == 0) { itemView.dot_IV.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.green_round)) } else if (adapterPosition == userLocationDataEntity.size - 1) { itemView.dot_IV.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.red_round)) } else if (adapterPosition % 2 == 0) { itemView.dot_IV.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.navy_blue_round)) } else { itemView.dot_IV.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.yellow_round)) } itemView.shop_tv.setText(userLocationDataEntity.get(adapterPosition).shops) // if (userLocationDataEntity.get(adapterPosition).shops == "0" || userLocationDataEntity.get(adapterPosition).shops == "1") { // itemView.shop_visited_tv.setText(context.getString(R.string.shop_visited)) // } else { // itemView.shop_visited_tv.setText(context.getString(R.string.no_of_shop_visited)) // } itemView.location_name_tv.setText(userLocationDataEntity.get(adapterPosition).locationName) itemView.distance_tv.setText(userLocationDataEntity.get(adapterPosition).distance) itemView.time_log.setText(userLocationDataEntity.get(adapterPosition).time) itemView.meridiem.setText(userLocationDataEntity.get(adapterPosition).meridiem) // itemView.shop_tv.setText(adapterPosition.toString()) // itemView.myshop_name_TV.setText(context.getString(R.string.name_colon)+" "+context.getString(R.string.capital_electronics)) // itemView.myshop_address_TV.setText(context.getString(R.string.breezepowell_address)) // itemView.map_IV.findViewById<ImageView>(R.id.map_IV).setOnClickListener(View.OnClickListener { // listener.mapClick() // }) // itemView.order_IV.findViewById<ImageView>(R.id.order_IV).setOnClickListener(View.OnClickListener { // listener.orderClick() // }) // itemView.location_IV.findViewById<ImageView>(R.id.location_IV).setOnClickListener(View.OnClickListener { // listener.callClick() // }) // // itemView.setOnClickListener { // listener.OnNearByShopsListClick(adapterPosition) // } } } open fun update(userLocationDataEntity: List<UserLocationDataEntity>) { this.userLocationDataEntity = userLocationDataEntity } }
0
null
1
1
e6114824d91cba2e70623631db7cbd9b4d9690ed
4,136
NationalPlastic
Apache License 2.0
app/src/main/java/com/douglasqueiroz/thewallet/feature/assets/AssetsScreen.kt
douglas-queiroz
643,561,645
false
null
package com.douglasqueiroz.thewallet.feature.assets import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.douglasqueiroz.thewallet.ui.components.TheWalletBottomBar import com.douglasqueiroz.thewallet.ui.components.BottomBarItem @OptIn(ExperimentalMaterial3Api::class) @Composable fun AssetsScreen( modifier: Modifier = Modifier, onBottomBarClick: (BottomBarItem) -> Unit = { } ) { Scaffold( bottomBar = { TheWalletBottomBar(onBottomBarClick = onBottomBarClick) } ) { Text( modifier = modifier.padding(it), text = "Assets" ) } } @Preview @Composable fun AssetsScreenPreview() { AssetsScreen() }
0
Kotlin
0
0
b32bc30c705696b7c5cbe8d1d8b2f348b3d5ff06
967
TheWallet
Apache License 2.0
app/src/commonMain/kotlin/datalayer/functions/simulateLiquidation.kt
luca992
716,489,959
false
{"Kotlin": 46440, "HTML": 359, "CSS": 108}
package datalayer.functions import Repository import com.ionspin.kotlin.bignum.decimal.BigDecimal import com.ionspin.kotlin.bignum.decimal.RoundingMode import com.ionspin.kotlin.bignum.decimal.toBigDecimal import com.ionspin.kotlin.bignum.integer.BigInteger import com.ionspin.kotlin.bignum.integer.toBigInteger import io.eqoty.secret.std.contract.msg.Snip20Msgs import io.eqoty.secretk.types.MsgExecuteContract import io.eqoty.secretk.types.TxOptions import io.eqoty.secretk.types.response.TxResponseData import io.ktor.util.* import json import kotlinx.serialization.encodeToString import logger import msg.market.ExecuteMsg import msg.market.LendSimulatedLiquidation import msg.market.QueryMsg import types.LendMarketBorrower import types.LendOverseerMarketAndUnderlyingAsset import types.Loan suspend fun Repository.getExchangeRate( market: LendOverseerMarketAndUnderlyingAsset, blockHeight: BigInteger ): BigDecimal { return json.decodeFromString<String>( client.queryContractSmart( contractAddress = market.contract.address, contractCodeHash = market.contract.codeHash, queryMsg = json.encodeToString(QueryMsg(exchangeRate = QueryMsg.ExchangeRate(blockHeight.ulongValue()))) ) ).toBigDecimal() } fun BigDecimal.toFixed(decimalPlaces: Long, roundingMode: RoundingMode = RoundingMode.FLOOR): String { return roundToDigitPositionAfterDecimalPoint(decimalPlaces, roundingMode) .toBigInteger() .toString() } suspend fun Repository.simulateLiquidation( market: LendOverseerMarketAndUnderlyingAsset, lendMarketBorrower: LendMarketBorrower, blockHeight: BigInteger, payable: BigDecimal, ): LendSimulatedLiquidation { return json.decodeFromString( client.queryContractSmart( contractAddress = market.contract.address, contractCodeHash = market.contract.codeHash, queryMsg = json.encodeToString( QueryMsg( simulateLiquidation = QueryMsg.SimulateLiquidation( blockHeight.ulongValue(), borrower = lendMarketBorrower.id, collateral = market.contract.address, amount = payable.toFixed(0) ) ) ) ) ) } suspend fun Repository.liquidate( loan: Loan, ): TxResponseData { val callbackB64 = json.encodeToString( ExecuteMsg( liquidate = ExecuteMsg.Liquidate( borrower = loan.candidate.id, collateral = loan.market.contract.address ) ) ).encodeBase64() val liquidateMsg = MsgExecuteContract( sender = senderAddress, contractAddress = loan.market.underlying.address, codeHash = loan.market.underlying.codeHash, msg = json.encodeToString( Snip20Msgs.Execute( send = Snip20Msgs.Execute.Send( amount = loan.candidate.payable.toFixed(0).toBigInteger(), recipient = loan.market.contract.address, msg = callbackB64 ) ) ), ) return client.execute(listOf(liquidateMsg), txOptions = TxOptions(gasLimit = config.gasCosts.liquidate)) }
0
Kotlin
0
1
ac2c3b226f059f250190bff932891b4e0667fbcb
3,310
sienna-lend-liquidator
MIT License
app/src/main/java/com/tomorrowit/budgetgamer/presentation/activities/AuthActivity.kt
2Morrow-IT-Solutions
848,266,910
false
{"Kotlin": 429313}
package com.tomorrowit.budgetgamer.presentation.activities import android.os.Bundle import com.tomorrowit.budgetgamer.common.config.extensions.finishAnimation import com.tomorrowit.budgetgamer.databinding.ActivityAuthBinding import com.tomorrowit.budgetgamer.domain.repo.LoggerRepo import com.tomorrowit.budgetgamer.presentation.base.BaseSlideActivity import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class AuthActivity : BaseSlideActivity() { private lateinit var binding: ActivityAuthBinding @Inject lateinit var loggerRepo: LoggerRepo override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAuthBinding.inflate(layoutInflater) setContentView(binding.root) } override fun finish() { super.finish() finishAnimation() } }
0
Kotlin
2
5
edcaff45925e39c15fa3ff8cb054bf06904c3cdf
888
budget-gamer-android
MIT License
tang-framework/src/main/kotlin/com/tang/framework/utils/AuthenticationUtils.kt
tangllty
585,187,319
false
{"Java": 407120, "Kotlin": 180218, "Shell": 2468, "Dockerfile": 354, "Batchfile": 183}
package com.tang.framework.utils import org.springframework.security.authentication.AbstractAuthenticationToken import org.springframework.security.core.GrantedAuthority import com.tang.commons.enumeration.LoginType import com.tang.framework.security.authentication.email.EmailAuthenticationToken import com.tang.framework.security.authentication.github.GitHubAuthenticationToken import com.tang.framework.security.authentication.username.UsernameAuthenticationToken /** * @author Tang */ object AuthenticationUtils { @JvmStatic fun newInstance(loginType: String, principal: Any, authorities: Collection<GrantedAuthority>): AbstractAuthenticationToken { return when (LoginType.getLoginType(loginType)) { LoginType.USERNAME -> UsernameAuthenticationToken(principal, authorities) LoginType.EMAIL -> EmailAuthenticationToken(principal, authorities) LoginType.GITHUB -> GitHubAuthenticationToken(principal) else -> throw IllegalArgumentException("Unexpected login type: $loginType") } } }
0
Java
4
13
6c8f7eb3903a71c111ef70f27cd20ef509037f84
1,068
tang-boot
MIT License
generator/web/src/main/kotlin/me/kcra/takenaka/generator/web/WebConfiguration.kt
zlataovce
596,960,001
false
null
/* * This file is part of takenaka, licensed under the Apache License, Version 2.0 (the "License"). * * Copyright (c) 2023-2024 <NAME> * * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.kcra.takenaka.generator.web import me.kcra.takenaka.core.mapping.adapter.replaceCraftBukkitNMSVersion import me.kcra.takenaka.generator.web.transformers.Transformer /** * Configuration for [WebGenerator]. * * @property welcomeMessage a welcoming message that is displayed on the main page, null if it should not be added, supports arbitrary HTML markup * @property themeColor the metadata theme color, defaults to `#21ff21` * @property emitMetaTags whether HTML metadata tags (per [me.kcra.takenaka.generator.web.components.metadataComponent]) should be added to pages * @property emitPseudoElements whether pseudo-elements should be used on the site (badges - for decreasing the output size) * @property transformers a list of transformers that transform the output * @property namespaceFriendlinessIndex an ordered list of namespaces that will be considered when selecting a "friendly" name * @property namespaces a map of namespaces and their descriptions, unspecified namespaces will not be shown * @property index a resolver for foreign class references * @property craftBukkitVersionReplaceCandidates namespaces that should have [replaceCraftBukkitNMSVersion] applied (most likely Spigot mappings or a flavor of them) * @author <NAME> */ data class WebConfiguration( val welcomeMessage: String? = null, val themeColor: String = "#21ff21", val emitMetaTags: Boolean = true, val emitPseudoElements: Boolean = true, val transformers: List<Transformer> = emptyList(), val namespaceFriendlinessIndex: List<String> = emptyList(), val namespaces: Map<String, NamespaceDescription> = emptyMap(), val index: ClassSearchIndex = emptyClassSearchIndex(), val craftBukkitVersionReplaceCandidates: List<String> = emptyList() ) /** * A builder for [WebConfiguration]. * * @author <NAME> */ class WebConfigurationBuilder { /** * A welcoming message that is displayed on the main page, null if it should not be added, supports arbitrary HTML markup. */ var welcomeMessage: String? = null /** * The metadata theme color. */ var themeColor = "#21ff21" /** * Whether HTML metadata tags (per [me.kcra.takenaka.generator.web.components.metadataComponent]) should be added to pages. */ var emitMetaTags = true /** * Whether pseudo-elements should be used on the site (badges - for decreasing the output size). */ var emitPseudoElements = true /** * Transformers that transform the output. */ var transformers = mutableListOf<Transformer>() /** * An ordered list of namespaces that will be considered when selecting a "friendly" name. */ var namespaceFriendlinessIndex = mutableListOf<String>() /** * A map of namespaces and their descriptions, unspecified namespaces will not be shown on the documentation. */ var namespaces = mutableMapOf<String, NamespaceDescription>() /** * A resolver for foreign class references, defaults to a no-op. */ var index: ClassSearchIndex = emptyClassSearchIndex() /** * Namespaces that should have [replaceCraftBukkitNMSVersion] applied (most likely Spigot mappings or a flavor of them). */ var craftBukkitVersionReplaceCandidates = mutableListOf<String>() /** * Namespaces that should be used for computing history, empty if namespaces from [namespaceFriendlinessIndex] should be considered (excluding the obfuscated one). */ var historyNamespaces = mutableListOf<String>() /** * Namespace that contains ancestry node indices, null if ancestry should be recomputed from scratch. */ var historyIndexNamespace: String? = null /** * Sets [welcomeMessage]. * * @param value the value */ fun welcomeMessage(value: String) { welcomeMessage = value } /** * Sets [themeColor]. * * @param value the value */ fun themeColor(value: String) { themeColor = value } /** * Sets [emitMetaTags]. * * @param value the value */ fun emitMetaTags(value: Boolean) { emitMetaTags = value } /** * Sets [emitPseudoElements]. * * @param value the value */ fun emitPseudoElements(value: Boolean) { emitPseudoElements = value } /** * Appends transformers. * * @param items the transformers */ fun transformer(vararg items: Transformer) { transformers += items } /** * Appends transformers. * * @param items the transformers */ fun transformer(items: List<Transformer>) { transformers += items } /** * Appends friendly namespaces to the index. * * @param items the friendly namespaces */ fun friendlyNamespaces(vararg items: String) { namespaceFriendlinessIndex += items } /** * Appends friendly namespaces to the index. * * @param items the friendly namespaces */ fun friendlyNamespaces(items: List<String>) { namespaceFriendlinessIndex += items } /** * Appends a namespace. * * @param name the original name, as in the mapping tree * @param friendlyName the friendly name, this will be shown in the documentation * @param color the CSS-compatible color, this will be shown in the documentation * @param license the license reference */ fun namespace(name: String, friendlyName: String, color: String, license: LicenseReference? = null) { namespaces += name to NamespaceDescription(friendlyName, color, license) } /** * Appends a namespace. * * @param name the original name, as in the mapping tree * @param friendlyName the friendly name, this will be shown in the documentation * @param color the CSS-compatible color, this will be shown in the documentation * @param licenseContentKey the license content metadata key in the mapping tree * @param licenseSourceKey the license source metadata key in the mapping tree */ fun namespace(name: String, friendlyName: String, color: String, licenseContentKey: String, licenseSourceKey: String = "${licenseContentKey}_source") { namespaces += name to NamespaceDescription(friendlyName, color, licenseContentKey, licenseSourceKey) } /** * Replaces the class search index. * * @param items the indexers */ fun index(vararg items: ClassSearchIndex) { index(items.toList()) } /** * Replaces the class search index. * * @param items the indexers */ fun index(items: List<ClassSearchIndex>) { if (items.isNotEmpty()) { index = if (items.size == 1) items[0] else CompositeClassSearchIndex(items) } } /** * Appends namespaces to [craftBukkitVersionReplaceCandidates]. * * @param namespaces the namespaces */ fun replaceCraftBukkitVersions(vararg namespaces: String) { craftBukkitVersionReplaceCandidates += namespaces } /** * Builds a mapping configuration out of this builder. * * @return the configuration */ fun toWebConfig() = WebConfiguration( welcomeMessage, themeColor, emitMetaTags, emitPseudoElements, transformers, namespaceFriendlinessIndex, namespaces, index, craftBukkitVersionReplaceCandidates ) } /** * Builds a [WebGenerator] configuration with a builder. * * @param block the builder action * @return the configuration */ inline fun buildWebConfig(block: WebConfigurationBuilder.() -> Unit): WebConfiguration = WebConfigurationBuilder().apply(block).toWebConfig()
6
null
3
8
bf716f44463c88d9079e2a3296ca07593d8da692
8,418
takenaka
Apache License 2.0
src/main/kotlin/org/rust/cargo/runconfig/buildtool/CargoBuildAdapter.kt
Kobzol
174,706,351
false
null
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.buildtool import com.intellij.build.BuildContentDescriptor import com.intellij.build.BuildProgressListener import com.intellij.build.DefaultBuildDescriptor import com.intellij.build.events.impl.* import com.intellij.build.output.BuildOutputInstantReaderImpl import com.intellij.execution.ExecutorRegistry import com.intellij.execution.actions.StopProcessAction import com.intellij.execution.impl.ExecutionManagerImpl import com.intellij.execution.process.* import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionUtil import com.intellij.icons.AllIcons import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.DumbService import com.intellij.openapi.util.Key import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.util.text.StringUtil.convertLineSeparators import com.intellij.openapi.vfs.VfsUtil import org.rust.cargo.CargoConstants import org.rust.cargo.runconfig.createFilters import javax.swing.JComponent @Suppress("UnstableApiUsage") class CargoBuildAdapter( private val context: CargoBuildContext, private val buildProgressListener: BuildProgressListener ) : ProcessAdapter() { private val instantReader = BuildOutputInstantReaderImpl( context.buildId, context.buildId, buildProgressListener, listOf(RsBuildEventsConverter(context)) ) init { val processHandler = checkNotNull(context.processHandler) { "Process handler can't be null" } context.environment.notifyProcessStarted(processHandler) val buildContentDescriptor = BuildContentDescriptor(null, null, object : JComponent() {}, "Build") val activateToolWindow = context.environment.isActivateToolWindowBeforeRun buildContentDescriptor.isActivateToolWindowWhenAdded = activateToolWindow buildContentDescriptor.isActivateToolWindowWhenFailed = activateToolWindow val descriptor = DefaultBuildDescriptor(context.buildId, "Run Cargo command", context.workingDirectory.toString(), context.started) .withContentDescriptor { buildContentDescriptor } .withRestartAction(createRerunAction(processHandler, context.environment)) .withRestartAction(createStopAction(processHandler)) .apply { createFilters(context.cargoProject).forEach { withExecutionFilter(it) } } val buildStarted = StartBuildEventImpl(descriptor, "${context.taskName} running...") buildProgressListener.onEvent(context.buildId, buildStarted) } override fun processTerminated(event: ProcessEvent) { instantReader.closeAndGetFuture().whenComplete { _, error -> val isSuccess = event.exitCode == 0 && context.errors.get() == 0 val isCanceled = context.indicator?.isCanceled ?: false val (status, result) = when { isCanceled -> "canceled" to SkippedResultImpl() isSuccess -> "successful" to SuccessResultImpl() else -> "failed" to FailureResultImpl(error) } val buildFinished = FinishBuildEventImpl( context.buildId, null, System.currentTimeMillis(), "${context.taskName} $status", result ) buildProgressListener.onEvent(context.buildId, buildFinished) context.finished(isSuccess) context.environment.notifyProcessTerminated(event.processHandler, event.exitCode) val targetPath = context.workingDirectory.resolve(CargoConstants.ProjectLayout.target) val targetDir = VfsUtil.findFile(targetPath, true) ?: return@whenComplete VfsUtil.markDirtyAndRefresh(true, true, true, targetDir) } } override fun processWillTerminate(event: ProcessEvent, willBeDestroyed: Boolean) { context.environment.notifyProcessTerminating(event.processHandler) } override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) { // Progress messages end with '\r' instead of '\n'. We want to replace '\r' with '\n' // so that `instantReader` sends progress messages to parsers separately from other messages. val text = convertLineSeparators(event.text) instantReader.append(text) } companion object { private fun createStopAction(processHandler: ProcessHandler): StopProcessAction = StopProcessAction("Stop", "Stop", processHandler) private fun createRerunAction(processHandler: ProcessHandler, environment: ExecutionEnvironment): RestartProcessAction = RestartProcessAction(processHandler, environment) private class RestartProcessAction( private val processHandler: ProcessHandler, private val environment: ExecutionEnvironment ) : DumbAwareAction() { private val isEnabled: Boolean get() { val project = environment.project val settings = environment.runnerAndConfigurationSettings return (!DumbService.isDumb(project) || settings == null || settings.type.isDumbAware) && !ExecutorRegistry.getInstance().isStarting(environment) && !processHandler.isProcessTerminating } override fun update(event: AnActionEvent) { val presentation = event.presentation presentation.text = "Rerun '${StringUtil.escapeMnemonics(environment.runProfile.name)}'" presentation.icon = if (processHandler.isProcessTerminated) AllIcons.Actions.Compile else AllIcons.Actions.Restart presentation.isEnabled = isEnabled } override fun actionPerformed(event: AnActionEvent) { ExecutionManagerImpl.stopProcess(processHandler) ExecutionUtil.restart(environment) } } } }
0
null
0
4
7d5f70bcf89dcc9c772efbeecf20fea7b0fb331e
6,225
intellij-rust
MIT License
AcornGame/src/com/acornui/graphics/LightingRenderer.kt
konsoletyper
105,533,124
false
null
package com.acornui.graphics import com.acornui.core.Disposable import com.acornui.core.di.Injector import com.acornui.core.di.Scoped import com.acornui.core.di.inject import com.acornui.core.graphics.BlendMode import com.acornui.core.graphics.Camera import com.acornui.core.graphics.CameraRo import com.acornui.core.graphics.Window import com.acornui.gl.core.* import com.acornui.graphics.lighting.* import com.acornui.math.Matrix4 import com.acornui.math.matrix4 /** * @author nbilyk */ class LightingRenderer( override val injector: Injector, val numPointLights: Int = 10, val numShadowPointLights: Int = 3, private val useModel: Boolean = true, // Final lighting shader private val lightingShader: ShaderProgram = LightingShader(injector.inject(Gl20), numPointLights, numShadowPointLights, useModel = useModel), private val directionalShadowMapShader: ShaderProgram = DirectionalShadowShader(injector.inject(Gl20), useModel = useModel), private val pointShadowMapShader: ShaderProgram = PointShadowShader(injector.inject(Gl20), useModel = useModel), directionalShadowsResolution: Int = 1024, pointShadowsResolution: Int = 1024 ) : Scoped, Disposable { private val gl = inject(Gl20) private val glState = inject(GlState) private val window = inject(Window) private val directionalShadowsFbo = Framebuffer(injector, directionalShadowsResolution, directionalShadowsResolution, hasDepth = true) val directionalLightCamera = DirectionalLightCamera() // Point lights private val pointShadowUniforms = PointShadowUniforms(pointShadowMapShader) private val pointLightShadowMaps: Array<CubeMap> private val pointShadowsFbo = Framebuffer(injector, pointShadowsResolution, pointShadowsResolution, hasDepth = true) private val pointLightCamera = PointLightCamera(window, pointShadowsResolution.toFloat()) private val lightingShaderUniforms = LightingShaderUniforms(lightingShader, numPointLights, numShadowPointLights) private val bias = matrix4 { scl(0.5f, 0.5f, 0.5f) translate(1f, 1f, 1f) } var allowShadows: Boolean = true //-------------------------------------------- // DrivableComponent methods //-------------------------------------------- init { // Point lights. pointShadowsFbo.begin() pointLightShadowMaps = Array(numShadowPointLights) { val sides = Array(6, { BufferTexture(gl, glState, pointShadowsResolution, pointShadowsResolution) }) val cubeMap = CubeMap(sides[0], sides[1], sides[2], sides[3], sides[4], sides[5], gl, glState) cubeMap.refInc() //gl.framebufferTexture2D(Gl20.FRAMEBUFFER, Gl20.COLOR_ATTACHMENT0, Gl20.TEXTURE_2D, cubeMap.textureHandle!!, 0) cubeMap } pointShadowsFbo.end() glState.shader = lightingShader gl.uniform2f(lightingShaderUniforms.u_resolutionInv, 1.0f / directionalShadowsResolution.toFloat(), 1.0f / directionalShadowsResolution.toFloat()) // Poisson disk gl.uniform2f(lightingShader.getRequiredUniformLocation("poissonDisk[0]"), -0.94201624f, -0.39906216f) gl.uniform2f(lightingShader.getRequiredUniformLocation("poissonDisk[1]"), 0.94558609f, -0.76890725f) gl.uniform2f(lightingShader.getRequiredUniformLocation("poissonDisk[2]"), -0.09418410f, -0.92938870f) gl.uniform2f(lightingShader.getRequiredUniformLocation("poissonDisk[3]"), 0.34495938f, 0.29387760f) val modelUniform = glState.shader!!.getUniformLocation(ShaderProgram.U_MODEL_TRANS) if (modelUniform != null) gl.uniformMatrix4fv(modelUniform, false, Matrix4()) gl.uniform2f(lightingShaderUniforms.u_resolutionInv, 1.0f / directionalShadowsResolution.toFloat(), 1.0f / directionalShadowsResolution.toFloat()) gl.uniform1i(lightingShaderUniforms.u_directionalShadowMap, DIRECTIONAL_SHADOW_UNIT) for (i in 0..numShadowPointLights - 1) { gl.uniform1i(lightingShaderUniforms.u_pointLightShadowMaps[i], POINT_SHADOW_UNIT + i) } glState.shader = glState.defaultShader } fun render(camera: CameraRo, ambientLight: AmbientLight, directionalLight: DirectionalLight, pointLights: List<PointLight>, renderOcclusion: () -> Unit, renderWorld: () -> Unit) { val currentW = window.width.toInt() val currentH = window.height.toInt() if (currentW == 0 || currentH == 0) return if (allowShadows) { renderOcclusion(camera, directionalLight, pointLights, renderOcclusion) glState.batch.flush(true) } prepareLightingShader(ambientLight, directionalLight, pointLights) renderWorld() glState.batch.flush(true) glState.shader = glState.defaultShader } //-------------------------------------------- // Render steps //-------------------------------------------- /** * Step 3. * Render the directional and point light shadows. */ private fun renderOcclusion(camera: CameraRo, directionalLight: DirectionalLight, pointLights: List<PointLight>, renderOcclusion: () -> Unit) { val previousBlendingEnabled = glState.blendingEnabled glState.batch.flush(true) glState.blendingEnabled = false gl.enable(Gl20.DEPTH_TEST) gl.depthFunc(Gl20.LESS) directionalLightShadows(camera, directionalLight, renderOcclusion) pointLightShadows(pointLights, renderOcclusion) // Reset the gl properties gl.disable(Gl20.DEPTH_TEST) glState.blendingEnabled = previousBlendingEnabled } private fun directionalLightShadows(camera: CameraRo, directionalLight: DirectionalLight, renderOcclusion: () -> Unit) { // Directional light shadows glState.shader = directionalShadowMapShader directionalShadowsFbo.begin() val oldClearColor = window.clearColor gl.clearColor(Color.BLUE) // Blue represents a z / w depth of 1.0. (The camera's far position) gl.clear(Gl20.COLOR_BUFFER_BIT or Gl20.DEPTH_BUFFER_BIT) if (directionalLight.color != Color.BLACK) { glState.batch.flush(true) if (directionalLightCamera.update(directionalLight.direction, camera)) { gl.uniformMatrix4fv(directionalShadowMapShader.getRequiredUniformLocation("u_directionalLightMvp"), false, directionalLightCamera.combined) } renderOcclusion() } directionalShadowsFbo.end() gl.clearColor(oldClearColor) } private fun pointLightShadows(pointLights: List<PointLight>, renderOcclusion: () -> Unit) { glState.shader = pointShadowMapShader val u_pointLightMvp = pointShadowMapShader.getRequiredUniformLocation("u_pointLightMvp") val oldClearColor = window.clearColor gl.clearColor(Color.BLUE) // Blue represents a z / w depth of 1.0. (The camera's far position) pointShadowsFbo.begin() for (i in 0..minOf(numShadowPointLights - 1, pointLights.lastIndex)) { val pointLight = pointLights[i] val pointLightShadowMap = pointLightShadowMaps[i] glState.setTexture(pointLightShadowMap, POINT_SHADOW_UNIT + i) gl.uniform3f(pointShadowUniforms.u_lightPosition, pointLight.position) gl.uniform1f(pointShadowUniforms.u_lightRadius, pointLight.radius) if (pointLight.radius > 1f) { for (j in 0..5) { gl.framebufferTexture2D(Gl20.FRAMEBUFFER, Gl20.COLOR_ATTACHMENT0, Gl20.TEXTURE_CUBE_MAP_POSITIVE_X + j, pointLightShadowMap.textureHandle!!, 0) gl.clear(Gl20.COLOR_BUFFER_BIT or Gl20.DEPTH_BUFFER_BIT) pointLightCamera.update(pointLight, j) gl.uniformMatrix4fv(u_pointLightMvp, false, pointLightCamera.camera.combined) renderOcclusion() glState.batch.flush(true) } } } pointShadowsFbo.end() gl.clearColor(oldClearColor) } private val u_directionalLightMvp = Matrix4() /** * Step 4. * Set the light shader's uniforms. */ private fun prepareLightingShader(ambientLight: AmbientLight, directionalLight: DirectionalLight, pointLights: List<PointLight>) { glState.shader = lightingShader pointLightProperties(pointLights) glState.setTexture(directionalShadowsFbo.texture, DIRECTIONAL_SHADOW_UNIT) gl.uniformMatrix4fv(lightingShaderUniforms.u_directionalLightMvp, false, u_directionalLightMvp.set(bias).mul(directionalLightCamera.combined)) gl.uniform1i(lightingShaderUniforms.u_shadowsEnabled, if (allowShadows) 1 else 0) gl.uniform4f(lightingShaderUniforms.u_ambient, ambientLight.color.r, ambientLight.color.g, ambientLight.color.b, ambientLight.color.a) gl.uniform4f(lightingShaderUniforms.u_directional, directionalLight.color.r, directionalLight.color.g, directionalLight.color.b, directionalLight.color.a) if (lightingShaderUniforms.u_directionalLightDir != null) { gl.uniform3f(lightingShaderUniforms.u_directionalLightDir, directionalLight.direction) } glState.blendMode(BlendMode.NORMAL, premultipliedAlpha = false) } private fun pointLightProperties(pointLights: List<PointLight>) { for (i in 0..numPointLights - 1) { val pointLight = if (i < pointLights.size) pointLights[i] else PointLight.EMPTY_POINT_LIGHT val pLU = lightingShaderUniforms.u_pointLights[i] gl.uniform1f(pLU.radius, pointLight.radius) gl.uniform3f(pLU.position, pointLight.position) gl.uniform3f(pLU.color, pointLight.color) } } override fun dispose() { // Dispose the point lights. for (i in 0..pointLightShadowMaps.lastIndex) { pointLightShadowMaps[i].refDec() } pointShadowsFbo.dispose() pointShadowMapShader.dispose() // Dispose the directional light. directionalShadowsFbo.dispose() directionalShadowMapShader.dispose() // Dispose the lighting shader. lightingShader.dispose() } companion object { private val DIRECTIONAL_SHADOW_UNIT = 1 private val POINT_SHADOW_UNIT = 2 } } private class LightingShaderUniforms( shader: ShaderProgram, private val numPointLights: Int, private val numShadowPointLights: Int) { val u_directionalLightMvp: GlUniformLocationRef val u_shadowsEnabled: GlUniformLocationRef val u_resolutionInv: GlUniformLocationRef val u_ambient: GlUniformLocationRef val u_directional: GlUniformLocationRef val u_directionalLightDir: GlUniformLocationRef? val u_directionalShadowMap: GlUniformLocationRef val u_pointLights: Array<PointLightUniforms> val u_pointLightShadowMaps: Array<GlUniformLocationRef> init { u_directionalLightMvp = shader.getRequiredUniformLocation("u_directionalLightMvp") u_shadowsEnabled = shader.getRequiredUniformLocation("u_shadowsEnabled") u_resolutionInv = shader.getRequiredUniformLocation("u_resolutionInv") u_ambient = shader.getRequiredUniformLocation("u_ambient") u_directional = shader.getRequiredUniformLocation("u_directional") u_directionalLightDir = shader.getUniformLocation("u_directionalLightDir") u_directionalShadowMap = shader.getRequiredUniformLocation("u_directionalShadowMap") u_pointLights = Array(numPointLights, { PointLightUniforms( shader.getRequiredUniformLocation("u_pointLights[$it].radius"), shader.getRequiredUniformLocation("u_pointLights[$it].position"), shader.getRequiredUniformLocation("u_pointLights[$it].color") ) }) u_pointLightShadowMaps = Array(numShadowPointLights, { shader.getRequiredUniformLocation("u_pointLightShadowMaps[$it]") }) } } private class PointLightUniforms( val radius: GlUniformLocationRef, val position: GlUniformLocationRef, val color: GlUniformLocationRef) private class PointShadowUniforms(shader: ShaderProgram) { val u_lightPosition: GlUniformLocationRef val u_lightRadius: GlUniformLocationRef init { this.u_lightPosition = shader.getRequiredUniformLocation("u_lightPosition") this.u_lightRadius = shader.getRequiredUniformLocation("u_lightRadius") } }
0
Kotlin
3
0
a84b559fe1d1cad01eb9223ad9af73b4d5fb5bc8
11,326
Acorn
Apache License 2.0