content
stringlengths
0
3.9M
path
stringlengths
4
242
contentHash
stringlengths
1
10
package redis.connection import io.ktor.network.sockets.Socket import redis.protocol.resp2.Resp2 import redis.protocol.resp2.decodeRdb import redis.response.Response public class MasterConnection(raw: Socket) : Connection(raw) { public val state: ClientConnectionState = ClientConnectionState(address = raw.remoteAddress) public val processed: Long get() = read.totalBytesRead public suspend fun receiveRdb(): ByteArray = decodeRdb(read) public suspend fun respond(response: Response) { response.writeTo(write) } } public suspend fun MasterConnection.receiveSimpleResponse(): String = receive<Resp2.String>().value private suspend fun MasterConnection.send(command: List<String>): String { sendCommand(command) return receiveSimpleResponse() } public suspend fun MasterConnection.ping() { val pong = send(listOf("ping")) println("received $pong") } public suspend fun MasterConnection.replConf( listeningPort: Int, capabilities: List<String>, ) { send(listOf("replconf", "listening-port", listeningPort.toString())) val caps = buildList { add("replconf") for (cap in capabilities) { add("capa") add(cap) } } send(caps) println("sent replconf") } public suspend fun MasterConnection.startPsync() { sendCommand(listOf("psync", "?", "-1")) println("Starting psync") }
codecrafters-redis-kotlin/src/main/kotlin/redis/connection/MasterConnection.kt
2262148852
package redis.connection import io.ktor.network.sockets.Socket import redis.response.Response public class ClientConnection( raw: Socket, public val state: ClientConnectionState = ClientConnectionState(address = raw.remoteAddress), ) : Connection(raw) { public suspend fun respond(response: Response) { response.writeTo(write) } public fun upgradeToReplica(): ReplicaConnection = ReplicaConnection(this) }
codecrafters-redis-kotlin/src/main/kotlin/redis/connection/ClientConnection.kt
211374252
package redis.protocol.resp2 public sealed class Resp2 { public data object Nil : Resp2() public data class String(val value: kotlin.String) : Resp2() { public companion object } public data class Number(val value: Int) : Resp2() { public companion object } public data class List(val values: kotlin.collections.List<Resp2>) : Resp2() { public companion object { public operator fun invoke(vararg values: Resp2): List = List(listOf(*values)) public operator fun invoke(values: kotlin.collections.List<kotlin.String>): List = List(values.map(Resp2::String)) } } public data class Error(val message: kotlin.String) : Resp2() public companion object }
codecrafters-redis-kotlin/src/main/kotlin/redis/protocol/resp2/Resp2.kt
2702763610
@file:Suppress("MagicNumber") package redis.protocol.resp2 import io.ktor.utils.io.ByteReadChannel import io.ktor.utils.io.core.readBytes public suspend fun Resp2.Companion.decode(source: ByteReadChannel): Resp2 { val type = Char(source.readByte().toInt()) return when (type) { '$', '+' -> Resp2.String.decode(source, simple = type == '+') '*' -> Resp2.List.decode(source) else -> error("Unknown type: $type") } } private suspend fun Resp2.List.Companion.decode(source: ByteReadChannel): Resp2.List { val items = source.readUTF8Line(10)?.toIntOrNull() ?: error("closed") val values = (0 until items).map { Resp2.decode(source) } return Resp2.List(values) } private suspend fun Resp2.String.Companion.decode(source: ByteReadChannel, simple: Boolean): Resp2.String = when (simple) { true -> { val s = source.readUTF8Line(1024) ?: error("closed") Resp2.String(s) } false -> { val length = source.readUTF8Line(18)?.toIntOrNull() ?: error("closed") val s = source.readPacket(length + 2).readText(0, length) Resp2.String(s) } } public suspend fun decodeRdb(source: ByteReadChannel): ByteArray { val type = source.readByte() check(type == '$'.code.toByte()) { "Not a RDB" } val size = source.readUTF8Line(18)?.toIntOrNull() ?: error("closed") return source.readPacket(size) .readBytes(size) }
codecrafters-redis-kotlin/src/main/kotlin/redis/protocol/resp2/decode.kt
2498588974
package redis.protocol.resp2 import io.ktor.utils.io.ByteWriteChannel import io.ktor.utils.io.writeStringUtf8 internal suspend fun Resp2.encode(sink: ByteWriteChannel) { when (this) { is Resp2.Error -> encode(sink) is Resp2.List -> encode(sink) Resp2.Nil -> Resp2.Nil.encode(sink) is Resp2.Number -> encode(sink) is Resp2.String -> encode(sink) } } internal suspend fun Resp2.String.encode(sink: ByteWriteChannel) { val length = value.length sink.writeStringUtf8("\$$length\r\n$value\r\n") } internal suspend fun Resp2.Number.encode(sink: ByteWriteChannel) { sink.writeStringUtf8(":$value\r\n") } @Suppress("UnusedReceiverParameter") internal suspend fun Resp2.Nil.encode(sink: ByteWriteChannel) { sink.writeStringUtf8("\$-1\r\n") } internal suspend fun Resp2.Error.encode(sink: ByteWriteChannel) { sink.writeStringUtf8("-$message\r\n") } internal suspend fun Resp2.List.encode(sink: ByteWriteChannel) { sink.writeStringUtf8("*${this.values.size}\r\n") for (value in values) { value.encode(sink) } }
codecrafters-redis-kotlin/src/main/kotlin/redis/protocol/resp2/encode.kt
3937924127
package redis.storage import kotlinx.datetime.Instant import redis.storage.values.RedisValue public interface Storage { public fun keys(): Sequence<String> public fun get(key: String): RedisValue? public fun set(key: String, value: RedisValue, expiration: Instant?) public fun getAux(key: String): String? public fun setAux(key: String, value: String) public fun getOrInsert(key: String, insert: () -> Pair<RedisValue, Instant?>): RedisValue public fun delete(key: String) public fun flush() { } }
codecrafters-redis-kotlin/src/main/kotlin/redis/storage/Storage.kt
2988483497
package redis.storage.values public sealed class RedisValue { public data class String(public val value: kotlin.String) : RedisValue() }
codecrafters-redis-kotlin/src/main/kotlin/redis/storage/values/RedisValue.kt
756175938
package redis.storage.values import kotlinx.datetime.Clock import java.util.TreeMap public class Stream( public val entries: TreeMap<StreamId, List<kotlin.String>>, public var lastId: StreamId, public var firstId: StreamId?, public var maxDeletedEntryId: StreamId?, public var entriesAdded: Long, ) : RedisValue() { public companion object { public fun empty(): Stream = Stream( entries = TreeMap(), lastId = StreamId.MIN, firstId = null, maxDeletedEntryId = null, entriesAdded = 0, ) } public fun append(id: StreamId, values: List<kotlin.String>): StreamId { if (id == StreamId.MIN) { error("ERR The ID specified in XADD must be greater than 0-0") } if (id <= lastId) { error("ERR The ID specified in XADD is equal or smaller than the target stream top item") } val nextId = id.allocate() entries[nextId] = values lastId = nextId if (firstId == null) { firstId = nextId } return nextId } public fun range( start: StreamId, inclusive: Boolean, end: StreamId? = null, ): Sequence<Pair<StreamId, List<kotlin.String>>> { val s = if (start == StreamId.MAX) { lastId } else { start } val e = if (end != null) { entries.subMap(s, inclusive, end, true) } else { entries.subMap(s, inclusive, StreamId.MAX, true) }.iterator() return sequence { while (true) { if (!e.hasNext()) { return@sequence } val (id, values) = e.next() yield(id to values) } } } private fun StreamId.allocate(): StreamId { if (ts == Long.MAX_VALUE) return StreamId(Clock.System.now().toEpochMilliseconds(), 0) return when { ts == lastId.ts && c == Long.MAX_VALUE -> StreamId(ts, lastId.c + 1) c == Long.MAX_VALUE -> StreamId(ts, 0) else -> this } } } public data class StreamId(val ts: Long, val c: Long) : Comparable<StreamId> { public override operator fun compareTo(other: StreamId): Int = ts.compareTo(other.ts).takeUnless { it == 0 } ?: c.compareTo(other.c) public override fun toString(): String = "$ts-$c" public companion object { public val MIN: StreamId = StreamId(0, 0) public val MAX: StreamId = StreamId(Long.MAX_VALUE, Long.MAX_VALUE) } }
codecrafters-redis-kotlin/src/main/kotlin/redis/storage/values/Stream.kt
3080169691
package redis.storage import kotlinx.datetime.Clock import kotlinx.datetime.Instant import redis.storage.values.RedisValue public class Memory(private val clock: Clock = Clock.System) : Storage { private val aux: MutableMap<String, String> = mutableMapOf() private val data: MutableMap<String, Pair<RedisValue, Instant?>> = mutableMapOf() override fun keys(): Sequence<String> = data.keys.asSequence() override fun get(key: String): RedisValue? { val (value, expiresAt) = data[key] ?: return null if (expiresAt != null && clock.now() >= expiresAt) { delete(key) return null } return value } override fun set(key: String, value: RedisValue, expiration: Instant?) { data[key] = value to expiration } override fun getAux(key: String): String? = aux[key] override fun setAux(key: String, value: String) { aux[key] = value } override fun getOrInsert(key: String, insert: () -> Pair<RedisValue, Instant?>): RedisValue = data.getOrPut(key) { insert() }.first override fun delete(key: String) { data.remove(key) } }
codecrafters-redis-kotlin/src/main/kotlin/redis/storage/Memory.kt
2365853517
package redis.request import redis.connection.ClientConnectionState public data class Request( val command: String, val args: List<String>, val resources: Map<Class<*>, Any>, val connectionState: ClientConnectionState, ) { public companion object { public fun fromCommands(commands: List<String>, connection: ClientConnectionState): Request = Request( command = commands[0].lowercase(), args = commands.subList(1, commands.size), resources = mapOf(), connectionState = connection, ) } }
codecrafters-redis-kotlin/src/main/kotlin/redis/request/Request.kt
3655925040
package redis.replication import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.selects.select import kotlinx.coroutines.withTimeout import redis.connection.ReplicaConnection import redis.connection.receiveCommand import redis.engine.RedisEngine import redis.engine.UpdateEvent import kotlin.coroutines.CoroutineContext import kotlin.io.encoding.Base64 import kotlin.io.encoding.ExperimentalEncodingApi import kotlin.time.Duration.Companion.milliseconds @OptIn(ExperimentalEncodingApi::class) @Suppress("MaxLineLength") private val EMPTY_RDB: ByteArray = Base64.decode( "UkVESVMwMDEx+glyZWRpcy12ZXIFNy4yLjD6CnJlZGlzLWJpdHPAQPoFY3RpbWXCbQi8ZfoIdXNlZC1tZW3CsMQQAPoIYW9mLWJhc2XAAP/wbjv+wP9aog==", ) public fun masterReplication( context: CoroutineContext, engine: RedisEngine, state: ReplicationState, ): IncomingReplicaConnectionChannel { val channel = Channel<ReplicaConnection>() CoroutineScope(context + Dispatchers.Default) .launch { replicationLoop(channel, engine, state) } return IncomingReplicaConnectionChannel(channel) } private suspend fun replicationLoop( connections: ReceiveChannel<ReplicaConnection>, engine: RedisEngine, state: ReplicationState, ) { val replicas = mutableListOf<ReplicaConnection>() val replicationLog = engine.replicationChannel while (true) { select<Unit> { connections.onReceive { connection -> println("Received new replica") connection.initialize(state) replicas.add(connection) state.activeReplicasCount.update { it + 1 } state.replicaAcks.emit(state.replicaCount to 0) } replicationLog.onReceive { event -> if (replicas.isEmpty()) return@onReceive replicas.broadcast(event) state.replicationOffsetFlow.value = replicas[0].bytesWritten } state.acksRequest.onReceive { replicas.collectAcks(state) } } } } private suspend fun List<ReplicaConnection>.collectAcks( state: ReplicationState, ) { val command = listOf("replconf", "GETACK", "*") val target = state.replicationOffset coroutineScope { val acks = map { connection -> async { kotlin.runCatching { val (_, _, rawOffset) = withTimeout(50.milliseconds) { connection.sendCommand(command) connection.receiveCommand() } val offset = rawOffset.toLong() println("Collected ack from ${connection.id}") offset >= target }.getOrElse { false } } } .awaitAll() .count { it } state.replicaAcks.emit(acks to target) } } private suspend fun List<ReplicaConnection>.broadcast(event: UpdateEvent) { val command = when (event) { is UpdateEvent.Set -> buildList<String> { add("set") add(event.key) add(event.value) if (event.expiresAt != null) { add("pxat") add(event.expiresAt.toEpochMilliseconds().toString()) } } is UpdateEvent.StreamAdd -> listOf( "xadd", event.key, event.id.toString(), ) + event.values } coroutineScope { for (connection in this@broadcast) { launch { connection.sendCommand(command) } } } } private suspend fun ReplicaConnection.initialize(replicationState: ReplicationState) { sendSimple("FULLRESYNC ${replicationState.replicationId} 0") sendRdb(EMPTY_RDB) println("sent rdb") }
codecrafters-redis-kotlin/src/main/kotlin/redis/replication/master.kt
2353616999
package redis.replication import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlin.random.Random import kotlin.text.HexFormat import kotlin.text.toHexString public class ReplicationState private constructor(public val role: Role) { public val replicaAcks: MutableSharedFlow<Pair<Int, Long>> = MutableSharedFlow(replay = 1, extraBufferCapacity = 0, onBufferOverflow = BufferOverflow.DROP_OLDEST) internal val activeReplicasCount: MutableStateFlow<Int> = MutableStateFlow(0) internal val replicationOffsetFlow: MutableStateFlow<Long> = MutableStateFlow(0) private val replid: MutableStateFlow<String> = MutableStateFlow("") internal val acksRequest: Channel<Unit> = Channel(0, onBufferOverflow = BufferOverflow.DROP_LATEST) public var replicationId: String get() = replid.value set(value) { replid.value = value } public val replicationOffset: Long get() = replicationOffsetFlow.value public val replicaCount: Int get() = activeReplicasCount.value public companion object { public fun master(): ReplicationState = ReplicationState(Role.Master) .apply { replicationId = generateReplicationId() } public fun replica(): ReplicationState = ReplicationState(Role.Slave) } } public enum class Role { Master, Slave, ; override fun toString(): String = name.lowercase() } @OptIn(ExperimentalStdlibApi::class) private fun generateReplicationId(): String { @Suppress("MagicNumber") return Random.Default.nextBytes(20).toHexString(format = HexFormat.Default) }
codecrafters-redis-kotlin/src/main/kotlin/redis/replication/ReplicationState.kt
4291242656
package redis.replication import kotlinx.coroutines.channels.SendChannel import redis.connection.ReplicaConnection @JvmInline public value class IncomingReplicaConnectionChannel(public val channel: SendChannel<ReplicaConnection>) : SendChannel<ReplicaConnection> by channel
codecrafters-redis-kotlin/src/main/kotlin/redis/replication/IncomingReplicaConnectionChannel.kt
3074776030
package redis.replication import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import redis.commands.replica.Ack import redis.commands.replica.Ping import redis.commands.replica.Set import redis.commands.replica.Xadd import redis.connection.MasterConnection import redis.connection.receiveCommand import redis.connection.receiveSimpleResponse import redis.engine.RedisEngine import redis.request.Request import redis.routing.Router import kotlin.coroutines.CoroutineContext internal fun startReplication( scope: CoroutineContext, connection: MasterConnection, engine: RedisEngine, replicationState: ReplicationState, ) { CoroutineScope(scope + Dispatchers.Default) .launch { replicationLoop(connection, engine, replicationState) } } private suspend fun replicationLoop( connection: MasterConnection, engine: RedisEngine, replicationState: ReplicationState, ) { val (syncType, masterReplicationId, offsetId) = connection.receiveSimpleResponse().split(" ") check(syncType == "FULLRESYNC") { "only support full resynchronization right now" } check(offsetId == "0") { "only support replication from the start right now" } replicationState.replicationId = masterReplicationId println("Starting full resynchronization") val replicationOffsetFlow = replicationState.replicationOffsetFlow replicationOffsetFlow.value = offsetId.toLong() // TODO: read rdb into memory @Suppress("UnusedPrivateProperty") val rdbState = connection.receiveRdb() println("Received RDB") val handshakeSize = connection.processed val router = Router.define { resource(engine) resource(replicationState) route("set") { Set() } route("ping") { Ping() } route("replconf") { Ack() } route("xadd") { Xadd() } } while (true) { replicationState.replicationOffsetFlow.value = connection.processed - handshakeSize val raw = connection.receiveCommand() println("Received request from master: $raw") val request = Request.fromCommands(raw, connection.state) val response = router.handle(request) connection.respond(response) } }
codecrafters-redis-kotlin/src/main/kotlin/redis/replication/replica.kt
2522289568
package redis.commands import redis.engine.RedisEngine import redis.response.Response import redis.response.SimpleResponse import redis.routing.Command import redis.routing.options.arg import redis.routing.options.resource public class Ping : Command() { override suspend fun handle(): Response = SimpleResponse("PONG") } public class Echo : Command() { private val message by arg(1) override suspend fun handle(): Response = SimpleResponse(message) } public class Type : Command() { private val key by arg(1) private val engine by resource<RedisEngine>() override suspend fun handle(): Response = SimpleResponse(engine.type(key)) }
codecrafters-redis-kotlin/src/main/kotlin/redis/commands/simple.kt
2285370039
package redis.commands import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.withTimeout import redis.engine.RedisEngine import redis.protocol.resp2.Resp2 import redis.response.NullResponse import redis.response.Resp2Response import redis.response.Response import redis.response.SimpleResponse import redis.routing.Command import redis.routing.options.arg import redis.routing.options.default import redis.routing.options.flag import redis.routing.options.resource import redis.routing.options.transform import redis.routing.options.vararg import redis.storage.values.StreamId import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds public class Xadd : Command() { private val engine by resource<RedisEngine>() private val streamKey by arg(1) private val id by arg(2) { it.toStreamId() } private val values by vararg(startPosition = 3) override suspend fun handle(): Response { val key = engine.add(streamKey, id, values) return SimpleResponse(key.toString()) } } public class Xrange : Command() { private val engine by resource<RedisEngine>() private val streamKey by arg(1) private val start by arg(2) { it.toStreamRangeStart() } private val count by flag("count") { it.toInt() }.default(Int.MAX_VALUE) private val end by arg(3) { it.toStreamRangeEnd() } override suspend fun handle(): Response { val entries = engine.range(streamKey, start, true, end, count) .toResp2() return Resp2Response(entries) } } public class Xread : Command() { private val engine by resource<RedisEngine>() private val block by flag("block") { it.toLong().takeUnless { n -> n == 0L }?.milliseconds ?: Duration.INFINITE } private val count by flag("count") { it.toInt() }.default(Int.MAX_VALUE) private val streams by flag("streams", values = Int.MAX_VALUE).transform { check(it.size % 2 == 0) val half = it.size / 2 (0 until half) .map { index -> it[index] to it[half + index].toStreamReadStart() } } override suspend fun handle(): Response { val output = mutableListOf<Resp2.List>() for ((streamKey, rangeStart) in streams) { if (rangeStart == StreamId.MAX) continue val range = engine.range(streamKey, rangeStart, false, StreamId.MAX, count) if (range.isEmpty()) continue output.add(Resp2.List(Resp2.String(streamKey), range.toResp2())) } if (output.isEmpty() && block != null) { try { withTimeout(checkNotNull(block)) { engine.wait().forKeys(keys = streams.map { it.first }.toTypedArray()) } } catch (_: TimeoutCancellationException) { return NullResponse } for ((streamKey, rangeStart) in streams) { val range = engine.range(streamKey, rangeStart, rangeStart == StreamId.MAX, StreamId.MAX, count) if (range.isEmpty()) continue output.add(Resp2.List(Resp2.String(streamKey), range.toResp2())) } } return Resp2Response(Resp2.List(output)) } } private fun List<Pair<StreamId, List<String>>>.toResp2(): Resp2.List = map { (key, entries) -> Resp2.List( listOf( Resp2.String(key.toString()), Resp2.List(entries), ), ) }.let(Resp2::List) private fun String.toStreamReadStart(): StreamId { if (this == "$") return StreamId.MAX val (ts, c) = split("-") return StreamId(ts.toLong(), c.toLong()) } private fun String.toStreamRangeStart(): StreamId { if (this == "-") return StreamId.MIN val (ts, c) = split("-") return StreamId(ts.toLong(), c.toLong()) } private fun String.toStreamRangeEnd(): StreamId { if (this == "+") return StreamId.MAX val (ts, c) = split("-") return StreamId(ts.toLong(), c.toLong()) } private fun String.toStreamId(): StreamId { if (this == "*") return StreamId.MAX val (ts, c) = split("-") return if (c == "*") { StreamId(ts.toLong(), Long.MAX_VALUE) } else { StreamId(ts.toLong(), c.toLong()) } }
codecrafters-redis-kotlin/src/main/kotlin/redis/commands/streams.kt
2244895503
package redis.commands.replica import kotlinx.datetime.Instant import redis.engine.RedisEngine import redis.replication.ReplicationState import redis.response.ArrayResponse import redis.response.None import redis.response.Response import redis.routing.Command import redis.routing.options.arg import redis.routing.options.flag import redis.routing.options.resource import redis.routing.options.vararg import redis.storage.values.StreamId public class Set : Command() { private val engine by resource<RedisEngine>() private val key by arg(1) private val value by arg(2) private val expiresAt by flag("PXAT") { Instant.fromEpochMilliseconds(it.toLong()) } override suspend fun handle(): Response { engine.set(key, value, expiresAt) return None } } public class Ping : Command() { override suspend fun handle(): Response = None } public class Ack : Command() { private val state by resource<ReplicationState>() override suspend fun handle(): Response = ArrayResponse(listOf("REPLCONF", "ACK", "${state.replicationOffset}")) } public class Xadd : Command() { private val engine by resource<RedisEngine>() private val streamKey by arg(1) private val id by arg(2) { it.toStreamId() } private val values by vararg(startPosition = 3) override suspend fun handle(): Response { engine.add(streamKey, id, values) return None } } private fun String.toStreamId(): StreamId { val (ts, c) = split("-") return StreamId(ts.toLong(), c.toLong()) }
codecrafters-redis-kotlin/src/main/kotlin/redis/commands/replica/replication.kt
535116582
package redis.commands import kotlinx.datetime.Clock import redis.engine.RedisEngine import redis.response.NullResponse import redis.response.Response import redis.response.SimpleResponse import redis.routing.Command import redis.routing.options.arg import redis.routing.options.flag import redis.routing.options.resource import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds public class Get : Command() { private val key: String by arg(1) private val engine by resource<RedisEngine>() override suspend fun handle(): Response { val value = engine.get(key) ?: return NullResponse return SimpleResponse(value) } } public class Set(private val clock: Clock = Clock.System) : Command() { private val key: String by arg(1) private val value: String by arg(2) private val expirationMs: Duration? by flag("px") { it.toInt().milliseconds } private val expirationSec: Duration? by flag("ex") { it.toInt().seconds } private val engine by resource<RedisEngine>() override suspend fun handle(): Response { val expiration = expirationMs ?: expirationSec val expiresAt = expiration?.let { clock.now() + it } engine.set(key, value, expiresAt) return SimpleResponse("OK") } }
codecrafters-redis-kotlin/src/main/kotlin/redis/commands/kv.kt
2459929538
package redis.commands import kotlinx.coroutines.withTimeout import redis.replication.ReplicationState import redis.response.NumberResponse import redis.response.Response import redis.response.SimpleResponse import redis.response.Upgrade import redis.routing.Command import redis.routing.options.arg import redis.routing.options.connectionState import redis.routing.options.flag import redis.routing.options.multiFlag import redis.routing.options.resource import kotlin.coroutines.cancellation.CancellationException import kotlin.math.max import kotlin.math.min import kotlin.time.Duration import kotlin.time.Duration.Companion.milliseconds public class Info : Command() { private val replicationState by resource<ReplicationState>() private val section by arg(1) override suspend fun handle(): Response { check(section == "replication") { "other sections are not supported yet" } val response = """ # Replication role:${replicationState.role} master_replid:${replicationState.replicationId} master_repl_offset:${replicationState.replicationOffset} """.trimIndent() return SimpleResponse(response) } } public class Replconf : Command() { private val state by connectionState() private val listeningPort by flag("listening-port") { it.toInt() } private val capabilities by multiFlag("capa") override suspend fun handle(): Response { state.listeningPort = listeningPort state.capabilities.addAll(capabilities) return SimpleResponse("OK") } } public class Psync : Command() { private val replicationId by arg(1) private val offset by arg(2) { it.toInt() } override suspend fun handle(): Response = Upgrade } public class Wait : Command() { private val state by resource<ReplicationState>() private val replicaCount by arg(1) { it.toInt() } private val timeout by arg(2) { it.toInt().takeIf { n -> n != 0 }?.milliseconds ?: Duration.INFINITE } override suspend fun handle(): Response { val currentOffset = state.replicationOffset val targetReplicas = min(replicaCount, state.replicaCount) if (targetReplicas == 0) return NumberResponse(0) var acks = 0 try { withTimeout(timeout) { val (replicas, offset) = state.replicaAcks.replayCache.last() if (offset >= currentOffset) { acks = replicas } if (acks >= targetReplicas) { throw CancellationException() } state.acksRequest.send(Unit) state.replicaAcks.collect { (replicas, offset) -> if (offset < currentOffset) return@collect acks = max(acks, replicas) if (acks >= targetReplicas) { throw CancellationException() } } } } catch (_: CancellationException) { } return NumberResponse(acks) } }
codecrafters-redis-kotlin/src/main/kotlin/redis/commands/repl.kt
700617551
package redis.routing.options import redis.request.Request import redis.routing.Command import kotlin.properties.PropertyDelegateProvider import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty public interface Option { public fun process(request: Request) } public interface OptionWithValue<T> : Option, ReadOnlyProperty<Command, T>, PropertyDelegateProvider<Command, ReadOnlyProperty<Command, T>> { public val value: T override operator fun provideDelegate( thisRef: Command, property: KProperty<*>, ): ReadOnlyProperty<Command, T> { thisRef.registerOption(this) return this } override fun getValue(thisRef: Command, property: KProperty<*>): T = value }
codecrafters-redis-kotlin/src/main/kotlin/redis/routing/options/Option.kt
3559578537
@file:OptIn(InternalAPI::class) @file:Suppress("TooManyFunctions") package redis.routing.options import io.ktor.utils.io.InternalAPI import redis.connection.ClientConnectionState import redis.request.Request import redis.routing.Command import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty @Suppress("UnusedReceiverParameter") public fun Command.arg(position: Int): OptionWithValue<String> { check(position > 0) return object : OptionWithValue<String> { override var value: String by NullableLateinit() override fun process(request: Request) { val v = request.args.getOrNull(position - 1) ?: error("Argument at position $position is missing") value = v } } } @Suppress("UnusedReceiverParameter") public fun <T> Command.arg(position: Int, transform: (String) -> T): OptionWithValue<T> = arg(position).transform(transform) @Suppress("UnusedReceiverParameter") public fun Command.flag(name: String): OptionWithValue<String?> = object : OptionWithValue<String?> { override var value: String? by NullableLateinit() override fun process(request: Request) { value = null val position = request.args.indexOfFirst { it.equals(name, ignoreCase = true) }.takeUnless { it == -1 } ?: return val v = request.args.getOrNull(position + 1) ?: error("missing value for flag") value = v } } @Suppress("UnusedReceiverParameter") public fun Command.flag(name: String, values: Int): OptionWithValue<List<String>> { return object : OptionWithValue<List<String>> { override var value: List<String> = listOf() override fun provideDelegate( thisRef: Command, property: KProperty<*>, ): ReadOnlyProperty<Command, List<String>> { thisRef.registerOption(this) return this } override fun process(request: Request) { val position = request.args.indexOfFirst { it.equals(name, ignoreCase = true) }.takeUnless { it == -1 } ?: return value = request.args.subList( position + 1, request.args.size, ).take(values) } } } @Suppress("UnusedReceiverParameter") public fun Command.multiFlag(name: String): OptionWithValue<List<String>> = object : OptionWithValue<List<String>> { override var value: List<String> = listOf() override fun provideDelegate( thisRef: Command, property: KProperty<*>, ): ReadOnlyProperty<Command, List<String>> { thisRef.registerOption(this) return this } override fun process(request: Request) { value = request.args.mapIndexedNotNull { index, s -> if (!s.equals(name, ignoreCase = true)) return@mapIndexedNotNull null val value = request.args.getOrNull(index + 1) ?: error("missing value for flag") value } } } @Suppress("UnusedReceiverParameter") public fun Command.vararg(startPosition: Int): OptionWithValue<List<String>> = object : OptionWithValue<List<String>> { override var value: List<String> = listOf() override fun provideDelegate( thisRef: Command, property: KProperty<*>, ): ReadOnlyProperty<Command, List<String>> { thisRef.registerOption(this) return this } override fun process(request: Request) { value = request.args.subList(startPosition - 1, request.args.size) } } @Suppress("UnusedReceiverParameter") public fun <T> Command.flag(name: String, transform: (String) -> T): OptionWithValue<T?> = flag(name).transformNullable(transform) @Suppress("UnusedReceiverParameter") public inline fun <reified T : Any> Command.resource(): OptionWithValue<T> { val type = T::class.java return object : OptionWithValue<T> { override var value: T by NullableLateinit() override fun process(request: Request) { val v = request.resources[type] ?: error("Resource of type $type is not registered") value = v as T } } } @Suppress("UnusedReceiverParameter") public fun Command.connectionState(): OptionWithValue<ClientConnectionState> = object : OptionWithValue<ClientConnectionState> { override var value: ClientConnectionState by NullableLateinit() override fun process(request: Request) { value = request.connectionState } } public fun <T, U> OptionWithValue<T>.transform(transformer: (T) -> U): OptionWithValue<U> = object : OptionWithValue<U> { override var value: U by NullableLateinit() override fun process(request: Request) { [email protected](request) value = transformer([email protected]) } } public fun <T, U> OptionWithValue<T?>.transformNullable(transformer: (T) -> U): OptionWithValue<U?> = object : OptionWithValue<U?> { override var value: U? by NullableLateinit() override fun process(request: Request) { [email protected](request) value = [email protected]?.let { transformer(it) } } } public fun <T> OptionWithValue<T?>.default(default: T): OptionWithValue<T> = object : OptionWithValue<T> { override var value: T = default override fun process(request: Request) { [email protected](request) value = [email protected] ?: default } } @InternalAPI public class NullableLateinit<T> : ReadWriteProperty<Any, T> { private object UNINITIALIZED private var value: Any? = UNINITIALIZED override fun getValue(thisRef: Any, property: KProperty<*>): T { if (value === UNINITIALIZED) error("Cannot read from option delegate before processing request") try { @Suppress("UNCHECKED_CAST") return value as T } catch (_: ClassCastException) { error("Value is of invalid type") } } override fun setValue(thisRef: Any, property: KProperty<*>, value: T) { this.value = value } }
codecrafters-redis-kotlin/src/main/kotlin/redis/routing/options/options.kt
3511845891
@file:OptIn(InternalAPI::class) package redis.routing import io.ktor.utils.io.InternalAPI import redis.request.Request import redis.response.ErrorResponse import redis.response.Response public typealias HandlerBuilder = suspend () -> Handler public class Router { @InternalAPI public val resources: MutableMap<Class<*>, Any> = mutableMapOf() internal val routes: MutableMap<String, HandlerBuilder> = mutableMapOf() public inline fun<reified T : Any> resource(): T = checkNotNull(resources[T::class.java]) { "Resource not registered" } as T public suspend fun handle(request: Request): Response = runCatching { val handler = routes[request.command] ?: error("unknown command: ${request.command}") return handler() .handle(request.copy(resources = resources)) }.getOrElse { ErrorResponse("${it.message}") } public companion object { public inline fun define(block: RouterBuilder.() -> Unit): Router = RouterBuilder() .run { block() build() } } } public class RouterBuilder { @InternalAPI public val router: Router = Router() public fun build(): Router = router public fun route(command: String, builder: HandlerBuilder) { router.routes[command.lowercase()] = { builder() } } public inline fun <reified T : Any> resource(value: T) { router.resources[T::class.java] = value as Any } }
codecrafters-redis-kotlin/src/main/kotlin/redis/routing/Router.kt
1533142252
package redis.routing import redis.request.Request import redis.response.Response public abstract class Handler { public abstract suspend fun handle(request: Request): Response }
codecrafters-redis-kotlin/src/main/kotlin/redis/routing/Handler.kt
2680316839
package redis.routing import redis.request.Request import redis.response.Response import redis.routing.options.Option public abstract class Command : Handler() { private val options: MutableList<Option> = mutableListOf() internal fun registerOption(option: Option) { options.add(option) } override suspend fun handle(request: Request): Response { for (option in options) { option.process(request) } return handle() } public abstract suspend fun handle(): Response }
codecrafters-redis-kotlin/src/main/kotlin/redis/routing/Command.kt
1569420313
package redis.engine import kotlinx.datetime.Instant import redis.storage.values.StreamId public interface Engine { public suspend fun get(key: String): String? public suspend fun set(key: String, value: String, expiration: Instant?) public suspend fun type(key: String): String public suspend fun add(stream: String, id: StreamId, values: List<String>): StreamId public suspend fun range( stream: String, start: StreamId, inclusive: Boolean, end: StreamId, count: Int, ): List<Pair<StreamId, List<String>>> public suspend fun wait(): WaitBuilder }
codecrafters-redis-kotlin/src/main/kotlin/redis/engine/Engine.kt
3653992097
package redis.engine import kotlinx.coroutines.flow.MutableSharedFlow import kotlin.coroutines.cancellation.CancellationException public class WaitBuilder internal constructor(private val events: MutableSharedFlow<UpdateEvent>) { public suspend fun forKeys(vararg keys: String) { val k = keys.toSet() try { events.collect { event -> val key = when (event) { is UpdateEvent.Set -> event.key is UpdateEvent.StreamAdd -> event.key } if (key in k) throw CancellationException() } } catch (_: CancellationException) { } } }
codecrafters-redis-kotlin/src/main/kotlin/redis/engine/WaitBuilder.kt
3646598685
package redis.engine import kotlinx.datetime.Instant import redis.storage.values.StreamId public sealed class UpdateEvent { public data class Set( val key: String, val value: String, val expiresAt: Instant?, ) : UpdateEvent() public data class StreamAdd( val key: String, val id: StreamId, val values: List<String>, ) : UpdateEvent() }
codecrafters-redis-kotlin/src/main/kotlin/redis/engine/UpdateEvent.kt
2369392346
package redis.engine import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import kotlinx.datetime.Instant import redis.storage.Storage import redis.storage.values.RedisValue import redis.storage.values.Stream import redis.storage.values.StreamId public class RedisEngine(private val storage: Storage) : Engine { private val replication: Channel<UpdateEvent> = Channel(capacity = 256) private val updates: MutableSharedFlow<UpdateEvent> = MutableSharedFlow( replay = 0, extraBufferCapacity = 32, onBufferOverflow = BufferOverflow.DROP_OLDEST, ) private val lock: Mutex = Mutex() public val replicationChannel: ReceiveChannel<UpdateEvent> get() = replication override suspend fun get(key: String): String? { lock.withLock { val value = storage.get(key) ?: return null return when (value) { is RedisValue.String -> value.value else -> { error("invalid type") } } } } override suspend fun set(key: String, value: String, expiration: Instant?) { lock.withLock { storage.set(key, RedisValue.String(value), expiration) } val event = UpdateEvent.Set(key, value, expiration) replication.send(event) updates.emit(event) } override suspend fun type(key: String): String { lock.withLock { val value = storage.get(key) ?: return "none" return when (value) { is RedisValue.String -> "string" is Stream -> "stream" } } } override suspend fun add(stream: String, id: StreamId, values: List<String>): StreamId { val added = lock.withLock { val value = storage.getOrInsert(stream) { Stream.empty() to null } when (value) { is Stream -> value.append(id, values) else -> error("invalid type") } } val event = UpdateEvent.StreamAdd(stream, added, values) replication.send(event) updates.emit(event) return added } override suspend fun range( stream: String, start: StreamId, inclusive: Boolean, end: StreamId, count: Int, ): List<Pair<StreamId, List<String>>> { lock.withLock { val value = storage.get(stream) ?: return listOf() return when (value) { is Stream -> value.range(start, inclusive, end) .take(count) .toList() else -> error("invalid type") } } } override suspend fun wait(): WaitBuilder = WaitBuilder(updates) }
codecrafters-redis-kotlin/src/main/kotlin/redis/engine/RedisEngine.kt
451972365
import io.ktor.network.selector.ActorSelectorManager import io.ktor.network.sockets.InetSocketAddress import io.ktor.network.sockets.Socket import io.ktor.network.sockets.SocketAddress import io.ktor.network.sockets.aSocket import io.ktor.network.sockets.tcpNoDelay import io.ktor.utils.io.errors.IOException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.channels.SendChannel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.retry import kotlinx.coroutines.flow.single import kotlinx.coroutines.job import kotlinx.coroutines.launch import redis.commands.Echo import redis.commands.Get import redis.commands.Info import redis.commands.Ping import redis.commands.Psync import redis.commands.Replconf import redis.commands.Set import redis.commands.Type import redis.commands.Wait import redis.commands.Xadd import redis.commands.Xrange import redis.commands.Xread import redis.connection.ClientConnection import redis.connection.MasterConnection import redis.connection.ReplicaConnection import redis.connection.ping import redis.connection.replConf import redis.connection.startPsync import redis.engine.RedisEngine import redis.replication.IncomingReplicaConnectionChannel import redis.replication.ReplicationState import redis.replication.masterReplication import redis.replication.startReplication import redis.request.Request import redis.response.Upgrade import redis.routing.Router import redis.storage.Memory import kotlin.coroutines.CoroutineContext public suspend fun main(argv: Array<String>) { val args = Args() args.main(argv) coroutineScope { val serverScope = SupervisorJob(coroutineContext.job) val listener = aSocket(ActorSelectorManager(serverScope)).tcp().tcpNoDelay().bind( InetSocketAddress("0.0.0.0", args.port), ) val router = if (args.replicaof != null) { replica(SupervisorJob(coroutineContext.job), args.port, checkNotNull(args.replicaof)) } else { master(SupervisorJob(coroutineContext.job)) } println("Listening on ${listener.localAddress}") while (true) { val client = listener.accept() println("Accepted client: ${client.remoteAddress}") serve(client, router) } } } private fun master(context: CoroutineContext): Router { val replicationState = ReplicationState.master() val engine = RedisEngine(Memory()) val clients = masterReplication(context, engine, replicationState) return Router.define { resource(engine) resource(replicationState) resource(clients) route("ping") { Ping() } route("echo") { Echo() } route("get") { Get() } route("set") { Set() } route("info") { Info() } route("replconf") { Replconf() } route("psync") { Psync() } route("wait") { Wait() } route("type") { Type() } route("xadd") { Xadd() } route("xrange") { Xrange() } route("xread") { Xread() } } } private suspend fun replica(context: CoroutineContext, myPort: Int, replicaOf: InetSocketAddress): Router { val replicationState = ReplicationState.replica() val engine = RedisEngine(Memory()) val masterConnection = handshake(context, replicaOf, myPort) startReplication(context, masterConnection, engine, replicationState) return Router.define { resource(engine) resource(replicationState) route("ping") { Ping() } route("echo") { Echo() } route("get") { Get() } route("info") { Info() } route("type") { Type() } route("xrange") { Xrange() } route("xread") { Xread() } } } private suspend fun handshake( context: CoroutineContext, address: SocketAddress, myPort: Int, ): MasterConnection { val connect = flow { emit(aSocket(ActorSelectorManager(context)).tcp().tcpNoDelay().connect(address)) } .retry(10) { er -> er is IOException } .single() val connection = MasterConnection(connect) connection.ping() connection.replConf( listeningPort = myPort, capabilities = listOf("eof", "psync2"), ) connection.startPsync() return connection } private fun CoroutineScope.serve( rawConnection: Socket, router: Router, ) { val connection = ClientConnection(rawConnection) val commands = connection.commands(coroutineContext) launch { for (raw in commands) { println("Accepted command: $raw") val request = Request.fromCommands(raw, connection.state) val response = router.handle(request) connection.respond(response) if (response is Upgrade) { val clients = router.resource<IncomingReplicaConnectionChannel>() clients.send(connection.upgradeToReplica()) break } } commands.cancel() } }
codecrafters-redis-kotlin/src/main/kotlin/main.kt
1409940824
package com.multilanguagesample import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled import com.facebook.react.defaults.DefaultReactActivityDelegate class MainActivity : ReactActivity() { /** * Returns the name of the main component registered from JavaScript. This is used to schedule * rendering of the component. */ override fun getMainComponentName(): String = "MultiLanguageSample" /** * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate] * which allows you to enable New Architecture with a single boolean flags [fabricEnabled] */ override fun createReactActivityDelegate(): ReactActivityDelegate = DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled) }
MultiLanguage-ReactNative/android/app/src/main/java/com/multilanguagesample/MainActivity.kt
2516945885
package com.multilanguagesample import android.app.Application import com.facebook.react.PackageList import com.facebook.react.ReactApplication import com.facebook.react.ReactHost import com.facebook.react.ReactNativeHost import com.facebook.react.ReactPackage import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load import com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost import com.facebook.react.defaults.DefaultReactNativeHost import com.facebook.react.flipper.ReactNativeFlipper import com.facebook.soloader.SoLoader class MainApplication : Application(), ReactApplication { override val reactNativeHost: ReactNativeHost = object : DefaultReactNativeHost(this) { override fun getPackages(): List<ReactPackage> = PackageList(this).packages.apply { // Packages that cannot be autolinked yet can be added manually here, for example: // add(MyReactNativePackage()) } override fun getJSMainModuleName(): String = "index" override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED } override val reactHost: ReactHost get() = getDefaultReactHost(this.applicationContext, reactNativeHost) override fun onCreate() { super.onCreate() SoLoader.init(this, false) if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) { // If you opted-in for the New Architecture, we load the native entry point for this app. load() } ReactNativeFlipper.initializeFlipper(this, reactNativeHost.reactInstanceManager) } }
MultiLanguage-ReactNative/android/app/src/main/java/com/multilanguagesample/MainApplication.kt
4279625743
package com.nextlevelprogrammers.fingerprint import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.nextlevelprogrammers.fingerprint", appContext.packageName) } }
FingerPrint/app/src/androidTest/java/com/nextlevelprogrammers/fingerprint/ExampleInstrumentedTest.kt
230911087
package com.nextlevelprogrammers.fingerprint import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
FingerPrint/app/src/test/java/com/nextlevelprogrammers/fingerprint/ExampleUnitTest.kt
828773702
package com.nextlevelprogrammers.fingerprint import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.biometric.BiometricPrompt import java.util.concurrent.Executor import java.util.concurrent.Executors class MainActivity : AppCompatActivity() { private lateinit var executor: Executor private lateinit var biometricPrompt: BiometricPrompt private lateinit var sharedPreferences: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) executor = Executors.newSingleThreadExecutor() sharedPreferences = getSharedPreferences("FingerprintPrefs", MODE_PRIVATE) if (isFingerprintRegistered()) { authenticateWithFingerprint() } else { startActivity(Intent(this, RegistrationActivity::class.java)) finish() // Finish MainActivity to prevent user from going back to it after registration } } private fun isFingerprintRegistered(): Boolean { return sharedPreferences.getBoolean("isFingerprintRegistered", false) } private fun authenticateWithFingerprint() { val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle("Authenticate with Fingerprint") .setSubtitle("Place your finger on the sensor to authenticate") .setNegativeButtonText("Cancel") .build() biometricPrompt = BiometricPrompt(this, executor, object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { super.onAuthenticationSucceeded(result) runOnUiThread { showToast("Fingerprint authentication succeeded! Data matched.") } startActivity(Intent(this@MainActivity, HomeActivity::class.java)) finish() // Finish MainActivity after successful authentication } override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) runOnUiThread { showToast("Fingerprint authentication failed: $errString") } } }) biometricPrompt.authenticate(promptInfo) } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } }
FingerPrint/app/src/main/java/com/nextlevelprogrammers/fingerprint/MainActivity.kt
1971010184
package com.nextlevelprogrammers.fingerprint import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat class HomeActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_home) } }
FingerPrint/app/src/main/java/com/nextlevelprogrammers/fingerprint/HomeActivity.kt
2524861436
package com.nextlevelprogrammers.fingerprint import android.content.Intent import android.content.SharedPreferences import android.os.Bundle import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.biometric.BiometricPrompt import java.util.concurrent.Executor import java.util.concurrent.Executors class RegistrationActivity : AppCompatActivity() { private lateinit var executor: Executor private lateinit var sharedPreferences: SharedPreferences override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_registration) executor = Executors.newSingleThreadExecutor() sharedPreferences = getSharedPreferences("FingerprintPrefs", MODE_PRIVATE) // Register fingerprint when user clicks a button findViewById<Button>(R.id.btnRegister).setOnClickListener { registerFingerprint() } } private fun registerFingerprint() { val promptInfo = BiometricPrompt.PromptInfo.Builder() .setTitle("Register Fingerprint") .setSubtitle("Place your finger on the sensor to register") .setNegativeButtonText("Cancel") .build() val biometricPrompt = BiometricPrompt(this, executor, object : BiometricPrompt.AuthenticationCallback() { override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) { super.onAuthenticationSucceeded(result) runOnUiThread { showToast("Fingerprint registered successfully!") startActivity(Intent(this@RegistrationActivity, HomeActivity::class.java)) finish() // Finish RegistrationActivity after successful registration } // Store a flag indicating that fingerprint is registered sharedPreferences.edit().putBoolean("isFingerprintRegistered", true).apply() } override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { super.onAuthenticationError(errorCode, errString) runOnUiThread { showToast("Fingerprint registration failed: $errString") } } }) biometricPrompt.authenticate(promptInfo) } private fun showToast(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } }
FingerPrint/app/src/main/java/com/nextlevelprogrammers/fingerprint/RegistrationActivity.kt
1454328017
package com.example.ws54_compose_speedrun1 import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.ws54_compose_speedrun1", appContext.packageName) } }
ws54_compose_speedrun1/app/src/androidTest/java/com/example/ws54_compose_speedrun1/ExampleInstrumentedTest.kt
556696036
package com.example.ws54_compose_speedrun1 import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
ws54_compose_speedrun1/app/src/test/java/com/example/ws54_compose_speedrun1/ExampleUnitTest.kt
1886126440
package com.example.ws54_compose_speedrun1.ui.theme import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val Shapes = Shapes( small = RoundedCornerShape(4.dp), medium = RoundedCornerShape(4.dp), large = RoundedCornerShape(0.dp) )
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/ui/theme/Shape.kt
2841154677
package com.example.ws54_compose_speedrun1.ui.theme import androidx.compose.ui.graphics.Color val Purple200 = Color(0xFFBB86FC) val Purple500 = Color(0xFF6200EE) val Purple700 = Color(0xFF3700B3) val Teal200 = Color(0xFF03DAC5)
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/ui/theme/Color.kt
319396717
package com.example.ws54_compose_speedrun1.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable private val DarkColorPalette = darkColors( primary = Purple200, primaryVariant = Purple700, secondary = Teal200 ) private val LightColorPalette = lightColors( primary = Purple500, primaryVariant = Purple700, secondary = Teal200 /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun Ws54_compose_speedrun1Theme( darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit ) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } MaterialTheme( colors = colors, typography = Typography, shapes = Shapes, content = content ) }
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/ui/theme/Theme.kt
3891836568
package com.example.ws54_compose_speedrun1.ui.theme import androidx.compose.material.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp import com.example.ws54_compose_speedrun1.R // Set of Material typography styles to start with val Typography = Typography( body1 = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp ) /* Other default text styles to override button = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.W500, fontSize = 14.sp ), caption = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 12.sp ) */ ) val Averta = FontFamily(Font(R.font.avertastd))
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/ui/theme/Type.kt
297419643
package com.example.ws54_compose_speedrun1.page import Current import DayData import Forecast import HourData import WeatherResponse import android.annotation.SuppressLint import android.view.RoundedCorner import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.ws54_compose_speedrun1.service.* import com.example.ws54_compose_speedrun1.ui.theme.Averta import com.example.ws54_compose_speedrun1.widget.HomeAppBar import com.example.ws54_compose_speedrun1.widget.NavDrawerContent import kotlinx.coroutines.CoroutineScope import com.example.ws54_compose_speedrun1.R object HomePage { @SuppressLint("UnusedMaterialScaffoldPaddingParameter") @Composable fun build(onNavigateToRegion:()->Unit, scope : CoroutineScope, drawerState: DrawerState, data :WeatherResponse){ val lazyListState = rememberLazyListState() ModalDrawer(drawerState = drawerState,drawerContent = {NavDrawerContent.build(scope = scope , drawerState = drawerState, onNavigateToRegion = onNavigateToRegion)}) { //!!! {} lambda Scaffold( modifier = Modifier.fillMaxSize(), topBar = { HomeAppBar.build(scope,drawerState)} ) { LazyColumn( modifier = Modifier .fillMaxSize() .padding(10.dp, top = 0.dp, 10.dp, 10.dp), horizontalAlignment = Alignment.CenterHorizontally, state = lazyListState ) { item{ Text(text = "${data.Taichung.current.temp_c}°", fontSize = 80.sp, fontFamily = Averta ) Text(text = "${data.Taichung.current.maxTemp_c}° / ${data.Taichung.current.minTemp_c}°", fontSize = 60.sp, fontFamily = Averta) Text(text = "${getTranslatedDescription(description = data.Taichung.current.description)}", fontSize = 40.sp, fontFamily = Averta) Spacer(modifier = Modifier.height(20.dp)) _buildTempPerHour(data.Taichung.forecast.hourly) Spacer(modifier = Modifier.height(20.dp)) _buildDailyWeather(data.Taichung.forecast.day) Spacer(modifier = Modifier.height(20.dp)) _buildPM25(data.Taichung.current) } } } } } @Composable fun _buildTempPerHour(data: List<HourData>){ val lazyListState = rememberLazyListState() val hoursData = data //list Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.SpaceAround, modifier = Modifier .height(185.dp) .clip(RoundedCornerShape(size = 15.dp)) .background(color = Color.Gray.copy(alpha = 0.5f)) .padding(5.dp) ) { Row( Modifier .fillMaxWidth() ,horizontalArrangement = Arrangement.Center) { Text(text = stringResource(id = R.string.hourly_weather), fontFamily = Averta, color = Color.White, fontSize = 15.sp, textAlign = TextAlign.Center) } Divider(color = Color.White, modifier = Modifier .fillMaxWidth(0.92f) .padding(5.dp)) LazyRow(verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth(), state = lazyListState, ) { items(hoursData.size) { _buildPerHourData(data = hoursData[it]) } } } } // 每小時溫度小物件 @Composable fun _buildPerHourData(data:HourData){ Column(verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(5.dp) ) { Text(text = data.time.takeLast(5), fontSize = 15.sp, color = Color.White) getIconByDescription(description = data.description)?.let { Image(painter = it,contentDescription = null, modifier = Modifier.size(57.dp)) } Text(text = "${data.temp_c}°", fontFamily = Averta, color = Color.White, fontSize = 15.sp) Text(text = "${data.daily_chance_of_rain}%", fontFamily = Averta, color = Color.White, fontSize = 15.sp) } } @Composable fun _buildDailyWeather(data:List<DayData>){ Column( verticalArrangement = Arrangement.SpaceAround, horizontalAlignment = Alignment.CenterHorizontally,modifier = Modifier .fillMaxWidth() .clip( RoundedCornerShape(15.dp) ) .background(Color.Gray.copy(alpha = 0.5f))) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center){ Text(text = stringResource(id = R.string.weather_in_ten_days), fontFamily = Averta, color = Color.White, fontSize = 15.sp, textAlign = TextAlign.Center) } Divider(color = Color.White, modifier = Modifier .fillMaxWidth(0.92f) .padding(5.dp)) data.forEach(){ _buildDailyWeatherData(it) } } } @Composable fun _buildDailyWeatherData(data:DayData){ Row() { Row(Modifier.width(80.dp)){ Text(text = data.date, fontFamily = Averta, color = Color.White, fontSize = 15.sp) } Row( Modifier.width(60.dp) ){ getIconByDescription(description = data.description)?.let { Image(painter = it, contentDescription = null,Modifier.size(54.dp)) } } Row( Modifier.width(60.dp) ){ Text(text = "${data.daily_chance_of_rain}%", fontFamily = Averta, color = Color.White, fontSize = 15.sp) } Row( Modifier.width(60.dp) ){ Text(text = "${data.maxTemp_c}°", fontFamily = Averta, color = Color.White, fontSize = 15.sp) } Row( Modifier.width(60.dp) ){ Text(text = "${data.minTemp_c}°", fontFamily = Averta, color = Color.White, fontSize = 15.sp) } } } @Composable fun _buildPM25(data:Current){ Column( verticalArrangement = Arrangement.SpaceAround, horizontalAlignment = Alignment.CenterHorizontally,modifier = Modifier .fillMaxWidth() .clip( RoundedCornerShape(15.dp) ) .background(Color.Gray.copy(alpha = 0.5f))) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center){ Text(text = "PM2.5", fontFamily = Averta, color = Color.White, fontSize = 15.sp, textAlign = TextAlign.Center) } Divider(color = Color.White, modifier = Modifier .fillMaxWidth(0.92f) .padding(5.dp)) Text(text = data.pm25.toString(),color = Color.White, fontSize = 40.sp, fontFamily = Averta, fontWeight = FontWeight.Bold) } } }
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/page/HomePage.kt
1424355342
package com.example.ws54_compose_speedrun1.page import android.annotation.SuppressLint import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable object RegionPage { @SuppressLint("UnusedMaterialScaffoldPaddingParameter") @Composable fun bulid(onNavigateBack: ()->Unit){ Scaffold( topBar = { regionAppBar(onNavigateBack) } ) { } } @Composable fun regionAppBar(onNavigateBack:()->Unit){ TopAppBar( title = { Text(text = "地區頁面") }, navigationIcon = { IconButton(onClick = onNavigateBack){ Icon(imageVector = Icons.Default.ArrowBack, contentDescription = null) } } ) } }
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/page/RegionPage.kt
603196670
package com.example.ws54_compose_speedrun1 import WeatherResponse import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.* import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.ws54_compose_speedrun1.page.HomePage import com.example.ws54_compose_speedrun1.page.RegionPage import com.example.ws54_compose_speedrun1.service.JsonService import com.example.ws54_compose_speedrun1.ui.theme.Ws54_compose_speedrun1Theme import kotlinx.coroutines.CoroutineScope class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Ws54_compose_speedrun1Theme { val scope = rememberCoroutineScope() val drawerState = rememberDrawerState(initialValue = DrawerValue.Closed) // !!! DrawerValue.Closed val jsonService = JsonService val jsonString = jsonService.readJsonFromAssets(this,"weatherData.json") val data = JsonService.parseJson(jsonString) Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background ) { AppScreen(scope, drawerState,data) } } } } @Composable fun AppScreen(scope:CoroutineScope, drawerState: DrawerState,data:WeatherResponse){ var currentScreen by remember { mutableStateOf("Home") } when (currentScreen){ "Home" -> HomePage.build({currentScreen = "Region"}, scope = scope, drawerState = drawerState, data = data) "Region" -> RegionPage.bulid({currentScreen = "Home"}) } } }
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/MainActivity.kt
3119401510
package com.example.ws54_compose_speedrun1.widget import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.DrawerState import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.LocationOn import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.paint import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.example.ws54_compose_speedrun1.R import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch object NavDrawerContent { @Composable fun build(scope: CoroutineScope, drawerState: DrawerState, onNavigateToRegion:()->Unit){ Column(modifier = Modifier.padding(15.dp)) { Row{ IconButton(onClick = { scope.launch { drawerState.close() } }) { Icon(imageVector = Icons.Default.Close, contentDescription = null) } } Row ( modifier = Modifier .fillMaxWidth() .height(70.dp) .clip(RoundedCornerShape(15.dp)) .paint( painter = painterResource( id = R.drawable.icon, ), contentScale = ContentScale.Crop ). clickable { onNavigateToRegion() }, horizontalArrangement = Arrangement.SpaceAround, verticalAlignment = Alignment.CenterVertically ){ Text(text = stringResource(id = R.string.NavDrawerContent_region),color = Color.White, fontSize = 43.sp) Icon(imageVector = Icons.Default.LocationOn, contentDescription = null, tint = Color.White,modifier = Modifier.size(40.dp)) } } } }
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/widget/NavDrawerContent.kt
1716436763
package com.example.ws54_compose_speedrun1.widget import androidx.compose.foundation.layout.Row import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.LocationOn import androidx.compose.material.icons.filled.Menu import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.res.stringResource import com.example.ws54_compose_speedrun1.R import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch object HomeAppBar{ @Composable fun build(scope:CoroutineScope,drawerState: DrawerState){ TopAppBar( title = { Row() { Text(text = stringResource(id = R.string.current_location)) Icon(imageVector = Icons.Default.LocationOn, contentDescription = null) } }, navigationIcon = { IconButton(onClick = { scope.launch { drawerState.open() } }){ Icon(imageVector = Icons.Default.Menu, contentDescription = null) } }, ) } }
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/widget/HomeAppBar.kt
2194241694
package com.example.ws54_compose_speedrun1.service import WeatherResponse import android.content.ClipDescription import android.content.Context import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import com.example.ws54_compose_speedrun1.R import com.google.gson.Gson //!!! object JsonService { fun readJsonFromAssets(context:Context, fileName:String):String{ return context.assets.open(fileName).bufferedReader().use{it.readText()} } fun parseJson(jsonString:String):WeatherResponse { val gson = Gson() return gson.fromJson(jsonString,WeatherResponse::class.java) } }
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/service/JsonService.kt
1633470771
data class WeatherResponse( val Taichung:taichung, val Taipei:taipei, val Ayo:ayo, val TestCity:testcity, val Yee:yee ) data class taichung( val current:Current, val forecast:Forecast ) data class taipei( val current: Current, ) data class ayo( val current: Current, ) data class testcity( val current: Current, ) data class yee( val current: Current, ) // --------------------------------------------- data class Current( val temp_c: Int, val temp_f: Double, val maxTemp_c:Int, val minTemp_c:Int, val maxTemp_f:Double, val minTemp_f: Double, val uv:Double, val pm25:Double, val daily_chance_of_rain:Int, val description: String ) data class Forecast( val day:List<DayData>, val hourly:List<HourData> ) data class DayData( val date:String, val maxTemp_c: Int, val maxTemp_f: Double, val minTemp_c: Int, val mixTemp_f:Double, val daily_chance_of_rain:Int, val description: String ) data class HourData( val time:String, val temp_c:Int, val temp_f:Double, val daily_chance_of_rain: Int, val description: String )
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/service/weather_modal.kt
1128226135
package com.example.ws54_compose_speedrun1.service import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import com.example.ws54_compose_speedrun1.R @Composable fun getTranslatedDescription(description: String ): String? { val descriptionMap = mapOf( "sunny" to stringResource(id = R.string.sunny), "rainy" to stringResource(id = R.string.middle_rain), "cloudy" to stringResource(id = R.string.cloudy) ) return descriptionMap[description] } @Composable fun getIconByDescription(description: String): Painter? { val iconMap = mapOf( "sunny" to painterResource(id = R.drawable.morning_sun_sunrise_icon), "rainy" to painterResource(id = R.drawable.clouds_cloudy_rain_sunny_icon), "cloudy" to painterResource(id = R.drawable.clouds_cloudy_rain_sunny_icon) ) return iconMap[description] }
ws54_compose_speedrun1/app/src/main/java/com/example/ws54_compose_speedrun1/service/Description_Service.kt
1817456808
package app.music import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("app.music", appContext.packageName) } }
D-Music-App/app/src/androidTest/java/app/music/ExampleInstrumentedTest.kt
1438611535
package app.music import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
D-Music-App/app/src/test/java/app/music/ExampleUnitTest.kt
3490969463
package app.music import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.PopupMenu import android.widget.RelativeLayout import android.widget.TextView import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import app.music.adapter.CategoryAdapter import app.music.adapter.SectionSongListAdapter import app.music.databinding.ActivityMainBinding import app.music.models.CategoryModel import app.music.models.SongModel import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.Query import com.google.firebase.firestore.toObjects class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding lateinit var categoryAdapter: CategoryAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) getCategoriesFromFirebase() setupSection("section_1", binding.section1MainLayout, binding.section1Title, binding.section1RecyclerView) setupSection("section_2", binding.section2MainLayout, binding.section2Title, binding.section2RecyclerView) setupMostlyPlayedSection("mostly_played", binding.mostlyPlayedMainLayout, binding.mostlyPlayedTitle, binding.mostlyPlayedRecyclerView) binding.optionBtn.setOnClickListener { showPopupMenu() } } fun getCategoriesFromFirebase(){ FirebaseFirestore.getInstance().collection("category").get().addOnSuccessListener { val categoryList = it.toObjects(CategoryModel::class.java) Log.e("CATEGORY", categoryList.size.toString()) setupCategoryRecyclerView(categoryList) } } fun setupCategoryRecyclerView(categoryList: List<CategoryModel>){ categoryAdapter = CategoryAdapter(categoryList) binding.categoriesRecyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) binding.categoriesRecyclerView.adapter = categoryAdapter } //Sections fun setupSection(id: String, sectionLayout: RelativeLayout, titleView: TextView, recyclerView: RecyclerView){ FirebaseFirestore.getInstance().collection("sections") .document(id) .get().addOnSuccessListener { val section = it.toObject(CategoryModel::class.java) section?.apply { sectionLayout.visibility = View.VISIBLE titleView.text = name recyclerView.layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.HORIZONTAL, false) recyclerView.adapter = SectionSongListAdapter(songs) sectionLayout.setOnClickListener{ SongsListActivity.category = section startActivity(Intent(this@MainActivity, SongsListActivity::class.java)) } } } } fun setupMostlyPlayedSection(id: String, sectionLayout: RelativeLayout, titleView: TextView, recyclerView: RecyclerView){ FirebaseFirestore.getInstance().collection("sections") .document(id) .get().addOnSuccessListener { //get most played songs FirebaseFirestore.getInstance().collection("songs") .orderBy("count", Query.Direction.DESCENDING) .limit(5) .get().addOnSuccessListener {songListSnapshot -> val songsModelList = songListSnapshot.toObjects<SongModel>() val songsIdList = songsModelList.map { it.id }.toList() val section = it.toObject(CategoryModel::class.java) section?.apply { section.songs = songsIdList sectionLayout.visibility = View.VISIBLE titleView.text = name recyclerView.layoutManager = LinearLayoutManager(this@MainActivity, LinearLayoutManager.HORIZONTAL, false) recyclerView.adapter = SectionSongListAdapter(songs) sectionLayout.setOnClickListener{ SongsListActivity.category = section startActivity(Intent(this@MainActivity, SongsListActivity::class.java)) } } } } } fun showPopupMenu(){ val popupMenu = PopupMenu(this, binding.optionBtn) val inflater = popupMenu.menuInflater inflater.inflate(R.menu.option_menu, popupMenu.menu) popupMenu.show() popupMenu.setOnMenuItemClickListener { when(it.itemId){ R.id.logout -> { logout() true } } false } } fun logout(){ MyExoPlayer.getInstance()?.release() FirebaseAuth.getInstance().signOut() startActivity(Intent(this, LoginActivity::class.java)) finish() } }
D-Music-App/app/src/main/java/app/music/MainActivity.kt
2532571579
package app.music import android.content.Context import androidx.media3.common.MediaItem import androidx.media3.exoplayer.ExoPlayer import app.music.models.SongModel import com.google.firebase.firestore.FirebaseFirestore object MyExoPlayer { private var exoPlayer: ExoPlayer? = null private var currentSong: SongModel? = null fun getCurrentSong(): SongModel?{ return currentSong } fun getInstance(): ExoPlayer?{ return exoPlayer } fun startPlaying(context: Context, song: SongModel){ if(exoPlayer==null) exoPlayer = ExoPlayer.Builder(context).build() if(currentSong!=song){ //Its a new song so start playing currentSong = song updateCount() currentSong?.url?.apply { val mediaItem = MediaItem.fromUri(this) exoPlayer?.setMediaItem(mediaItem) exoPlayer?.prepare() exoPlayer?.play() } } } fun updateCount(){ currentSong?.id?.let {id -> FirebaseFirestore.getInstance().collection("songs") .document(id) .get().addOnSuccessListener { var latestCount = it.getLong("count") if(latestCount==null){ latestCount = 1L }else{ latestCount = latestCount + 1 } FirebaseFirestore.getInstance().collection("songs") .document(id) .update(mapOf("count" to latestCount)) } } } }
D-Music-App/app/src/main/java/app/music/MyExoPlayer.kt
903638886
package app.music import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import androidx.media3.common.Player import androidx.media3.exoplayer.ExoPlayer import app.music.databinding.ActivityPlayerBinding import com.bumptech.glide.Glide class PlayerActivity : AppCompatActivity() { lateinit var binding: ActivityPlayerBinding lateinit var exoPlayer: ExoPlayer var playerListener = object : Player.Listener{ override fun onIsPlayingChanged(isPlaying: Boolean) { super.onIsPlayingChanged(isPlaying) showGif(isPlaying) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityPlayerBinding.inflate(layoutInflater) setContentView(binding.root) MyExoPlayer.getCurrentSong()?.apply { binding.songTitleTextview.text = title binding.songSubtitleTextview.text = subtitle Glide.with(binding.songCoverImageview).load(coverUrl) .circleCrop() .into(binding.songCoverImageview) Glide.with(binding.songGifImageview).load(R.drawable.media_playing) .circleCrop() .into(binding.songGifImageview) exoPlayer = MyExoPlayer.getInstance()!! binding.playerView.player = exoPlayer binding.playerView.showController() exoPlayer.addListener(playerListener) } } fun showGif(show: Boolean){ if(show){ binding.songGifImageview.visibility = View.VISIBLE }else{ binding.songGifImageview.visibility = View.INVISIBLE } } override fun onDestroy() { super.onDestroy() exoPlayer.removeListener(playerListener) } }
D-Music-App/app/src/main/java/app/music/PlayerActivity.kt
2517000206
package app.music.models data class CategoryModel( val name : String, val coverUrl : String, var songs: List<String> ){ constructor() : this("","", listOf()) }
D-Music-App/app/src/main/java/app/music/models/CategoryModel.kt
3425894085
package app.music.models data class SongModel( val id:String, val title: String, val subtitle: String, val url: String, val coverUrl: String ){ constructor() : this("","","","","") }
D-Music-App/app/src/main/java/app/music/models/SongModel.kt
1078641852
package app.music.adapter import android.content.Intent import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView.Adapter import androidx.recyclerview.widget.RecyclerView.ViewHolder import app.music.MyExoPlayer import app.music.PlayerActivity import app.music.databinding.SongListItemBinding import app.music.models.SongModel import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.request.RequestOptions import com.google.firebase.firestore.FirebaseFirestore class SongsListAdapter(private val songIdList: List<String>): Adapter<SongsListAdapter.MyViewHolder>() { class MyViewHolder(private val binding: SongListItemBinding) : ViewHolder(binding.root){ fun bindData(songId:String){ FirebaseFirestore.getInstance().collection("songs") .document(songId).get() .addOnSuccessListener { val song = it.toObject(SongModel::class.java) song?.apply { binding.songTitleTextview.text = title binding.songSubtitleTextview.text = subtitle Glide.with(binding.songCoverImageview).load(coverUrl) .apply(RequestOptions().transform(RoundedCorners(32)) ) .into(binding.songCoverImageview) binding.root.setOnClickListener{ MyExoPlayer.startPlaying(binding.root.context, song) it.context.startActivity(Intent(it.context, PlayerActivity::class.java)) } } } binding.songTitleTextview.text = songId } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val binding = SongListItemBinding.inflate(LayoutInflater.from(parent.context),parent,false) return MyViewHolder(binding) } override fun getItemCount(): Int { return songIdList.size } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bindData(songIdList[position]) } }
D-Music-App/app/src/main/java/app/music/adapter/SongsListAdapter.kt
4123656777
package app.music.adapter import android.content.Intent import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import app.music.MyExoPlayer import app.music.PlayerActivity import app.music.databinding.SectionSongListItemBinding import app.music.models.SongModel import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.request.RequestOptions import com.google.firebase.firestore.FirebaseFirestore class SectionSongListAdapter(private val songIdList: List<String>): RecyclerView.Adapter<SectionSongListAdapter.MyViewHolder>() { class MyViewHolder(private val binding: SectionSongListItemBinding) : RecyclerView.ViewHolder(binding.root){ fun bindData(songId:String){ FirebaseFirestore.getInstance().collection("songs") .document(songId).get() .addOnSuccessListener { val song = it.toObject(SongModel::class.java) song?.apply { binding.songTitleTextview.text = title binding.songSubtitleTextview.text = subtitle Glide.with(binding.songCoverImageview).load(coverUrl) .apply( RequestOptions().transform(RoundedCorners(32)) ) .into(binding.songCoverImageview) binding.root.setOnClickListener{ MyExoPlayer.startPlaying(binding.root.context, song) it.context.startActivity(Intent(it.context, PlayerActivity::class.java)) } } } binding.songTitleTextview.text = songId } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val binding = SectionSongListItemBinding.inflate(LayoutInflater.from(parent.context),parent,false) return MyViewHolder(binding) } override fun getItemCount(): Int { return songIdList.size } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bindData(songIdList[position]) } }
D-Music-App/app/src/main/java/app/music/adapter/SectionSongListAdapter.kt
4065568652
package app.music.adapter import android.content.Intent import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView.Adapter import androidx.recyclerview.widget.RecyclerView.ViewHolder import app.music.SongsListActivity import app.music.databinding.CategoryItemBinding import app.music.models.CategoryModel import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.request.RequestOptions class CategoryAdapter(private val categoryList: List<CategoryModel>) : Adapter<CategoryAdapter.MyViewHolder>() { class MyViewHolder(private val binding : CategoryItemBinding) : ViewHolder(binding.root){ fun bindData(category: CategoryModel){ binding.nameTextView.text = category.name Glide.with(binding.coverImageView).load(category.coverUrl) .apply( RequestOptions().transform(RoundedCorners(32)) ) .into(binding.coverImageView) //Start SongsList Activity //Log.i("SONGS", category.songs.size.toString()) val context = binding.root.context binding.root.setOnClickListener { SongsListActivity.category = category context.startActivity(Intent(context, SongsListActivity::class.java)) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder { val binding = CategoryItemBinding.inflate(LayoutInflater.from(parent.context),parent,false) return MyViewHolder(binding) } override fun getItemCount(): Int { return categoryList.size } override fun onBindViewHolder(holder: MyViewHolder, position: Int) { holder.bindData(categoryList[position]) } }
D-Music-App/app/src/main/java/app/music/adapter/CategoryAdapter.kt
232335254
package app.music import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Patterns import android.view.View import android.widget.Toast import app.music.databinding.ActivityLoginBinding import com.google.firebase.auth.FirebaseAuth import java.util.regex.Pattern class LoginActivity : AppCompatActivity() { lateinit var binding: ActivityLoginBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityLoginBinding.inflate(layoutInflater) setContentView(binding.root) binding.loginBtn.setOnClickListener{ val email = binding.emailEdittext.text.toString() val password = binding.passwordEdittext.text.toString() if(!Pattern.matches(Patterns.EMAIL_ADDRESS.pattern(), email)){ binding.emailEdittext.setError("Invalid email") return@setOnClickListener } if(password.length<6){ binding.passwordEdittext.setError("Length should be 6 char") return@setOnClickListener } loginWithFirebase(email, password) } binding.gotoSignupBtn.setOnClickListener { startActivity(Intent(this, SignUpActivity::class.java)) } } fun loginWithFirebase(email: String, password: String){ setInProgress(true) FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password) .addOnSuccessListener { setInProgress(false) startActivity(Intent(this@LoginActivity, MainActivity::class.java)) finish() //Toast.makeText(applicationContext, "User login successfully", Toast.LENGTH_SHORT).show() }.addOnFailureListener{ setInProgress(false) Toast.makeText(applicationContext, "Login account failed", Toast.LENGTH_SHORT).show() } } fun setInProgress(inProgress: Boolean){ if(inProgress){ binding.loginBtn.visibility = View.GONE binding.progressBar.visibility = View.VISIBLE }else{ binding.loginBtn.visibility = View.VISIBLE binding.progressBar.visibility = View.GONE } } override fun onResume() { super.onResume() FirebaseAuth.getInstance().currentUser?.apply { startActivity(Intent(this@LoginActivity, MainActivity::class.java)) finish() } } }
D-Music-App/app/src/main/java/app/music/LoginActivity.kt
2394837241
package app.music import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Patterns import android.view.View import android.widget.Toast import app.music.databinding.ActivitySignUpBinding import com.google.firebase.auth.FirebaseAuth import java.util.regex.Pattern class SignUpActivity : AppCompatActivity() { lateinit var binding: ActivitySignUpBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySignUpBinding.inflate(layoutInflater) setContentView(binding.root) binding.createAccountBtn.setOnClickListener{ val email = binding.emailEdittext.text.toString() val password = binding.passwordEdittext.text.toString() val confirmPassword = binding.confirmPasswordEdittext.text.toString() if(!Pattern.matches(Patterns.EMAIL_ADDRESS.pattern(), email)){ binding.emailEdittext.setError("Invalid email") return@setOnClickListener } if(password.length<6){ binding.passwordEdittext.setError("Length should be 6 char") return@setOnClickListener } if(!password.equals(confirmPassword)){ binding.confirmPasswordEdittext.setError("Password not matched") return@setOnClickListener } createAccountWithFirebase(email, password) } binding.gotoLoginBtn.setOnClickListener { finish() } } fun createAccountWithFirebase(email: String, password: String){ setInProgress(true) FirebaseAuth.getInstance().createUserWithEmailAndPassword(email, password) .addOnSuccessListener { setInProgress(false) Toast.makeText(applicationContext, "User created successfully", Toast.LENGTH_SHORT).show() finish() }.addOnFailureListener{ setInProgress(false) Toast.makeText(applicationContext, "Create account failed", Toast.LENGTH_SHORT).show() } } fun setInProgress(inProgress: Boolean){ if(inProgress){ binding.createAccountBtn.visibility = View.GONE binding.progressBar.visibility = View.VISIBLE }else{ binding.createAccountBtn.visibility = View.VISIBLE binding.progressBar.visibility = View.GONE } } }
D-Music-App/app/src/main/java/app/music/SignUpActivity.kt
353577057
package app.music import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import app.music.adapter.SongsListAdapter import app.music.databinding.ActivitySongsListBinding import app.music.models.CategoryModel import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.bitmap.RoundedCorners import com.bumptech.glide.request.RequestOptions class SongsListActivity : AppCompatActivity() { lateinit var binding: ActivitySongsListBinding lateinit var songsListAdapter: SongsListAdapter companion object{ lateinit var category: CategoryModel } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivitySongsListBinding.inflate(layoutInflater) setContentView(binding.root) binding.nameTextView.text = category.name Glide.with(binding.coverImageView).load(category.coverUrl) .apply( RequestOptions().transform(RoundedCorners(32)) ) .into(binding.coverImageView) setupSongsListRecyclerView() } fun setupSongsListRecyclerView(){ songsListAdapter = SongsListAdapter(category.songs) binding.songListRecyclerView.layoutManager = LinearLayoutManager(this) binding.songListRecyclerView.adapter = songsListAdapter } }
D-Music-App/app/src/main/java/app/music/SongsListActivity.kt
475267193
package com.example.androidappincubator import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.androidappincubator", appContext.packageName) } }
Android-App-Incubator/app/src/androidTest/java/com/example/androidappincubator/ExampleInstrumentedTest.kt
4277374291
package com.example.androidappincubator import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Android-App-Incubator/app/src/test/java/com/example/androidappincubator/ExampleUnitTest.kt
3414757229
package com.example.androidappincubator import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } }
Android-App-Incubator/app/src/main/java/com/example/androidappincubator/MainActivity.kt
3045069989
package com.gyub.kkangtongdummy import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.gyub.kkangtongdummy", appContext.packageName) } }
Clone-Fashion-APP/app/src/androidTest/java/com/gyub/kkangtongdummy/ExampleInstrumentedTest.kt
3159456744
package com.gyub.kkangtongdummy import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
Clone-Fashion-APP/app/src/test/java/com/gyub/kkangtongdummy/ExampleUnitTest.kt
1837338808
package com.gyub.kkangtongdummy.ui.theme import androidx.compose.ui.graphics.Color val White = Color(0xFFFFFFFF) val Black = Color(0xFF000000) val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260) val Gray01 = Color(0xFFF1F3F7) val Gray02 = Color(0xFFE6E9EE) val Gray03 = Color(0xFFDCE0E5) val Gray04 = Color(0xFFCED3D9) val Gray05 = Color(0xFFC0C6CC) val Gray06 = Color(0xFFA1A8AF) val Gray07 = Color(0xFF868C95) val Gray08 = Color(0xFF697077) val Gray09 = Color(0xFF5B6167) val Gray10 = Color(0xFF4D5358) val Gray11 = Color(0xFF343A3F) val Gray12 = Color(0xFF21272A) val Gray13 = Color(0xFF121619)
Clone-Fashion-APP/app/src/main/java/com/gyub/kkangtongdummy/ui/theme/Color.kt
438045767
package com.gyub.kkangtongdummy.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun KkangTongDummyTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current dynamicLightColorScheme(context) // if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } // darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
Clone-Fashion-APP/app/src/main/java/com/gyub/kkangtongdummy/ui/theme/Theme.kt
2178582891
package com.gyub.kkangtongdummy.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
Clone-Fashion-APP/app/src/main/java/com/gyub/kkangtongdummy/ui/theme/Type.kt
4204328513
@file:OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterial3Api::class) package com.gyub.kkangtongdummy.home import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent 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.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size 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.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.gyub.kkangtongdummy.R import com.gyub.kkangtongdummy.ui.theme.Gray05 import com.gyub.kkangtongdummy.ui.theme.Gray13 import com.gyub.kkangtongdummy.ui.theme.KkangTongDummyTheme import com.gyub.kkangtongdummy.ui.theme.White /** * MainActivity * * @author Gyul * @created 2023/11/25 */ class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { KkangTongDummyTheme { Surface(modifier = Modifier.fillMaxSize(), color = White) { HomeScreen() } } } } } @Preview @Composable fun HomeScreenPreview() { HomeScreen() } @Composable fun HomeScreen() { val apps = remember { listOf( AppViewState("세컨웨어", true), AppViewState("Comming Soon", false), AppViewState("Comming Soon", false), AppViewState("Comming Soon", false), AppViewState("Comming Soon", false), AppViewState("Comming Soon", false), AppViewState("Comming Soon", false), AppViewState("Comming Soon", false), ) } Scaffold( topBar = { TopAppBar( title = { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center ) { Text( text = stringResource(R.string.title_home), color = Color.White, modifier = Modifier.padding(top = 5.dp) ) } }, ) } ) { paddingValues -> Box( modifier = Modifier.padding(paddingValues) ) { Column { LazyVerticalGrid( columns = GridCells.Fixed(3), contentPadding = PaddingValues(3.dp), ) { items(apps) { appState -> val backGroundColor = if (appState.isEnable) Gray13 else Gray05 Button( onClick = {}, shape = RoundedCornerShape(10.dp), colors = ButtonDefaults.buttonColors(containerColor = backGroundColor), modifier = Modifier .size(100.dp) .padding(10.dp) ) { Text( text = appState.appName, textAlign = TextAlign.Center, fontSize = 12.sp ) } } } } } } } data class AppViewState( val appName: String = "", val isEnable: Boolean = false )
Clone-Fashion-APP/app/src/main/java/com/gyub/kkangtongdummy/home/MainActivity.kt
3718605700
package com.gyub.kkangtongdummy.secondware.di import android.util.Log import com.google.gson.Gson import com.gyub.kkangtongdummy.secondware.network.ApiUrl.BASE_URL import com.gyub.kkangtongdummy.secondware.network.NetworkUtil import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Named import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Singleton @Provides @Named("RetrofitInterceptor") fun provideRetrofitInterceptor(): HttpLoggingInterceptor { return HttpLoggingInterceptor { message -> Log.d("SecondWare", "### Retrofit -- ${NetworkUtil.getPrettyLogs(message)}") } } @Singleton @Provides fun provideOkHttpClient( @Named("RetrofitInterceptor") interceptor: HttpLoggingInterceptor ): OkHttpClient { return OkHttpClient.Builder() .addInterceptor(NetworkUtil.createHeader()) .addInterceptor(interceptor) .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .build() } @Singleton @Provides fun provideGson() = Gson() @Singleton @Provides fun provideRetrofit( okHttpClient: OkHttpClient, gson: Gson, ): Retrofit.Builder { return Retrofit.Builder() .baseUrl(BASE_URL) .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create(gson)) } }
Clone-Fashion-APP/app/src/main/java/com/gyub/kkangtongdummy/secondware/di/NetworkModule.kt
534541795
package com.gyub.kkangtongdummy.secondware.di import dagger.Provides import retrofit2.Retrofit import javax.inject.Singleton object ApiServiceModule { // @Singleton // @Provides // fun provideAuthService(retrofit: Retrofit.Builder): AuthService { // return retrofit // .build() // .create(AuthService::class.java) // } }
Clone-Fashion-APP/app/src/main/java/com/gyub/kkangtongdummy/secondware/di/ApiServiceModule.kt
2754104344
package com.gyub.kkangtongdummy.secondware.network import com.google.gson.Gson import com.google.gson.GsonBuilder import com.google.gson.JsonParser import okhttp3.Interceptor import java.util.Locale object NetworkUtil { fun getPrettyLogs(text: String?): String { text ?: return "" return try { val jsonElement = JsonParser().parse(text) val gson: Gson = GsonBuilder().setPrettyPrinting().create() gson.toJson(jsonElement) } catch (e: Throwable) { text } } /** * 헤더 세팅 * * @return */ fun createHeader() = Interceptor { chain: Interceptor.Chain -> val original = chain.request() val builder = original.newBuilder().apply { getHeaders().forEach { (key, value) -> header(key, value) } if ("POST" == original.method || "PUT" == original.method) { header("content-type", "application/x-www-form-urlencoded") } original.headers["Accept-Encoding"]?.let { header("content-type", "application/json") } } chain.proceed(builder.build()) } private fun getHeaders(): Map<String, String> { return mapOf( "Accept-Language" to Locale.getDefault().language, "Accept" to "application/json", ) } }
Clone-Fashion-APP/app/src/main/java/com/gyub/kkangtongdummy/secondware/network/NetworkUtil.kt
2478457221
package com.gyub.kkangtongdummy.secondware.network import android.util.Log import com.fasterxml.jackson.annotation.JsonAutoDetect import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.jackson.JacksonConverterFactory import java.util.Locale import java.util.concurrent.TimeUnit object RetrofitClient { private const val METHOD_POST = "POST" const val METHOD_PUT = "PUT" /** * 공통 헤더 Interceptor */ private val gHeaderInterceptor = Interceptor { chain: Interceptor.Chain -> val original = chain.request() var request: Request? = null try { var builder: Request.Builder = original.newBuilder() .header(Headers.ACCEPT_LANGUAGE, Locale.getDefault().language) .header(Headers.ACCEPT, "application/json") .method(original.method, original.body) if (original.headers["Accept-Encoding"] != null) { builder = builder.header("Content-type", "application/json") } else if (METHOD_POST == original.method || METHOD_PUT == original.method) { builder = builder.header(Headers.CONTENT_TYPE, "application/x-www-form-urlencoded") } request = builder.build() } catch (e: Exception) { Log.e(e.message, e.cause?.message, e.cause) } chain.proceed(request!!) } private val gLogging: HttpLoggingInterceptor by lazy { HttpLoggingInterceptor() } private var gRetrofitClient: Retrofit? = null /** * Singleton Retrofit * * @return */ fun getClient(): Retrofit? { if (gRetrofitClient == null) { synchronized(RetrofitClient::class.java) { if (gRetrofitClient == null) { val okClient = unsafeOkHttpClient val objectMapper = ObjectMapper() objectMapper.setVisibility(objectMapper.visibilityChecker.withFieldVisibility(JsonAutoDetect.Visibility.ANY)) objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false) val converter = JacksonConverterFactory.create(objectMapper) gRetrofitClient = Retrofit.Builder() .baseUrl(ApiUrl.BASE_URL) .client(okClient) .addConverterFactory(converter) .build() } } } return gRetrofitClient } private val unsafeOkHttpClient: OkHttpClient get() = try { OkHttpClient.Builder() .addInterceptor(gHeaderInterceptor) .addInterceptor(gLogging) // .addNetworkInterceptor(new StethoInterceptor()) .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(60, TimeUnit.SECONDS) .writeTimeout(60, TimeUnit.SECONDS) .build() } catch (e: Exception) { throw RuntimeException(e) } /** * 헤더 정의 */ object Headers { const val ACCEPT_LANGUAGE = "Accept-Language" const val ACCEPT = "Accept" const val CONTENT_TYPE = "content-type" } }
Clone-Fashion-APP/app/src/main/java/com/gyub/kkangtongdummy/secondware/network/RetrofitClient.kt
2163164822
package com.gyub.kkangtongdummy.secondware.network object ApiUrl { const val BASE_URL = "https://653e0936f52310ee6a9a7c37.mockapi.io/gyub/" }
Clone-Fashion-APP/app/src/main/java/com/gyub/kkangtongdummy/secondware/network/ApiUrl.kt
3591292808
package com.example.diceroller import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.diceroller", appContext.packageName) } }
kotlin_task_5_Building-app-UI/DiceRoller/app/src/androidTest/java/com/example/diceroller/ExampleInstrumentedTest.kt
2731144987
package com.example.diceroller import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
kotlin_task_5_Building-app-UI/DiceRoller/app/src/test/java/com/example/diceroller/ExampleUnitTest.kt
1412805653
package com.example.diceroller.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)
kotlin_task_5_Building-app-UI/DiceRoller/app/src/main/java/com/example/diceroller/ui/theme/Color.kt
2898381871
package com.example.diceroller.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun DiceRollerTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
kotlin_task_5_Building-app-UI/DiceRoller/app/src/main/java/com/example/diceroller/ui/theme/Theme.kt
751687589
package com.example.diceroller.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
kotlin_task_5_Building-app-UI/DiceRoller/app/src/main/java/com/example/diceroller/ui/theme/Type.kt
2881408862
package com.example.diceroller import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.Button import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.example.diceroller.ui.theme.DiceRollerTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { DiceRollerTheme { DiceRollerApp() } } } } @Preview @Composable fun DiceRollerApp() { DiceWithButtonAndImage(modifier = Modifier .fillMaxSize() .wrapContentSize(Alignment.Center) )} @Composable fun DiceWithButtonAndImage(modifier: Modifier = Modifier) { var result by remember { mutableStateOf(1) } val imageResource = when (result) { 1 -> R.drawable.dice_1 2 -> R.drawable.dice_2 3 -> R.drawable.dice_3 4 -> R.drawable.dice_4 5 -> R.drawable.dice_5 else -> R.drawable.dice_6 } Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally ) { Image(painter = painterResource(id = imageResource), contentDescription = result.toString()) Spacer(modifier = Modifier.height(16.dp)) Button(onClick = { result = (1..6).random() }) { Text(stringResource(R.string.roll)) } } }
kotlin_task_5_Building-app-UI/DiceRoller/app/src/main/java/com/example/diceroller/MainActivity.kt
3269374856
package com.example.myapplication import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.myapplication", appContext.packageName) } }
kotlin_task_5_Building-app-UI/Calculator/app/src/androidTest/java/com/example/myapplication/ExampleInstrumentedTest.kt
1188990709
package com.example.myapplication import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
kotlin_task_5_Building-app-UI/Calculator/app/src/test/java/com/example/myapplication/ExampleUnitTest.kt
2019423820
package com.example.myapplication.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)
kotlin_task_5_Building-app-UI/Calculator/app/src/main/java/com/example/myapplication/ui/theme/Color.kt
2513741509
package com.example.myapplication.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun MyApplicationTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
kotlin_task_5_Building-app-UI/Calculator/app/src/main/java/com/example/myapplication/ui/theme/Theme.kt
196007232
package com.example.myapplication.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
kotlin_task_5_Building-app-UI/Calculator/app/src/main/java/com/example/myapplication/ui/theme/Type.kt
3481532690
package com.example.myapplication import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.annotation.DrawableRes import androidx.annotation.StringRes import androidx.annotation.VisibleForTesting import androidx.activity.enableEdgeToEdge import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.statusBarsPadding import androidx.compose.foundation.layout.wrapContentWidth import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import java.text.NumberFormat class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { enableEdgeToEdge() super.onCreate(savedInstanceState) setContent { Surface( modifier = Modifier.fillMaxSize(), ) { CalculatorLayout() } } } } @Composable fun CalculatorLayout() { var amountInput by remember { mutableStateOf("") } var tipInput by remember { mutableStateOf("") } var roundUp by remember { mutableStateOf(false) } val amount = amountInput.toDoubleOrNull() ?: 0.0 val tipPercent = tipInput.toDoubleOrNull() ?: 0.0 val tip = calculateTip(amount, tipPercent, roundUp) Column( modifier = Modifier .statusBarsPadding() .padding(horizontal = 40.dp) .verticalScroll(rememberScrollState()) .safeDrawingPadding(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Text( text = stringResource(R.string.calculate_tip), modifier = Modifier .padding(bottom = 16.dp, top = 40.dp) .align(alignment = Alignment.Start) ) EditNumberField( label = R.string.bill_amount, leadingIcon = R.drawable.money, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Next ), value = amountInput, onValueChanged = { amountInput = it }, modifier = Modifier.padding(bottom = 32.dp).fillMaxWidth(), ) EditNumberField( label = R.string.how_was_the_service, leadingIcon = R.drawable.percent, keyboardOptions = KeyboardOptions.Default.copy( keyboardType = KeyboardType.Number, imeAction = ImeAction.Done ), value = tipInput, onValueChanged = { tipInput = it }, modifier = Modifier.padding(bottom = 32.dp).fillMaxWidth(), ) RoundTheTipRow( roundUp = roundUp, onRoundUpChanged = { roundUp = it }, modifier = Modifier.padding(bottom = 32.dp) ) Text( text = stringResource(R.string.tip_amount, tip), style = MaterialTheme.typography.displaySmall ) Spacer(modifier = Modifier.height(150.dp)) } } @Composable fun EditNumberField( @StringRes label: Int, @DrawableRes leadingIcon: Int, keyboardOptions: KeyboardOptions, value: String, onValueChanged: (String) -> Unit, modifier: Modifier = Modifier ) { TextField( value = value, singleLine = true, leadingIcon = { Icon(painter = painterResource(id = leadingIcon), null) }, modifier = modifier, onValueChange = onValueChanged, label = { Text(stringResource(label)) }, keyboardOptions = keyboardOptions ) } @Composable fun RoundTheTipRow( roundUp: Boolean, onRoundUpChanged: (Boolean) -> Unit, modifier: Modifier = Modifier ) { Row( modifier = modifier .fillMaxWidth() .size(48.dp), verticalAlignment = Alignment.CenterVertically ) { Text(text = stringResource(R.string.round_up_tip)) Switch( modifier = Modifier .fillMaxWidth() .wrapContentWidth(Alignment.End), checked = roundUp, onCheckedChange = onRoundUpChanged ) } } @VisibleForTesting internal fun calculateTip(amount: Double, tipPercent: Double = 15.0, roundUp: Boolean): String { var tip = tipPercent / 100 * amount if (roundUp) { tip = kotlin.math.ceil(tip) } return NumberFormat.getCurrencyInstance().format(tip) } @Preview(showBackground = true) @Composable fun CalculatorLayoutPreview() { CalculatorLayout() }
kotlin_task_5_Building-app-UI/Calculator/app/src/main/java/com/example/myapplication/MainActivity.kt
1693653678
// // 2. Mobile notifications // fun main() { // val morningNotification = 51 // val eveningNotification = 135 // printNotificationSummary(morningNotification) // printNotificationSummary(eveningNotification) // } // fun printNotificationSummary(numberOfMessages: Int) { // if (numberOfMessages < 100) { // println("You have ${numberOfMessages} notifications.") // } else { // println("Your phone is blowing up! You have 99+ notifications.") // } // } // // 3. Movie-ticket price // fun main() { // val child = 5 // val adult = 28 // val senior = 87 // val isMonday = true // println("The movie ticket price for a person aged $child is \$${ticketPrice(child, isMonday)}.") // println("The movie ticket price for a person aged $adult is \$${ticketPrice(adult, isMonday)}.") // println("The movie ticket price for a person aged $senior is \$${ticketPrice(senior, isMonday)}.") // } // fun ticketPrice(age: Int, isMonday: Boolean): Int { // return when(age) { // in 0..12 -> 15 // in 13..60 -> if (isMonday) 25 else 30 // in 61..100 -> 20 // else -> -1 // } // } // // 4. Temperature converter // fun main() { // printFinalTemperature(27.0, "Celsius", "Fahrenheit") { 9.0 / 5.0 * it + 32 } // printFinalTemperature(350.0, "Kelvin", "Celsius") { it - 273.15 } // printFinalTemperature(10.0, "Fahrenheit", "Kelvin") { 5.0 / 9.0 * (it - 32) + 273.15 } // } // fun printFinalTemperature( // initialMeasurement: Double, // initialUnit: String, // finalUnit: String, // conversionFormula: (Double) -> Double // ) { // val finalMeasurement = String.format("%.2f", conversionFormula(initialMeasurement)) // two decimal places // println("$initialMeasurement degrees $initialUnit is $finalMeasurement degrees $finalUnit.") // } // // 5. Song catalog // fun main() { // val brunoSong = Song("We Don't Talk About Bruno", "Encanto Cast", 2022, 1_000_000) // brunoSong.printDescription() // println(brunoSong.isPopular) // } // class Song( // val title: String, // val artist: String, // val yearPublished: Int, // val playCount: Int // ){ // val isPopular: Boolean // get() = playCount >= 1000 // fun printDescription() { // println("$title, performed by $artist, was released in $yearPublished.") // } // } // // 6. Internet profile // fun main() { // val amanda = Person("Amanda", 33, "play tennis", null) // val atiqah = Person("Atiqah", 28, "climb", amanda) // amanda.showProfile() // atiqah.showProfile() // } // class Person(val name: String, val age: Int, val hobby: String?, val referrer: Person?) { // fun showProfile() { // println("Name: $name") // println("Age: $age") // if(hobby != null) { // print("Likes to $hobby. ") // } // if(referrer != null) { // print("Has a referrer named ${referrer.name}") // if(referrer.hobby != null) { // print(", who likes to ${referrer.hobby}.") // } else { // print(".") // } // } else { // print("Doesn't have a referrer.") // } // print("\n\n") // } // } // // 7. Foldable phones // open class Phone(var isScreenLightOn: Boolean = false){ // open fun switchOn() { // isScreenLightOn = true // } // fun switchOff() { // isScreenLightOn = false // } // fun checkPhoneScreenLight() { // val phoneScreenLight = if (isScreenLightOn) "on" else "off" // println("The phone screen's light is $phoneScreenLight.") // } // } // class FoldablePhone(var isFolded: Boolean = true): Phone() { // override fun switchOn() { // if (!isFolded) { // isScreenLightOn = true // } // } // fun fold() { // isFolded = true // } // fun unfold() { // isFolded = false // } // } // fun main() { // val newFoldablePhone = FoldablePhone() // newFoldablePhone.switchOn() // newFoldablePhone.checkPhoneScreenLight() // newFoldablePhone.unfold() // newFoldablePhone.switchOn() // newFoldablePhone.checkPhoneScreenLight() // } // // 8. Special auction fun main() { val winningBid = Bid(5000, "Private Collector") println("Item A is sold at ${auctionPrice(winningBid, 2000)}.") println("Item B is sold at ${auctionPrice(null, 3000)}.") } class Bid(val amount: Int, val bidder: String) fun auctionPrice(bid: Bid?, minimumPrice: Int): Int { return bid?.amount ?: minimumPrice }
kotlin_task_5_Building-app-UI/Practice Kotlin Fundamentals.kt
1133142084
package com.example.lemonade import androidx.test.platform.app.InstrumentationRegistry import androidx.test.ext.junit.runners.AndroidJUnit4 import org.junit.Test import org.junit.runner.RunWith import org.junit.Assert.* /** * Instrumented test, which will execute on an Android device. * * See [testing documentation](http://d.android.com/tools/testing). */ @RunWith(AndroidJUnit4::class) class ExampleInstrumentedTest { @Test fun useAppContext() { // Context of the app under test. val appContext = InstrumentationRegistry.getInstrumentation().targetContext assertEquals("com.example.lemonade", appContext.packageName) } }
kotlin_task_5_Building-app-UI/Lemonade/app/src/androidTest/java/com/example/lemonade/ExampleInstrumentedTest.kt
2320908135
package com.example.lemonade import org.junit.Test import org.junit.Assert.* /** * Example local unit test, which will execute on the development machine (host). * * See [testing documentation](http://d.android.com/tools/testing). */ class ExampleUnitTest { @Test fun addition_isCorrect() { assertEquals(4, 2 + 2) } }
kotlin_task_5_Building-app-UI/Lemonade/app/src/test/java/com/example/lemonade/ExampleUnitTest.kt
4073365401
package com.example.lemonade.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)
kotlin_task_5_Building-app-UI/Lemonade/app/src/main/java/com/example/lemonade/ui/theme/Color.kt
2678759376
package com.example.lemonade.ui.theme import android.app.Activity import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.runtime.SideEffect import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalView import androidx.core.view.WindowCompat private val DarkColorScheme = darkColorScheme( primary = Purple80, secondary = PurpleGrey80, tertiary = Pink80 ) private val LightColorScheme = lightColorScheme( primary = Purple40, secondary = PurpleGrey40, tertiary = Pink40 /* Other default colors to override background = Color(0xFFFFFBFE), surface = Color(0xFFFFFBFE), onPrimary = Color.White, onSecondary = Color.White, onTertiary = Color.White, onBackground = Color(0xFF1C1B1F), onSurface = Color(0xFF1C1B1F), */ ) @Composable fun LemonadeTheme( darkTheme: Boolean = isSystemInDarkTheme(), // Dynamic color is available on Android 12+ dynamicColor: Boolean = true, content: @Composable () -> Unit ) { val colorScheme = when { dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { val context = LocalContext.current if (darkTheme) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) } darkTheme -> DarkColorScheme else -> LightColorScheme } val view = LocalView.current if (!view.isInEditMode) { SideEffect { val window = (view.context as Activity).window window.statusBarColor = colorScheme.primary.toArgb() WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = darkTheme } } MaterialTheme( colorScheme = colorScheme, typography = Typography, content = content ) }
kotlin_task_5_Building-app-UI/Lemonade/app/src/main/java/com/example/lemonade/ui/theme/Theme.kt
2612359972
package com.example.lemonade.ui.theme import androidx.compose.material3.Typography import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.sp // Set of Material typography styles to start with val Typography = Typography( bodyLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 16.sp, lineHeight = 24.sp, letterSpacing = 0.5.sp ) /* Other default text styles to override titleLarge = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Normal, fontSize = 22.sp, lineHeight = 28.sp, letterSpacing = 0.sp ), labelSmall = TextStyle( fontFamily = FontFamily.Default, fontWeight = FontWeight.Medium, fontSize = 11.sp, lineHeight = 16.sp, letterSpacing = 0.5.sp ) */ )
kotlin_task_5_Building-app-UI/Lemonade/app/src/main/java/com/example/lemonade/ui/theme/Type.kt
2539446318
package com.example.lemonade import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent 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.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Button import androidx.compose.material3.ButtonDefaults import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { LemonadeApp() } } } @OptIn(ExperimentalMaterial3Api::class) @Composable fun LemonadeApp() { var currentStep by remember { mutableStateOf(1) } var squeezeCount by remember { mutableStateOf(0) } Scaffold( topBar = { CenterAlignedTopAppBar( title = { Text( text = "Lemonade", fontWeight = FontWeight.Bold ) }, colors = TopAppBarDefaults.smallTopAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer, navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer, actionIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer ) ) } ) { innerPadding -> Surface( modifier = Modifier .fillMaxSize() .padding(innerPadding) .background(MaterialTheme.colorScheme.tertiaryContainer), color = MaterialTheme.colorScheme.background ) { when (currentStep) { 1 -> { LemonTextAndImage( textLabelResourceId = R.string.lemon_select, drawableResourceId = R.drawable.lemon_tree, contentDescriptionResourceId = R.string.lemon_tree_content_description, onImageClick = { currentStep = 2 squeezeCount = (2..4).random() } ) } 2 -> { LemonTextAndImage( textLabelResourceId = R.string.lemon_squeeze, drawableResourceId = R.drawable.lemon_squeeze, contentDescriptionResourceId = R.string.lemon_content_description, onImageClick = { squeezeCount-- if (squeezeCount == 0) { currentStep = 3 } } ) } 3 -> { LemonTextAndImage( textLabelResourceId = R.string.lemon_drink, drawableResourceId = R.drawable.lemon_drink, contentDescriptionResourceId = R.string.lemonade_content_description, onImageClick = { currentStep = 4 } ) } 4 -> { LemonTextAndImage( textLabelResourceId = R.string.lemon_empty_glass, drawableResourceId = R.drawable.lemon_restart, contentDescriptionResourceId = R.string.empty_glass_content_description, onImageClick = { currentStep = 1 } ) } } } } } @Composable fun LemonTextAndImage( textLabelResourceId: Int, drawableResourceId: Int, contentDescriptionResourceId: Int, onImageClick: () -> Unit, modifier: Modifier = Modifier ) { Box( modifier = modifier ) { Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier.fillMaxSize() ) { Button( onClick = onImageClick, shape = RoundedCornerShape(dimensionResource(R.dimen.button_corner_radius)), colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.tertiaryContainer) ) { Image( painter = painterResource(drawableResourceId), contentDescription = stringResource(contentDescriptionResourceId), modifier = Modifier .width(dimensionResource(R.dimen.button_image_width)) .height(dimensionResource(R.dimen.button_image_height)) .padding(dimensionResource(R.dimen.button_interior_padding)) ) } Spacer(modifier = Modifier.height(dimensionResource(R.dimen.padding_vertical))) Text( text = stringResource(textLabelResourceId), style = MaterialTheme.typography.bodyLarge ) } } } @Preview @Composable fun LemonPreview() { LemonadeApp() }
kotlin_task_5_Building-app-UI/Lemonade/app/src/main/java/com/example/lemonade/MainActivity.kt
906155057
// // 2. Use nullable variables // fun main() { // var number: Int? = 10 // println(number) // 10 // number = null // println(number) // null // } // // 3. Handle nullable variables // fun main() { // var favoriteActor: String = "Sandra Oh" // println(favoriteActor.length) // 9 // } // fun main() { // //var favoriteActor: String? = "Sandra Oh" // var favoriteActor: String? = null // println(favoriteActor?.length) // } // fun main() { // //var favoriteActor: String? = "Sandra Oh" // var favoriteActor: String? = null // println(favoriteActor!!.length) // ошибка при null // } // fun main() { // var favoriteActor: String? = null // //var favoriteActor: String? = "Sandra Oh" // if(favoriteActor != null) { // println("The number of characters in your favorite actor's name is ${favoriteActor.length}.") // } else { // println("You didn't input a name.") // } // } // fun main() { // var favoriteActor: String? = "Sandra Oh" // val lengthOfName = if (favoriteActor != null) { // favoriteActor.length // } else { // 0 // } // println("The number of characters in your favorite actor's name is $lengthOfName.") // } fun main() { var favoriteActor: String? = "Sandra Oh" val lengthOfName = favoriteActor?.length ?: 0 println("The number of characters in your favorite actor's name is $lengthOfName.") // 9 }
kotlin_task_5_Building-app-UI/Use nullability in Kotlin.kt
1505249344
// // 2. Use if/else statements to express conditions // val number = 1 // fun main() { // println(1 == 1) // true // } // fun main() { // println(1 < 1) // false // } // fun main() { // val trafficLightColor = "Red" // if (trafficLightColor == "Red") { // println("Stop") // stop, потому что trafficLightColor = Red // } // } // fun main() { // //val trafficLightColor = "Red" // val trafficLightColor = "Green" // if (trafficLightColor == "Red") { // println("Stop") // выведет Stop при Red // } else { // println("Go") // Выведет go при Green // } // } // fun main() { // val trafficLightColor = "Yellow" // if (trafficLightColor == "Red") { // println("Stop") // } else if (trafficLightColor == "Yellow") { // println("Slow") // выведет Slow, потому что trafficLightColor = Yellow // } else { // println("Go") // } // } // fun main() { // val trafficLightColor = "Black" // // val trafficLightColor = "Yellow" // // val trafficLightColor = "Green" // if (trafficLightColor == "Red") { // println("Stop") // } else if (trafficLightColor == "Yellow") { // println("Slow") // } else if (trafficLightColor == "Green") { // println("Go") // } else { // println("Invalid traffic-light color") // при Black // } // } // // 3. Use a when statement for multiple branches // fun main() { // val trafficLightColor = "Black" // // val trafficLightColor = "Yellow" // when (trafficLightColor) { // "Red" -> println("Stop") // "Yellow" -> println("Slow") // "Green" -> println("Go") // else -> println("Invalid traffic-light color") // } // } // fun main() { // val x = 3 // when (x) { // 2 -> println("x is a prime number between 1 and 10.") // 3 -> println("x is a prime number between 1 and 10.") // 5 -> println("x is a prime number between 1 and 10.") // 7 -> println("x is a prime number between 1 and 10.") // else -> println("x isn't a prime number between 1 and 10.") // } // } // fun main() { // val x = 3 // // val x = 5 // // val x = 7 // when (x) { // 2, 3, 5, 7 -> println("x is a prime number between 1 and 10.") // else -> println("x isn't a prime number between 1 and 10.") // } // } // fun main() { // val x = 4 // when (x) { // 2, 3, 5, 7 -> println("x is a prime number between 1 and 10.") // in 1..10 -> println("x is a number between 1 and 10, but not a prime number.") // else -> println("x isn't a prime number between 1 and 10.") // } // } // fun main() { // val x: Any = 20 // when (x) { // 2, 3, 5, 7 -> println("x is a prime number between 1 and 10.") // in 1..10 -> println("x is a number between 1 and 10, but not a prime number.") // is Int -> println("x is an integer number, but not between 1 and 10.") // else -> println("x isn't an integer number.") // } // } // fun main() { // val trafficLightColor = "Yellow" // // val trafficLightColor = "Amber" // when (trafficLightColor) { // "Red" -> println("Stop") // "Yellow", "Amber" -> println("Slow") // "Green" -> println("Go") // else -> println("Invalid traffic-light color") // } // } // 4. Use if/else and when as expressions fun main() { val trafficLightColor = "Amber" val message = when(trafficLightColor) { "Red" -> "Stop" "Yellow", "Amber" -> "Slow" "Green" -> "Go" else -> "Invalid traffic-light color" } println(message) // выведет Slow }
kotlin_task_5_Building-app-UI/Write conditionals in Kotlin.kt
572594193
import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty open class SmartDevice(val name: String, val category: String) { var deviceStatus = "online" protected set open val deviceType = "unknown" open fun printDeviceInfo() { println("Device name: $name, category: $category, type: $deviceType") } open fun turnOn() { deviceStatus = "on" } open fun turnOff() { deviceStatus = "off" } } class SmartTvDevice(deviceName: String, deviceCategory: String) : SmartDevice(name = deviceName, category = deviceCategory) { override val deviceType = "Smart TV" private var speakerVolume by RangeRegulator(initialValue = 2, minValue = 0, maxValue = 100) private var channelNumber by RangeRegulator(initialValue = 1, minValue = 0, maxValue = 200) fun decreaseVolume() { speakerVolume-- println("Speaker volume decreased to $speakerVolume.") } fun increaseSpeakerVolume() { speakerVolume++ println("Speaker volume increased to $speakerVolume.") } fun previousChannel() { channelNumber-- println("Channel number decreased to $channelNumber.") } fun nextChannel() { channelNumber++ println("Channel number increased to $channelNumber.") } override fun turnOn() { super.turnOn() println( "$name is turned on. Speaker volume is set to $speakerVolume and channel number is " + "set to $channelNumber." ) } override fun turnOff() { super.turnOff() println("$name turned off") } } class SmartLightDevice(deviceName: String, deviceCategory: String) : SmartDevice(name = deviceName, category = deviceCategory) { override val deviceType = "Smart Light" private var brightnessLevel by RangeRegulator(initialValue = 0, minValue = 0, maxValue = 100) fun increaseBrightness() { brightnessLevel++ println("Brightness increased to $brightnessLevel.") } fun decreaseBrightness() { brightnessLevel-- println("Brightness decreased to $brightnessLevel.") } override fun turnOn() { super.turnOn() brightnessLevel = 2 println("$name turned on. The brightness level is $brightnessLevel.") } override fun turnOff() { super.turnOff() brightnessLevel = 0 println("Smart Light turned off") } } class SmartHome( val smartTvDevice: SmartTvDevice, val smartLightDevice: SmartLightDevice, val smartdevice: SmartDevice ) { var deviceTurnOnCount = 0 private set fun turnOnTv() { if (smartTvDevice.deviceStatus == "on") { deviceTurnOnCount++ smartTvDevice.turnOn() } } fun turnOffTv() { if (smartTvDevice.deviceStatus == "on") { deviceTurnOnCount-- smartTvDevice.turnOff() } } fun increaseTvVolume() { if (smartTvDevice.deviceStatus == "on") { smartTvDevice.increaseSpeakerVolume() } } fun decreaseTvVolume() { if (smartTvDevice.deviceStatus == "on") { smartTvDevice.decreaseVolume() } } fun changeTvChannelToNext() { if (smartTvDevice.deviceStatus == "on") { smartTvDevice.nextChannel() } } fun changeTvChannelToPrevios() { if (smartTvDevice.deviceStatus == "on") { smartTvDevice.previousChannel() } } fun printSmartTvInfo() { if (smartTvDevice.deviceStatus == "on") { smartdevice.printDeviceInfo() } } fun printSmartLightInfo() { if (smartLightDevice.deviceStatus == "on") { smartdevice.printDeviceInfo() } } fun turnOnLight() { if (smartLightDevice.deviceStatus == "on") { deviceTurnOnCount++ smartLightDevice.turnOn() } } fun turnOffLight() { if (smartLightDevice.deviceStatus == "on") { deviceTurnOnCount-- smartLightDevice.turnOff() } } fun increaseLightBrightness() { if (smartLightDevice.deviceStatus == "on") { smartLightDevice.increaseBrightness() } } fun decreaseLightBrightness() { if (smartLightDevice.deviceStatus == "on") { smartLightDevice.decreaseBrightness() } } fun turnOffAllDevices() { turnOffTv() turnOffLight() } } class RangeRegulator( initialValue: Int, private val minValue: Int, private val maxValue: Int ) : ReadWriteProperty<Any?, Int> { var fieldData = initialValue override fun getValue(thisRef: Any?, property: KProperty<*>): Int { return fieldData } override fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) { if (value in minValue..maxValue) { fieldData = value } } } fun main() { val smartTvDevice = SmartTvDevice("Android TV", "Entertainment") smartTvDevice.turnOn() smartTvDevice.decreaseVolume() smartTvDevice.previousChannel() smartTvDevice.printDeviceInfo() val smartLightDevice = SmartLightDevice("Google Light", "Utility") smartLightDevice.turnOn() smartLightDevice.printDeviceInfo() smartLightDevice.decreaseBrightness() }
kotlin_task_5_Building-app-UI/Use classes and objects in Kotlin.kt
2759579200
package com.ranjs.expense.tracker import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class ExpenseTrackerApplicationTests { @Test fun contextLoads() { } }
kotlin-springBoot-mongoDB-demo/src/test/kotlin/com/ranjs/expense/tracker/ExpenseTrackerApplicationTests.kt
3351838743