path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/fireblade/effectivecamera/utils/AutoFitPreviewBuilder.kt | The-Shader | 199,191,831 | false | null | package com.fireblade.effectivecamera.utils
import android.content.Context
import android.graphics.Matrix
import android.hardware.display.DisplayManager
import android.util.Size
import android.view.*
import androidx.camera.core.Preview
import androidx.camera.core.PreviewConfig
import java.lang.ref.WeakReference
import java.util.*
class AutoFitPreviewBuilder private constructor(
config: PreviewConfig,
viewFinderRef: WeakReference<TextureView>
) {
val preview: Preview
private var bufferRotation = 0
private var viewFinderRotation: Int? = null
private var bufferDimens: Size = Size(0, 0)
private var viewFinderDimens: Size = Size(0, 0)
private var viewFinderDisplay: Int = -1
private lateinit var displayManager: DisplayManager
private val displayListener = object : DisplayManager.DisplayListener {
override fun onDisplayAdded(displayId: Int) = Unit
override fun onDisplayRemoved(displayId: Int) = Unit
override fun onDisplayChanged(displayId: Int) {
val viewFinder = viewFinderRef.get() ?: return
if (displayId == viewFinderDisplay) {
val display = displayManager.getDisplay(displayId)
val rotation = getDisplaySurfaceRotation(display)
updateTransform(viewFinder, rotation, bufferDimens, viewFinderDimens)
}
}
}
init {
// Make sure that the view finder reference is valid
val viewFinder = viewFinderRef.get() ?:
throw IllegalArgumentException("Invalid reference to view finder used")
// Initialize the display and rotation from texture view information
viewFinderDisplay = viewFinder.display.displayId
viewFinderRotation = getDisplaySurfaceRotation(viewFinder.display) ?: 0
// Initialize public use-case with the given config
preview = Preview(config)
// Every time the view finder is updated, recompute layout
preview.onPreviewOutputUpdateListener = Preview.OnPreviewOutputUpdateListener {
val viewFinder =
viewFinderRef.get() ?: return@OnPreviewOutputUpdateListener
// To update the SurfaceTexture, we have to remove it and re-add it
val parent = viewFinder.parent as ViewGroup
parent.removeView(viewFinder)
parent.addView(viewFinder, 0)
// Update internal texture
viewFinder.surfaceTexture = it.surfaceTexture
// Apply relevant transformations
bufferRotation = it.rotationDegrees
val rotation = getDisplaySurfaceRotation(viewFinder.display)
updateTransform(viewFinder, rotation, it.textureSize, viewFinderDimens)
}
// Every time the provided texture view changes, recompute layout
viewFinder.addOnLayoutChangeListener { view, left, top, right, bottom, _, _, _, _ ->
val viewFinder = view as TextureView
val newViewFinderDimens = Size(right - left, bottom - top)
val rotation = getDisplaySurfaceRotation(viewFinder.display)
updateTransform(viewFinder, rotation, bufferDimens, newViewFinderDimens)
}
// Every time the orientation of device changes, recompute layout
// NOTE: This is unnecessary if we listen to display orientation changes in the camera
// fragment and call [Preview.setTargetRotation()] (like we do in this sample), which will
// trigger [Preview.OnPreviewOutputUpdateListener] with a new
// [PreviewOutput.rotationDegrees]. CameraX Preview use case will not rotate the frames for
// us, it will just tell us about the buffer rotation with respect to sensor orientation.
// In this sample, we ignore the buffer rotation and instead look at the view finder's
// rotation every time [updateTransform] is called, which gets triggered by
// [CameraFragment] display listener -- but the approach taken in this sample is not the
// only valid one.
displayManager = viewFinder.context
.getSystemService(Context.DISPLAY_SERVICE) as DisplayManager
displayManager.registerDisplayListener(displayListener, null)
// Remove the display listeners when the view is detached to avoid holding a reference to
// it outside of the Fragment that owns the view.
// NOTE: Even though using a weak reference should take care of this, we still try to avoid
// unnecessary calls to the listener this way.
viewFinder.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
override fun onViewAttachedToWindow(view: View?) =
displayManager.registerDisplayListener(displayListener, null)
override fun onViewDetachedFromWindow(view: View?) =
displayManager.unregisterDisplayListener(displayListener)
})
}
/** Helper function that fits a camera preview into the given [TextureView] */
private fun updateTransform(textureView: TextureView?, rotation: Int?, newBufferDimens: Size,
newViewFinderDimens: Size) {
// This should not happen anyway, but now the linter knows
val textureView = textureView ?: return
if (rotation == viewFinderRotation &&
Objects.equals(newBufferDimens, bufferDimens) &&
Objects.equals(newViewFinderDimens, viewFinderDimens)) {
// Nothing has changed, no need to transform output again
return
}
if (rotation == null) {
// Invalid rotation - wait for valid inputs before setting matrix
return
} else {
// Update internal field with new inputs
viewFinderRotation = rotation
}
if (newBufferDimens.width == 0 || newBufferDimens.height == 0) {
// Invalid buffer dimens - wait for valid inputs before setting matrix
return
} else {
// Update internal field with new inputs
bufferDimens = newBufferDimens
}
if (newViewFinderDimens.width == 0 || newViewFinderDimens.height == 0) {
// Invalid view finder dimens - wait for valid inputs before setting matrix
return
} else {
// Update internal field with new inputs
viewFinderDimens = newViewFinderDimens
}
val matrix = Matrix()
// Compute the center of the view finder
val centerX = viewFinderDimens.width / 2.0f
val centerY = viewFinderDimens.height / 2.0f
// Correct preview output to account for display rotation
matrix.postRotate(-viewFinderRotation!!.toFloat(), centerX, centerY)
// Buffers are rotated relative to the device's 'natural' orientation: swap width and height
val bufferRatio = bufferDimens.height / bufferDimens.width.toFloat()
val scaledWidth: Int
val scaledHeight: Int
// Match longest sides together -- i.e. apply center-crop transformation
if (viewFinderDimens.width > viewFinderDimens.height) {
scaledHeight = viewFinderDimens.width
scaledWidth = Math.round(viewFinderDimens.width * bufferRatio)
} else {
scaledHeight = viewFinderDimens.height
scaledWidth = Math.round(viewFinderDimens.height * bufferRatio)
}
// Compute the relative scale value
val xScale = scaledWidth / viewFinderDimens.width.toFloat()
val yScale = scaledHeight / viewFinderDimens.height.toFloat()
// Scale input buffers to fill the view finder
matrix.preScale(xScale, yScale, centerX, centerY)
// Finally, apply transformations to our TextureView
textureView.setTransform(matrix)
}
companion object {
private val TAG = AutoFitPreviewBuilder::class.java.simpleName
/** Helper function that gets the rotation of a [Display] in degrees */
fun getDisplaySurfaceRotation(display: Display?) = (display?.rotation ?: 0) * 90
/**
* Main entrypoint for users of this class: instantiates the adapter and returns an instance
* of [Preview] which automatically adjusts in size and rotation to compensate for
* config changes.
*/
fun build(config: PreviewConfig, viewFinder: TextureView) =
AutoFitPreviewBuilder(config, WeakReference(viewFinder)).preview
}
} | 1 | Kotlin | 0 | 0 | ffdb0b5c542e4d0f624f9d1953b2681ac74b3c52 | 7,847 | EffectiveCamera | MIT License |
core/src/main/java/id/web/dedekurniawan/moviexplorer/core/enum/Sort.kt | BlueShadowBird | 608,123,499 | false | {"Kotlin": 115107} | package id.web.dedekurniawan.moviexplorer.core.enum
interface Sort{
enum class Popularity(private val string: String): Sort{
ASCENDING("asc"),
DESCENDING("desc");
override fun toString() = "popularity.$string"
}
enum class Vote(private val string: String): Sort{
ASCENDING("asc"),
DESCENDING("desc");
override fun toString() = "vote_average.$string"
}
enum class Revenue(private val string: String): Sort{
ASCENDING("asc"),
DESCENDING("desc");
override fun toString() = "revenue.$string"
}
} | 0 | Kotlin | 0 | 0 | b1addd44e7098b982c1495a18a5771f0659a945a | 595 | Android-Movie-Xporer | MIT License |
devp2p-eth/src/main/kotlin/org/apache/tuweni/devp2p/eth/EthHandler.kt | sambacha | 268,169,446 | true | {"Git Config": 1, "Gradle": 44, "YAML": 2, "JavaScript": 1, "Shell": 1, "Markdown": 9, "JSON": 14123, "Java Properties": 2, "Text": 2, "Ignore List": 1, "Groovy": 1, "Git Attributes": 1, "EditorConfig": 1, "Java": 493, "Dockerfile": 4, "Kotlin": 184, "XML": 4, "XSLT": 1, "TOML": 4, "ANTLR": 2} | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.tuweni.devp2p.eth
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import org.apache.tuweni.bytes.Bytes
import org.apache.tuweni.concurrent.AsyncCompletion
import org.apache.tuweni.concurrent.CompletableAsyncCompletion
import org.apache.tuweni.concurrent.coroutines.asyncCompletion
import org.apache.tuweni.eth.BlockBody
import org.apache.tuweni.eth.BlockHeader
import org.apache.tuweni.eth.Hash
import org.apache.tuweni.eth.TransactionReceipt
import org.apache.tuweni.eth.repository.BlockchainRepository
import org.apache.tuweni.rlpx.RLPxService
import org.apache.tuweni.rlpx.wire.DisconnectReason
import org.apache.tuweni.rlpx.wire.SubProtocolHandler
import org.slf4j.LoggerFactory
import kotlin.coroutines.CoroutineContext
internal class EthHandler(
override val coroutineContext: CoroutineContext = Dispatchers.Default,
private val blockchainInfo: BlockchainInformation,
private val service: RLPxService,
private val repository: BlockchainRepository
) : SubProtocolHandler, CoroutineScope {
companion object {
val logger = LoggerFactory.getLogger(EthHandler::class.java)
}
val peersMap: MutableMap<String, PeerInfo> = mutableMapOf()
val blockHeaderRequests = ArrayList<Hash>()
val blockBodyRequests = ArrayList<Hash>()
override fun handle(connectionId: String, messageType: Int, message: Bytes) = asyncCompletion {
logger.debug("Receiving message of type {}", messageType)
when (messageType) {
0 -> handleStatus(connectionId, StatusMessage.read(message))
1 -> handleNewBlockHashes(NewBlockHashes.read(message))
// 2 -> // do nothing.
3 -> handleGetBlockHeaders(connectionId, GetBlockHeaders.read(message))
4 -> handleHeaders(connectionId, BlockHeaders.read(message))
5 -> handleGetBlockBodies(connectionId, GetBlockBodies.read(message))
6 -> handleBlockBodies(BlockBodies.read(message))
7 -> handleNewBlock(NewBlock.read(message))
0x0d -> handleGetNodeData(connectionId, GetNodeData.read(message))
// 0x0e -> // not implemented yet.
0x0f -> handleGetReceipts(connectionId, GetReceipts.read(message))
// 0x10 -> handleReceipts(Receipts.read(message)) // not implemented yet
}
}
private fun handleStatus(connectionId: String, status: StatusMessage) {
if (!status.networkID.equals(blockchainInfo.networkID())) {
peersMap[connectionId]?.cancel()
service.disconnect(connectionId, DisconnectReason.SUBPROTOCOL_REASON)
}
peersMap[connectionId]?.connect()
}
// private fun handleReceipts(receipts: Receipts) {
// repository.storeTransactionReceipts()
// }
private suspend fun handleGetReceipts(connectionId: String, getReceipts: GetReceipts) {
val receipts = ArrayList<List<TransactionReceipt>>()
getReceipts.hashes.forEach {
receipts.add(repository.retrieveTransactionReceipts(it))
}
service.send(EthSubprotocol.ETH64, 0x10, connectionId, Receipts(receipts).toBytes())
}
private fun handleGetNodeData(connectionId: String, nodeData: GetNodeData) {
nodeData.toBytes()
service.send(EthSubprotocol.ETH64, 0x0e, connectionId, NodeData(emptyList()).toBytes())
}
private suspend fun handleNewBlock(read: NewBlock) {
repository.storeBlock(read.block)
}
private fun handleBlockBodies(message: BlockBodies) {
message.bodies.forEach {
// if (blockBodyRequests.remove(it)) {
// repository.
// } else {
// service.disconnect(connectionId, DisconnectReason.PROTOCOL_BREACH)
// }
}
}
private suspend fun handleGetBlockBodies(connectionId: String, message: GetBlockBodies) {
val bodies = ArrayList<BlockBody>()
message.hashes.forEach { hash ->
repository.retrieveBlockBody(hash)?.let {
bodies.add(it)
}
}
service.send(EthSubprotocol.ETH64, 6, connectionId, BlockBodies(bodies).toBytes())
}
private suspend fun handleHeaders(connectionId: String, headers: BlockHeaders) {
connectionId.toString()
headers.headers.forEach {
println(it.number)
repository.storeBlockHeader(it)
// if (blockHeaderRequests.remove(it.hash)) {
//
// } else {
// service.disconnect(connectionId, DisconnectReason.PROTOCOL_BREACH)
// }
}
}
private suspend fun handleGetBlockHeaders(connectionId: String, blockHeaderRequest: GetBlockHeaders) {
val matches = repository.findBlockByHashOrNumber(blockHeaderRequest.hash)
if (matches.isEmpty()) {
return
}
val headers = ArrayList<BlockHeader>()
val header = repository.retrieveBlockHeader(matches[0])
header?.let {
headers.add(it)
var blockNumber = it.number
for (i in 1..blockHeaderRequest.maxHeaders) {
blockNumber = if (blockHeaderRequest.reverse) {
blockNumber.subtract(blockHeaderRequest.skip)
} else {
blockNumber.add(blockHeaderRequest.skip)
}
val nextMatches = repository.findBlockByHashOrNumber(blockNumber.toBytes())
if (nextMatches.isEmpty()) {
break
}
val nextHeader = repository.retrieveBlockHeader(nextMatches[0]) ?: break
headers.add(nextHeader)
}
service.send(EthSubprotocol.ETH64, 4, connectionId, BlockHeaders(headers).toBytes())
}
}
private suspend fun handleNewBlockHashes(message: NewBlockHashes) {
message.hashes.forEach { pair ->
repository.retrieveBlockHeader(pair.first).takeIf { null == it }.apply {
requestBlockHeader(pair.first)
}
repository.retrieveBlockBody(pair.first).takeIf { null == it }.apply {
requestBlockBody(pair.first)
}
}
}
private fun requestBlockHeader(blockHash: Hash) {
blockHeaderRequests.add(blockHash)
}
private fun requestBlockBody(blockHash: Hash) {
blockBodyRequests.add(blockHash)
}
override fun handleNewPeerConnection(connectionId: String): AsyncCompletion {
service.send(
EthSubprotocol.ETH64, 0, connectionId, StatusMessage(
EthSubprotocol.ETH64.version(),
blockchainInfo.networkID(), blockchainInfo.totalDifficulty(),
blockchainInfo.bestHash(), blockchainInfo.genesisHash(), blockchainInfo.getLatestForkHash(),
blockchainInfo.getLatestFork()
).toBytes()
)
val newPeer = PeerInfo()
peersMap[connectionId] = newPeer
return newPeer.ready
}
override fun stop() = asyncCompletion {
TODO("not implemented") // To change body of created functions use File | Settings | File Templates.
}
}
class PeerInfo() {
val ready: CompletableAsyncCompletion = AsyncCompletion.incomplete()
fun connect() {
ready.complete()
}
fun cancel() {
ready.cancel()
}
}
| 0 | null | 0 | 0 | a93915406c58861e0b2a0a396690fa50bff1f844 | 7,518 | incubator-tuweni | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/AnatomicalHeart.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.AnatomicalHeart: ImageVector
get() {
if (_anatomicalHeart != null) {
return _anatomicalHeart!!
}
_anatomicalHeart = Builder(name = "AnatomicalHeart", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(23.0f, 5.005f)
reflectiveCurveToRelative(-0.746f, -0.009f, -1.091f, 0.0f)
curveToRelative(-1.177f, 0.002f, -2.237f, 0.08f, -3.191f, 0.212f)
curveToRelative(-0.132f, -0.418f, -0.302f, -0.804f, -0.52f, -1.147f)
lineToRelative(1.102f, -1.47f)
curveToRelative(0.332f, -0.442f, 0.242f, -1.069f, -0.2f, -1.4f)
curveToRelative(-0.441f, -0.331f, -1.067f, -0.241f, -1.399f, 0.2f)
lineToRelative(-0.953f, 1.271f)
curveToRelative(-0.509f, -0.292f, -1.093f, -0.495f, -1.747f, -0.594f)
verticalLineToRelative(-1.077f)
curveToRelative(0.0f, -0.552f, -0.447f, -1.0f, -1.0f, -1.0f)
reflectiveCurveToRelative(-1.0f, 0.448f, -1.0f, 1.0f)
verticalLineToRelative(1.076f)
curveToRelative(-0.685f, 0.099f, -1.304f, 0.301f, -1.872f, 0.564f)
lineToRelative(-0.796f, -1.194f)
curveToRelative(-0.306f, -0.459f, -0.926f, -0.584f, -1.387f, -0.277f)
curveToRelative(-0.46f, 0.306f, -0.584f, 0.927f, -0.277f, 1.387f)
lineToRelative(0.77f, 1.155f)
curveToRelative(-1.263f, 1.056f, -2.075f, 2.352f, -2.503f, 3.159f)
curveTo(6.447f, 2.3f, 3.056f, 0.391f, 1.196f, 0.02f)
curveTo(0.658f, -0.087f, 0.135f, 0.26f, 0.023f, 0.799f)
curveToRelative(-0.111f, 0.539f, 0.237f, 1.066f, 0.774f, 1.181f)
curveToRelative(0.168f, 0.035f, 4.005f, 0.918f, 4.185f, 5.682f)
curveToRelative(-1.769f, 0.983f, -2.983f, 2.965f, -2.983f, 5.248f)
curveToRelative(0.0f, 5.074f, 4.232f, 9.456f, 10.533f, 10.904f)
curveToRelative(0.545f, 0.125f, 1.055f, 0.188f, 1.535f, 0.188f)
curveToRelative(0.609f, 0.0f, 1.17f, -0.101f, 1.693f, -0.303f)
curveToRelative(3.112f, -1.206f, 4.739f, -5.54f, 4.738f, -9.198f)
curveToRelative(0.0f, -2.347f, -0.66f, -4.395f, -1.213f, -5.699f)
curveToRelative(-0.143f, -0.335f, -0.275f, -0.791f, -0.1f, -1.053f)
curveToRelative(0.18f, -0.269f, 0.809f, -0.7f, 2.98f, -0.743f)
horizontalLineToRelative(0.832f)
curveToRelative(0.553f, 0.0f, 1.0f, -0.448f, 1.0f, -1.0f)
reflectiveCurveToRelative(-0.447f, -1.0f, -1.0f, -1.0f)
close()
moveTo(11.477f, 8.399f)
curveToRelative(-0.815f, -0.558f, -1.636f, -0.933f, -2.441f, -1.158f)
curveToRelative(0.812f, -1.296f, 2.446f, -3.241f, 4.965f, -3.241f)
curveToRelative(1.412f, 0.0f, 2.332f, 0.539f, 2.753f, 1.602f)
curveToRelative(-2.847f, 0.726f, -4.462f, 1.956f, -5.276f, 2.797f)
close()
moveTo(15.04f, 21.833f)
curveToRelative(-0.554f, 0.213f, -1.226f, 0.222f, -2.06f, 0.031f)
curveToRelative(-5.287f, -1.215f, -8.98f, -4.897f, -8.98f, -8.955f)
curveToRelative(0.0f, -2.156f, 1.57f, -3.909f, 3.5f, -3.909f)
curveToRelative(0.905f, 0.0f, 1.96f, 0.433f, 3.015f, 1.189f)
curveToRelative(-0.051f, 1.024f, -0.474f, 3.194f, -3.002f, 4.604f)
curveToRelative(-0.482f, 0.269f, -0.655f, 0.878f, -0.386f, 1.36f)
curveToRelative(0.183f, 0.329f, 0.523f, 0.513f, 0.874f, 0.513f)
curveToRelative(0.165f, 0.0f, 0.332f, -0.041f, 0.486f, -0.126f)
curveToRelative(3.36f, -1.874f, 3.951f, -4.794f, 4.023f, -6.262f)
curveToRelative(0.0f, 0.0f, 0.001f, 0.0f, 0.001f, -0.001f)
curveToRelative(0.014f, -0.024f, 1.111f, -1.784f, 4.638f, -2.712f)
curveToRelative(-0.097f, 0.525f, -0.054f, 1.193f, 0.296f, 2.017f)
curveToRelative(0.48f, 1.134f, 1.054f, 2.907f, 1.055f, 4.919f)
curveToRelative(0.0f, 3.415f, -1.487f, 6.567f, -3.46f, 7.332f)
close()
}
}
.build()
return _anatomicalHeart!!
}
private var _anatomicalHeart: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,314 | icons | MIT License |
src/main/kotlin/com/workos/passwordless/models/SendSessionResponse.kt | workos | 419,780,611 | false | null | package com.workos.passwordless.models
import com.fasterxml.jackson.annotation.JsonCreator
/**
* Represents a response from sending a passwordless session.
* This class is not meant to be instantiated directly.
*
* @param success Whether or not the passwordless session was sent successfully.
*/
data class SendSessionResponse @JsonCreator constructor(
@JvmField
val success: Boolean
)
| 1 | Kotlin | 6 | 9 | 8be0571a48e643cea2f0c783ddb4c5fa79be1ed5 | 397 | workos-kotlin | MIT License |
examples/travel-agency-common/src/main/kotlin/io/holunda/axon/camunda/example/travel/hotel/Hotel.kt | holunda-io | 126,392,447 | false | null | package io.holunda.axon.camunda.example.travel.hotel
import io.holunda.axon.camunda.example.travel.end
import io.holunda.axon.camunda.example.travel.interval
import io.holunda.axon.camunda.example.travel.start
import mu.KLogging
import org.axonframework.commandhandling.CommandHandler
import org.axonframework.eventsourcing.EventSourcingHandler
import org.axonframework.modelling.command.AggregateIdentifier
import org.axonframework.modelling.command.AggregateLifecycle.apply
import org.axonframework.spring.stereotype.Aggregate
import org.threeten.extra.Interval
@Aggregate
class HotelBooking() {
companion object : KLogging()
@AggregateIdentifier
private lateinit var hotelName: String
private val reserved = mutableMapOf<String, Pair<Interval, String>>()
@CommandHandler
constructor(c: CreateHotel) : this() {
apply(HotelCreated(c.hotelName, c.city))
}
@CommandHandler
fun handle(c: BookHotel) {
if (reserved.values.filter { it.first.overlaps(interval(c.arrival, c.departure)) }.isNotEmpty()) {
throw HotelReservationNotPossibleException("No rooms free")
}
apply(HotelBooked(
arrival = c.arrival,
departure = c.departure,
guestName = c.guestName,
hotelName = c.hotelName,
hotelConfirmationCode = "${c.hotelName}_${c.guestName}_${c.reservationId}",
reservationId = c.reservationId
))
}
@CommandHandler
fun handle(c: CancelHotel) {
if (reserved.containsKey(c.reservationId)) {
val reservation = reserved[c.reservationId]!!.first
val confirmationCode = reserved[c.reservationId]!!.second
apply(
HotelCancelled(
arrival = start(reservation),
departure = end(reservation),
hotelConfirmationCode = confirmationCode,
reservationId = c.reservationId
)
)
}
}
@EventSourcingHandler
fun on(e: HotelCreated) {
this.hotelName = e.hotelName
}
@EventSourcingHandler
fun on(e: HotelBooked) {
reserved[e.reservationId] = interval(e.arrival, e.departure) to e.hotelConfirmationCode
}
}
| 1 | Kotlin | 1 | 20 | 901b3fc618a8779715ff75cce83924c85600aac5 | 2,077 | axon-camunda | Apache License 2.0 |
src/main/kotlin/graphql/execution/ExecutorServiceExecutionStrategy.kt | LarsKrogJensen | 78,951,235 | false | null | package graphql.execution
import graphql.ExecutionResult
import graphql.ExecutionResultImpl
import graphql.GraphQLException
import graphql.language.Field
import graphql.schema.GraphQLObjectType
import java.util.LinkedHashMap
import java.util.concurrent.*
/**
*
* ExecutorServiceExecutionStrategy uses an [ExecutorService] to parallelize the resolve.
* Due to the nature of [.execute] implementation, [ExecutorService]
* MUST have the following 2 characteristics:
*
* * 1. The underlying [java.util.concurrent.ThreadPoolExecutor] MUST have a reasonable `maximumPoolSize`
* * 2. The underlying [java.util.concurrent.ThreadPoolExecutor] SHALL NOT use its task queue.
*
*
* Failure to follow 1. and 2. can result in a very large number of threads created or hanging. (deadlock)
* See `graphql.execution.ExecutorServiceExecutionStrategyTest` for example usage.
*/
class ExecutorServiceExecutionStrategy(val executorService: ExecutorService) : AbstractExecutionStrategy() {
override fun execute(executionContext: ExecutionContext,
parentType: GraphQLObjectType,
source: Any,
fields: Map<String, List<Field>>): CompletionStage<ExecutionResult> {
val futures = fields.asSequence()
.associateBy({ it.key }) {
executorService.submit( Callable {
resolveField(executionContext, parentType, source, it.value)
})
}
try {
val promise = CompletableFuture<ExecutionResult>()
val results = LinkedHashMap<String, Any?>()
for ((fieldName, future) in futures) {
future.get().thenAccept({ executionResult ->
results.put(fieldName, executionResult?.data())
// Last one to finish completes the promise
if (results.size == futures.keys.size) {
promise.complete(ExecutionResultImpl(results, executionContext.errors()))
}
})
}
return promise
} catch (e: InterruptedException) {
throw GraphQLException(e)
} catch (e: ExecutionException) {
throw GraphQLException(e)
}
}
}
| 0 | Kotlin | 1 | 3 | aa8e3c645dedf1048e2124d43e1deff28ad16cdf | 2,587 | graphql-kotlin | MIT License |
defitrack-rest/defitrack-protocol-services/defitrack-protocol-service/src/main/java/io/defitrack/market/pooling/DefaultPoolingMarketRestController.kt | decentri-fi | 426,174,152 | false | null | package io.defitrack.market.pooling
import io.defitrack.common.network.Network
import io.defitrack.common.utils.BigDecimalExtensions.dividePrecisely
import io.defitrack.common.utils.BigDecimalExtensions.isZero
import io.defitrack.farming.vo.TransactionPreparationVO
import io.defitrack.invest.PrepareInvestmentCommand
import io.defitrack.market.pooling.domain.PoolingMarket
import io.defitrack.market.pooling.vo.PoolingMarketTokenShareVO
import io.defitrack.market.pooling.vo.PoolingMarketVO
import io.defitrack.network.toVO
import io.defitrack.price.PriceResource
import io.defitrack.protocol.toVO
import io.defitrack.token.ERC20Resource
import io.defitrack.token.TokenType
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.runBlocking
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import java.math.BigDecimal
@RestController
@RequestMapping("/pooling")
class DefaultPoolingMarketRestController(
private val poolingMarketProviders: List<PoolingMarketProvider>,
private val erC20Resource: ERC20Resource,
private val priceResource: PriceResource
) {
companion object {
val logger: Logger = LoggerFactory.getLogger(this::class.java)
}
@GetMapping(value = ["/all-markets"])
fun allMarkets(): List<PoolingMarketVO> = runBlocking {
poolingMarketProviders.map {
async {
it.getMarkets().map {
it.toVO()
}
}
}.awaitAll().flatten()
}
@PostMapping(value = ["/markets/{id}/invest"])
fun prepareInvestment(
@PathVariable("id") id: String,
@RequestBody prepareInvestmentCommand: PrepareInvestmentCommand
): ResponseEntity<TransactionPreparationVO> = runBlocking(Dispatchers.Default) {
poolingMarketById(id)?.investmentPreparer?.prepare(prepareInvestmentCommand)?.let { transactions ->
ResponseEntity.ok(
TransactionPreparationVO(
transactions
)
)
} ?: ResponseEntity.badRequest().build()
}
@GetMapping(value = ["/markets"], params = ["token", "network"])
fun searchByToken(
@RequestParam("token") tokenAddress: String,
@RequestParam("network") network: Network
): List<PoolingMarketVO> {
return poolingMarketProviders
.filter {
it.getNetwork() == network
}
.flatMap {
it.getMarkets()
}.filter {
it.tokens.any { t ->
t.address.lowercase() == tokenAddress.lowercase()
} || it.address.lowercase() == tokenAddress.lowercase()
}.map { it.toVO() }
}
@GetMapping(value = ["/markets/{id}"])
fun getById(
@PathVariable("id") id: String,
): ResponseEntity<PoolingMarketVO> {
return poolingMarketById(id)?.let {
ResponseEntity.ok(it.toVO())
} ?: ResponseEntity.notFound().build()
}
private fun poolingMarketById(
id: String
) = poolingMarketProviders.flatMap {
it.getMarkets()
}.firstOrNull {
it.id == id
}
@GetMapping(value = ["/markets/alternatives"], params = ["token", "network"])
fun findAlternatives(
@RequestParam("token") tokenAddress: String,
@RequestParam("network") network: Network
): List<PoolingMarketVO> = runBlocking {
val token = erC20Resource.getTokenInformation(
network, tokenAddress,
)
poolingMarketProviders
.filter {
it.getNetwork() == network
}
.flatMap {
it.getMarkets()
}.filter { poolingMarketElement ->
when {
(token.type) != TokenType.SINGLE -> {
poolingMarketElement.tokens.map { pt ->
pt.address.lowercase()
}.containsAll(
token.underlyingTokens.map {
it.address.lowercase()
}
)
}
else -> false
}
}.map { it.toVO() }
}
fun PoolingMarket.toVO(): PoolingMarketVO {
val totalReserveUSD = breakdown?.sumOf {
it.reserveUSD
} ?: BigDecimal.ZERO
return PoolingMarketVO(
name = name,
protocol = protocol.toVO(),
network = network.toVO(),
tokens = tokens,
id = id,
breakdown = breakdown?.map {
PoolingMarketTokenShareVO(
token = it.token,
reserve = it.reserve,
reserveUSD = it.reserveUSD,
weight = if (it.reserveUSD.isZero() || totalReserveUSD.isZero()) BigDecimal.ZERO else it.reserveUSD.dividePrecisely(
totalReserveUSD
)
)
},
decimals = decimals,
address = address,
apr = apr,
marketSize = marketSize,
prepareInvestmentSupported = investmentPreparer != null,
erc20Compatible = erc20Compatible,
)
}
} | 16 | Kotlin | 6 | 5 | e4640223e69c30f986b8b4238e026202b08a5548 | 5,433 | defi-hub | MIT License |
Cognito/app/src/main/java/jp/mknod/sample/cognito/MyAmplifyApp.kt | u26 | 481,791,218 | false | {"Kotlin": 21534, "Java": 6888} | package jp.mknod.sample.cognito
import android.app.Application
import android.util.Log
import com.amplifyframework.AmplifyException
import com.amplifyframework.auth.AuthChannelEventName
import com.amplifyframework.auth.cognito.AWSCognitoAuthPlugin
import com.amplifyframework.core.Amplify
import com.amplifyframework.core.InitializationStatus
import com.amplifyframework.hub.HubChannel
class MyAmplifyApp : Application() {
override fun onCreate() {
super.onCreate()
AmplifyAPI.init(applicationContext)
}
} | 0 | Kotlin | 0 | 0 | def21c4e4341a9e684c6d9dd069eafcf711f2311 | 533 | AmplifyAndroid | Apache License 2.0 |
app/src/main/java/com/example/waterme/MainActivity.kt | ruman1609 | 471,906,705 | true | {"Kotlin": 34144} | /*
* Copyright (C) 2021 The Android Open Source Project.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.waterme
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import com.example.waterme.ui.viewmodel.SplashScreenViewModel
class MainActivity : AppCompatActivity() {
private val viewModel: SplashScreenViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
installSplashScreen().apply {
setKeepOnScreenCondition {
viewModel.isLoading.value
}
}
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| 0 | Kotlin | 0 | 0 | 4c40aed876a4e31b53f8f2ecc3d7dfe248fe2af1 | 1,306 | water-me-app | Apache License 2.0 |
app/src/main/java/pl/polsl/workflow/manager/client/model/data/AllowableValue.kt | SzymonGajdzica | 306,075,061 | false | null | package pl.polsl.workflow.manager.client.model.data
import java.io.Serializable
sealed class AllowableValue<T: Identifiable>(val id: Long?): Serializable {
data class NotAllowed<T: Identifiable>(val mId: Long?): AllowableValue<T>(mId)
data class Allowed<T: Identifiable>(val value: T): AllowableValue<T>(value.id)
} | 0 | Kotlin | 0 | 0 | 93c99cc67c7af0bc55ca8fb03f077cdd363cb7e8 | 328 | workflow-manager-client | MIT License |
src/main/java/miyucomics/hexical/registry/HexicalDamageTypes.kt | miyucomics | 757,094,041 | false | {"Kotlin": 326871, "Java": 28642, "GLSL": 1075, "Shell": 45} | package miyucomics.hexical.inits
import miyucomics.hexical.entities.SpikeEntity
import net.minecraft.entity.Entity
import net.minecraft.entity.damage.DamageSource
import net.minecraft.entity.damage.ProjectileDamageSource
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.projectile.PersistentProjectileEntity
object HexicalDamageTypes {
fun magicMissile(projectile: PersistentProjectileEntity, attacker: Entity?): DamageSource = ProjectileDamageSource("magic_missile", projectile, attacker).setProjectile().setUnblockable().setUsesMagic().setBypassesArmor().setBypassesProtection()
fun spike(spike: SpikeEntity, attacker: PlayerEntity?): DamageSource = ProjectileDamageSource("spike", spike, attacker)
} | 0 | Kotlin | 3 | 1 | 8b1a6e9c8a2ff2f489fccb7dfcfcbe605b10771d | 733 | hexical | MIT License |
subprojects/library/src/commonSample/kotlin/org/kotools/types/EmailAddressCompanionCommonSample.kt | kotools | 581,475,148 | false | {"Kotlin": 410831, "Java": 11605} | package org.kotools.types
import kotools.types.experimental.ExperimentalKotoolsTypesApi
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
@OptIn(ExperimentalKotoolsTypesApi::class)
class EmailAddressCompanionCommonSample {
@Test
fun patternSample() {
val actual: String = EmailAddress.PATTERN
val expected = "^\\S+@\\S+\\.\\S+\$"
assertEquals(expected, actual)
}
@Test
fun fromStringAny() {
val text: Any = "<EMAIL>"
val isSuccess: Boolean = try {
EmailAddress.fromString(text)
true
} catch (exception: IllegalArgumentException) {
false
}
assertTrue(isSuccess)
}
@Test
fun fromStringAnyAny() {
val text: Any = "<EMAIL>"
val pattern: Any = "^[a-z]+@[a-z]+\\.[a-z]+\$"
val isSuccess: Boolean = try {
EmailAddress.fromString(text, pattern)
true
} catch (exception: IllegalArgumentException) {
false
}
assertTrue(isSuccess)
}
@Test
fun fromStringOrNullAny() {
val text: Any = "<EMAIL>"
val actual: EmailAddress? = EmailAddress.fromStringOrNull(text)
assertNotNull(actual)
}
@Test
fun fromStringOrNullAnyAny() {
val text: Any = "<EMAIL>"
val pattern: Any = "^[a-z]+@[a-z]+\\.[a-z]+\$"
val actual: EmailAddress? = EmailAddress.fromStringOrNull(text, pattern)
assertNotNull(actual)
}
}
| 40 | Kotlin | 6 | 86 | 88c42f6f1dab2828c8edab8b7d2a9e6ac026a7ab | 1,554 | types | MIT License |
app/src/main/java/com/example/codaquest/ui/components/onboarding/OnboardingScreen.kt | studiegruppe-2nd-semester | 782,521,831 | false | {"Kotlin": 165558, "Shell": 418} | package com.example.codaquest.ui.components.onboarding
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.codaquest.domain.models.QuestionTypes
import com.example.codaquest.ui.components.common.StepDropdown
import com.example.codaquest.ui.components.common.StepIntField
import com.example.codaquest.ui.components.common.StepRadioButtons
import com.example.codaquest.ui.components.common.StepTextField
import com.example.codaquest.ui.components.viewmodels.OnboardingViewModel
import com.example.codaquest.ui.components.viewmodels.SharedViewModel
@Composable
fun OnboardingScreen(
navController: NavController,
sharedViewModel: SharedViewModel,
) {
val onboardingViewModel: OnboardingViewModel = viewModel()
Column(
modifier = Modifier
.padding(0.5.dp)
.fillMaxSize(),
) {
// PROGRESS BAR
Row(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.1f),
verticalAlignment = Alignment.CenterVertically,
) {
Button(
modifier = Modifier
.padding(horizontal = 5.dp)
.fillMaxWidth(0.1f),
contentPadding = PaddingValues(0.dp),
onClick = { navController.navigate("profile") },
colors = ButtonDefaults.buttonColors(
containerColor = Color.Transparent,
),
) {
Text(text = "X")
}
LinearProgressIndicator(
progress = { (onboardingViewModel.currentQuestion + 1).toFloat() / onboardingViewModel.questions.size.toFloat() },
modifier = Modifier
.padding(horizontal = 5.dp)
.fillMaxWidth(0.8f),
color = MaterialTheme.colorScheme.primary, // progress color
)
Box(
modifier = Modifier
.fillMaxWidth(),
contentAlignment = Alignment.Center,
) {
Text(
modifier = Modifier
.padding(horizontal = 5.dp),
text = "${onboardingViewModel.currentQuestion + 1}/${onboardingViewModel.questions.size}",
)
}
}
Box(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.5f),
contentAlignment = Alignment.Center,
) {
when (onboardingViewModel.questions[onboardingViewModel.currentQuestion].type) {
QuestionTypes.RadioButton -> StepRadioButtons(
questionInfo = onboardingViewModel.questions[onboardingViewModel.currentQuestion],
)
QuestionTypes.TextField -> StepTextField(
questionInfo = onboardingViewModel.questions[onboardingViewModel.currentQuestion],
)
QuestionTypes.IntField -> StepIntField(
questionInfo = onboardingViewModel.questions[onboardingViewModel.currentQuestion],
)
QuestionTypes.Dropdown -> StepDropdown(
questionInfo = onboardingViewModel.questions[onboardingViewModel.currentQuestion],
expanded = onboardingViewModel.dropdownExpanded,
onExpandedChange = { onboardingViewModel.dropdownExpanded = it },
)
}
}
Row(
modifier = Modifier
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
) {
Button(
enabled = onboardingViewModel.currentQuestion != 0,
modifier = Modifier.padding(5.dp),
onClick = { onboardingViewModel.previousQuestion() },
colors = ButtonDefaults.buttonColors(
containerColor = if (onboardingViewModel.currentQuestion == 0) MaterialTheme.colorScheme.inversePrimary else MaterialTheme.colorScheme.primary,
),
) {
Text("Previous")
}
Button(
modifier = Modifier.padding(5.dp),
onClick = {
sharedViewModel.user?.let { user ->
onboardingViewModel.nextQuestion(
user,
onSuccess = {
sharedViewModel.changeUser(it)
navController.navigate("profile")
},
)
}
},
colors = ButtonDefaults.buttonColors(
containerColor = MaterialTheme.colorScheme.primary,
),
) {
Text(onboardingViewModel.nextButton)
}
}
}
}
| 0 | Kotlin | 0 | 0 | 800dfce55cd1f62af4f31a0b780ceab639543671 | 5,851 | codaquest | MIT License |
app/src/main/java/com/wwy/android/vm/ReadHistoryViewMode.kt | wwy863399246 | 209,758,901 | false | null | package com.wwy.android.vm
import androidx.lifecycle.MutableLiveData
import com.wwy.android.data.bean.Article
import com.wwy.android.data.bean.base.ResultData
import com.wwy.android.data.repository.ReadHistoryUserCase
import com.wwy.android.util.ListModel
import com.wwy.android.view.loadpage.LoadPageStatus
import com.wwy.android.vm.base.BaseViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
*@创建者wwy
*@创建时间 2020/8/21 0021 上午 0:22
*@描述
*/
class ReadHistoryViewMode(private val readHistoryUserCase: ReadHistoryUserCase) : BaseViewModel() {
val mReadHistoryListModel = MutableLiveData<ListModel<Article>>()
private val mReadHistoryLoadPageStatus = MutableLiveData<LoadPageStatus>()
val mDeleteReadHistoryState = MutableLiveData<ListModel<Int>>()
fun queryAllReadHistory() {
launchUI {
withContext(Dispatchers.IO) {
readHistoryUserCase.queryAllReadHistory(
mReadHistoryListModel,
mReadHistoryLoadPageStatus
)
}
}
}
fun deleteReadHistory(article: Article) = launchUI {
withContext(Dispatchers.IO) {
readHistoryUserCase.deleteReadHistory(article, mDeleteReadHistoryState)
}
}
} | 0 | Kotlin | 9 | 71 | 672b054b5c1aba0b323e8e082a3dea13b25bf971 | 1,288 | WanAndroid | Apache License 2.0 |
integration/graalvm/ktor-graalvm-server/src/main/kotlin/com/expediagroup/graalvm/ktor/Application.kt | ExpediaGroup | 148,706,161 | false | {"Kotlin": 2410561, "MDX": 720089, "HTML": 12165, "JavaScript": 10447, "CSS": 297, "Dockerfile": 147} | /*
* Copyright 2023 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.expediagroup.graalvm.ktor
import com.expediagroup.graalvm.hooks.CustomHooks
import com.expediagroup.graalvm.ktor.context.CustomContextFactory
import com.expediagroup.graalvm.schema.ArgumentQuery
import com.expediagroup.graalvm.schema.AsyncQuery
import com.expediagroup.graalvm.schema.BasicMutation
import com.expediagroup.graalvm.schema.ContextualQuery
import com.expediagroup.graalvm.schema.CustomScalarQuery
import com.expediagroup.graalvm.schema.EnumQuery
import com.expediagroup.graalvm.schema.ErrorQuery
import com.expediagroup.graalvm.schema.IdQuery
import com.expediagroup.graalvm.schema.InnerClassQuery
import com.expediagroup.graalvm.schema.ListQuery
import com.expediagroup.graalvm.schema.PolymorphicQuery
import com.expediagroup.graalvm.schema.ScalarQuery
import com.expediagroup.graalvm.schema.TypesQuery
import com.expediagroup.graalvm.schema.dataloader.ExampleDataLoader
import com.expediagroup.graalvm.schema.model.ExampleInterface
import com.expediagroup.graalvm.schema.model.ExampleUnion
import com.expediagroup.graalvm.schema.model.FirstImpl
import com.expediagroup.graalvm.schema.model.FirstUnionMember
import com.expediagroup.graalvm.schema.model.SecondImpl
import com.expediagroup.graalvm.schema.model.SecondUnionMember
import com.expediagroup.graphql.dataloader.KotlinDataLoaderRegistryFactory
import com.expediagroup.graphql.server.ktor.GraphQL
import com.expediagroup.graphql.server.ktor.graphQLGetRoute
import com.expediagroup.graphql.server.ktor.graphQLPostRoute
import com.expediagroup.graphql.server.ktor.graphQLSDLRoute
import com.expediagroup.graphql.server.ktor.graphiQLRoute
import io.ktor.server.application.install
import io.ktor.server.cio.CIO
import io.ktor.server.engine.embeddedServer
import io.ktor.server.routing.routing
fun main() {
embeddedServer(CIO, port = 8080, host = "0.0.0.0") {
install(GraphQL) {
schema {
packages = listOf("com.expediagroup.graalvm")
queries = listOf(
ArgumentQuery(),
AsyncQuery(),
ContextualQuery(),
CustomScalarQuery(),
EnumQuery(),
ErrorQuery(),
IdQuery(),
InnerClassQuery(),
ListQuery(),
PolymorphicQuery(),
ScalarQuery(),
TypesQuery()
)
mutations = listOf(
BasicMutation()
)
hooks = CustomHooks()
typeHierarchy = mapOf(
ExampleInterface::class to listOf(FirstImpl::class, SecondImpl::class),
ExampleUnion::class to listOf(FirstUnionMember::class, SecondUnionMember::class)
)
}
engine {
dataLoaderRegistryFactory = KotlinDataLoaderRegistryFactory(
ExampleDataLoader
)
}
server {
contextFactory = CustomContextFactory()
}
}
routing {
graphQLGetRoute()
graphQLPostRoute()
graphQLSDLRoute()
graphiQLRoute()
}
}.start(wait = true)
}
| 68 | Kotlin | 345 | 1,739 | d3ad96077fc6d02471f996ef34c67066145acb15 | 3,869 | graphql-kotlin | Apache License 2.0 |
client/app/src/main/java/com/example/healthc/presentation/widget/ObjectDetectionDialog.kt | Solution-Challenge-HealthC | 601,915,784 | false | null | package com.example.healthc.presentation.widget
import android.annotation.SuppressLint
import android.content.Context
import android.os.Bundle
import com.example.healthc.databinding.DialogObjectDetectionBinding
import com.example.healthc.domain.model.object_detection.DetectedObject
import com.google.android.material.bottomsheet.BottomSheetDialog
class ObjectDetectionDialog(
context : Context,
private val category : DetectedObject,
private val onClickPosButton : (String) -> Unit,
private val onClickNegButton : () -> Unit,
): BottomSheetDialog(context) {
private val binding by lazy { DialogObjectDetectionBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.setContentView(binding.root)
initViews()
}
@SuppressLint("SetTextI18n")
private fun initViews(){
binding.dialogCategoryTextView.text = "인식된 음식 : ${category.category}"
binding.dialogObjectDetectNegButton.setOnClickListener {
onClickNegButton()
dismiss()
}
binding.dialogObjectDetectPosButton.setOnClickListener {
onClickPosButton(category.category)
dismiss()
}
}
} | 5 | Kotlin | 1 | 2 | 11d38169ecdc42dc12943b829b842f0e5b360788 | 1,259 | HealthC_Android | MIT License |
foundation/domain-model/main/ru/pixnews/domain/model/news/GameNewsRatings.kt | illarionov | 305,333,284 | false | null | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ru.pixnews.domain.model.news
public data class GameNewsRatings(
public val id: GameNewsId,
val rating: Int,
val comments: UInt,
val reposts: UInt,
)
| 0 | Kotlin | 0 | 2 | 8912bf1116dd9fe94d110162ff9a302e93af1509 | 764 | Pixnews | Apache License 2.0 |
app/src/main/java/com/affise/app/ui/fragments/buttons/ButtonsContract.kt | affise | 496,592,599 | false | {"Kotlin": 859274, "JavaScript": 39328, "HTML": 33916} | package com.affise.app.ui.fragments.buttons
interface ButtonsContract {
interface ViewModel
} | 0 | Kotlin | 0 | 5 | ab7d393c6583208e33cef9e10e01ba9dd752bbcb | 98 | sdk-android | MIT License |
features/times/src/main/java/com/metinkale/prayer/times/MainActivity.kt | metinkale38 | 48,848,634 | false | {"Kotlin": 562178, "Java": 292077, "HTML": 242192, "CSS": 382} | /*
* Copyright (c) 2013-2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.metinkale.prayer.times
import android.os.Bundle
import com.metinkale.prayer.BaseActivity
import com.metinkale.prayer.times.LocationReceiver.Companion.triggerUpdate
import com.metinkale.prayer.times.fragments.SearchCityFragment
import com.metinkale.prayer.times.fragments.TimesFragment
open class MainActivity : BaseActivity(R.string.appName, R.mipmap.ic_launcher, TimesFragment()) {
override fun onStart() {
super.onStart()
triggerUpdate(this)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent.getBooleanExtra("openCitySearch", false)) {
moveToFrag(SearchCityFragment())
}
}
} | 25 | Kotlin | 108 | 230 | f1fb9ca7f538efed5725169c8c61eaa471f66056 | 1,309 | prayer-times-android | Apache License 2.0 |
app/src/main/kotlin/kozyriatskyi/anton/sked/day/DayView.kt | antonKozyriatskyi | 123,421,471 | false | null | package kozyriatskyi.anton.sked.day
import kozyriatskyi.anton.sked.data.pojo.DayUi
import kozyriatskyi.anton.sked.data.pojo.LessonUi
import moxy.MvpView
import moxy.viewstate.strategy.AddToEndSingleStrategy
import moxy.viewstate.strategy.OneExecutionStateStrategy
import moxy.viewstate.strategy.StateStrategyType
@StateStrategyType(AddToEndSingleStrategy::class)
interface DayView : MvpView {
fun showDay(day: DayUi)
@StateStrategyType(OneExecutionStateStrategy::class)
fun showError(message: String)
@StateStrategyType(OneExecutionStateStrategy::class)
fun showStudentLessonDetails(lesson: LessonUi)
@StateStrategyType(OneExecutionStateStrategy::class)
fun showTeacherLessonDetails(lesson: LessonUi)
} | 1 | Kotlin | 1 | 3 | 5480feff757ff9fa99ea2c7c0ff51f18a747a2ab | 736 | sked | Apache License 2.0 |
app/src/main/java/com/jakting/shareclean/utils/ModuleCheckerExt.kt | TigerBeanst | 259,865,941 | false | null | package com.jakting.shareclean.utils
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import com.jakting.shareclean.utils.application.Companion.appContext
import com.topjohnwu.superuser.Shell
fun moduleApplyAvailable(): Boolean {
val resolveInfoList = appContext.packageManager!!.queryIntentActivities(
Intent(Intent.ACTION_PROCESS_TEXT).setType("text/tigerinthewall"),
PackageManager.MATCH_ALL
)
for (resolveInfo in resolveInfoList) {
if (resolveInfo.activityInfo.packageName == appContext.packageName) {
return false
}
}
return true
}
fun Context?.moduleInfo(): Array<String> {
// 检查 Riru 版
val riruShell = runShell("cat /data/adb/modules/riru_ifw_enhance_tiw/module.prop")
if(riruShell.isSuccess){
return arrayOf("Riru", moduleVersion(riruShell)[0]!!, moduleVersion(riruShell)[1]!!)
}
val zygiskShell = runShell("cat /data/adb/modules/zygisk_ifw_enhance_tiw/module.prop")
if(zygiskShell.isSuccess){
return arrayOf("Zygisk", moduleVersion(zygiskShell)[0]!!, moduleVersion(zygiskShell)[1]!!)
}
return arrayOf("", "", "")
}
fun Context?.moduleVersion(sr: Shell.Result): Array<String?> {
val shellResult = sr.getPureCat()
logd(shellResult)
if (shellResult.isEmpty()) return arrayOf("", "")
val version = Regex(".*?version=(.*?),.*?versionCode=(.*?),").find(shellResult)?.groupValues
return arrayOf(version?.get(1), version?.get(2))
}
| 10 | Kotlin | 14 | 133 | 7825c8d6b8563cd57317fc9180bfe28a3a3d375a | 1,523 | TigerInTheWall | Apache License 2.0 |
kotlin/396.Rotate Function(旋转函数).kt | learningtheory | 141,790,045 | false | {"Python": 4025652, "C++": 1999023, "Java": 1995266, "JavaScript": 1990554, "C": 1979022, "Ruby": 1970980, "Scala": 1925110, "Kotlin": 1917691, "Go": 1898079, "Swift": 1827809, "HTML": 124958, "Shell": 7944} | /**
<p>
Given an array of integers <code>A</code> and let <i>n</i> to be its length.
</p>
<p>
Assume <code>B<sub>k</sub></code> to be an array obtained by rotating the array <code>A</code> <i>k</i> positions clock-wise, we define a "rotation function" <code>F</code> on <code>A</code> as follow:
</p>
<p>
<code>F(k) = 0 * B<sub>k</sub>[0] + 1 * B<sub>k</sub>[1] + ... + (n-1) * B<sub>k</sub>[n-1]</code>.</p>
<p>Calculate the maximum value of <code>F(0), F(1), ..., F(n-1)</code>.
</p>
<p><b>Note:</b><br />
<i>n</i> is guaranteed to be less than 10<sup>5</sup>.
</p>
<p><b>Example:</b>
<pre>
A = [4, 3, 2, 6]
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
So the maximum value of F(0), F(1), F(2), F(3) is F(3) = 26.
</pre>
</p><p>给定一个长度为 <em>n</em> 的整数数组 <code>A</code> 。</p>
<p>假设 <code>B<sub>k</sub></code> 是数组 <code>A</code> 顺时针旋转 <em>k</em> 个位置后的数组,我们定义 <code>A</code> 的“旋转函数” <code>F</code> 为:</p>
<p><code>F(k) = 0 * B<sub>k</sub>[0] + 1 * B<sub>k</sub>[1] + ... + (n-1) * B<sub>k</sub>[n-1]</code>。</p>
<p>计算<code>F(0), F(1), ..., F(n-1)</code>中的最大值。</p>
<p><strong>注意:</strong><br />
可以认为<em> n</em> 的值小于 10<sup>5</sup>。</p>
<p><strong>示例:</strong></p>
<pre>
A = [4, 3, 2, 6]
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
所以 F(0), F(1), F(2), F(3) 中的最大值是 F(3) = 26 。
</pre>
<p>给定一个长度为 <em>n</em> 的整数数组 <code>A</code> 。</p>
<p>假设 <code>B<sub>k</sub></code> 是数组 <code>A</code> 顺时针旋转 <em>k</em> 个位置后的数组,我们定义 <code>A</code> 的“旋转函数” <code>F</code> 为:</p>
<p><code>F(k) = 0 * B<sub>k</sub>[0] + 1 * B<sub>k</sub>[1] + ... + (n-1) * B<sub>k</sub>[n-1]</code>。</p>
<p>计算<code>F(0), F(1), ..., F(n-1)</code>中的最大值。</p>
<p><strong>注意:</strong><br />
可以认为<em> n</em> 的值小于 10<sup>5</sup>。</p>
<p><strong>示例:</strong></p>
<pre>
A = [4, 3, 2, 6]
F(0) = (0 * 4) + (1 * 3) + (2 * 2) + (3 * 6) = 0 + 3 + 4 + 18 = 25
F(1) = (0 * 6) + (1 * 4) + (2 * 3) + (3 * 2) = 0 + 4 + 6 + 6 = 16
F(2) = (0 * 2) + (1 * 6) + (2 * 4) + (3 * 3) = 0 + 6 + 8 + 9 = 23
F(3) = (0 * 3) + (1 * 2) + (2 * 6) + (3 * 4) = 0 + 2 + 12 + 12 = 26
所以 F(0), F(1), F(2), F(3) 中的最大值是 F(3) = 26 。
</pre>
**/
class Solution {
fun maxRotateFunction(A: IntArray): Int {
}
} | 0 | Python | 1 | 3 | 6731e128be0fd3c0bdfe885c1a409ac54b929597 | 2,734 | leetcode | MIT License |
app/src/main/java/dev/pankaj/cleanarchitecture/presentation/auth/viewmodel/AuthViewModel.kt | pankaj046 | 806,227,972 | false | {"Kotlin": 79661} | package dev.pankaj.cleanarchitecture.presentation.auth.viewmodel
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.scopes.ViewModelScoped
import dev.pankaj.cleanarchitecture.App
import dev.pankaj.cleanarchitecture.data.remote.model.auth.LoginRequest
import dev.pankaj.cleanarchitecture.data.remote.model.auth.LoginResponse
import dev.pankaj.cleanarchitecture.domain.usecase.AuthUseCase
import dev.pankaj.cleanarchitecture.domain.usecase.UserUseCase
import kotlinx.coroutines.launch
import dev.pankaj.cleanarchitecture.utils.*
import dev.pankaj.cleanarchitecture.utils.NetworkUtils.isNetworkAvailable
@ViewModelScoped
class AuthViewModel(
private val app: App,
private val userUseCase: UserUseCase,
private val authUseCase: AuthUseCase,
) : AndroidViewModel(app) {
private val _loginResponse: MutableLiveData<CallBack<LoginResponse>> = MutableLiveData()
val loginResponse: LiveData<CallBack<LoginResponse>> = _loginResponse
private val _loginValidate = MutableLiveData<CallBack<Boolean>>()
val loginValidate: LiveData<CallBack<Boolean>> = _loginValidate
fun login(loginRequest: LoginRequest) = viewModelScope.launch {
_loginResponse.value = CallBack.Loading(true)
if (isNetworkAvailable(app)){
authUseCase.login(loginRequest).apply {
_loginResponse.value = this
_loginResponse.value = CallBack.Loading(false)
}
}else {
_loginResponse.value = CallBack.Message("No Internet connection")
_loginResponse.value = CallBack.Loading(false)
}
}
fun validateLogin(email: String, password: String) = viewModelScope.launch {
if (email.isEmpty()){
_loginValidate.value = CallBack.Message("Invalid username")
}
if (password.isEmpty()){
_loginValidate.value = CallBack.Message("Invalid password")
}
if (email.isNotEmpty() && password.isNotEmpty()){
_loginValidate.value = CallBack.Success(true)
}
}
} | 0 | Kotlin | 0 | 0 | 050fa0aae45e4500c9fc85a04c6b7ee5b6439d71 | 2,168 | Clean-Architecture | The Unlicense |
src/test/kotlin/no/nav/brukerdialog/ytelse/ungdomsytelse/kafka/UngdomsytelsesøknadKonsumentTest.kt | navikt | 585,578,757 | false | {"Kotlin": 1442549, "Handlebars": 126943, "Dockerfile": 98} | package no.nav.brukerdialog.ytelse.ungdomsytelse.kafka
import io.mockk.coEvery
import io.mockk.coVerify
import no.nav.brukerdialog.AbstractIntegrationTest
import no.nav.brukerdialog.common.MetaInfo
import no.nav.brukerdialog.config.JacksonConfiguration
import no.nav.brukerdialog.dittnavvarsel.DittnavVarselTopologyConfiguration
import no.nav.brukerdialog.dittnavvarsel.K9Beskjed
import no.nav.brukerdialog.kafka.types.TopicEntry
import no.nav.brukerdialog.utils.KafkaUtils.leggPåTopic
import no.nav.brukerdialog.utils.KafkaUtils.lesMelding
import no.nav.brukerdialog.utils.MockMvcUtils.sendInnSøknad
import no.nav.brukerdialog.utils.TokenTestUtils.hentToken
import no.nav.brukerdialog.ytelse.ungdomsytelse.utils.SøknadUtils
import no.nav.brukerdialog.ytelse.ungdomsytelse.utils.UngdomsytelsesøknadUtils
import org.intellij.lang.annotations.Language
import org.json.JSONObject
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.skyscreamer.jsonassert.JSONAssert
import java.net.URI
import java.time.ZonedDateTime
import java.util.*
class UngdomsytelsesøknadKonsumentTest : AbstractIntegrationTest() {
override val consumerGroupPrefix = "ungdomsytelse-soknad"
override val consumerGroupTopics = listOf(
UngdomsytelsesøknadTopologyConfiguration.UNGDOMSYTELSE_SØKNAD_MOTTATT_TOPIC,
UngdomsytelsesøknadTopologyConfiguration.UNGDOMSYTELSE_SØKNAD_PREPROSESSERT_TOPIC,
UngdomsytelsesøknadTopologyConfiguration.UNGDOMSYTELSE_SØKNAD_CLEANUP_TOPIC
)
@Test
fun `forvent at melding konsumeres riktig og dokumenter blir slettet`() {
val søker = mockSøker()
mockBarn()
mockLagreDokument()
mockJournalføring()
val søknadId = UUID.randomUUID().toString()
val søknad = SøknadUtils.defaultSøknad.copy(søknadId = søknadId)
mockMvc.sendInnSøknad(søknad, mockOAuth2Server.hentToken())
coVerify(exactly = 1, timeout = 120 * 1000) {
k9DokumentMellomlagringService.slettDokumenter(any(), any())
}
k9DittnavVarselConsumer.lesMelding(
key = søknadId,
topic = DittnavVarselTopologyConfiguration.K9_DITTNAV_VARSEL_TOPIC
).value().assertDittnavVarsel(
K9Beskjed(
metadata = no.nav.brukerdialog.utils.SøknadUtils.metadata,
grupperingsId = søknadId,
tekst = "Søknad om ungdomsytelse er mottatt",
link = null,
dagerSynlig = 7,
søkerFødselsnummer = søker.fødselsnummer,
eventId = "testes ikke",
ytelse = "UNGDOMSYTELSE",
)
)
}
@Test
fun `Forvent at melding bli prosessert på 5 forsøk etter 4 feil`() {
val søknadId = UUID.randomUUID().toString()
val mottattString = "2020-01-01T10:30:15Z"
val mottatt = ZonedDateTime.parse(mottattString, JacksonConfiguration.zonedDateTimeFormatter)
val søknadMottatt = UngdomsytelsesøknadUtils.gyldigSøknad(søknadId = søknadId, mottatt = mottatt)
val correlationId = UUID.randomUUID().toString()
val metadata = MetaInfo(version = 1, correlationId = correlationId)
val topicEntry = TopicEntry(metadata, søknadMottatt)
val topicEntryJson = objectMapper.writeValueAsString(topicEntry)
coEvery { k9DokumentMellomlagringService.lagreDokument(any()) }
.throws(IllegalStateException("Feilet med lagring av dokument..."))
.andThenThrows(IllegalStateException("Feilet med lagring av dokument..."))
.andThenThrows(IllegalStateException("Feilet med lagring av dokument..."))
.andThenThrows(IllegalStateException("Feilet med lagring av dokument..."))
.andThenMany(listOf("123456789", "987654321").map { URI("http://localhost:8080/dokument/$it") })
producer.leggPåTopic(
key = søknadId,
value = topicEntryJson,
topic = UngdomsytelsesøknadTopologyConfiguration.UNGDOMSYTELSE_SØKNAD_MOTTATT_TOPIC
)
val lesMelding =
consumer.lesMelding(key = søknadId, topic = UngdomsytelsesøknadTopologyConfiguration.UNGDOMSYTELSE_SØKNAD_PREPROSESSERT_TOPIC)
.value()
val preprosessertSøknadJson = JSONObject(lesMelding).getJSONObject("data").toString()
JSONAssert.assertEquals(preprosessertSøknadSomJson(søknadId, mottattString), preprosessertSøknadJson, true)
}
@Language("JSON")
private fun preprosessertSøknadSomJson(søknadId: String, mottatt: String) = """
{
"søknadId": "$søknadId",
"mottatt": "$mottatt",
"søker": {
"etternavn": "Nordmann",
"mellomnavn": "Mellomnavn",
"aktørId": "123456",
"fødselsdato": "2000-01-01",
"fornavn": "Ola",
"fødselsnummer": "02119970078"
},
"fraOgMed": "2022-01-01",
"tilOgMed": "2022-02-01",
"språk": "nb",
"harForståttRettigheterOgPlikter": true,
"dokumentId": [
[
"123456789",
"987654321"
]
],
"harBekreftetOpplysninger": true,
"k9Format": {
"språk": "nb",
"kildesystem": "søknadsdialog",
"mottattDato": "$mottatt",
"søknadId": "$søknadId",
"søker": {
"norskIdentitetsnummer": "02119970078"
},
"ytelse": {
"søknadsperiode": [],
"type": "UNGDOMSYTELSE"
},
"journalposter": [],
"begrunnelseForInnsending": {
"tekst": null
},
"versjon": "1.0.0"
}
}
""".trimIndent()
private fun String.assertDittnavVarsel(k9Beskjed: K9Beskjed) {
val k9BeskjedJson = JSONObject(this)
Assertions.assertEquals(k9Beskjed.grupperingsId, k9BeskjedJson.getString("grupperingsId"))
Assertions.assertEquals(k9Beskjed.tekst, k9BeskjedJson.getString("tekst"))
Assertions.assertEquals(k9Beskjed.ytelse, k9BeskjedJson.getString("ytelse"))
Assertions.assertEquals(k9Beskjed.dagerSynlig, k9BeskjedJson.getLong("dagerSynlig"))
}
}
| 4 | Kotlin | 0 | 0 | 402a0658544afc0f238f3a3c7babd0addad556b0 | 6,267 | k9-brukerdialog-prosessering | MIT License |
Core/src/jvmTest/kotlin/io/nacular/doodle/utils/PathTests.kt | nacular | 108,631,782 | false | {"Kotlin": 3150677} | package io.nacular.doodle.utils
import kotlin.test.Test
import kotlin.test.expect
/**
* Created by <NAME> on 7/18/20.
*/
class PathTests {
@Test fun `top works`() {
val paths = listOf(
listOf(0, 0, 2, 5),
listOf(0),
listOf()
)
paths.forEach {
expect(it.firstOrNull()) { Path(it).top }
}
}
@Test fun `bottom works`() {
val paths = listOf(
listOf(0, 0, 2, 5),
listOf(0),
listOf()
)
paths.forEach {
expect(it.lastOrNull()) { Path(it).bottom }
}
}
@Test fun `parent works`() {
val paths = listOf(
listOf(0, 0, 2, 5),
listOf(0),
listOf()
)
paths.forEach {
val parent = Path(it).parent
if (it.isEmpty()) {
expect(null) { parent }
} else {
expect(Path(it.dropLast(1))) { parent }
}
}
}
@Test fun `depth works`() {
val paths = listOf(
listOf(0, 0, 2, 5),
listOf(0),
listOf()
)
paths.forEach {
expect(it.size) { Path(it).depth }
}
}
@Test fun `overlapping root works`() {
data class Inputs<T>(val first: List<T>, val second: List<T>, val expect: List<T>)
val paths = listOf(
Inputs(listOf(0, 1), listOf(0, 1, 2, 3, 4, 5), expect = listOf(0, 1)),
Inputs(listOf(0, 1, 9, 8), listOf(0, 1, 2, 3, 4, 5), expect = listOf(0, 1))
)
paths.forEach {
expect(Path(it.expect)) { Path(it.second).overlappingRoot(Path(it.first )) }
expect(Path(it.expect)) { Path(it.first ).overlappingRoot(Path(it.second)) }
}
}
@Test fun `non-overlapping stem works`() {
data class Inputs<T>(val first: List<T>, val second: List<T>, val expect: List<T>)
val paths = listOf(
Inputs(listOf(0, 1), listOf(0, 1, 2, 3, 4, 5), expect = listOf(2, 3, 4, 5)),
Inputs(listOf(0, 1, 9, 8), listOf(0, 1, 2, 3, 4, 5), expect = listOf(2, 3, 4, 5))
)
paths.forEach {
expect(it.expect) { Path(it.second).nonOverlappingStem(Path(it.first )) }
}
}
@Test fun `root is always ancestor`() {
val paths = listOf(
listOf(0, 0, 2, 5),
listOf(0)
)
paths.forEach {
expect(true) { Path<Int>() ancestorOf Path(it) }
}
}
} | 3 | Kotlin | 26 | 613 | f7414d4c30cdd7632992071234223653e52b978c | 2,624 | doodle | MIT License |
twitter4j-v2-support/src/main/kotlin/twitter4j/ErrorInfo.kt | takke | 280,848,830 | false | null | package twitter4j
data class ErrorInfo(
val resourceType: String,
val field: String,
val parameter: String,
val value: String,
val title: String,
val section: String,
val detail: String,
val type: String
) {
constructor(json: JSONObject) : this(
resourceType = json.optString("resource_type"),
field = json.optString("field"),
parameter = json.optString("parameter"),
value = json.optString("value"),
title = json.optString("title"),
section = json.optString("section"),
detail = json.optString("detail"),
type = json.optString("type"),
)
}
| 6 | null | 13 | 82 | f13b6f15f47078517251e72bbee9854ec07285a5 | 710 | twitter4j-v2 | Apache License 2.0 |
testbot/src/main/java/lavaplayer/demo/controller/BotCommandMappingHandler.kt | mixtape-bot | 397,835,411 | true | {"Kotlin": 781109, "Java": 315803} | package lavaplayer.demo.controller
import net.dv8tion.jda.api.entities.Message
interface BotCommandMappingHandler {
fun commandNotFound(message: Message, name: String)
fun commandWrongParameterCount(message: Message, name: String, usage: String, given: Int, required: Int)
fun commandWrongParameterType(message: Message, name: String, usage: String, index: Int, value: String, expectedType: Class<*>)
fun commandRestricted(message: Message, name: String)
fun commandException(message: Message, name: String, throwable: Throwable)
}
| 0 | Kotlin | 0 | 6 | 06b02d8e711930c52d8ca67ad6347a17ca352ba2 | 554 | lavaplayer | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/data/DogViewModel.kt | MarkHan1213 | 342,127,734 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.data
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import com.example.androiddevchallenge.Dog
import com.example.androiddevchallenge.R
class DogViewModel : ViewModel() {
var dogs by mutableStateOf(
listOf(
Dog(
"吉娃娃",
"吉娃娃犬属于小型犬中体形最小的,但是这并不能说明它们是最娇弱的,相反,吉娃娃有着坚韧的意志,非常忠诚与主人,灵活度极高,是一种聪明的宠物。姿态优雅、性格警惕、动作迅速,以匀称的体格和娇小的体型而广泛的受人所青睐。",
R.drawable.jiwawa
),
Dog(
"金毛",
"金毛犬,属于匀称有力、性格活泼的一个犬种,特征是结构稳固、身体各个部位的比例合理而协调,腿既不太长也会显得笨拙,表情友善,热情、机警、自信,而且不怕生。",
R.drawable.jinmao
),
Dog(
"柴犬",
"柴犬是体型中等并且又最古老的犬。柴犬能够应付陡峭的丘陵和山脉的斜坡,拥有灵敏的感官,使得柴犬屡次成为上乘的狩猎犬。柴犬性格活泼、好动。对自己喜欢的玩具、会一天到晚的把玩。其对外有极强警惕性,能为户主看家护院。其特别是对大型同类,并且不服输。\n",
R.drawable.chaiquan
),
Dog(
"杜宾犬",
"杜宾犬,起源于19世纪后期。按体型它属于大型犬;按毛发,它则属于短毛型;按用途,它又属于狩猎犬。活泼友善、坚定机敏、遇事镇静;顺从,对家庭十分忠诚,喜欢小孩。脾气温和、警惕性一般。在和饲主关系融洽的情况下,通常是不会轻易发怒的。",
R.drawable.dubin
),
Dog(
"哈士奇",
"西伯利亚雪橇犬是原始的古老犬种,主要生活在在西伯利亚东北部、格陵兰南部。哈士奇名字是源自其独特的嘶哑叫声。\n" +
" \n" +
" 友好、温柔、警觉,聪明,温顺,热情并喜欢交往。它不会呈现出护卫犬那种强烈的领地占有欲,也不会对陌生人产生过多的怀疑,对别的犬类也不会有攻击性。成年犬应该具备一定程度的谨慎和威严。\n" +
" ",
R.drawable.hashiqi
),
Dog(
"萨摩耶",
" 萨摩耶犬(英文:Samoyed),别称萨摩耶,原是西伯利亚的原住民萨摩耶族培育出的犬种,一岁前调皮、灵动。",
R.drawable.samoye
),
Dog(
"拉布拉多",
"拉布拉多猎犬,别名:拉布拉多、拉不拉多,英文名:labrador retriever.属于一种结构坚固、中等体型、接合较短的犬,它健康、稳定性良好的结构使其可成为寻回猎物的猎犬。",
R.drawable.labuladuo
),
Dog(
"吉娃娃",
"吉娃娃犬属于小型犬中体形最小的,但是这并不能说明它们是最娇弱的,相反,吉娃娃有着坚韧的意志,非常忠诚与主人,灵活度极高,是一种聪明的宠物。姿态优雅、性格警惕、动作迅速,以匀称的体格和娇小的体型而广泛的受人所青睐。",
R.drawable.jiwawa
),
Dog(
"金毛",
"金毛犬,属于匀称有力、性格活泼的一个犬种,特征是结构稳固、身体各个部位的比例合理而协调,腿既不太长也会显得笨拙,表情友善,热情、机警、自信,而且不怕生。",
R.drawable.jinmao
),
Dog(
"柴犬",
"柴犬是体型中等并且又最古老的犬。柴犬能够应付陡峭的丘陵和山脉的斜坡,拥有灵敏的感官,使得柴犬屡次成为上乘的狩猎犬。柴犬性格活泼、好动。对自己喜欢的玩具、会一天到晚的把玩。其对外有极强警惕性,能为户主看家护院。其特别是对大型同类,并且不服输。\n",
R.drawable.chaiquan
),
Dog(
"杜宾犬",
"杜宾犬,起源于19世纪后期。按体型它属于大型犬;按毛发,它则属于短毛型;按用途,它又属于狩猎犬。活泼友善、坚定机敏、遇事镇静;顺从,对家庭十分忠诚,喜欢小孩。脾气温和、警惕性一般。在和饲主关系融洽的情况下,通常是不会轻易发怒的。",
R.drawable.dubin
),
Dog(
"哈士奇",
"西伯利亚雪橇犬是原始的古老犬种,主要生活在在西伯利亚东北部、格陵兰南部。哈士奇名字是源自其独特的嘶哑叫声。\n" +
" \n" +
" 友好、温柔、警觉,聪明,温顺,热情并喜欢交往。它不会呈现出护卫犬那种强烈的领地占有欲,也不会对陌生人产生过多的怀疑,对别的犬类也不会有攻击性。成年犬应该具备一定程度的谨慎和威严。\n" +
" ",
R.drawable.hashiqi
),
Dog(
"萨摩耶",
" 萨摩耶犬(英文:Samoyed),别称萨摩耶,原是西伯利亚的原住民萨摩耶族培育出的犬种,一岁前调皮、灵动。",
R.drawable.samoye
),
Dog(
"拉布拉多",
"拉布拉多猎犬,别名:拉布拉多、拉不拉多,英文名:labrador retriever.属于一种结构坚固、中等体型、接合较短的犬,它健康、稳定性良好的结构使其可成为寻回猎物的猎犬。",
R.drawable.labuladuo
),
Dog(
"吉娃娃",
"吉娃娃犬属于小型犬中体形最小的,但是这并不能说明它们是最娇弱的,相反,吉娃娃有着坚韧的意志,非常忠诚与主人,灵活度极高,是一种聪明的宠物。姿态优雅、性格警惕、动作迅速,以匀称的体格和娇小的体型而广泛的受人所青睐。",
R.drawable.jiwawa
),
Dog(
"金毛",
"金毛犬,属于匀称有力、性格活泼的一个犬种,特征是结构稳固、身体各个部位的比例合理而协调,腿既不太长也会显得笨拙,表情友善,热情、机警、自信,而且不怕生。",
R.drawable.jinmao
),
Dog(
"柴犬",
"柴犬是体型中等并且又最古老的犬。柴犬能够应付陡峭的丘陵和山脉的斜坡,拥有灵敏的感官,使得柴犬屡次成为上乘的狩猎犬。柴犬性格活泼、好动。对自己喜欢的玩具、会一天到晚的把玩。其对外有极强警惕性,能为户主看家护院。其特别是对大型同类,并且不服输。\n",
R.drawable.chaiquan
),
Dog(
"杜宾犬",
"杜宾犬,起源于19世纪后期。按体型它属于大型犬;按毛发,它则属于短毛型;按用途,它又属于狩猎犬。活泼友善、坚定机敏、遇事镇静;顺从,对家庭十分忠诚,喜欢小孩。脾气温和、警惕性一般。在和饲主关系融洽的情况下,通常是不会轻易发怒的。",
R.drawable.dubin
),
Dog(
"哈士奇",
"西伯利亚雪橇犬是原始的古老犬种,主要生活在在西伯利亚东北部、格陵兰南部。哈士奇名字是源自其独特的嘶哑叫声。\n" +
" \n" +
" 友好、温柔、警觉,聪明,温顺,热情并喜欢交往。它不会呈现出护卫犬那种强烈的领地占有欲,也不会对陌生人产生过多的怀疑,对别的犬类也不会有攻击性。成年犬应该具备一定程度的谨慎和威严。\n" +
" ",
R.drawable.hashiqi
),
Dog(
"萨摩耶",
" 萨摩耶犬(英文:Samoyed),别称萨摩耶,原是西伯利亚的原住民萨摩耶族培育出的犬种,一岁前调皮、灵动。",
R.drawable.samoye
),
Dog(
"拉布拉多",
"拉布拉多猎犬,别名:拉布拉多、拉不拉多,英文名:labrador retriever.属于一种结构坚固、中等体型、接合较短的犬,它健康、稳定性良好的结构使其可成为寻回猎物的猎犬。",
R.drawable.labuladuo
)
)
)
var openMode: Mode? by mutableStateOf(null)
var currentDog: Dog? by mutableStateOf(null)
private set
fun goToDetail(dog: Dog) {
openMode = Mode.Dog
currentDog = dog
}
fun endDetail() {
openMode = null
}
}
| 0 | Kotlin | 0 | 0 | a4fadbb5dbe590f943b89365d12a7295e656c08b | 5,939 | android-dev-challenge-compose-1 | Apache License 2.0 |
base/src/main/java/org/kin/stellarfork/xdr/TrustLineFlags.kt | wangpeikai | 364,139,277 | true | {"Kotlin": 2253108, "Java": 312868} | // Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
package org.kin.stellarfork.xdr
import java.io.IOException
// === xdr source ============================================================
// enum TrustLineFlags
// {
// // issuer has authorized account to perform transactions with its credit
// AUTHORIZED_FLAG = 1
// };
// ===========================================================================
enum class TrustLineFlags(val value: Int) {
AUTHORIZED_FLAG(1);
companion object {
@JvmStatic
@Throws(IOException::class)
fun decode(stream: XdrDataInputStream): TrustLineFlags {
val value = stream.readInt()
return when (value) {
1 -> AUTHORIZED_FLAG
else -> throw RuntimeException("Unknown enum value: $value")
}
}
@JvmStatic
@Throws(IOException::class)
fun encode(stream: XdrDataOutputStream, value: TrustLineFlags) {
stream.writeInt(value.value)
}
}
}
| 0 | null | 0 | 0 | 7b0ccee81d00f445af7ca25252bb0bf2d7c02b40 | 1,067 | kin-core | MIT License |
json-builder/kotlin/src/generated/kotlin/divkit/dsl/AnimatorBase.kt | divkit | 523,491,444 | false | {"Kotlin": 7244467, "Swift": 4739379, "Svelte": 1127035, "TypeScript": 893641, "Dart": 626262, "Python": 534486, "Java": 501637, "JavaScript": 152498, "CSS": 36535, "HTML": 23434, "C++": 20911, "CMake": 18677, "Shell": 8282, "PEG.js": 7210, "Ruby": 3723, "C": 1425, "Objective-C": 38} | @file:Suppress(
"unused",
"UNUSED_PARAMETER",
)
package divkit.dsl
import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonIgnore
import com.fasterxml.jackson.annotation.JsonValue
import divkit.dsl.annotation.*
import divkit.dsl.core.*
import divkit.dsl.scope.*
import kotlin.Any
import kotlin.String
import kotlin.Suppress
import kotlin.collections.List
import kotlin.collections.Map
/**
* Can be created using the method [animatorBase].
*
* Required parameters: `variable_name, id, duration`.
*/
@Generated
class AnimatorBase internal constructor(
@JsonIgnore
val properties: Properties,
) {
@JsonAnyGetter
internal fun getJsonProperties(): Map<String, Any> = properties.mergeWith(emptyMap())
operator fun plus(additive: Properties): AnimatorBase = AnimatorBase(
Properties(
cancelActions = additive.cancelActions ?: properties.cancelActions,
direction = additive.direction ?: properties.direction,
duration = additive.duration ?: properties.duration,
endActions = additive.endActions ?: properties.endActions,
id = additive.id ?: properties.id,
interpolator = additive.interpolator ?: properties.interpolator,
repeatCount = additive.repeatCount ?: properties.repeatCount,
startDelay = additive.startDelay ?: properties.startDelay,
variableName = additive.variableName ?: properties.variableName,
)
)
class Properties internal constructor(
/**
* Actions performed when the animator is cancelled. For example, when an action with `animator_stop` type is received
*/
val cancelActions: Property<List<Action>>?,
/**
* Animation direction. This property sets whether an animation should play forward, backward, or alternate back and forth between playing the sequence forward and backward.
* Default value: `normal`.
*/
val direction: Property<AnimationDirection>?,
/**
* Animation duration in milliseconds.
*/
val duration: Property<Long>?,
/**
* Actions performed when the animator completes animation.
*/
val endActions: Property<List<Action>>?,
/**
* Animator identificator
*/
val id: Property<String>?,
/**
* Interpolation function.
* Default value: `linear`.
*/
val interpolator: Property<AnimationInterpolator>?,
/**
* The number of times the animation will repeat before it finishes. `0` enables infinite repeats.
* Default value: `1`.
*/
val repeatCount: Property<Int>?,
/**
* Animation start delay in milliseconds.
* Default value: `0`.
*/
val startDelay: Property<Int>?,
/**
* Name of the variable being animated.
*/
val variableName: Property<String>?,
) {
internal fun mergeWith(properties: Map<String, Any>): Map<String, Any> {
val result = mutableMapOf<String, Any>()
result.putAll(properties)
result.tryPutProperty("cancel_actions", cancelActions)
result.tryPutProperty("direction", direction)
result.tryPutProperty("duration", duration)
result.tryPutProperty("end_actions", endActions)
result.tryPutProperty("id", id)
result.tryPutProperty("interpolator", interpolator)
result.tryPutProperty("repeat_count", repeatCount)
result.tryPutProperty("start_delay", startDelay)
result.tryPutProperty("variable_name", variableName)
return result
}
}
}
/**
* @param cancelActions Actions performed when the animator is cancelled. For example, when an action with `animator_stop` type is received
* @param direction Animation direction. This property sets whether an animation should play forward, backward, or alternate back and forth between playing the sequence forward and backward.
* @param duration Animation duration in milliseconds.
* @param endActions Actions performed when the animator completes animation.
* @param id Animator identificator
* @param interpolator Interpolation function.
* @param repeatCount The number of times the animation will repeat before it finishes. `0` enables infinite repeats.
* @param startDelay Animation start delay in milliseconds.
* @param variableName Name of the variable being animated.
*/
@Generated
fun DivScope.animatorBase(
`use named arguments`: Guard = Guard.instance,
cancelActions: List<Action>? = null,
direction: AnimationDirection? = null,
duration: Long? = null,
endActions: List<Action>? = null,
id: String? = null,
interpolator: AnimationInterpolator? = null,
repeatCount: Int? = null,
startDelay: Int? = null,
variableName: String? = null,
): AnimatorBase = AnimatorBase(
AnimatorBase.Properties(
cancelActions = valueOrNull(cancelActions),
direction = valueOrNull(direction),
duration = valueOrNull(duration),
endActions = valueOrNull(endActions),
id = valueOrNull(id),
interpolator = valueOrNull(interpolator),
repeatCount = valueOrNull(repeatCount),
startDelay = valueOrNull(startDelay),
variableName = valueOrNull(variableName),
)
)
/**
* @param cancelActions Actions performed when the animator is cancelled. For example, when an action with `animator_stop` type is received
* @param direction Animation direction. This property sets whether an animation should play forward, backward, or alternate back and forth between playing the sequence forward and backward.
* @param duration Animation duration in milliseconds.
* @param endActions Actions performed when the animator completes animation.
* @param id Animator identificator
* @param interpolator Interpolation function.
* @param repeatCount The number of times the animation will repeat before it finishes. `0` enables infinite repeats.
* @param startDelay Animation start delay in milliseconds.
* @param variableName Name of the variable being animated.
*/
@Generated
fun DivScope.animatorBaseProps(
`use named arguments`: Guard = Guard.instance,
cancelActions: List<Action>? = null,
direction: AnimationDirection? = null,
duration: Long? = null,
endActions: List<Action>? = null,
id: String? = null,
interpolator: AnimationInterpolator? = null,
repeatCount: Int? = null,
startDelay: Int? = null,
variableName: String? = null,
) = AnimatorBase.Properties(
cancelActions = valueOrNull(cancelActions),
direction = valueOrNull(direction),
duration = valueOrNull(duration),
endActions = valueOrNull(endActions),
id = valueOrNull(id),
interpolator = valueOrNull(interpolator),
repeatCount = valueOrNull(repeatCount),
startDelay = valueOrNull(startDelay),
variableName = valueOrNull(variableName),
)
/**
* @param cancelActions Actions performed when the animator is cancelled. For example, when an action with `animator_stop` type is received
* @param direction Animation direction. This property sets whether an animation should play forward, backward, or alternate back and forth between playing the sequence forward and backward.
* @param duration Animation duration in milliseconds.
* @param endActions Actions performed when the animator completes animation.
* @param id Animator identificator
* @param interpolator Interpolation function.
* @param repeatCount The number of times the animation will repeat before it finishes. `0` enables infinite repeats.
* @param startDelay Animation start delay in milliseconds.
* @param variableName Name of the variable being animated.
*/
@Generated
fun TemplateScope.animatorBaseRefs(
`use named arguments`: Guard = Guard.instance,
cancelActions: ReferenceProperty<List<Action>>? = null,
direction: ReferenceProperty<AnimationDirection>? = null,
duration: ReferenceProperty<Long>? = null,
endActions: ReferenceProperty<List<Action>>? = null,
id: ReferenceProperty<String>? = null,
interpolator: ReferenceProperty<AnimationInterpolator>? = null,
repeatCount: ReferenceProperty<Int>? = null,
startDelay: ReferenceProperty<Int>? = null,
variableName: ReferenceProperty<String>? = null,
) = AnimatorBase.Properties(
cancelActions = cancelActions,
direction = direction,
duration = duration,
endActions = endActions,
id = id,
interpolator = interpolator,
repeatCount = repeatCount,
startDelay = startDelay,
variableName = variableName,
)
/**
* @param cancelActions Actions performed when the animator is cancelled. For example, when an action with `animator_stop` type is received
* @param direction Animation direction. This property sets whether an animation should play forward, backward, or alternate back and forth between playing the sequence forward and backward.
* @param duration Animation duration in milliseconds.
* @param endActions Actions performed when the animator completes animation.
* @param id Animator identificator
* @param interpolator Interpolation function.
* @param repeatCount The number of times the animation will repeat before it finishes. `0` enables infinite repeats.
* @param startDelay Animation start delay in milliseconds.
* @param variableName Name of the variable being animated.
*/
@Generated
fun AnimatorBase.override(
`use named arguments`: Guard = Guard.instance,
cancelActions: List<Action>? = null,
direction: AnimationDirection? = null,
duration: Long? = null,
endActions: List<Action>? = null,
id: String? = null,
interpolator: AnimationInterpolator? = null,
repeatCount: Int? = null,
startDelay: Int? = null,
variableName: String? = null,
): AnimatorBase = AnimatorBase(
AnimatorBase.Properties(
cancelActions = valueOrNull(cancelActions) ?: properties.cancelActions,
direction = valueOrNull(direction) ?: properties.direction,
duration = valueOrNull(duration) ?: properties.duration,
endActions = valueOrNull(endActions) ?: properties.endActions,
id = valueOrNull(id) ?: properties.id,
interpolator = valueOrNull(interpolator) ?: properties.interpolator,
repeatCount = valueOrNull(repeatCount) ?: properties.repeatCount,
startDelay = valueOrNull(startDelay) ?: properties.startDelay,
variableName = valueOrNull(variableName) ?: properties.variableName,
)
)
/**
* @param cancelActions Actions performed when the animator is cancelled. For example, when an action with `animator_stop` type is received
* @param direction Animation direction. This property sets whether an animation should play forward, backward, or alternate back and forth between playing the sequence forward and backward.
* @param duration Animation duration in milliseconds.
* @param endActions Actions performed when the animator completes animation.
* @param id Animator identificator
* @param interpolator Interpolation function.
* @param repeatCount The number of times the animation will repeat before it finishes. `0` enables infinite repeats.
* @param startDelay Animation start delay in milliseconds.
* @param variableName Name of the variable being animated.
*/
@Generated
fun AnimatorBase.defer(
`use named arguments`: Guard = Guard.instance,
cancelActions: ReferenceProperty<List<Action>>? = null,
direction: ReferenceProperty<AnimationDirection>? = null,
duration: ReferenceProperty<Long>? = null,
endActions: ReferenceProperty<List<Action>>? = null,
id: ReferenceProperty<String>? = null,
interpolator: ReferenceProperty<AnimationInterpolator>? = null,
repeatCount: ReferenceProperty<Int>? = null,
startDelay: ReferenceProperty<Int>? = null,
variableName: ReferenceProperty<String>? = null,
): AnimatorBase = AnimatorBase(
AnimatorBase.Properties(
cancelActions = cancelActions ?: properties.cancelActions,
direction = direction ?: properties.direction,
duration = duration ?: properties.duration,
endActions = endActions ?: properties.endActions,
id = id ?: properties.id,
interpolator = interpolator ?: properties.interpolator,
repeatCount = repeatCount ?: properties.repeatCount,
startDelay = startDelay ?: properties.startDelay,
variableName = variableName ?: properties.variableName,
)
)
/**
* @param direction Animation direction. This property sets whether an animation should play forward, backward, or alternate back and forth between playing the sequence forward and backward.
* @param duration Animation duration in milliseconds.
* @param interpolator Interpolation function.
* @param repeatCount The number of times the animation will repeat before it finishes. `0` enables infinite repeats.
* @param startDelay Animation start delay in milliseconds.
*/
@Generated
fun AnimatorBase.evaluate(
`use named arguments`: Guard = Guard.instance,
direction: ExpressionProperty<AnimationDirection>? = null,
duration: ExpressionProperty<Long>? = null,
interpolator: ExpressionProperty<AnimationInterpolator>? = null,
repeatCount: ExpressionProperty<Int>? = null,
startDelay: ExpressionProperty<Int>? = null,
): AnimatorBase = AnimatorBase(
AnimatorBase.Properties(
cancelActions = properties.cancelActions,
direction = direction ?: properties.direction,
duration = duration ?: properties.duration,
endActions = properties.endActions,
id = properties.id,
interpolator = interpolator ?: properties.interpolator,
repeatCount = repeatCount ?: properties.repeatCount,
startDelay = startDelay ?: properties.startDelay,
variableName = properties.variableName,
)
)
@Generated
fun AnimatorBase.asList() = listOf(this)
| 5 | Kotlin | 122 | 2,219 | c7d6aa88277e2373e15a4cff3033a66b80227cd2 | 14,005 | divkit | Apache License 2.0 |
kool-core/src/jsMain/kotlin/de/fabmax/kool/NativeAssetLoader.kt | kool-engine | 81,503,047 | false | {"Kotlin": 5929566, "C++": 3256, "CMake": 1870, "HTML": 1464, "JavaScript": 597} | package de.fabmax.kool
import de.fabmax.kool.math.Vec2i
import de.fabmax.kool.modules.audio.AudioClipImpl
import de.fabmax.kool.pipeline.BufferedImageData2d
import de.fabmax.kool.pipeline.TexFormat
import de.fabmax.kool.pipeline.TextureProps
import de.fabmax.kool.platform.ImageAtlasTextureData
import de.fabmax.kool.platform.ImageTextureData
import de.fabmax.kool.util.Uint8BufferImpl
import de.fabmax.kool.util.logE
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.await
import org.khronos.webgl.Uint8Array
import org.w3c.dom.Image
import org.w3c.dom.ImageBitmap
class NativeAssetLoader(val basePath: String) : AssetLoader() {
override suspend fun loadBlob(ref: AssetRef.Blob): LoadedAsset.Blob {
val url = ref.path
val prefixedUrl = if (Assets.isHttpAsset(url)) url else "${basePath}/$url"
val result = fetchData(prefixedUrl).map { Uint8BufferImpl(Uint8Array(it.arrayBuffer().await())) }
return LoadedAsset.Blob(ref, result)
}
override suspend fun loadImage2d(ref: AssetRef.Image2d): LoadedAsset.Image2d {
val resolveSz = ref.props?.resolveSize
val result = loadImageBitmap(ref.path, ref.isHttp, resolveSz).map {
ImageTextureData(it, trimAssetPath(ref.path), ref.props?.format ?: TexFormat.RGBA)
}
return LoadedAsset.Image2d(ref, result)
}
override suspend fun loadImageAtlas(ref: AssetRef.ImageAtlas): LoadedAsset.ImageAtlas {
val resolveSz = ref.props?.resolveSize
val result = loadImageBitmap(ref.path, ref.isHttp, resolveSz).map {
ImageAtlasTextureData(it, ref.tilesX, ref.tilesY, trimAssetPath(ref.path), ref.props?.format ?: TexFormat.RGBA)
}
return LoadedAsset.ImageAtlas(ref, result)
}
override suspend fun loadBufferedImage2d(ref: AssetRef.BufferedImage2d): LoadedAsset.BufferedImage2d {
val props = ref.props ?: TextureProps()
val texRef = AssetRef.Image2d(ref.path, props)
val result = loadImage2d(texRef).result.mapCatching {
val texData = it as ImageTextureData
BufferedImageData2d(
ImageTextureData.imageBitmapToBuffer(texData.data, props),
texData.width,
texData.height,
props.format,
trimAssetPath(ref.path)
)
}
return LoadedAsset.BufferedImage2d(ref, result)
}
override suspend fun loadAudio(ref: AssetRef.Audio): LoadedAsset.Audio {
val assetPath = ref.path
val clip = if (Assets.isHttpAsset(assetPath)) {
AudioClipImpl(assetPath)
} else {
AudioClipImpl("${basePath}/$assetPath")
}
return LoadedAsset.Audio(ref, Result.success(clip))
}
private suspend fun loadImageBitmap(path: String, isHttp: Boolean, resize: Vec2i?): Result<ImageBitmap> {
val mime = MimeType.forFileName(path)
val prefixedUrl = if (isHttp) path else "${basePath}/${path}"
return if (mime != MimeType.IMAGE_SVG) {
// raster image type -> fetch blob and create ImageBitmap directly
fetchData(prefixedUrl).mapCatching {
val imgBlob = it.blob().await()
createImageBitmap(imgBlob, ImageBitmapOptions(resize)).await()
}
} else {
// svg image -> use an Image element to convert it to an ImageBitmap
val deferredBitmap = CompletableDeferred<ImageBitmap>()
val img = resize?.let { Image(it.x, it.y) } ?: Image()
img.onload = {
createImageBitmap(img, ImageBitmapOptions(resize)).then { bmp -> deferredBitmap.complete(bmp) }
}
img.onerror = { _, _, _, _, _ ->
deferredBitmap.completeExceptionally(IllegalStateException("Failed loading tex from $prefixedUrl"))
}
img.crossOrigin = ""
img.src = prefixedUrl
try {
Result.success(deferredBitmap.await())
} catch (t: Throwable) {
Result.failure(t)
}
}
}
private suspend fun fetchData(path: String): Result<Response> {
val response = fetch(path).await()
return if (!response.ok) {
logE { "Failed loading resource $path: ${response.status} ${response.statusText}" }
Result.failure(IllegalStateException("Failed loading resource $path: ${response.status} ${response.statusText}"))
} else {
Result.success(response)
}
}
} | 11 | Kotlin | 20 | 303 | 8d05acd3e72ff2fc115d0939bf021a5f421469a5 | 4,555 | kool | Apache License 2.0 |
app/src/main/java/io/horizontalsystems/bankwallet/core/App.kt | numsecurelab | 241,082,600 | false | null | package io.horizontalsystems.bankwallet.core
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Configuration
import android.preference.PreferenceManager
import android.util.Log
import androidx.core.app.NotificationManagerCompat
import com.squareup.leakcanary.LeakCanary
import io.horizontalsystems.bankwallet.BuildConfig
import io.horizontalsystems.bankwallet.core.factories.*
import io.horizontalsystems.bankwallet.core.managers.*
import io.horizontalsystems.bankwallet.core.security.EncryptionManager
import io.horizontalsystems.bankwallet.core.security.KeyStoreManager
import io.horizontalsystems.bankwallet.core.storage.*
import io.horizontalsystems.bankwallet.localehelper.LocaleHelper
import io.horizontalsystems.bankwallet.modules.fulltransactioninfo.FullTransactionInfoFactory
import io.horizontalsystems.bankwalval.core.utils.EmojiHelper
import io.reactivex.plugins.RxJavaPlugins
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
class App : Application() {
companion object {
lateinit var preferences: SharedPreferences
lateinit var feeRateProvider: FeeRateProvider
lateinit var secureStorage: ISecuredStorage
lateinit var localStorage: LocalStorageManager
lateinit var keyStoreManager: IKeyStoreManager
lateinit var keyProvider: IKeyProvider
lateinit var encryptionManager: IEncryptionManager
lateinit var wordsManager: WordsManager
lateinit var randomManager: IRandomProvider
lateinit var networkManager: INetworkManager
lateinit var currencyManager: ICurrencyManager
lateinit var backgroundManager: BackgroundManager
lateinit var languageManager: ILanguageManager
lateinit var systemInfoManager: ISystemInfoManager
lateinit var pinManager: IPinManager
lateinit var lockManager: ILockManager
lateinit var keyStoreChangeListener: KeyStoreChangeListener
lateinit var appConfigProvider: IAppConfigProvider
lateinit var adapterManager: IAdapterManager
lateinit var walletManager: IWalletManager
lateinit var walletFactory: IWalletFactory
lateinit var walletStorage: IWalletStorage
lateinit var accountManager: IAccountManager
lateinit var backupManager: IBackupManager
lateinit var accountCreator: IAccountCreator
lateinit var predefinedAccountTypeManager: IPredefinedAccountTypeManager
lateinit var walletRemover: WalletRemover
lateinit var xRateManager: IRateManager
lateinit var connectivityManager: ConnectivityManager
lateinit var appDatabase: AppDatabase
lateinit var rateStorage: IRateStorage
lateinit var accountsStorage: IAccountsStorage
lateinit var priceAlertsStorage: IPriceAlertsStorage
lateinit var priceAlertManager: PriceAlertManager
lateinit var enabledWalletsStorage: IEnabledWalletStorage
lateinit var transactionInfoFactory: FullTransactionInfoFactory
lateinit var transactionDataProviderManager: TransactionDataProviderManager
lateinit var ethereumKitManager: IEthereumKitManager
lateinit var eosKitManager: IEosKitManager
lateinit var binanceKitManager: BinanceKitManager
lateinit var numberFormatter: IAppNumberFormatter
lateinit var addressParserFactory: AddressParserFactory
lateinit var feeCoinProvider: FeeCoinProvider
lateinit var priceAlertHandler: IPriceAlertHandler
lateinit var backgroundPriceAlertManager: IBackgroundPriceAlertManager
lateinit var emojiHelper: IEmojiHelper
lateinit var notificationManager: INotificationManager
lateinit var notificationFactory: INotificationFactory
lateinit var appStatusManager: IAppStatusManager
lateinit var appVersionManager: AppVersionManager
lateinit var backgroundRateAlertScheduler: IBackgroundRateAlertScheduler
lateinit var coinSettingsManager: ICoinSettingsManager
lateinit var instance: App
private set
var lastExitDate: Long = 0
}
override fun onCreate() {
super.onCreate()
if (LeakCanary.isInAnalyzerProcess(this)) {
// This process is dedicated to LeakCanary for heap analysis.
// You should not init your app in this process.
return
}
LeakCanary.install(this)
if (!BuildConfig.DEBUG) {
//Disable logging for lower levels in Release build
Logger.getLogger("").level = Level.SEVERE
}
RxJavaPlugins.setErrorHandler { e: Throwable? ->
Log.w("RxJava ErrorHandler", e)
}
instance = this
preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
appConfigProvider = AppConfigProvider()
feeRateProvider = FeeRateProvider(instance, appConfigProvider)
backgroundManager = BackgroundManager(this)
KeyStoreManager("MASTER_KEY").apply {
keyStoreManager = this
keyProvider = this
}
encryptionManager = EncryptionManager(keyProvider)
secureStorage = SecuredStorageManager(encryptionManager)
ethereumKitManager = EthereumKitManager(appConfigProvider)
eosKitManager = EosKitManager(appConfigProvider)
binanceKitManager = BinanceKitManager(appConfigProvider)
appDatabase = AppDatabase.getInstance(this)
rateStorage = RatesRepository(appDatabase)
accountsStorage = AccountsStorage(appDatabase)
walletFactory = WalletFactory()
enabledWalletsStorage = EnabledWalletsStorage(appDatabase)
walletStorage = WalletStorage(appConfigProvider, walletFactory, enabledWalletsStorage)
localStorage = LocalStorageManager()
wordsManager = WordsManager(localStorage)
networkManager = NetworkManager()
accountManager = AccountManager(accountsStorage, AccountCleaner(appConfigProvider.testMode))
backupManager = BackupManager(accountManager)
walletManager = WalletManager(accountManager, walletFactory, walletStorage)
accountCreator = AccountCreator(AccountFactory(), wordsManager)
predefinedAccountTypeManager = PredefinedAccountTypeManager(accountManager, accountCreator)
walletRemover = WalletRemover(accountManager, walletManager)
randomManager = RandomProvider()
systemInfoManager = SystemInfoManager()
pinManager = PinManager(secureStorage, localStorage)
lockManager = LockManager(pinManager).apply {
backgroundManager.registerListener(this)
}
keyStoreChangeListener = KeyStoreChangeListener(systemInfoManager, keyStoreManager).apply {
backgroundManager.registerListener(this)
}
languageManager = LanguageManager(appConfigProvider, "en")
currencyManager = CurrencyManager(localStorage, appConfigProvider)
numberFormatter = NumberFormatter(languageManager)
connectivityManager = ConnectivityManager()
adapterManager = AdapterManager(walletManager, AdapterFactory(instance, appConfigProvider, ethereumKitManager, eosKitManager, binanceKitManager), ethereumKitManager, eosKitManager, binanceKitManager)
xRateManager = RateManager(this, walletManager, currencyManager)
transactionDataProviderManager = TransactionDataProviderManager(appConfigProvider, localStorage)
transactionInfoFactory = FullTransactionInfoFactory(networkManager, transactionDataProviderManager)
addressParserFactory = AddressParserFactory()
feeCoinProvider = FeeCoinProvider(appConfigProvider)
priceAlertsStorage = PriceAlertsStorage(appConfigProvider, appDatabase)
priceAlertManager = PriceAlertManager(walletManager, priceAlertsStorage)
emojiHelper = EmojiHelper()
notificationFactory = NotificationFactory(emojiHelper, instance)
notificationManager = NotificationManager(NotificationManagerCompat.from(this))
priceAlertHandler = PriceAlertHandler(priceAlertsStorage, notificationManager, notificationFactory)
backgroundRateAlertScheduler = BackgroundRateAlertScheduler(instance)
backgroundPriceAlertManager = BackgroundPriceAlertManager(localStorage, backgroundRateAlertScheduler, priceAlertsStorage, xRateManager, walletStorage, currencyManager, rateStorage, priceAlertHandler, notificationManager).apply {
backgroundManager.registerListener(this)
}
appStatusManager = AppStatusManager(systemInfoManager, localStorage, accountManager, predefinedAccountTypeManager, walletManager, adapterManager, appConfigProvider, ethereumKitManager, eosKitManager, binanceKitManager)
appVersionManager = AppVersionManager(systemInfoManager, localStorage).apply {
backgroundManager.registerListener(this)
}
coinSettingsManager = CoinSettingsManager()
}
override fun attachBaseContext(base: Context) {
super.attachBaseContext(localeAwareContext(base))
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
localeAwareContext(this)
}
fun localeAwareContext(base: Context): Context {
return LocaleHelper.onAttach(base)
}
fun getLocale(): Locale {
return LocaleHelper.getLocale(this)
}
fun setLocale(currentLocale: Locale) {
LocaleHelper.setLocale(this, currentLocale)
}
fun isLocaleRTL(): Boolean {
return LocaleHelper.isRTL(Locale.getDefault())
}
}
| 4 | Kotlin | 0 | 1 | 7bbaf88819bac92b2c0296cb5ab1e5584688903e | 9,708 | w-and | MIT License |
kcrypto/src/main/kotlin/org/bouncycastle/kcrypto/spec/symmetric/HMacSHA512GenSpec.kt | bcgit | 196,159,414 | false | {"Kotlin": 458444, "HTML": 419} | package org.bouncycastle.kcrypto.spec.symmetric
import KCryptoServices
import org.bouncycastle.kcrypto.AuthenticationKey
import org.bouncycastle.kcrypto.KeyType
import org.bouncycastle.kcrypto.spec.AuthGenSpec
import org.bouncycastle.kcrypto.spec.AuthKeyGenSpec
import java.security.SecureRandom
/**
* HMAC SHA-512 key generator specification.
*/
class HMacSHA512GenSpec(val keySize: Int, override val random: SecureRandom): AuthKeyGenSpec
{
constructor() : this(512)
constructor(keySize: Int): this(keySize, KCryptoServices.secureRandom)
override val authType: KeyType<AuthenticationKey> get() = Companion.authType
companion object: AuthGenSpec {
override val authType = KeyType.AUTHENTICATION.forAlgorithm("HMacSHA512")
}
} | 0 | Kotlin | 15 | 69 | dc86103f5fef1baf9f6e1cdff17bbf31927637ab | 759 | bc-kotlin | MIT License |
app/src/main/java/com/byteteam/bluesense/core/data/source/remote/response/MessageResponse.kt | BlueSense-by-ByteTeam | 738,355,445 | false | {"Kotlin": 443744} | package com.byteteam.bluesense.core.data.source.remote.response
import com.google.gson.annotations.SerializedName
data class MessageResponse(
@field:SerializedName("message")
val message: String? = null
)
| 0 | Kotlin | 0 | 1 | 013db3c26b47e8d9b49c335d467318a49640aa9c | 210 | bluesense-android | Apache License 2.0 |
core-kotlin-modules/core-kotlin-lang-oop-3/src/test/kotlin/com/baeldung/staticFunInEnum/StaticFunctionInEnumUnitTest.kt | Baeldung | 260,481,121 | false | {"Kotlin": 1855665, "Java": 48276, "HTML": 4883, "Dockerfile": 292} | package com.baeldung.staticFunInEnum
import com.baeldung.staticFunInEnum.MagicNumber.*
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
enum class MagicNumber(val value: Int) {
ONE(1), TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6);
companion object {
fun pickOneRandomly(): MagicNumber {
return values().random()
}
@JvmStatic
fun greaterThan(n: Int): List<MagicNumber> {
return values().filter { it.value > n }
}
}
}
class StaticFunctionInEnumUnitTest {
@Test
fun `given enum with companion object when call functions in companion object, should get expected result`() {
assertNotNull(MagicNumber.pickOneRandomly())
assertEquals(listOf(THREE, FOUR, FIVE, SIX), MagicNumber.greaterThan(2))
}
} | 14 | Kotlin | 294 | 465 | f1ef5d5ded3f7ddc647f1b6119f211068f704577 | 850 | kotlin-tutorials | MIT License |
app/src/main/java/com/msg/gcms/data/remote/dto/club/response/ClubInfoResponse.kt | GSM-MSG | 465,292,111 | false | null | package com.msg.gcms.data.remote.dto.club.response
import com.msg.gcms.data.remote.dto.user.response.UserData
import java.io.Serializable
data class ClubInfoResponse(
val club: ClubResponse,
val activityUrls: List<String>,
val head: UserInfo,
val member: List<UserData>,
val scope: String,
val isApplied: Boolean
): Serializable
| 4 | Kotlin | 0 | 0 | 8239a015cc311b1631e0c6fc5047e231b5a7ec20 | 355 | GCMS-Android | MIT License |
src/main/kotlin/design_patterns/Adapter.kt | DmitryTsyvtsyn | 418,166,620 | false | {"Kotlin": 175531} | package design_patterns
/**
*
* pattern: Adapter
*
* using: used when we cannot directly use the functionality of an object
*
* description: to use the functionality of an object, a special class is created, which is called an adapter
*
*/
interface Adapter<T> {
fun getItem(position: Int) : T
fun getItemCount() : Int
}
/**
* here is a simplified imitation of RecyclerView component from Android
*/
class RecyclerView<T> {
private var adapter: Adapter<T>? = null
fun changeAdapter(adapter: Adapter<T>) {
this.adapter = adapter
}
/**
* renders elements from the adapter and returns a list of elements to test
*/
fun draw() : List<T> {
val items = mutableListOf<T>()
val myAdapter = adapter
if (myAdapter != null) {
val count = myAdapter.getItemCount()
for (i in 0 until count) {
items.add(myAdapter.getItem(i))
// draw item
}
}
return items
}
} | 0 | Kotlin | 134 | 743 | 371aa2126fb3ddc4c817c82aa20f53d3b2bf4863 | 1,019 | Kotlin-Algorithms-and-Design-Patterns | MIT License |
swipe-downer/src/main/java/com/prongbang/ui/swipedowner/BaseSwipeDowner.kt | prongbang | 120,561,167 | false | null | package com.prongbang.ui.swipedowner
import android.app.Activity
import android.view.GestureDetector
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import androidx.annotation.ColorRes
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.content.ContextCompat
import androidx.core.view.MotionEventCompat
/**
* Created by prongbang on 2/7/2018 AD.
*/
open class BaseSwipeDowner(private val activity: Activity) : SwipeDownAdapter<BaseSwipeDowner> {
private var imageSuccess: Int = R.drawable.ic_check_circle
private var imageError: Int = R.drawable.ic_sentiment_dissatisfied
private var imageWarning: Int = R.drawable.ic_warning
private var duration: Long = 2000
private var isClosed = false
private var onItemClickListener: OnSwipeDownItemClickListener? = null
private var mViewLayout: View? = null
private var mTvMessage: AppCompatTextView? = null
private var mImage: AppCompatImageView? = null
private var onCloseListener: OnCloseListener? = null
private var mViewParent: ViewGroup? = null
override fun builder(view: View?): BaseSwipeDowner {
if (view != null) {
mViewParent = view as ViewGroup
val v = LayoutInflater.from(activity.applicationContext)
.inflate(R.layout.item_swipe_downer, mViewParent, false)
if (v != null) {
// Check Swipe down message created.
val findView = view.findViewById<View>(R.id.vMsgContainer)
if (findView == null) {
view.addView(v)
}
mViewLayout = view.findViewById(R.id.vMsgContainer)
mImage = view.findViewById(R.id.ivNotiImage)
mTvMessage = view.findViewById(R.id.tvMessage)
}
}
return this
}
override fun builder(): BaseSwipeDowner {
return builder(activity.window.decorView.rootView ?: getRootView(activity))
}
private fun getRootView(activity: Activity): View {
return activity.findViewById<View>(android.R.id.content).rootView
}
override fun setHeight(h: Int): BaseSwipeDowner {
val params = mViewLayout?.layoutParams
params?.height = h
return this
}
override fun setBackground(@ColorRes color: Int): BaseSwipeDowner {
mViewLayout?.setBackgroundColor(ContextCompat.getColor(activity.applicationContext, color))
return this
}
override fun setTextColor(@ColorRes color: Int): BaseSwipeDowner {
mTvMessage?.setTextColor(ContextCompat.getColor(activity.applicationContext, color))
return this
}
override fun setImageSuccess(@DrawableRes imageRes: Int): BaseSwipeDowner {
imageSuccess = imageRes
return this
}
override fun setImageError(@DrawableRes imageRes: Int): BaseSwipeDowner {
imageError = imageRes
return this
}
override fun setImageWarning(@DrawableRes imageRes: Int): BaseSwipeDowner {
imageWarning = imageRes
return this
}
override fun isSuccess(): BaseSwipeDowner {
mViewLayout?.background = ContextCompat.getDrawable(activity.applicationContext,
R.drawable.bg_swipe_down_success)
setTextColor(R.color.white)
mImage?.setImageDrawable(
ContextCompat.getDrawable(activity.applicationContext, imageSuccess))
return this
}
override fun isError(): BaseSwipeDowner {
mViewLayout?.background = ContextCompat.getDrawable(activity.applicationContext,
R.drawable.bg_swipe_down_fail)
setTextColor(R.color.white)
mImage?.setImageDrawable(ContextCompat.getDrawable(activity.applicationContext, imageError))
return this
}
override fun isWarning(): BaseSwipeDowner {
mViewLayout?.background = ContextCompat.getDrawable(activity.applicationContext,
R.drawable.bg_swipe_down_warning)
setTextColor(R.color.white)
mImage?.setImageDrawable(
ContextCompat.getDrawable(activity.applicationContext, imageWarning))
return this
}
override fun message(msg: String): BaseSwipeDowner {
mTvMessage?.text = msg
return this
}
override fun message(@StringRes msg: Int): BaseSwipeDowner {
mTvMessage?.text = activity.applicationContext.getString(msg)
return this
}
override fun show() {
isClosed = false
val gestureDetector = GestureDetector(activity.applicationContext, SingleTapConfirm())
val slideDown = AnimationUtils.loadAnimation(activity.applicationContext, R.anim.slide_down)
mViewLayout?.apply {
visibility = View.VISIBLE
startAnimation(slideDown)
setOnTouchListener(View.OnTouchListener { v, event ->
val action = MotionEventCompat.getActionMasked(event)
if (gestureDetector.onTouchEvent(event)) {
onItemClickListener?.onClick(v)
} else {
when (action) {
MotionEvent.ACTION_MOVE -> return@OnTouchListener true
MotionEvent.ACTION_UP -> {
hide()
return@OnTouchListener true
}
}
}
true
})
postDelayed({
if (!isClosed) {
hide()
}
}, duration)
}
}
override fun hide() {
val slideUp = AnimationUtils.loadAnimation(activity.applicationContext, R.anim.slide_up)
mViewLayout?.apply {
startAnimation(slideUp)
postDelayed({
isClosed = true
mViewLayout?.visibility = View.GONE
mViewParent?.removeView(mViewLayout)
onCloseListener?.onClosed()
}, 500)
}
}
override fun setOnItemClickListener(
onItemClickListener: OnSwipeDownItemClickListener): BaseSwipeDowner {
this.onItemClickListener = onItemClickListener
return this
}
override fun setDuration(duration: Long): BaseSwipeDowner {
this.duration = duration
return this
}
override fun onClosed(onCloseListener: OnCloseListener): BaseSwipeDowner {
this.onCloseListener = onCloseListener
return this
}
} | 1 | null | 1 | 1 | 20940052d8a230eeb71bf4a8d3c21c98a81d539a | 5,703 | SwipeDowner | MIT License |
app/src/main/java/ch/admin/foitt/pilotwallet/feature/credentialActivities/di/CredentialActivitiesModule.kt | e-id-admin | 775,912,525 | false | {"Kotlin": 1521284} | package ch.admin.foitt.pilotwallet.feature.credentialActivities.di
import ch.admin.foitt.pilotwallet.feature.credentialActivities.domain.usecase.GetActivitiesForCredentialFlow
import ch.admin.foitt.pilotwallet.feature.credentialActivities.domain.usecase.GetCredentialActivityDetailFlow
import ch.admin.foitt.pilotwallet.feature.credentialActivities.domain.usecase.implementation.GetActivitiesForCredentialFlowImpl
import ch.admin.foitt.pilotwallet.feature.credentialActivities.domain.usecase.implementation.GetCredentialActivityDetailFlowImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityRetainedComponent
@Module
@InstallIn(ActivityRetainedComponent::class)
interface CredentialActivitiesModule {
@Binds
fun bindGetCredentialActivityDetailFlow(
useCase: GetCredentialActivityDetailFlowImpl
): GetCredentialActivityDetailFlow
@Binds
fun bindGetActivitiesForCredentialFlow(
useCase: GetActivitiesForCredentialFlowImpl
): GetActivitiesForCredentialFlow
}
| 1 | Kotlin | 1 | 4 | 6572b418ec5abc5d94b18510ffa87a1e433a5c82 | 1,067 | eidch-pilot-android-wallet | MIT License |
Code/CurrencyConversionApp/app-core/data/database/src/main/kotlin/com/istudio/database/domain/CurrencyDbFeatures.kt | devrath | 708,793,882 | false | {"Kotlin": 421370} | package com.istudio.database.domain
import com.istudio.models.local.CurrencyAndRates
import com.istudio.models.local.CurrencyEntity
import com.istudio.models.local.RatesEntity
import kotlinx.coroutines.flow.Flow
interface CurrencyDbFeatures {
/**
* OPERATION : Retrieving
*
* RETURNS : List of currencies
*/
suspend fun getCurrencyList() : Flow<List<CurrencyEntity>>
/**
* OPERATION : Adding
*
* RETURNS : Adding a new currency value into the database for currency table
*/
suspend fun addCurrency(currency: CurrencyEntity)
/**
* OPERATION : Adding
*
* RETURNS : Adding a new rate value into the database for the rates table
*/
suspend fun addRates(rate: RatesEntity)
/**
* OPERATION : Retrieving
*
* RETURNS : List of rates and the currency matched to each rates combined
*/
suspend fun getCurrencyAndRates() : List<CurrencyAndRates>
} | 0 | Kotlin | 0 | 0 | 2be65d3388acfb5436cebeb4e03b0da581e2b437 | 953 | Droid-Testing-kit | Apache License 2.0 |
src/main/kotlin/de/mtorials/dialbot/webhooks/WebHooks.kt | mtorials | 276,343,624 | false | null | package de.mtorials.dialbot.webhooks
import de.mtorials.dialbot.logger
import de.mtorials.dialphone.DialPhone
import de.mtorials.dialphone.entities.entityfutures.RoomFuture
import de.mtorials.dialphone.sendHtmlMessage
import de.mtorials.dialphone.sendTextMessage
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.http4k.core.*
import org.http4k.lens.Query
import org.http4k.lens.string
import org.http4k.routing.bind
import org.http4k.routing.routes
import org.http4k.server.Jetty
import org.http4k.server.asServer
fun startWebhooks(phone: DialPhone, token: String, port: Int) {
val bodyLens = Body.string(ContentType.TEXT_PLAIN).toLens()
val queryLens = Query.optional("roomId")
val authLens = Query.optional("token")
val auth = Filter { next ->
block@{ request ->
if (authLens(request) != token) return@block Response(Status.UNAUTHORIZED)
next(request)
}
}
val handlerText : HttpHandler = block@{ request ->
logger.info { "Text Webhook ${bodyLens(request)}" }
val roomId: String = queryLens(request) ?: return@block Response(Status.BAD_REQUEST).body("no room id")
val mayRoom: RoomFuture?
runBlocking { mayRoom = phone.getJoinedRoomFutureById(roomId) }
val room: RoomFuture = mayRoom ?: return@block Response(Status.NOT_FOUND).body("cant find room")
runBlocking { room.sendTextMessage(bodyLens(request)) }
Response(Status.OK)
}
val handlerHtml : HttpHandler = block@{ request ->
logger.info { "Html Webhook ${bodyLens(request)}" }
val roomId: String = queryLens(request) ?: return@block Response(Status.BAD_REQUEST).body("no room id")
val mayRoom: RoomFuture?
runBlocking { mayRoom = phone.getJoinedRoomFutureById(roomId) }
val room: RoomFuture = mayRoom ?: return@block Response(Status.NOT_FOUND).body("cant find room")
GlobalScope.launch { room.sendHtmlMessage(bodyLens(request)) }
Response(Status.OK)
}
val app = auth.then(routes(
"sendText" bind Method.POST to handlerText,
"sendHtml" bind Method.POST to handlerHtml,
"ping" bind Method.GET to {
Response(Status.OK).body("pong!")
}
))
logger.info("starting server...")
app.asServer(Jetty(port)).start()
} | 3 | Kotlin | 0 | 2 | 681fe3a718e2c1f0dcad4e5c910cd3dc1b76e0dc | 2,386 | dialbot | Apache License 2.0 |
snackbar/src/main/java/com/vkondrav/ram/snackbar/SnackbarController.kt | vkondrav | 481,052,423 | false | null | package com.vkondrav.ram.snackbar
import androidx.compose.material.SnackbarHostState
import com.vkondrav.ram.common.util.FlowWrapper
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collectLatest
internal class SnackbarController(private val wrapper: FlowWrapper = FlowWrapper()) {
private val messages = MutableSharedFlow<String>(extraBufferCapacity = Int.MAX_VALUE)
fun showMessage(message: String) {
messages.tryEmit(message)
}
suspend fun handleSnackbarState(snackbarHostState: SnackbarHostState) {
wrapper(messages).collectLatest { message ->
snackbarHostState.currentSnackbarData?.dismiss()
snackbarHostState.showSnackbar(message)
}
}
}
| 0 | Kotlin | 1 | 0 | 78c466563652800d8001a58504a533b764507461 | 747 | rick_and_morty_compose | MIT License |
app/src/main/java/gsrv/klassenplaner/notifications/NotificationChannelHelper.kt | jonas-haeusler | 207,426,160 | false | null | package gsrv.klassenplaner.notifications
import android.annotation.TargetApi
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.core.app.NotificationManagerCompat
import gsrv.klassenplaner.R
class NotificationChannelHelper(val context: Context) {
private val manager: NotificationManagerCompat by lazy {
NotificationManagerCompat.from(context)
}
/**
* Creates the notification channels.
*
* Attempting to create an existing notification channel with its original values
* performs no operation, so it's safe to execute the method when starting the app.
*/
fun createChannels() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
manager.createNotificationChannels(
listOf(
createHomeworkChannel(),
createExamChannel()
)
)
}
}
@TargetApi(Build.VERSION_CODES.O)
private fun createHomeworkChannel(): NotificationChannel {
val channelId = context.getString(R.string.notification_channel_id_homework)
val channelName = context.getString(R.string.notification_channel_name_homework)
val channelImportance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(channelId, channelName, channelImportance)
channel.enableVibration(true)
return channel
}
@TargetApi(Build.VERSION_CODES.O)
private fun createExamChannel(): NotificationChannel {
val channelId = context.getString(R.string.notification_channel_id_exam)
val channelName = context.getString(R.string.notification_channel_name_exam)
val channelImportance = NotificationManager.IMPORTANCE_DEFAULT
val channel = NotificationChannel(channelId, channelName, channelImportance)
channel.enableVibration(true)
return channel
}
}
| 0 | Kotlin | 0 | 0 | 562394d80f0c6e037c010949229d4719de0683cc | 1,989 | klassenplaner | Apache License 2.0 |
core/testing/src/main/java/com/keisardev/samples/apps/notenest/core/testing/util/TestAnalyticsHelper.kt | shaharKeisarApps | 710,775,973 | false | {"Kotlin": 640247, "Shell": 10235} |
package com.keisardev.samples.apps.notenest.core.testing.util
import com.keisardev.samples.apps.notenest.core.analytics.AnalyticsEvent
import com.keisardev.samples.apps.notenest.core.analytics.AnalyticsHelper
class TestAnalyticsHelper : AnalyticsHelper {
private val events = mutableListOf<AnalyticsEvent>()
override fun logEvent(event: AnalyticsEvent) {
events.add(event)
}
fun hasLogged(event: AnalyticsEvent) = events.contains(event)
}
| 0 | Kotlin | 0 | 0 | 4346a6b920e4d4d370e6ec28a909ea74e34839f8 | 469 | NoteNest | Apache License 2.0 |
ceres-components/src/main/kotlin/dev/teogor/ceres/components/toolbar/ToolbarType.kt | teogor | 555,090,893 | false | null | /*
* Copyright 2022 teogor (Teodor Grigor) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.teogor.ceres.components.toolbar
import androidx.annotation.Keep
// todo have this as an interface to pass in the base model
enum class ToolbarType {
@Keep
HIDDEN,
@Keep
ROUNDED,
// todo fixme
@Keep
COLLAPSABLE,
@Keep
BACK_BUTTON,
@Keep
ACTION,
@Keep
ONLY_LOGO,
@Keep
NOT_SET,
}
| 6 | Kotlin | 3 | 22 | dd556d2f43fa8b0fd44edf9d091d8059a9c8caac | 952 | ceres | Apache License 2.0 |
app/src/main/java/io/vproxy/app/app/GlobalInspectionHttpServerLauncher.kt | wkgcass | 166,255,932 | false | null | package io.vproxy.app.app
import io.vproxy.lib.common.coroutine
import io.vproxy.lib.common.launch
import io.vproxy.lib.http1.CoroutineHttp1Server
import kotlinx.coroutines.suspendCancellableCoroutine
import java.io.IOException
import kotlin.coroutines.resume
class GlobalInspectionHttpServerLauncher private constructor() {
private var app: CoroutineHttp1Server? = null
private var loop: io.vproxy.base.selector.SelectorEventLoop? = null
private fun launch0(l4addr: io.vproxy.vfd.IPPort) {
if (app != null) {
throw IOException("GlobalInspectionHttpServer already started: $app")
}
val serverSock = io.vproxy.base.connection.ServerSock.create(l4addr)
if (loop == null) {
loop = io.vproxy.base.selector.SelectorEventLoop.open()
loop!!.loop { io.vproxy.base.util.thread.VProxyThread.create(it, "global-inspection") }
}
val app = CoroutineHttp1Server(serverSock.coroutine(loop!!.ensureNetEventLoop()))
app.get("/metrics") { it.conn.response(200).send(io.vproxy.base.GlobalInspection.getInstance().prometheusString) }
app.get("/lsof") {
val data = suspendCancellableCoroutine<String> { cont ->
io.vproxy.base.GlobalInspection.getInstance().getOpenFDs { data -> cont.resume(data) }
}
it.conn.response(200).send(data)
}
app.get("/lsof/tree") {
val data = suspendCancellableCoroutine<String> { cont ->
io.vproxy.base.GlobalInspection.getInstance().getOpenFDsTree { data -> cont.resume(data) }
}
it.conn.response(200).send(data)
}
app.get("/jstack") { it.conn.response(200).send(io.vproxy.base.GlobalInspection.getInstance().stackTraces) }
loop!!.launch {
app.start()
}
}
private fun stop0() {
if (app != null) {
app!!.close()
app = null
}
if (loop != null) {
loop!!.close()
loop = null
}
}
companion object {
private val instance = GlobalInspectionHttpServerLauncher()
@Throws(IOException::class)
@JvmStatic
fun launch(l4addr: io.vproxy.vfd.IPPort) {
instance.launch0(l4addr)
}
@JvmStatic
fun stop() {
instance.stop0()
}
}
}
| 6 | null | 37 | 150 | 316ff3f0594a7b403e43c7f738862e8a9b180040 | 2,160 | vproxy | MIT License |
app/src/main/java/com/deymer/ibank/ui/theme/Theme.kt | Deimer | 817,640,789 | false | {"Kotlin": 341824} | package com.deymer.ibank.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
import com.deymer.ibank.ui.colors.black40
import com.deymer.ibank.ui.colors.dark
import com.deymer.ibank.ui.colors.dark40
import com.deymer.ibank.ui.colors.dark60
import com.deymer.ibank.ui.colors.dark80
import com.deymer.ibank.ui.colors.navy
import com.deymer.ibank.ui.colors.snow
import com.deymer.ibank.ui.colors.white40
import com.deymer.ibank.ui.colors.white60
import com.deymer.ibank.ui.colors.white80
private val DarkColorScheme = darkColorScheme(
primary = snow,
onPrimary = dark,
secondary = navy,
onSecondary = snow,
background = dark80,
surface = dark,
tertiary = white60,
onTertiary = white40,
tertiaryContainer = white80,
onTertiaryContainer = white60,
scrim = white40,
)
private val LightColorScheme = lightColorScheme(
primary = snow,
onPrimary = dark,
secondary = snow,
onSecondary = snow,
background = snow,
surface = snow,
tertiary = dark60,
onTertiary = dark40,
tertiaryContainer = dark80,
onTertiaryContainer = dark60,
scrim = black40,
)
@Composable
fun IBankTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = false,
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 = if (darkTheme) {
dark.toArgb()
} else {
colorScheme.primary.toArgb()
}
WindowCompat.getInsetsController(window, view).isAppearanceLightStatusBars = !darkTheme
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = AppTypography,
content = content
)
} | 0 | Kotlin | 0 | 0 | fa2adcf5f49ae4ff3be2c57076e644d9b74ee1f0 | 2,750 | iBank | MIT License |
app/src/main/java/com/example/photohuntcompose/ui/screens/huntview/HuntErrorScreen.kt | burhankamran5 | 834,095,911 | false | {"Kotlin": 49177} | package com.example.photohuntcompose.ui.screens.huntview
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.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.example.photohuntcompose.navigation.Screen
import com.example.photohuntcompose.viewmodel.HuntViewModel
@Composable
fun HuntErrorScreen(
navController: NavHostController,
huntViewModel: HuntViewModel
) {
Box(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Column(
modifier = Modifier
.align(Alignment.Center),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = "🫠", style = MaterialTheme.typography.displayLarge.copy(
color = MaterialTheme.colorScheme.onPrimary
)
)
Spacer(modifier = Modifier.height(16.dp))
Text(
text = "AI decided to take a break...",
style = MaterialTheme.typography.titleLarge
)
Spacer(modifier = Modifier.height(50.dp))
}
Button(
onClick = {
huntViewModel.reset()
navController.navigate(Screen.Home.route) {
popUpTo(Screen.Home.route) { inclusive = true }
}
},
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 35.dp)
) {
Text(text = "Try again")
}
}
}
@Preview(showBackground = true)
@Composable
fun HuntErrorScreenPreview() {
val navController = rememberNavController()
val huntViewModel = HuntViewModel()
HuntErrorScreen(navController, huntViewModel)
} | 0 | Kotlin | 0 | 0 | f7324dfecd2a4fb6cea0d5390696a04dd4fb8111 | 2,489 | Photo-Hunt-Compose | MIT License |
code/src/main/kotlin/utils/IBufferedLaabStream.kt | HotCL | 120,297,748 | false | {"TeX": 261407, "Kotlin": 233661, "HCL": 8763, "C++": 3550} | package utils
/**
* Generic interface for Buffered Look Ahead And Behind Stream
*/
interface IBufferedLaabStream<out T> {
val current: T
fun hasNext(): Boolean
fun hasAhead(n: Int): Boolean
fun hasBehind(n: Int): Boolean
fun moveNext(): T
fun moveAhead(indexes: Int): T
fun lookAhead(indexes: Int): T
fun lookBehind(indexes: Int): T
fun peek(): T
fun <U> findElement(getFunc: (T) -> U?, exitCondition: (T) -> Boolean = { false }, startAhead: Int = 0): U?
}
| 1 | TeX | 1 | 4 | b6adbc46cc7347aacd45dce5fddffd6fee2d37ac | 505 | P4-HCL | Apache License 2.0 |
app/src/main/java/com/example/doughnutopia/screens/details/DetailsRoute.kt | mahmmedn19 | 664,349,956 | false | null | /*
* Created by <NAME> on 7/14/23, 3:24 PM, 2023.
*
* Copyright (c) 2023 All rights reserved.
*/
package com.example.doughnutopia.screens.details
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import com.example.doughnutopia.navigation.Screen
fun NavGraphBuilder.detailsRoute() {
composable(route = Screen.DetailsScreen.route) {
DetailsScreen()
}
} | 0 | Kotlin | 0 | 1 | 470d767d8762837d104ce680347a040c32ac8ef2 | 413 | Doughnutopia | MIT License |
webasyst-x/installations/src/main/java/InstallationListAdapter.kt | 1312inc | 289,607,475 | false | null | package com.webasyst.x.installations
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.webasyst.x.common.XComponentProvider
import com.webasyst.x.installations.databinding.RowInstallationListBinding
import kotlinx.coroutines.runBlocking
class InstallationListAdapter(
private val componentProvider: XComponentProvider
) : ListAdapter<Installation, InstallationListAdapter.InstallationViewHolder>(Companion) {
var selectedPosition = RecyclerView.NO_POSITION
private set
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InstallationViewHolder =
DataBindingUtil.inflate<RowInstallationListBinding>(
LayoutInflater.from(parent.context),
R.layout.row_installation_list,
parent,
false
).let {
InstallationViewHolder(it)
}
override fun onBindViewHolder(holder: InstallationViewHolder, position: Int) =
holder.bind(getItem(position), position == selectedPosition)
fun setSelectedItem(position: Int) {
if (position < itemCount) {
selectedPosition = position
notifyDataSetChanged()
val installation = getItem(position)
runBlocking {
InstallationsController.instance(componentProvider)
.setSelectedInstallation(installation)
}
}
}
fun setSelectedItemById(id: String) {
val position = currentList.indexOfFirst { it.id == id }
if (position >= 0) setSelectedItem(position)
}
inner class InstallationViewHolder(private val binding: RowInstallationListBinding) : RecyclerView.ViewHolder(binding.root) {
fun bind(installation: Installation, selected: Boolean) {
itemView.setOnClickListener {
setSelectedItem(layoutPosition)
}
itemView.isSelected = selected
binding.installation = installation
binding.selected = selected
binding.executePendingBindings()
}
}
companion object : DiffUtil.ItemCallback<Installation>() {
override fun areItemsTheSame(oldItem: Installation, newItem: Installation): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Installation, newItem: Installation): Boolean =
oldItem == newItem
}
}
| 0 | Kotlin | 0 | 3 | 306e163e4def3e21b625c10e1f1703d42878af9c | 2,582 | Webasyst-X-Android | MIT License |
template-cordova/src/main/kotlin/com/example/App.kt | tcbuddy | 203,054,675 | true | {"Kotlin": 609365, "JavaScript": 47141, "HTML": 11136, "TSQL": 594, "CSS": 156} | package com.example
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import pl.treksoft.kvision.cordova.Camera
import pl.treksoft.kvision.cordova.CameraException
import pl.treksoft.kvision.cordova.CameraOptions
import pl.treksoft.kvision.cordova.File
import pl.treksoft.kvision.cordova.Result
import pl.treksoft.kvision.cordova.failure
import pl.treksoft.kvision.cordova.success
import pl.treksoft.kvision.hmr.ApplicationBase
import pl.treksoft.kvision.html.Button.Companion.button
import pl.treksoft.kvision.html.Div.Companion.div
import pl.treksoft.kvision.html.Image.Companion.image
import pl.treksoft.kvision.i18n.DefaultI18nManager
import pl.treksoft.kvision.i18n.I18n
import pl.treksoft.kvision.i18n.I18n.tr
import pl.treksoft.kvision.panel.FlexAlignItems
import pl.treksoft.kvision.panel.Root
import pl.treksoft.kvision.panel.SimplePanel.Companion.simplePanel
import pl.treksoft.kvision.panel.VPanel.Companion.vPanel
import pl.treksoft.kvision.redux.StateBinding.Companion.stateBinding
import pl.treksoft.kvision.redux.createReduxStore
import pl.treksoft.kvision.require
import pl.treksoft.kvision.utils.px
import redux.RAction
data class ImageState(val url: String?, val errorMessage: String?)
sealed class ImageAction : RAction {
data class Image(val url: String) : ImageAction()
data class Error(val errorMessage: String) : ImageAction()
}
fun imageReducer(state: ImageState, action: ImageAction): ImageState = when (action) {
is ImageAction.Image -> ImageState(action.url, null)
is ImageAction.Error -> ImageState(null, action.errorMessage)
}
object App : ApplicationBase {
private val store = createReduxStore(::imageReducer, ImageState(null, null))
private lateinit var root: Root
override fun start(state: Map<String, Any>) {
I18n.manager =
DefaultI18nManager(
mapOf(
"pl" to require("i18n/messages-pl.json"),
"en" to require("i18n/messages-en.json")
)
)
root = Root("kvapp") {
vPanel(alignItems = FlexAlignItems.STRETCH, spacing = 10) {
marginTop = 10.px
button(tr("Take a photo"), "fa-camera") {
alignItems = FlexAlignItems.CENTER
width = 200.px
onClick {
GlobalScope.launch {
val result = Camera.getPicture(
CameraOptions(
mediaType = Camera.MediaType.PICTURE,
destinationType = Camera.DestinationType.FILE_URI
)
)
processCameraResult(result)
}
}
}
simplePanel {
margin = 10.px
}.stateBinding(store) { state ->
if (state.errorMessage != null) {
div(state.errorMessage)
} else if (state.url != null) {
image(state.url, centered = true, responsive = true)
}
}
}
}
Camera.addCameraResultCallback {
processCameraResult(it)
}
}
private fun processCameraResult(result: Result<String, CameraException>) {
result.success {
GlobalScope.launch {
File.resolveLocalFileSystemURLForFile(it).success {
store.dispatch(ImageAction.Image(it.toInternalURL()))
}
}
}
result.failure {
store.dispatch(ImageAction.Error(it.message ?: tr("No data")))
}
}
override fun dispose(): Map<String, Any> {
root.dispose()
return mapOf()
}
val css = require("css/kvapp.css")
}
| 0 | Kotlin | 0 | 0 | 7eaf5b78799cd233ec971aabf22d10f1e184ed21 | 3,929 | kvision-examples | MIT License |
core/src/main/kotlin/uk/lobsterdoodle/namepicker/storage/ActiveGroupUseCase.kt | fifersheep | 21,071,767 | false | null | package uk.lobsterdoodle.namepicker.storage
import org.greenrobot.eventbus.Subscribe
import javax.inject.Inject
import uk.lobsterdoodle.namepicker.events.EventBus
class ActiveGroupUseCase @Inject
constructor(private val bus: EventBus, private val store: KeyValueStore) {
init {
bus.register(this)
}
@Subscribe
fun on(event: SetActiveGroupEvent) {
store.edit().put(KEY, event.groupId).commit()
}
@Subscribe
fun on(event: ClearActiveGroupEvent) {
store.edit().remove(KEY).commit()
}
@Subscribe
fun on(event: CheckForActiveGroupEvent) {
bus.post(if (store.contains(KEY))
GroupActiveEvent(store.getLong(KEY, 0L))
else
GroupNotActiveEvent)
}
companion object {
private val KEY = "active_group_id"
}
}
| 0 | Kotlin | 0 | 0 | 94e3776e3515f4ce7192c9199d87fe4f368f7355 | 829 | android-names-in-a-hat | Apache License 2.0 |
mongo_service/src/main/kotlin/com/example/kotlin_example_app/user/UserService.kt | jeffreychuuu | 410,302,595 | false | null | package com.example.kotlin_example_app.user
import com.example.kotlin_example_app.documents.UserRepository
import com.example.kotlin_example_app.user.documents.UserDocument
import com.example.kotlin_example_app.user.dto.CreateUserDto
import com.example.kotlin_example_app.user.dto.UpdateUserDto
import com.example.kotlin_example_app.util.RedisUtil
import com.fasterxml.jackson.module.kotlin.convertValue
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Service
import javax.annotation.Resource
import javax.validation.Valid
@Service
class UserService(private val userRepository: UserRepository) {
val key = "user"
val mapper = jacksonObjectMapper()
@Value("\${spring.redis.ttl}")
val ttl: Long = 0
@Resource
private lateinit var redisUtil: RedisUtil
fun findAll(): List<UserDocument> {
val result = userRepository.findAll()
return result
}
fun save(@Valid createUserDto: CreateUserDto): UserDocument {
val userDocument: UserDocument = mapper.convertValue<UserDocument>(createUserDto)
val result = userRepository.save(userDocument)
Thread {
redisUtil.hset(key, userDocument.id, mapper.writeValueAsString(result), ttl)
}.start()
return result
}
fun findById(id: String): ResponseEntity<UserDocument> {
var redisResult = redisUtil.hget(key, id)
if (redisResult != null) {
val result = mapper.readValue(redisResult.toString(), UserDocument::class.java)
return ResponseEntity.ok(result)
} else
return userRepository.findById(id).map { result ->
redisUtil.hset(key, id, mapper.writeValueAsString(result), ttl)
ResponseEntity.ok(result)
}.orElse(ResponseEntity.notFound().build())
}
fun update(
id: String,
@Valid updateUserDto: UpdateUserDto
): ResponseEntity<UserDocument> {
redisUtil.hdel(key, id)
return userRepository.findById(id).map { existingArticle ->
val updatedUser: UserDocument = existingArticle
.copy(
name = if (updateUserDto?.name != null) updateUserDto.name else existingArticle.name,
age = if (updateUserDto?.age != null) updateUserDto.age else existingArticle.age,
gender = if (updateUserDto?.gender != null) updateUserDto.gender else existingArticle.gender
)
ResponseEntity.ok().body(userRepository.save(updatedUser))
}.orElse(ResponseEntity.notFound().build())
}
fun delete(id: String): ResponseEntity<Void> {
redisUtil.hdel(key, id)
return userRepository.findById(id).map { article ->
userRepository.delete(article)
ResponseEntity<Void>(HttpStatus.OK)
}.orElse(ResponseEntity.notFound().build())
}
} | 0 | Kotlin | 1 | 1 | cdf49347147e578442effd81accdb84412024389 | 3,068 | kotlin_example_app | DOC License |
mongo_service/src/main/kotlin/com/example/kotlin_example_app/user/UserService.kt | jeffreychuuu | 410,302,595 | false | null | package com.example.kotlin_example_app.user
import com.example.kotlin_example_app.documents.UserRepository
import com.example.kotlin_example_app.user.documents.UserDocument
import com.example.kotlin_example_app.user.dto.CreateUserDto
import com.example.kotlin_example_app.user.dto.UpdateUserDto
import com.example.kotlin_example_app.util.RedisUtil
import com.fasterxml.jackson.module.kotlin.convertValue
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.stereotype.Service
import javax.annotation.Resource
import javax.validation.Valid
@Service
class UserService(private val userRepository: UserRepository) {
val key = "user"
val mapper = jacksonObjectMapper()
@Value("\${spring.redis.ttl}")
val ttl: Long = 0
@Resource
private lateinit var redisUtil: RedisUtil
fun findAll(): List<UserDocument> {
val result = userRepository.findAll()
return result
}
fun save(@Valid createUserDto: CreateUserDto): UserDocument {
val userDocument: UserDocument = mapper.convertValue<UserDocument>(createUserDto)
val result = userRepository.save(userDocument)
Thread {
redisUtil.hset(key, userDocument.id, mapper.writeValueAsString(result), ttl)
}.start()
return result
}
fun findById(id: String): ResponseEntity<UserDocument> {
var redisResult = redisUtil.hget(key, id)
if (redisResult != null) {
val result = mapper.readValue(redisResult.toString(), UserDocument::class.java)
return ResponseEntity.ok(result)
} else
return userRepository.findById(id).map { result ->
redisUtil.hset(key, id, mapper.writeValueAsString(result), ttl)
ResponseEntity.ok(result)
}.orElse(ResponseEntity.notFound().build())
}
fun update(
id: String,
@Valid updateUserDto: UpdateUserDto
): ResponseEntity<UserDocument> {
redisUtil.hdel(key, id)
return userRepository.findById(id).map { existingArticle ->
val updatedUser: UserDocument = existingArticle
.copy(
name = if (updateUserDto?.name != null) updateUserDto.name else existingArticle.name,
age = if (updateUserDto?.age != null) updateUserDto.age else existingArticle.age,
gender = if (updateUserDto?.gender != null) updateUserDto.gender else existingArticle.gender
)
ResponseEntity.ok().body(userRepository.save(updatedUser))
}.orElse(ResponseEntity.notFound().build())
}
fun delete(id: String): ResponseEntity<Void> {
redisUtil.hdel(key, id)
return userRepository.findById(id).map { article ->
userRepository.delete(article)
ResponseEntity<Void>(HttpStatus.OK)
}.orElse(ResponseEntity.notFound().build())
}
} | 0 | Kotlin | 1 | 1 | cdf49347147e578442effd81accdb84412024389 | 3,068 | kotlin_example_app | DOC License |
app/src/main/java/com/finogeeks/finclip/CurrentApplication.kt | finogeeks | 762,226,722 | false | {"Kotlin": 107805} | package com.finogeeks.finclip
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.ToastUtils.MODE.DARK
import com.finogeeks.finclip.base.BaseApplication
import com.finogeeks.finclip.business.common.LocalData
class CurrentApplication : BaseApplication() {
override fun doInMain() {
LogUtils.getConfig().isLogSwitch = BuildConfig.DEBUG
LogUtils.getConfig().globalTag = "FinClip"
ToastUtils.getDefaultMaker().setMode(DARK)
}
override fun doInMainProcess() {
if (LocalData.isLogin()) {
FinAppletInitializer.init(this)
}
}
} | 0 | Kotlin | 0 | 0 | 43a52370bdfe346b5dae8adf02c85e3e73d02ced | 657 | FinClipBroswer-Android | MIT License |
app/src/main/java/com/example/adidas/data/model/ReviewModel.kt | extmkv | 405,866,203 | false | {"Kotlin": 65240} | package com.example.adidas.data.model
import android.os.Parcelable
import com.google.gson.annotations.Expose
import kotlinx.android.parcel.Parcelize
@Parcelize
data class ReviewModel(
@Expose val productId: String? = null,
@Expose val rating: Int,
@Expose val text: String
) : Parcelable | 0 | null | 0 | 0 | 2d35a04ddc35c92977213b68a4bf7fd8f3cbbecb | 301 | productshowcase | MIT License |
src/main/java/catmoe/fallencrystal/moefilter/common/check/name/valid/ValidNameCheck.kt | CatMoe | 638,486,044 | false | null | /*
* Copyright 2023. CatMoe / FallenCrystal
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package catmoe.fallencrystal.moefilter.common.check.name.valid
import catmoe.fallencrystal.moefilter.common.check.AbstractCheck
import catmoe.fallencrystal.moefilter.common.check.info.CheckInfo
import catmoe.fallencrystal.moefilter.common.check.info.impl.Joining
import catmoe.fallencrystal.moefilter.common.check.name.valid.AutoFirewallMode.*
import catmoe.fallencrystal.moefilter.common.config.LocalConfig
import catmoe.fallencrystal.moefilter.common.firewall.Firewall
import catmoe.fallencrystal.moefilter.common.firewall.Throttler
import catmoe.fallencrystal.moefilter.common.state.StateManager
class ValidNameCheck : AbstractCheck() {
private var regexPattern = "(?i)^(?!.*(?:mcstorm|mcdown|bot))[A-Za-z0-9_]{3,16}$"
private var autoFirewallMode = DISABLED
init { instance =this }
override fun increase(info: CheckInfo): Boolean {
val result = !Regex(regexPattern).matches((info as Joining).username)
val address = info.address
if (result) {
when (autoFirewallMode) {
THROTTLE -> { if (Throttler.isThrottled(address)) { Firewall.addAddressTemp(address) } }
ALWAYS -> { Firewall.addAddressTemp(address) }
ATTACK -> { if (StateManager.inAttack.get()) { Firewall.addAddressTemp(address) } }
DISABLED -> {}
}
}
return result
}
fun init() {
val config = LocalConfig.getAntibot().getConfig("name-check.valid-check")
regexPattern=config.getString("valid-regex")
autoFirewallMode=try { AutoFirewallMode.valueOf(config.getAnyRef("firewall-mode").toString()) } catch (_: Exception) { DISABLED }
}
companion object {
lateinit var instance: ValidNameCheck
private set
}
} | 4 | Kotlin | 0 | 8 | a9d69f468eea2f5dfdcb07aa7a9a6e4496938c17 | 2,391 | MoeFilter | Apache License 2.0 |
matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/sync/RoomFullyReadHandler.kt | saad100104006 | 212,864,777 | true | {"Kotlin": 3623105, "Java": 26427, "HTML": 22563, "Shell": 20524} | /*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.matrix.android.internal.session.sync
import im.vector.matrix.android.internal.database.model.EventEntity
import im.vector.matrix.android.internal.session.room.read.FullyReadContent
import im.vector.matrix.android.internal.database.model.ReadMarkerEntity
import im.vector.matrix.android.internal.database.model.RoomSummaryEntity
import im.vector.matrix.android.internal.database.model.TimelineEventEntity
import im.vector.matrix.android.internal.database.model.TimelineEventEntityFields
import im.vector.matrix.android.internal.database.query.getOrCreate
import im.vector.matrix.android.internal.database.query.where
import io.realm.Realm
import timber.log.Timber
import javax.inject.Inject
internal class RoomFullyReadHandler @Inject constructor() {
fun handle(realm: Realm, roomId: String, content: FullyReadContent?) {
if (content == null) {
return
}
Timber.v("Handle for roomId: $roomId eventId: ${content.eventId}")
RoomSummaryEntity.getOrCreate(realm, roomId).apply {
readMarkerId = content.eventId
}
// Remove the old markers if any
val oldReadMarkerEvents = TimelineEventEntity
.where(realm, roomId = roomId, linkFilterMode = EventEntity.LinkFilterMode.BOTH)
.isNotNull(TimelineEventEntityFields.READ_MARKER.`$`)
.findAll()
oldReadMarkerEvents.forEach { it.readMarker = null }
val readMarkerEntity = ReadMarkerEntity.getOrCreate(realm, roomId).apply {
this.eventId = content.eventId
}
// Attach to timelineEvent if known
val timelineEventEntities = TimelineEventEntity.where(realm, roomId = roomId, eventId = content.eventId).findAll()
timelineEventEntities.forEach { it.readMarker = readMarkerEntity }
}
} | 2 | null | 0 | 2 | 588e5d6e63ecfee9d93ef3da5987b8deb59f412f | 2,428 | NovaChat | Apache License 2.0 |
src/main/kotlin/com/github/theirish81/taskalog/messages/TalTimer.kt | theirish81 | 237,031,757 | false | null | /*
* Copyright 2020 <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* @author <NAME>
*
*/
package com.github.theirish81.taskalog.messages
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import java.util.*
/**
* Timer and timer submission message
* @param id the ID of the timer
* @param everySeconds within which time span the event should happen
* @param executionTime the time this timer executed
*/
class TalTimer(val id : String,
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("within_seconds") var everySeconds : Int,
@JsonInclude(JsonInclude.Include.NON_NULL) @JsonProperty("execution_time") var executionTime : Date? = null){
fun clone() : TalTimer = TalTimer(id,everySeconds,executionTime)
} | 0 | Kotlin | 0 | 0 | a6dab4fe412a60f9bef0a5f75c966dfb13928a86 | 1,358 | taskalog | Apache License 2.0 |
src/main/kotlin/com/sourcegraph/cody/config/migration/DeprecatedChatLlmMigration.kt | sourcegraph | 702,947,607 | false | {"Kotlin": 914689, "Java": 201176, "Shell": 4636, "TypeScript": 2153, "Nix": 1122, "JavaScript": 436, "HTML": 294} | package com.sourcegraph.cody.config.migration
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.sourcegraph.Icons
import com.sourcegraph.cody.agent.CodyAgentService
import com.sourcegraph.cody.agent.protocol.ChatModelsParams
import com.sourcegraph.cody.agent.protocol.ChatModelsResponse
import com.sourcegraph.cody.agent.protocol.ModelUsage
import com.sourcegraph.cody.history.HistoryService
import com.sourcegraph.cody.history.state.AccountData
import com.sourcegraph.cody.history.state.LLMState
import com.sourcegraph.common.CodyBundle
import com.sourcegraph.common.CodyBundle.fmt
import com.sourcegraph.common.NotificationGroups
import java.util.concurrent.TimeUnit
object DeprecatedChatLlmMigration {
fun migrate(project: Project) {
CodyAgentService.withAgent(project) { agent ->
val chatModels = agent.server.chatModels(ChatModelsParams(ModelUsage.CHAT.value))
val models =
chatModels.completeOnTimeout(null, 10, TimeUnit.SECONDS).get()?.models ?: return@withAgent
migrateHistory(
HistoryService.getInstance(project).state.accountData,
models,
this::showLlmUpgradeNotification)
}
}
fun migrateHistory(
accountData: List<AccountData>,
models: List<ChatModelsResponse.ChatModelProvider>,
notify: (Set<String>) -> Unit
) {
val defaultModel = models.find { it.default } ?: return
fun isDeprecated(modelState: LLMState): Boolean =
models.firstOrNull { it.model == modelState.model }?.deprecated ?: false
val migratedLlms = mutableSetOf<String>()
accountData.forEach { accData ->
accData.chats
.mapNotNull { it.llm }
.forEach { llm ->
if (isDeprecated(llm)) {
llm.title?.let { migratedLlms.add(it) }
llm.model = defaultModel.model
llm.title = defaultModel.title
llm.provider = defaultModel.provider
}
}
}
if (migratedLlms.isNotEmpty()) {
notify(migratedLlms)
}
}
private fun showLlmUpgradeNotification(migratedLlms: Set<String>) {
ApplicationManager.getApplication().invokeLater {
val title = CodyBundle.getString("settings.migration.llm-upgrade-notification.title")
val msg =
CodyBundle.getString("settings.migration.llm-upgrade-notification.body")
.fmt(migratedLlms.joinToString("</li><li>", "<li>", "</li>"))
val notification =
Notification(NotificationGroups.CODY_UPDATES, title, msg, NotificationType.INFORMATION)
notification.setIcon(Icons.CodyLogo)
Notifications.Bus.notify(notification)
}
}
}
| 230 | Kotlin | 16 | 55 | 1eb25809c3e51b64f08e851c8da09778000540c6 | 2,845 | jetbrains | Apache License 2.0 |
android_mobile/src/main/java/com/alexstyl/specialdates/settings/PreferenceNotFoundException.kt | alexstyl | 66,690,455 | false | null | package com.alexstyl.specialdates.settings
class PreferenceNotFoundException : Throwable()
| 0 | Java | 49 | 211 | d224f0af53ee3d4ecadad5df0a2731e2c9031a23 | 93 | Memento-Calendar | MIT License |
src/com/vitorblog/antiop/dao/JarDao.kt | VitorBlog | 228,723,461 | false | null | package com.vitorblog.antiop.dao
import com.vitorblog.antiop.model.Jar
import java.io.File
object JarDao {
val JARS = hashMapOf<File, Jar>()
fun add(jar: Jar) = JARS.put(jar.file, jar)
fun get(file: File) = JARS[file]
} | 0 | Kotlin | 1 | 0 | c8ac20128dd2eb1201975214ca6e45bfcc0d1dc8 | 237 | BlogAntiForceOp | MIT License |
libraries/stdlib/test/collections/MutableCollectionsTest.kt | erokhins | 44,854,854 | true | {"Markdown": 33, "XML": 665, "Ant Build System": 45, "Ignore List": 7, "Git Attributes": 1, "Kotlin": 20967, "Java": 4534, "Protocol Buffer": 7, "Text": 4663, "JavaScript": 63, "JAR Manifest": 3, "Roff": 46, "Roff Manpage": 11, "INI": 17, "HTML": 152, "Groovy": 23, "Java Properties": 14, "Maven POM": 49, "Gradle": 74, "CSS": 2, "Proguard": 1, "JFlex": 2, "Shell": 11, "Batchfile": 10, "ANTLR": 1} | package test.collections
import kotlin.test.*
import java.util.*
import org.junit.Test as test
class MutableCollectionTest {
// TODO: Use apply scope function
@test fun addAll() {
val data = listOf("foo", "bar")
fun assertAdd(f: MutableList<String>.() -> Unit) = assertEquals(data, arrayListOf<String>().let { it.f(); it })
assertAdd { addAll(data) }
assertAdd { addAll(data.toTypedArray()) }
assertAdd { addAll(data.toTypedArray().asIterable()) }
assertAdd { addAll(data.asSequence()) }
}
@test fun removeAll() {
val content = arrayOf("foo", "bar", "bar")
val data = listOf("bar")
val expected = listOf("foo")
fun assertRemove(f: MutableList<String>.() -> Unit) = assertEquals(expected, arrayListOf(*content).let { it.f(); it })
assertRemove { removeAll(data) }
assertRemove { removeAll(data.toTypedArray()) }
assertRemove { removeAll(data.toTypedArray().asIterable()) }
assertRemove { removeAll(data.asSequence()) }
}
@test fun retainAll() {
val content = arrayOf("foo", "bar", "bar")
val data = listOf("bar")
val expected = listOf("bar", "bar")
fun assertRetain(f: MutableList<String>.() -> Unit) = assertEquals(expected, arrayListOf(*content).let { it.f(); it })
assertRetain { retainAll(data) }
assertRetain { retainAll(data.toTypedArray()) }
assertRetain { retainAll(data.toTypedArray().asIterable()) }
assertRetain { retainAll(data.asSequence()) }
}
}
| 0 | Java | 0 | 1 | ff00bde607d605c4eba2d98fbc9e99af932accb6 | 1,579 | kotlin | Apache License 2.0 |
src/main/java/com/github/greennick/properties/subscriptions/CompositeSubscription.kt | green-nick | 170,363,475 | false | null | package com.github.greennick.properties.subscriptions
import java.util.concurrent.CopyOnWriteArrayList
class CompositeSubscription : Subscription {
private val subscriptions = CopyOnWriteArrayList<Subscription>()
private var _subscribed = true
override val subscribed get() = _subscribed
override fun unsubscribe() {
if (!_subscribed) return
_subscribed = false
clear()
}
fun clear() {
subscriptions.forEach(Subscription::unsubscribe)
subscriptions.clear()
}
fun add(vararg subscriptions: Subscription) {
this.subscriptions.addAll(subscriptions)
}
operator fun plusAssign(subscription: Subscription): Unit = add(subscription)
}
fun Subscription.addTo(compositeSubscription: CompositeSubscription): Unit = compositeSubscription.add(this) | 0 | Kotlin | 0 | 8 | 969741bf9750634e7c5a673c7551746fc4a1e1ab | 833 | properties | MIT License |
src/jvmMain/kotlin/com/lehaine/littlekt/samples/flappybird/FlappyBirdApp.kt | littlektframework | 442,309,959 | false | {"Kotlin": 71106, "HTML": 1152, "Shell": 962} | package com.lehaine.littlekt.samples.flappybird
import com.lehaine.littlekt.createLittleKtApp
/**
* @author <NAME>
* @date 3/5/2022
*/
fun main(args: Array<String>) {
createLittleKtApp {
width = 540
height = 1024
vSync = true
title = "LittleKt - Flappy Bird CLone"
}.start {
FlappyBird(it)
}
} | 0 | Kotlin | 2 | 9 | 26738ab90678396b32c1e46164b9754dd7d4f762 | 350 | littlekt-samples | Apache License 2.0 |
elasticsearch-jdk7/src/main/kotlin/uy/klutter/elasticsearch/XContent.kt | naveensrinivasan | 55,024,359 | true | {"Kotlin": 247131} | package uy.klutter.elasticsearch
import org.elasticsearch.common.xcontent.XContentBuilder
import org.elasticsearch.common.xcontent.XContentFactory
import java.math.BigDecimal
import kotlin.reflect.KProperty1
public class XContentJsonObjectWithEnum<T: Enum<T>>(x: XContentBuilder): XContentJsonObject(x) {
public fun setValue(field: T, value: String): Unit { x.field(field.name, value) }
public fun setValue(field: T, value: Long): Unit { x.field(field.name, value) }
public fun setValue(field: T, value: Int): Unit { x.field(field.name, value) }
public fun setValue(field: T, value: Short): Unit { x.field(field.name, value) }
public fun setValue(field: T, value: Byte): Unit { x.field(field.name, value) }
public fun setValue(field: T, value: Double): Unit { x.field(field.name, value) }
public fun setValue(field: T, value: Float): Unit { x.field(field.name, value) }
public fun setValue(field: T, value: BigDecimal): Unit { x.field(field.name, value) }
public fun setValue(field: T, value: Boolean): Unit { x.field(field.name, value) }
public fun setValueNull(field: T): Unit { x.nullField(field.name) }
public fun Object(field: T, init: XContentJsonObject.()->Unit): Unit {
x.startObject(field.name)
XContentJsonObject(x).init()
x.endObject()
}
public fun <R: Enum<R>> ObjectWithFieldEnum(field: T, init: XContentJsonObjectWithEnum<R>.()->Unit): Unit {
x.startObject(field.name)
XContentJsonObjectWithEnum<R>(x).init()
x.endObject()
}
public fun <R: Any> ObjectWithFieldClass(field: T, init: XContentJsonObjectWithClass<R>.()->Unit): Unit {
x.startObject(field.name)
XContentJsonObjectWithClass<R>(x).init()
x.endObject()
}
public fun Array(field: T, init: XContentJsonArray.()->Unit): Unit {
x.startArray(field.name)
XContentJsonArray(x).init()
x.endArray()
}
}
public class XContentJsonObjectWithClass<T: Any>(x: XContentBuilder): XContentJsonObject(x) {
public fun setValue(field: KProperty1<T, *>, value: String): Unit { x.field(field.name, value) }
public fun setValue(field: KProperty1<T, *>, value: Long): Unit { x.field(field.name, value) }
public fun setValue(field: KProperty1<T, *>, value: Int): Unit { x.field(field.name, value) }
public fun setValue(field: KProperty1<T, *>, value: Short): Unit { x.field(field.name, value) }
public fun setValue(field: KProperty1<T, *>, value: Byte): Unit { x.field(field.name, value) }
public fun setValue(field: KProperty1<T, *>, value: Double): Unit { x.field(field.name, value) }
public fun setValue(field: KProperty1<T, *>, value: Float): Unit { x.field(field.name, value) }
public fun setValue(field: KProperty1<T, *>, value: BigDecimal): Unit { x.field(field.name, value) }
public fun setValue(field: KProperty1<T, *>, value: Boolean): Unit { x.field(field.name, value) }
public fun setValueNull(field: KProperty1<T, *>): Unit { x.nullField(field.name) }
public fun Object(field: KProperty1<T, *>, init: XContentJsonObject.()->Unit): Unit {
x.startObject(field.name)
XContentJsonObject(x).init()
x.endObject()
}
public fun <R: Enum<R>> ObjectWithFieldEnum(field: KProperty1<T, *>, init: XContentJsonObjectWithEnum<R>.()->Unit): Unit {
x.startObject(field.name)
XContentJsonObjectWithEnum<R>(x).init()
x.endObject()
}
public fun <R: Any> ObjectWithFieldClass(field: KProperty1<T, *>, init: XContentJsonObjectWithClass<R>.()->Unit): Unit {
x.startObject(field.name)
XContentJsonObjectWithClass<R>(x).init()
x.endObject()
}
public fun Array(field: KProperty1<T, *>, init: XContentJsonArray.()->Unit): Unit {
x.startArray(field.name)
XContentJsonArray(x).init()
x.endArray()
}
}
public open class XContentJsonObject(protected val x: XContentBuilder) {
public fun setValue(name: String, value: String): Unit { x.field(name, value) }
public fun setValue(name: String, value: Long): Unit { x.field(name, value) }
public fun setValue(name: String, value: Int): Unit { x.field(name, value) }
public fun setValue(name: String, value: Short): Unit { x.field(name, value) }
public fun setValue(name: String, value: Byte): Unit { x.field(name, value) }
public fun setValue(name: String, value: Double): Unit { x.field(name, value) }
public fun setValue(name: String, value: Float): Unit { x.field(name, value) }
public fun setValue(name: String, value: BigDecimal): Unit { x.field(name, value) }
public fun setValue(name: String, value: Boolean): Unit { x.field(name, value) }
public fun setValueNull(name: String): Unit { x.nullField(name) }
public fun Object(name: String, init: XContentJsonObject.()->Unit): Unit {
x.startObject(name)
XContentJsonObject(x).init()
x.endObject()
}
public fun <R: Enum<R>> ObjectWithFieldEnum(name: String, init: XContentJsonObjectWithEnum<R>.()->Unit): Unit {
x.startObject(name)
XContentJsonObjectWithEnum<R>(x).init()
x.endObject()
}
public fun <R: Any> ObjectWithFieldClass(name: String, init: XContentJsonObjectWithClass<R>.()->Unit): Unit {
x.startObject(name)
XContentJsonObjectWithClass<R>(x).init()
x.endObject()
}
public fun Array(name: String, init: XContentJsonArray.()->Unit): Unit {
x.startArray(name)
XContentJsonArray(x).init()
x.endArray()
}
}
public class XContentJsonArray(private val x: XContentBuilder) {
public fun addValue(value: String): Unit { x.value(value) }
public fun addValue(value: Long): Unit { x.value(value) }
public fun addValue(value: Int): Unit { x.value(value) }
public fun addValue(value: Short): Unit { x.value(value) }
public fun addValue(value: Byte): Unit { x.value(value) }
public fun addValue(value: Double): Unit { x.value(value) }
public fun addValue(value: Float): Unit { x.value(value) }
public fun addValue(value: BigDecimal): Unit { x.value(value) }
public fun addValue(value: Boolean): Unit { x.value(value) }
public fun addValueNull(): Unit { x.nullValue() }
public fun addObject(init: XContentJsonObject.()->Unit): Unit {
x.startObject()
XContentJsonObject(x).init()
x.endObject()
}
public fun addArray(init: XContentJsonArray.()->Unit): Unit {
x.startArray()
XContentJsonArray(x).init()
x.endArray()
}
}
public fun <T: Enum<T>> xsonObjectWithFieldEnum(init: XContentJsonObjectWithEnum<T>.()->Unit): XContentBuilder {
val builder = XContentFactory.jsonBuilder()
builder.startObject()
XContentJsonObjectWithEnum<T>(builder).init()
builder.endObject()
return builder
}
public fun <T: Any> xsonObjectWithFieldClass(init: XContentJsonObjectWithClass<T>.()->Unit): XContentBuilder {
val builder = XContentFactory.jsonBuilder()
builder.startObject()
XContentJsonObjectWithClass<T>(builder).init()
builder.endObject()
return builder
}
public fun xsonObject(init: XContentJsonObject.()->Unit): XContentBuilder {
val builder = XContentFactory.jsonBuilder()
builder.startObject()
XContentJsonObject(builder).init()
builder.endObject()
return builder
}
public fun xsonArray(init: XContentJsonArray.()->Unit): XContentBuilder {
val builder = XContentFactory.jsonBuilder()
builder.startArray()
XContentJsonArray(builder).init()
builder.endArray()
return builder
}
| 0 | Kotlin | 0 | 0 | 76536ab3c4c712157919017b4b0ee121fa4cc1a8 | 7,585 | klutter | MIT License |
app/src/main/java/com/nicolas/nicolsflix/network/MovieRepositoryV2Impl.kt | Aleixo-Dev | 335,638,746 | false | null | package com.nicolas.nicolsflix.network
import com.nicolas.nicolsflix.data.model.Movie
import com.nicolas.nicolsflix.data.network.mapper.MovieMapper
import com.nicolas.nicolsflix.network.models.remote.MovieDetailsResponse
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
class MovieRepositoryV2Impl(
private val remote: MovieService
) : MovieRepositoryV2 {
override suspend fun getCasts(movieId: Int) = flow {
val response = remote.getCastsMovieDetails(movieId)
emit(response.castFromMovie)
}
override suspend fun getTrailerMovies(movieId: Int) = flow {
val response = remote.getTrailerVideo(movieId)
emit(response.trailers)
}
override suspend fun getPersonDetail(personId: Int) = flow {
val response = remote.getPersonDetail(personId)
emit(response)
}
override suspend fun getTrendingMovie(): Flow<List<Movie>> = flow {
val response = remote.getTrendingMovie()
emit(MovieMapper.responseToDomain(response.results))
}
override suspend fun getDetailsMovie(movieId: Int): Flow<MovieDetailsResponse> = flow {
val response = remote.getMovieDetails(movieId)
emit(response)
}
} | 7 | Kotlin | 1 | 2 | 3bbcb59c04c353bc312b9410c59d3a186cc85673 | 1,223 | NicolsFlix | MIT License |
app/src/main/java/com/eneskayiklik/word_diary/core/ui/components/MainScaffold.kt | Enes-Kayiklik | 651,794,521 | false | null | package com.eneskayiklik.word_diary.core.ui.components
import android.annotation.SuppressLint
import androidx.compose.animation.*
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Settings
import androidx.compose.material.icons.outlined.Style
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import com.eneskayiklik.word_diary.R
import com.eneskayiklik.word_diary.feature.destinations.ListsScreenDestination
import com.eneskayiklik.word_diary.feature.destinations.SettingsScreenDestination
import com.eneskayiklik.word_diary.feature.destinations.StatisticsScreenDestination
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class, ExperimentalAnimationApi::class)
@Composable
fun MainScaffold(
modifier: Modifier = Modifier,
onNavigate: (String) -> Unit,
currentRoute: String?,
showBottomBar: Boolean = true,
bottomNavItems: List<BottomNavItem> = listOf(
BottomNavItem(
route = ListsScreenDestination,
title = R.string.collections,
icon = Icons.Outlined.Style,
contentDescription = R.string.collections
),
BottomNavItem(
route = StatisticsScreenDestination,
title = R.string.statistics,
resIcon = R.drawable.ic_line_chart,
contentDescription = R.string.statistics
),
BottomNavItem(
route = SettingsScreenDestination,
title = R.string.settings,
icon = Icons.Outlined.Settings,
contentDescription = R.string.settings
),
),
content: @Composable () -> Unit
) {
Scaffold(
bottomBar = {
WDBottomBar(
showBottomBar = showBottomBar,
bottomNavItems = bottomNavItems,
currentRoute = currentRoute,
onNavigate = onNavigate
)
},
modifier = modifier
) {
content()
}
} | 0 | Kotlin | 0 | 1 | d03099b5eb8b2ba8857dbc8a3cabff8ff17b7d05 | 2,192 | WordDiary | MIT License |
dexfile/src/main/kotlin/com/github/netomi/bat/dexfile/instruction/Payload.kt | netomi | 265,488,804 | false | {"Kotlin": 1925501, "Smali": 713862, "ANTLR": 25494, "Shell": 12074, "Java": 2326} | /*
* Copyright (c) 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.netomi.bat.dexfile.instruction
import com.github.netomi.bat.dexfile.instruction.editor.OffsetMap
abstract class Payload protected constructor(opCode: DexOpCode) : DexInstruction(opCode) {
override fun updateOffsets(offset: Int, offsetMap: OffsetMap) {
offsetMap.setPayloadOffset(this, offset)
}
open fun updatePayloadOffsets(payloadInstructionOffset: Int, offsetMap: OffsetMap) {}
} | 1 | Kotlin | 3 | 10 | 5f5ec931c47dd34f14bd97230a29413ef1cf219c | 1,030 | bat | Apache License 2.0 |
SimpleStocks/app/src/main/java/com/tastytrade/stock/model/NoInternet.kt | appskode | 860,611,947 | false | {"Kotlin": 50634} | package com.tastytrade.stock.model
import java.io.IOException
class NoConnectivityException : IOException() {
override val message: String
get() =
"No network available, please check your WiFi or Data connection"
}
class NoInternetException() : IOException() {
override val message: String
get() =
"No internet available, please check your connected WIFi or Data"
}
| 0 | Kotlin | 0 | 0 | c7a61a0d354cdef0a329fce0f318fd28051b9294 | 416 | SimpleStocks | MIT License |
sdk/src/main/java/io/portone/sdk/android/type/Bank.kt | portone-io | 835,174,061 | false | {"Kotlin": 197769, "HTML": 1179} | package io.portone.sdk.android.type
enum class Bank {
BANK_OF_KOREA,
KOREA_DEVELOPMENT_BANK,
INDUSTRIAL_BANK_OF_KOREA,
KOOKMIN_BANK,
SUHYUP_BANK,
EXPORT_IMPORT_BANK_OF_KOREA,
NH_NONGHYUP_BANK,
LOCAL_NONGHYUP,
WOORI_BANK,
SC_BANK_KOREA,
CITI_BANK_KOREA,
DAEGU_BANK,
BUSAN_BANK,
GWANGJU_BANK,
JEJU_BANK,
JEONBUK_BANK,
KYONGNAM_BANK,
KFCC,
SHINHYUP,
SAVINGS_BANK_KOREA,
MORGAN_STANLEY_BANK,
HSBC_BANK,
DEUTSCHE_BANK,
JP_MORGAN_CHASE_BANK,
MIZUHO_BANK,
MUFG_BANK,
BANK_OF_AMERICA_BANK,
BNP_PARIBAS_BANK,
ICBC,
BANK_OF_CHINA,
NATIONAL_FORESTRY_COOPERATIVE_FEDERATION,
UNITED_OVERSEAS_BANK,
BANK_OF_COMMUNICATIONS,
CHINA_CONSTRUCTION_BANK,
EPOST,
KODIT,
KIBO,
HANA_BANK,
SHINHAN_BANK,
K_BANK,
KAKAO_BANK,
TOSS_BANK,
KCIS,
DAISHIN_SAVINGS_BANK,
SBI_SAVINGS_BANK,
HK_SAVINGS_BANK,
WELCOME_SAVINGS_BANK,
SHINHAN_SAVINGS_BANK,
KYOBO_SECURITIES,
DAISHIN_SECURITIES,
MERITZ_SECURITIES,
MIRAE_ASSET_SECURITIES,
BOOKOOK_SECURITIES,
SAMSUNG_SECURITIES,
SHINYOUNG_SECURITIES,
SHINHAN_FINANCIAL_INVESTMENT,
YUANTA_SECURITIES,
EUGENE_INVESTMENT_SECURITIES,
KAKAO_PAY_SECURITIES,
TOSS_SECURITIES,
KOREA_FOSS_SECURITIES,
HANA_FINANCIAL_INVESTMENT,
HI_INVESTMENT_SECURITIES,
KOREA_INVESTMENT_SECURITIES,
HANWHA_INVESTMENT_SECURITIES,
HYUNDAI_MOTOR_SECURITIES,
DB_FINANCIAL_INVESTMENT,
KB_SECURITIES,
KTB_INVESTMENT_SECURITIES,
NH_INVESTMENT_SECURITIES,
SK_SECURITIES,
SCI,
KIWOOM_SECURITIES,
EBEST_INVESTMENT_SECURITIES,
CAPE_INVESTMENT_CERTIFICATE;
}
| 0 | Kotlin | 0 | 2 | 07509908b066a19fc5e0e96afca415816687d2f4 | 1,732 | android-sdk | MIT License |
fiosdk/src/main/java/fiofoundation/io/fiosdk/errors/signatureprovider/SignTransactionError.kt | fioprotocol | 246,897,755 | false | {"C++": 2749293, "Kotlin": 540742, "C": 113874, "Java": 18371, "Objective-C": 7740, "CMake": 3521, "Shell": 870} | package fiofoundation.io.fiosdk.errors.signatureprovider
class GetAvailableKeysError: SignatureProviderError {
constructor():super()
constructor(message: String):super(message)
constructor(exception: Exception):super(exception)
constructor(message: String,exception: Exception):super(message,exception)
} | 5 | C++ | 5 | 3 | fc9809d05b4c13d5493267055c0c167d8fac6249 | 321 | fiosdk_kotlin | MIT License |
pkl-commons-cli/src/main/kotlin/org/pkl/commons/cli/commands/BaseCommand.kt | apple | 745,600,812 | false | {"Java": 2643874, "Kotlin": 1090692, "Pkl": 237790, "JavaScript": 32869, "ANTLR": 18705, "CSS": 12379, "Shell": 188} | /**
* Copyright © 2024 Apple Inc. and the Pkl project authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.pkl.commons.cli.commands
import com.github.ajalt.clikt.core.CliktCommand
import com.github.ajalt.clikt.parameters.groups.provideDelegate
abstract class BaseCommand(name: String, helpLink: String, help: String = "") :
CliktCommand(
name = name,
help = help,
epilog = "For more information, visit $helpLink",
) {
val baseOptions by BaseOptions()
}
| 107 | Java | 259 | 9,743 | 4a7f90157a6c17d5e672803216826d92ef87aba6 | 1,026 | pkl | Apache License 2.0 |
app/src/main/java/de/droidcon/berlin2018/analytics/AnalyticsLifecycleListener.kt | OpenConference | 100,889,869 | false | null | package de.droidcon.berlin2018.analytics
import android.view.View
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.Controller.LifecycleListener
import de.droidcon.berlin2018.ui.applicationComponent
/**
* Lifecycle Listener to track the current visibile screen
*
* @author <NAME>
*/
class AnalyticsLifecycleListener : LifecycleListener() {
override fun postCreateView(controller: Controller, view: View) {
controller.applicationComponent().analytics().trackScreen(controller)
}
}
| 1 | Kotlin | 1 | 27 | 142effaf4eb04abb12d5b812e797a89922b649a5 | 524 | DroidconBerlin2017 | Apache License 2.0 |
app/src/main/java/com/daveboy/wanandroid/entity/NavigationModel.kt | DaveBoy | 192,728,655 | false | null | package com.daveboy.wanandroid.entity
data class NavigationModel(
val articles: List<Article>,
val cid: Int,
val name: String
) | 0 | Kotlin | 0 | 1 | 9915c5c1bba9e6da9af1a40f085befda24c67a4e | 140 | WanAndroid | Apache License 2.0 |
cx-test-sync/src/main/kotlin/io/nuvalence/cx/tools/cxtestsync/model/test/DFCXTestModel.kt | Nuvalence | 641,553,939 | false | {"Kotlin": 237698, "FreeMarker": 11464} | package io.nuvalence.cx.tools.cxtestsync.model.test
enum class ResultLabel(private val value: String) {
PASS("PASS"),
WARN("WARN"),
FAIL("FAIL");
override fun toString(): String {
return value
}
}
open class DFCXTestStep(
val userInput: String,
val expectedAgentOutput: String,
val actualAgentOutput: String,
val expectedPage: String,
val actualPage: String,
var result: ResultLabel?
) {
constructor (userInput: String, expectedAgentOutput: String, actualAgentOutput: String, expectedPage: String, actualPage: String):
this(userInput, expectedAgentOutput, actualAgentOutput, expectedPage, actualPage, ResultLabel.PASS)
constructor (userInput: String, expectedAgentOutput: String):
this(userInput, expectedAgentOutput, "", "", "")
override fun toString(): String {
return "Step result: $result\nUser Input: $userInput \nExpected Agent Output: $expectedAgentOutput\nActual Agent Output: $actualAgentOutput\nExpected Page: $expectedPage\nActual Page: $actualPage\n"
}
}
class DFCXInjectableTestStep(userInput: String, expectedAgentOutput: String, actualAgentOutput: String, expectedPage: String, actualPage: String, result: ResultLabel?, payloads: Map<String, String>)
: DFCXTestStep (userInput, expectedAgentOutput, actualAgentOutput, expectedPage, actualPage, result) {
constructor (userInput: String, expectedAgentOutput: String, actualAgentOutput: String, expectedPage: String, actualPage: String, payloads: Map<String, String>)
: this(userInput, expectedAgentOutput, actualAgentOutput, expectedPage, actualPage, ResultLabel.PASS, payloads)
constructor (userInput: String, expectedAgentOutput: String, payloads: Map<String, String>)
: this(userInput, expectedAgentOutput, "", "", "", payloads)
}
open class DFCXTest <T: DFCXTestStep>(
val testCaseId: String,
val testCaseName: String,
val tags: List<String>,
val notes: String,
var result: ResultLabel?,
val resultSteps: MutableList<T>
) {
constructor (testCaseId: String, testCaseName: String, tags: List<String>, note: String) :
this(testCaseId, testCaseName, tags, note,
ResultLabel.PASS, mutableListOf<T>())
constructor (testCaseId: String, testCaseName: String, tags: List<String>, note: String, resultSteps: MutableList<T>) :
this(testCaseId, testCaseName, tags, note,
ResultLabel.PASS, resultSteps)
override fun toString(): String {
return "Test Case Name: $testCaseName, Result: $result, Result Steps:\n${resultSteps.joinToString("\n"){ resultStep -> resultStep.toString() }}"
}
}
class DFCXInjectableTest(testCaseId: String, testCaseName: String, tags: List<String>, notes: String, result: ResultLabel?, resultSteps: MutableList<DFCXInjectableTestStep>, val ssn: String)
: DFCXTest<DFCXInjectableTestStep>(testCaseId, testCaseName, tags, notes, result, resultSteps) {
constructor (testCaseId: String, testCaseName: String, tags: List<String>, notes: String, ssn: String) :
this(testCaseId, testCaseName, tags, notes,
ResultLabel.PASS, mutableListOf<DFCXInjectableTestStep>(), ssn)
constructor (testCaseId: String, testCaseName: String, tags: List<String>, notes: String, resultSteps: MutableList<DFCXInjectableTestStep>, ssn: String) :
this(testCaseId, testCaseName, tags, notes,
ResultLabel.PASS, resultSteps, ssn)
}
| 3 | Kotlin | 0 | 0 | 8b4a3408bbed44c72fb92414f9aa41e7e5ed3e73 | 3,491 | dialogflow-cx-tools | MIT License |
library/src/main/java/renetik/android/core/android/util/DisplayMetrics+.kt | renetik | 506,035,450 | false | {"Kotlin": 155819} | package renetik.android.core.android.util
import android.util.DisplayMetrics
import renetik.android.core.base.CSApplication.Companion.app
import renetik.android.core.extensions.content.isLandscape
val DisplayMetrics.orientedWidthPixels: Int
get() = if (app.isLandscape) heightPixels else widthPixels
val DisplayMetrics.orientedHeightPixels: Int
get() = if (app.isLandscape) widthPixels else heightPixels | 0 | Kotlin | 1 | 2 | 452871afa18f29bf70e3612606c41729484c7c1d | 414 | renetik-android-core | MIT License |
substrate-sdk-android/src/main/java/io/novasama/substrate_sdk_android/wsrpc/request/runtime/account/AccountInfoRequest.kt | novasamatech | 429,839,517 | false | {"Kotlin": 647838, "Rust": 10421, "Java": 4208} | package io.novasama.substrate_sdk_android.wsrpc.request.runtime.account
import io.novasama.substrate_sdk_android.runtime.Module
import io.novasama.substrate_sdk_android.wsrpc.request.runtime.storage.GetStorageRequest
class AccountInfoRequest(publicKey: ByteArray) : GetStorageRequest(
listOf(
Module.System.Account.storageKey(publicKey)
)
)
| 2 | Kotlin | 7 | 9 | 8deb9bcec9a5d9d74c509ccc6393cfd0b4ef7144 | 359 | substrate-sdk-android | Apache License 2.0 |
test-app/src/main/kotlin/uk/gov/justice/digital/hmpps/hmppstemplatepackagename/App.kt | ministryofjustice | 370,951,976 | false | {"Kotlin": 304896, "Shell": 3898} | package uk.gov.justice.digital.hmpps.hmppstemplatepackagename
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication
@SpringBootApplication
@ConfigurationPropertiesScan
class App
fun main(args: Array<String>) {
runApplication<App>(*args)
}
| 0 | Kotlin | 0 | 2 | ecbedef6f92e32c129f0c4cdb7dfc103275f734b | 384 | hmpps-spring-boot-sqs | MIT License |
app/src/main/java/dev/pankaj/cleanarchitecture/presentation/home/ProductDetailsFragment.kt | pankaj046 | 806,227,972 | false | {"Kotlin": 79661} | package dev.pankaj.cleanarchitecture.presentation.home
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import dagger.hilt.android.AndroidEntryPoint
import dev.pankaj.cleanarchitecture.data.remote.model.product.Product
import dev.pankaj.cleanarchitecture.databinding.FragmentProductDetailsBinding
import dev.pankaj.cleanarchitecture.extensions.hide
import dev.pankaj.cleanarchitecture.extensions.show
import dev.pankaj.cleanarchitecture.presentation.home.viewmodel.ProductViewModel
import dev.pankaj.cleanarchitecture.presentation.home.viewmodel.ProductViewModelFactory
import dev.pankaj.cleanarchitecture.utils.CallBack
import dev.pankaj.cleanarchitecture.utils.serializable
import dev.pankaj.cleanarchitecture.utils.showToast
import javax.inject.Inject
@AndroidEntryPoint
class ProductDetailsFragment : Fragment() {
private var _binding: FragmentProductDetailsBinding? = null
private val binding get() = _binding!!
@Inject
lateinit var factory: ProductViewModelFactory
private lateinit var viewModel: ProductViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
viewModel = ViewModelProvider(this, factory)[ProductViewModel::class.java]
_binding = FragmentProductDetailsBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
addObserver()
arguments?.let {
if (it.containsKey("Data")){
it.serializable<Product>("Data")?.let { data->
activity?.let {action->
(action as AppCompatActivity).supportActionBar?.let { actionBar->
actionBar.title = data.title
}
}
lifecycleScope.launchWhenStarted {
viewModel.product(data.id!!)
}
}
}
}
}
private fun addObserver() {
viewModel.productResponse.observe(viewLifecycleOwner) { result ->
when (result) {
is CallBack.Loading -> setLoadingIndicator(result.isLoading)
is CallBack.Success -> handleProudctSuccess(result.data)
is CallBack.Error -> showMessage(result.exception.message)
is CallBack.Message -> showMessage(result.msg)
}
}
}
private fun handleProudctSuccess(product: Product) {
Glide.with(requireContext())
.load(product.image)
.into(binding.productImage)
binding.productTitle.text = product.title
binding.productPrice.text = "$" + product.price
binding.productOldPrice.text = "$" + product.price
binding.productDescription.text = product.description
binding.productRating.text = ""+product.rating?.rate+ " (" + product.rating?.count + " Reviews)";
}
private fun setLoadingIndicator(loading: Boolean) {
if (loading){
binding.loading.show()
binding.viewRoot.hide()
}else{
binding.loading.hide()
binding.viewRoot.show()
}
}
private fun showMessage(message: String?) {
requireActivity().showToast(message ?: "Something went wrong")
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | Kotlin | 0 | 0 | 050fa0aae45e4500c9fc85a04c6b7ee5b6439d71 | 3,796 | Clean-Architecture | The Unlicense |
app/src/main/java/com/example/kotlin_essentials/db/ShowDB.kt | kashiflab | 552,276,013 | false | null | package com.example.kotlin_essentials.db
import androidx.room.Database
import androidx.room.RoomDatabase
import com.example.kotlin_essentials.data.models.TvShowResponseItem
@Database(entities = [TvShowResponseItem::class], version = 1)
abstract class ShowDB: RoomDatabase() {
abstract fun getShowDao() : ShowDao
} | 0 | Kotlin | 0 | 0 | 9735a5054699d0f7058dd4c4be555b364d8a5f47 | 320 | Kotlin-Essentials | MIT License |
modules/features/random_image/src/main/java/com/markettwits/random_image/data/network/models/RandomImageItemCloud.kt | MarketTwits | 689,047,730 | false | {"Kotlin": 242276} | package com.markettwits.random_image.data.network.models
import kotlinx.serialization.Serializable
@Serializable
data class RandomImageItemCloud(
val color_dominant: List<Int>,
val color_palette: List<List<Int>>,
val id: Int,
val artist : ArtistCloud?,
val id_v2: String,
val sample_url: String,
val image_url : String,
val source: String?,
val rating : String
){
@Serializable
data class ArtistCloud(
val aliases: List<String>,
val id: Int,
val image_url: String?,
val links: List<String>,
val name: String,
)
data class TagCloud(val tag : String)
}
@Serializable
data class RandomImageCloud(val items : List<RandomImageItemCloud>) | 0 | Kotlin | 0 | 0 | 6d40b53a68a12cffc635027e6ff9f10f86f06bb2 | 727 | WaifuPics | MIT License |
applications/workers/release/rest-worker/src/e2eTest/kotlin/net/corda/applications/workers/rest/kafka/KafkaTestToolKit.kt | corda | 346,070,752 | false | null | package net.corda.applications.workers.rpc.kafka
import com.typesafe.config.ConfigFactory
import com.typesafe.config.ConfigValueFactory
import net.corda.applications.workers.rpc.http.TestToolkit
import net.corda.libs.configuration.SmartConfigFactory
import net.corda.lifecycle.impl.LifecycleCoordinatorFactoryImpl
import net.corda.lifecycle.impl.LifecycleCoordinatorSchedulerFactoryImpl
import net.corda.lifecycle.impl.registry.LifecycleRegistryImpl
import net.corda.messagebus.kafka.consumer.builder.CordaKafkaConsumerBuilderImpl
import net.corda.messagebus.kafka.producer.builder.KafkaCordaProducerBuilderImpl
import net.corda.messagebus.kafka.serialization.CordaAvroSerializationFactoryImpl
import net.corda.messaging.api.processor.DurableProcessor
import net.corda.messaging.api.publisher.config.PublisherConfig
import net.corda.messaging.api.publisher.factory.PublisherFactory
import net.corda.messaging.api.records.Record
import net.corda.messaging.api.subscription.config.SubscriptionConfig
import net.corda.messaging.api.subscription.factory.SubscriptionFactory
import net.corda.messaging.publisher.factory.CordaPublisherFactory
import net.corda.messaging.subscription.consumer.builder.StateAndEventBuilderImpl
import net.corda.messaging.subscription.factory.CordaSubscriptionFactory
import net.corda.schema.configuration.BootConfig
import net.corda.schema.configuration.MessagingConfig
import net.corda.schema.configuration.MessagingConfig.Bus.KAFKA_PROPERTIES_COMMON
import net.corda.schema.registry.impl.AvroSchemaRegistryImpl
import java.util.concurrent.TimeUnit
import kotlin.random.Random
class KafkaTestToolKit(
private val toolkit: TestToolkit,
) {
private companion object {
const val KAFKA_PROPERTY_PREFIX = "CORDA_KAFKA_"
}
private val registry by lazy {
AvroSchemaRegistryImpl()
}
private val serializationFactory by lazy {
CordaAvroSerializationFactoryImpl(registry)
}
private val consumerBuilder by lazy {
CordaKafkaConsumerBuilderImpl(registry)
}
private val producerBuilder by lazy {
KafkaCordaProducerBuilderImpl(registry)
}
private val coordinatorFactory by lazy {
LifecycleCoordinatorFactoryImpl(
LifecycleRegistryImpl(),
LifecycleCoordinatorSchedulerFactoryImpl()
)
}
private val stateAndEventBuilder by lazy {
StateAndEventBuilderImpl(
consumerBuilder,
producerBuilder
)
}
val messagingConfiguration by lazy {
val kafkaProperties = System.getenv().filterKeys {
it.startsWith(KAFKA_PROPERTY_PREFIX)
}.mapKeys { (key, _) ->
key.removePrefix(KAFKA_PROPERTY_PREFIX)
}.mapKeys { (key, _) ->
key.lowercase().replace('_', '.')
}.mapKeys { (key, _) ->
"$KAFKA_PROPERTIES_COMMON.${key.trim()}"
}
SmartConfigFactory.createWithoutSecurityServices().create(
ConfigFactory.parseMap(kafkaProperties)
.withValue(MessagingConfig.Bus.BUS_TYPE, ConfigValueFactory.fromAnyRef("KAFKA"))
.withValue(MessagingConfig.Bus.KAFKA_PRODUCER_CLIENT_ID, ConfigValueFactory.fromAnyRef("e2e-test"))
.withValue(BootConfig.TOPIC_PREFIX, ConfigValueFactory.fromAnyRef(""))
.withValue(BootConfig.INSTANCE_ID, ConfigValueFactory.fromAnyRef(Random.nextInt().toString()))
)
}
private val subscriptionFactory: SubscriptionFactory by lazy {
CordaSubscriptionFactory(
serializationFactory,
coordinatorFactory,
producerBuilder,
consumerBuilder,
stateAndEventBuilder
)
}
private val publisherFactory: PublisherFactory by lazy {
CordaPublisherFactory(
serializationFactory,
producerBuilder,
consumerBuilder,
coordinatorFactory
)
}
/**
* Creates easily attributable to a testcase unique name
*/
val uniqueName: String get() = toolkit.uniqueName
fun publishRecordsToKafka(records: Collection<Record<*, *>>) {
if (records.isNotEmpty()) {
publisherFactory.createPublisher(
PublisherConfig(toolkit.uniqueName, false),
messagingConfiguration,
).use { publisher ->
publisher.start()
publisher.publish(records.toList()).forEach {
it.get(30, TimeUnit.SECONDS)
}
}
}
}
fun <K : Any, V : Any> acceptRecordsFromKafka(
topic: String,
keyClass: Class<K>,
valueClass: Class<V>,
block: (Record<K, V>) -> Unit,
): AutoCloseable {
return subscriptionFactory.createDurableSubscription(
subscriptionConfig = SubscriptionConfig(
groupName = toolkit.uniqueName,
eventTopic = topic,
),
messagingConfig = messagingConfiguration,
processor = object : DurableProcessor<K, V> {
override fun onNext(events: List<Record<K, V>>): List<Record<*, *>> {
events.forEach(block)
return emptyList()
}
override val keyClass = keyClass
override val valueClass = valueClass
},
partitionAssignmentListener = null,
).also {
it.start()
}
}
inline fun <reified K : Any, reified V : Any> acceptRecordsFromKafka(
topic: String,
noinline block: (Record<K, V>) -> Unit
): AutoCloseable {
return acceptRecordsFromKafka(
topic,
K::class.java,
V::class.java,
block,
)
}
}
| 82 | null | 7 | 42 | 6ef36ce2d679a07abf7a5d95a832e98bd4d4d763 | 5,799 | corda-runtime-os | Apache License 2.0 |
core/src/main/kotlin/com/cs/beam/core/constants/Exceptions.kt | beam-engine | 668,537,547 | false | null | package com.cs.beam.core.constants
/**
* @author KK
* @version 1.0
*/
import org.springframework.http.HttpStatus
class JsonException(message: String?) : RuntimeException(message)
class WorkflowEventError(message: String?) : RuntimeException(message)
class WorkflowParserError(message: String?, cause: Throwable? = null) : RuntimeException(message, cause)
class FileDownloadException(throwable: Throwable?) : RuntimeException(throwable)
class WorkflowEngineException : Exception {
constructor(message: String) : super(message)
constructor(cause: Throwable) : super(cause)
constructor(message: String, cause: Throwable) : super(message, cause)
}
class WorkflowStateTransitionError : RuntimeException {
constructor(message: String) : super(message)
constructor(cause: Throwable) : super(cause)
constructor(message: String, cause: Throwable) : super(message, cause)
}
class ServiceException(override val message: String?, val statusCode: HttpStatus) : RuntimeException(message)
class ResourceNotFoundException(override val message: String?) : RuntimeException(message) | 0 | Kotlin | 0 | 0 | 89d53d7b8607ecb79d9b91d861922763e2a9b629 | 1,110 | beam-kt | MIT License |
personnel/src/main/kotlin/com/itavgur/omul/personnel/web/dto/EmployeeDataRequest.kt | itAvgur | 211,451,348 | false | {"Kotlin": 297016, "Smarty": 4598, "Dockerfile": 1120} | package com.itavgur.omul.personnel.web.dto
import com.itavgur.omul.personnel.domain.Employee
import com.itavgur.omul.personnel.domain.Gender
import io.swagger.v3.oas.annotations.media.Schema
import java.time.LocalDate
@Schema(name = "EmployeeDataRequest", description = "Employee data request (create/update)")
data class EmployeeDataRequest(
val employeeId: Int? = null,
val email: String,
val firstName: String,
val lastName: String,
val gender: Gender,
val documentId: String,
val birthDay: LocalDate,
val phone: String,
val qualification: String
) {
fun toEmployee(): Employee {
return Employee(
employeeId = employeeId,
firstName = firstName,
lastName = lastName,
gender = gender,
documentedId = documentId,
birthDate = birthDay,
phone = phone,
email = email,
qualification = qualification
)
}
} | 0 | Kotlin | 1 | 0 | ecdad770074ca157d8041a4d97399aeea7604d2b | 973 | omul | The Unlicense |
src/test/kotlin/io/andrewohara/dynamokt/DataClassTableSchemaTest.kt | oharaandrew314 | 421,600,664 | false | {"Kotlin": 44558} | package io.andrewohara.dynamokt
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Test
import software.amazon.awssdk.core.SdkBytes
import software.amazon.awssdk.services.dynamodb.model.AttributeValue
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
import java.nio.ByteBuffer
class DataClassTableSchemaTest {
data class TestItem(
val foo: String,
val bar: Int,
@DynamoKtAttribute("baz") val third: ByteBuffer? = null
)
data class OuterTestItem(
val bang: String,
@DynamoKtFlatten
val inner: TestItem
)
private val schema = DataClassTableSchema(TestItem::class)
private val outerSchema = DataClassTableSchema(OuterTestItem::class)
@Test
fun `attribute names`() {
schema.attributeNames().shouldContainExactlyInAnyOrder(
"foo", "bar", "baz"
)
}
@Test
fun `get attribute value`() {
val instance = TestItem("troll", 9001)
schema.attributeValue(instance, "foo") shouldBe AttributeValue.builder().s("troll").build()
schema.attributeValue(instance, "bar") shouldBe AttributeValue.builder().n("9001").build()
}
@Test
fun `item to map - don't ignore nulls`() {
val instance = TestItem("troll", 9001)
schema.itemToMap(instance, false) shouldBe mapOf(
"foo" to AttributeValue.builder().s("troll").build(),
"bar" to AttributeValue.builder().n("9001").build(),
"baz" to AttributeValue.builder().nul(true).build()
)
}
@Test
fun `item to map - ignore nulls`() {
val instance = TestItem("troll", 9001)
schema.itemToMap(instance, true) shouldBe mapOf(
"foo" to AttributeValue.builder().s("troll").build(),
"bar" to AttributeValue.builder().n("9001").build(),
)
}
@Test
fun `item to map - specific attributes`() {
val instance = TestItem("troll", 9001, ByteBuffer.wrap("lolcats".toByteArray()))
schema.itemToMap(instance, setOf("foo", "bar")) shouldBe mapOf(
"foo" to AttributeValue.builder().s("troll").build(),
"bar" to AttributeValue.builder().n("9001").build(),
)
}
@Test
fun `item to map - flatten`() {
val instance = OuterTestItem(
bang = "BANG",
inner = TestItem("troll", 9001)
)
outerSchema.itemToMap(instance, true) shouldBe mapOf(
"foo" to AttributeValue.fromS("troll"),
"bar" to AttributeValue.fromN("9001"),
"bang" to AttributeValue.fromS("BANG")
)
}
@Test
fun `map to item`() {
val map = mapOf(
"foo" to AttributeValue.builder().s("troll").build(),
"bar" to AttributeValue.builder().n("9001").build(),
"baz" to AttributeValue.builder().b(SdkBytes.fromByteArray("lolcats".toByteArray())).build()
)
schema.mapToItem(map) shouldBe TestItem("troll", 9001, ByteBuffer.wrap("lolcats".toByteArray()))
}
@Test
fun `map to item - flatten`() {
val map = mapOf(
"foo" to AttributeValue.fromS("troll"),
"bar" to AttributeValue.fromN("9001"),
"bang" to AttributeValue.fromS("BANG")
)
outerSchema.mapToItem(map) shouldBe OuterTestItem(
bang = "BANG",
inner = TestItem("troll", 9001)
)
}
@Test
fun `is abstract`() {
schema.isAbstract shouldBe false
}
@Test
fun `map to item - missing entry for nullable field`() {
data class Foo(val name: String, val age: Int?)
val schema = DataClassTableSchema(Foo::class)
val map = mapOf(
"name" to AttributeValue.builder().s("Toggles").build()
)
schema.mapToItem(map) shouldBe Foo("Toggles", null)
}
@Test
fun `construct schema for invalid data class - non-constructor properties`() {
shouldThrow<IllegalArgumentException> {
DataClassTableSchema(Person::class)
}
}
@Test
fun `non-data class throws error`() {
shouldThrow<IllegalArgumentException> {
DataClassTableSchema(String::class)
}.message shouldBe "class kotlin.String must be a data class"
}
@Test
fun `data class with private constructor`() {
data class Person private constructor(val name: String)
shouldThrow<IllegalStateException> {
DataClassTableSchema(Person::class)
}.message shouldBe "Person must have a public primary constructor"
}
@Test
fun `recursive model`() {
data class Item(val id: Int, val inner: Item?)
val item = Item(1, Item(2, null))
DataClassTableSchema(Item::class).itemToMap(item, true) shouldBe mapOf(
"id" to AttributeValue.fromN("1"),
"inner" to AttributeValue.fromM(mapOf(
"id" to AttributeValue.fromN("2"),
"inner" to AttributeValue.fromNul(true)
))
)
}
} | 1 | Kotlin | 3 | 18 | b49adc3d367426250c049a28338da0467ffd413a | 5,198 | dynamodb-kotlin-module | Apache License 2.0 |
commons/src/test/java/info/metadude/android/eventfahrplan/commons/temporal/DateParserTest.kt | johnjohndoe | 12,616,092 | true | {"Gradle": 10, "Markdown": 8, "Java Properties": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 2, "YAML": 4, "Kotlin": 314, "Java": 6, "INI": 1, "Proguard": 2, "XML": 208, "Gradle Kotlin DSL": 1, "SVG": 29} | package info.metadude.android.eventfahrplan.commons.temporal
import com.google.common.truth.Truth.assertThat
import org.junit.Assert.fail
import org.junit.Test
import org.threeten.bp.DateTimeException
import org.threeten.bp.format.DateTimeParseException
class DateParserTest {
@Test
fun `parseDateTime returns milliseconds for 2019 date and time with time zone and offset`() {
assertThat(DateParser.parseDateTime("2019-01-01T00:00:00Z")).isEqualTo(1546300800000)
}
@Test
fun `parseDateTime returns milliseconds for 1970 epoch date and time UTC`() {
assertThat(DateParser.parseDateTime("1970-01-01T00:00:00Z")).isEqualTo(0)
}
@Test
fun `parseDateTime returns milliseconds for 1970 epoch date and time with time zone with zero offset`() {
assertThat(DateParser.parseDateTime("1970-01-01T00:00:00+00:00")).isEqualTo(0)
}
@Test
fun `parseDateTime returns milliseconds for short after 1970 epoch date and time with time zone with offset`() {
assertThat(DateParser.parseDateTime("1970-01-01T02:00:00+01:00")).isEqualTo(3600000)
}
@Test
fun `parseDateTime returns milliseconds for 2016 date and time with time zone with offset`() {
// Test format of date / times ever seen in schedule.xml files.
assertThat(DateParser.parseDateTime("2016-09-14T14:30:00+02:00")).isEqualTo(1473856200000)
}
@Test
fun `parseDateTime returns milliseconds for 2016 date and time UTC`() {
// Test format of date / times ever seen in schedule.xml files.
assertThat(DateParser.parseDateTime("2016-09-14T12:30:00Z")).isEqualTo(1473856200000)
}
@Test
fun `parseDateTime fails when time zone offset is missing without a colon`() {
// Test format of date / times ever seen in schedule.xml files.
try {
DateParser.parseDateTime("2016-09-14T14:30:00+0200")
fail("Failure expected because malformed date string should not be parsed.")
} catch (e: DateTimeParseException) {
assertThat(e.message).startsWith("Text '2016-09-14T14:30:00+0200' could not be parsed")
}
}
@Test
fun `parseDateTime fails when time zone offset is missing`() {
try {
DateParser.parseDateTime("1970-01-01T03:00:00")
fail("Failure expected because malformed date string should not be parsed.")
} catch (e: DateTimeException) {
assertThat(e.message).startsWith("Unable to obtain Instant from TemporalAccessor: DateTimeBuilder")
}
}
@Test
fun `parseTimeZoneOffset returns negative integer for negative time zone offset`() {
assertThat(DateParser.parseTimeZoneOffset("1980-01-01T02:00:00-01:00")).isEqualTo(-3600)
}
@Test
fun `parseTimeZoneOffset returns positive integer for positive time zone offset`() {
assertThat(DateParser.parseTimeZoneOffset("1980-01-01T02:00:00+01:00")).isEqualTo(3600)
}
@Test
fun `parseTimeZoneOffset returns 0 for UTC offset`() {
assertThat(DateParser.parseTimeZoneOffset("1980-01-01T02:00:00Z")).isEqualTo(0)
}
@Test
fun `parseTimeZoneOffset fails when time zone offset is missing`() {
try {
DateParser.parseTimeZoneOffset("1970-01-01T03:00:00")
fail("Failure expected because malformed date string should not be parsed.")
} catch (e: IllegalArgumentException) {
assertThat(e.message).startsWith("Error parsing time zone offset from: '1970-01-01T03:00:00'.")
}
}
}
| 0 | Kotlin | 4 | 27 | 4b91d7dcdfbc8de965a928b3ebfbfe595ec06b3f | 3,559 | CampFahrplan | Apache License 2.0 |
main/java/com/example/myapplicationgamekt/src/org/RPG1/www/game/story/StoryLine.kt | dragoues | 344,530,130 | false | null | package com.example.myapplicationgamekt.src.org.academiadecodigo.www.game.story
/**
* Created by oem on 22-07-2017.
*/
interface StoryLine {
fun initStoryLine()
} | 0 | Kotlin | 0 | 0 | af4677748e15713e38c037eb6e80e9985dbdad8e | 169 | game_app_KT | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Rotateright.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup
public val OutlineGroup.Rotateright: ImageVector
get() {
if (_rotateright != null) {
return _rotateright!!
}
_rotateright = Builder(name = "Rotateright", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0001f, 22.7499f)
curveTo(6.8001f, 22.7499f, 2.5801f, 18.5199f, 2.5801f, 13.3299f)
curveTo(2.5801f, 8.1399f, 6.8001f, 3.8999f, 12.0001f, 3.8999f)
curveTo(13.0701f, 3.8999f, 14.1101f, 4.0499f, 15.1101f, 4.3599f)
curveTo(15.5101f, 4.4799f, 15.7301f, 4.8999f, 15.6101f, 5.2999f)
curveTo(15.4901f, 5.6999f, 15.0701f, 5.9199f, 14.6701f, 5.7999f)
curveTo(13.8201f, 5.5399f, 12.9201f, 5.3999f, 12.0001f, 5.3999f)
curveTo(7.6301f, 5.3999f, 4.0801f, 8.9499f, 4.0801f, 13.3199f)
curveTo(4.0801f, 17.6899f, 7.6301f, 21.2399f, 12.0001f, 21.2399f)
curveTo(16.3701f, 21.2399f, 19.9201f, 17.6899f, 19.9201f, 13.3199f)
curveTo(19.9201f, 11.7399f, 19.4601f, 10.2199f, 18.5901f, 8.9199f)
curveTo(18.3601f, 8.5799f, 18.4501f, 8.1099f, 18.8001f, 7.8799f)
curveTo(19.1401f, 7.6499f, 19.6101f, 7.7399f, 19.8401f, 8.0899f)
curveTo(20.8801f, 9.6399f, 21.4301f, 11.4499f, 21.4301f, 13.3299f)
curveTo(21.4201f, 18.5199f, 17.2001f, 22.7499f, 12.0001f, 22.7499f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(16.1304f, 6.0702f)
curveTo(15.9204f, 6.0702f, 15.7104f, 5.9802f, 15.5604f, 5.8102f)
lineTo(12.6704f, 2.4902f)
curveTo(12.4004f, 2.1802f, 12.4304f, 1.7002f, 12.7404f, 1.4302f)
curveTo(13.0504f, 1.1602f, 13.5304f, 1.1902f, 13.8004f, 1.5002f)
lineTo(16.6904f, 4.8202f)
curveTo(16.9604f, 5.1302f, 16.9304f, 5.6102f, 16.6204f, 5.8802f)
curveTo(16.4904f, 6.0102f, 16.3104f, 6.0702f, 16.1304f, 6.0702f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.7602f, 8.5302f)
curveTo(12.5302f, 8.5302f, 12.3002f, 8.4202f, 12.1502f, 8.2202f)
curveTo(11.9102f, 7.8902f, 11.9802f, 7.4202f, 12.3102f, 7.1702f)
lineTo(15.6802f, 4.7102f)
curveTo(16.0102f, 4.4602f, 16.4802f, 4.5402f, 16.7302f, 4.8702f)
curveTo(16.9802f, 5.2002f, 16.9002f, 5.6702f, 16.5702f, 5.9202f)
lineTo(13.2002f, 8.3902f)
curveTo(13.0702f, 8.4902f, 12.9202f, 8.5302f, 12.7602f, 8.5302f)
close()
}
}
.build()
return _rotateright!!
}
private var _rotateright: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 4,209 | VuesaxIcons | MIT License |
navigation/core/src/androidMain/kotlin/com/taetae98/codelab/navigation/core/AppEntry.kt | taetae98coding | 708,459,882 | false | {"Kotlin": 36323, "Swift": 1197, "HTML": 233, "Ruby": 109} | package com.taetae98.codelab.navigation.core
public data object AppEntry {
internal const val PREFIX = "app://codelab"
public const val ROUTE: String = PREFIX
}
| 0 | Kotlin | 0 | 0 | 561dbd507f5c3737eeba46cb821cae690aae14a6 | 171 | CodeLab | Apache License 2.0 |
benchmarks/app/src/main/java/space/sdrmaker/sdrmobile/benchmarks/NativeUtils.kt | BelmY | 334,381,265 | false | {"HTML": 367652, "Jupyter Notebook": 152457, "Kotlin": 144485, "C": 18104, "C++": 9259, "Ruby": 6464, "CMake": 3516} | package space.sdrmaker.sdrmobile.benchmarks
class NativeUtils {
companion object {
@JvmStatic
external fun ndkFloatConvolutionBenchmark(filterLength: Int, dataLength: Int): Long
@JvmStatic
external fun ndkShortConvolutionBenchmark(filterLength: Int, dataLength: Int): Long
@JvmStatic
external fun ndkComplexFFTBenchmark(fftWidth: Int, dataLength: Int): Long
@JvmStatic
external fun ndkRealFFTBenchmark(fftWidth: Int, dataLength: Int): Long
@JvmStatic
external fun ndkShortFloatConversionBenchmark(conversionsToPerform: Int): Long
@JvmStatic
external fun ndkFloatShortConversionBenchmark(conversionsToPerform: Int): Long
@JvmStatic
external fun ndkShortComplexConversionBenchmark(conversionsToPerform: Int): Long
// Used to load the 'native-lib' library on application startup.
init {
System.loadLibrary("native-lib")
}
}
}
| 0 | HTML | 1 | 1 | e60f4fefcfa7948db13cf5486a62853459521dff | 983 | SDRMS-sdr-mobile | Apache License 2.0 |
src/test/kotlin/no/nav/eessi/pensjon/models/sed/RolleSerdeTest.kt | navikt | 178,813,650 | false | null | package no.nav.eessi.pensjon.models.sed
import no.nav.eessi.pensjon.json.mapJsonToAny
import no.nav.eessi.pensjon.json.toJson
import no.nav.eessi.pensjon.json.typeRefs
import no.nav.eessi.pensjon.personidentifisering.helpers.Rolle
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
internal class RolleSerdeTest {
@Test
fun `Serialize KravType`() {
assertEquals("\"01\"", Rolle.ETTERLATTE.toJson())
assertEquals("\"02\"", Rolle.FORSORGER.toJson())
assertEquals("\"03\"", Rolle.BARN.toJson())
}
@Test
fun `Serde Krav object`() {
val etterlatte = Rolle.ETTERLATTE
assertEquals(Rolle.ETTERLATTE, serde(etterlatte))
val forsorger = Rolle.FORSORGER
assertEquals(Rolle.FORSORGER, serde(forsorger))
val barn = Rolle.BARN
assertEquals(Rolle.BARN, serde(barn))
}
private fun serde(rolle: Rolle): Rolle {
val json = rolle.toJson()
return mapJsonToAny(json, typeRefs())
}
} | 1 | Kotlin | 1 | 4 | a6f241d54dbb36d364cc98eedabc9cfdda14f8b5 | 1,026 | eessi-pensjon-journalforing | MIT License |
repository/src/main/java/de/shecken/grillshow/repository/preferences/PreferencesRepository.kt | pynnie | 617,506,940 | false | {"Kotlin": 168809, "HTML": 12735} | package de.shecken.grillshow.repository.preferences
import kotlinx.coroutines.flow.Flow
interface PreferencesRepository {
/**
* [Flow] containing all app-side preferences
*/
val appPreferencesFlow: Flow<AppPreferences>
/**
* Update the flat for app initialization
*
* @param initCompleted new value for the flag
*/
suspend fun updateInitCompleted(initCompleted: Boolean)
/**
* Update the app version name
*
* @param version the new version name
*/
suspend fun updateAppVersion(version: String)
} | 9 | Kotlin | 0 | 2 | 132264aa50c5712605a0b2131fffdd1f416e1c38 | 574 | android-grillshow-app | Apache License 2.0 |
app/src/main/java/com/theone/demo/ui/fragment/login/LoginRegisterFragment.kt | Theoneee | 391,850,188 | false | null | package com.theone.demo.ui.fragment.login
import android.view.View
import com.qmuiteam.qmui.arch.QMUIFragment
import com.theone.common.constant.BundleConstant
import com.theone.common.ext.newFragment
import com.theone.demo.R
import com.theone.mvvm.base.viewmodel.BaseViewModel
import com.theone.mvvm.core.data.entity.QMUITabBean
import com.theone.mvvm.core.ext.qmui.addTab
import com.theone.mvvm.core.base.fragment.BaseTabInTitleFragment
// ┏┓ ┏┓
//┏┛┻━━━┛┻┓
//┃ ┃
//┃ ━ ┃
//┃ ┳┛ ┗┳ ┃
//┃ ┃
//┃ ┻ ┃
//┃ ┃
//┗━┓ ┏━┛
// ┃ ┃ 神兽保佑
// ┃ ┃ 永无BUG!
// ┃ ┗━━━┓
// ┃ ┣┓
// ┃ ┏┛
// ┗┓┓┏━┳┓┏┛
// ┃┫┫ ┃┫┫
// ┗┻┛ ┗┻┛
/**
* @author The one
* @date 2021/3/15 0015
* @describe TODO
* @email [email protected]
* @remark
*/
class LoginRegisterFragment:BaseTabInTitleFragment<BaseViewModel>() {
override fun initView(rootView: View) {
super.initView(rootView)
getTopBar()?.run {
addLeftImageButton(
R.drawable.mz_comment_titlebar_ic_close_dark,
R.id.topbar_left_button
).setOnClickListener {
popBackStack()
}
updateBottomDivider(0, 0, 0, 0)
}
// 这里直接放到initView里面
startInit()
}
override fun onLazyInit() {
// 这个方法要清空
}
override fun initTabAndFragments(
tabs: MutableList<QMUITabBean>,
fragments: MutableList<QMUIFragment>
) {
with(tabs){
addTab("登录")
addTab("注册")
}
with(fragments){
add(LoginRegisterItemFragment.newInstant(false))
// add(LoginRegisterItemFragment.newInstant(true))
add(
newFragment<LoginRegisterItemFragment> {
putBoolean(BundleConstant.TYPE,true)
}
)
}
}
/**
* 更改进出动画效果 QMUIFragment提供
*/
override fun onFetchTransitionConfig(): TransitionConfig = SCALE_TRANSITION_CONFIG
} | 0 | Kotlin | 1 | 5 | b084f00243fbec7bd1481209ad0843e871e2ceee | 2,058 | TheDemo-MVVM | Apache License 2.0 |
api/src/main/kotlin/com/starter/api/rest/users/core/UserController.kt | EmirDelicR | 772,962,825 | false | {"Kotlin": 183048, "TypeScript": 38933, "SCSS": 9749, "Dockerfile": 904, "JavaScript": 846, "HTML": 365} | package com.starter.api.rest.users.core
import com.starter.api.dtos.ResponseEnvelope
import com.starter.api.rest.users.dtos.UserResponse
import com.starter.api.rest.users.dtos.UserUpdateRequest
import com.starter.api.utils.logger
import jakarta.validation.Valid
import org.springframework.http.HttpStatus
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.bind.annotation.RestController
@Validated
@RestController
@RequestMapping(path = ["/api/v1/users"])
class UserController(val userService: UserService) {
@GetMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
fun getUser(
@PathVariable id: String,
): ResponseEnvelope<UserResponse> {
logger.info("Handling getUser Request")
val user = userService.getById(id)
return ResponseEnvelope(
data = user.toResponse(),
message = "Fetch user successful.",
status = HttpStatus.OK.value(),
)
}
@PutMapping("/{id}")
@ResponseStatus(HttpStatus.OK)
fun updateUser(
@PathVariable id: String,
@RequestBody @Valid userRequest: UserUpdateRequest,
): ResponseEnvelope<User> {
logger.info("Handling updateMessage Request")
val user = userService.update(id, userRequest)
return ResponseEnvelope(
data = user,
message = "User with id ($id) was updated successfully.",
status = HttpStatus.OK.value(),
)
}
@PutMapping("/{id}/admin")
@ResponseStatus(HttpStatus.OK)
fun updateUserAsAdmin(
@PathVariable id: String,
): ResponseEnvelope<UserResponse> {
logger.info("Handling updateUserAsAdmin Request")
val user = userService.updateUserAsAdmin(id)
return ResponseEnvelope(
data = user.toResponse(),
message = "User with id ($id) was updated as admin successfully.",
status = HttpStatus.OK.value(),
)
}
}
| 0 | Kotlin | 0 | 0 | e1bf0cce14aef75208b647f48b2a8edc10ba4abf | 2,328 | kotlin-starter-pack | MIT License |
app/src/main/java/com/omongole/fred/composenewsapp/ui/components/bottomNavigation/BottomBar.kt | EngFred | 719,675,736 | false | {"Kotlin": 64656} | package com.omongole.fred.composenewsapp.ui.components.bottomNavigation
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Star
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import androidx.navigation.NavDestination
import androidx.navigation.NavDestination.Companion.hierarchy
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import com.omongole.fred.composenewsapp.ui.navigation.Route
@Composable
fun BottomBar(
navController: NavHostController
) {
val screens = listOf(
NavigationBarItem(
Route.HomeScreen,
"Home",
Icons.Default.Home
),
NavigationBarItem(
Route.BookmarkScreen,
"Bookmarks",
Icons.Default.Star
)
)
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
val bottomBarDestinations = screens.any { it.screen.destination == currentDestination?.route }
if ( bottomBarDestinations ) {
NavigationBar(
Modifier.fillMaxWidth(),
containerColor = MaterialTheme.colorScheme.background,
tonalElevation = 10.dp
) {
screens.forEach {
AddItem(
screen = it.screen,
currentDestination = currentDestination ,
navController = navController,
title = it.title,
icon = it.icon
)
}
}
}
}
@Composable
fun RowScope.AddItem(
screen: Route,
currentDestination: NavDestination?,
navController: NavHostController,
title: String,
icon: ImageVector
) {
NavigationBarItem(
selected = currentDestination?.hierarchy?.any{
it.route == screen.destination
} == true ,
onClick = {
navController.navigate(screen.destination){
popUpTo(navController.graph.findStartDestination().id)
launchSingleTop = true
}
},
icon = { Icon(imageVector = icon, contentDescription = "") },
label = { Text(text = title) }
)
} | 0 | Kotlin | 0 | 0 | 06ca742f45b09936245463ad6a06b97235865e72 | 2,874 | News-Flash | MIT License |
app/src/main/java/com/implementing/cozyspace/inappscreens/task/screens/AddTaskBottomSheetContent.kt | Brindha-m | 673,871,291 | false | {"Kotlin": 635264} | package com.implementing.cozyspace.inappscreens.task.screens
import android.annotation.SuppressLint
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.IntrinsicSize
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.defaultMinSize
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.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDefaults
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.Divider
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Tab
import androidx.compose.material3.TabPosition
import androidx.compose.material3.TabRow
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TimePicker
import androidx.compose.material3.TimePickerDefaults
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
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
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import com.implementing.cozyspace.R
import com.implementing.cozyspace.inappscreens.task.SubTaskItem
import com.implementing.cozyspace.inappscreens.task.screens.widgets.NumberPicker
import com.implementing.cozyspace.model.SubTask
import com.implementing.cozyspace.model.Task
import com.implementing.cozyspace.util.Priority
import com.implementing.cozyspace.util.TaskFrequency
import com.implementing.cozyspace.util.formatDateDependingOnDay
import com.implementing.cozyspace.util.formatTime
import com.implementing.cozyspace.util.toInt
import com.implementing.cozyspace.util.toPriority
import com.implementing.cozyspace.util.toTaskFrequency
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Locale
@SuppressLint("StringFormatInvalid")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddTaskBottomSheetContent(
onAddTask: (Task) -> Unit,
focusRequester: FocusRequester
) {
var title by rememberSaveable { mutableStateOf("") }
var description by rememberSaveable { mutableStateOf("") }
var priority by rememberSaveable { mutableStateOf(Priority.LOW) }
var dueDate by rememberSaveable { mutableStateOf(Calendar.getInstance()) }
var dueDateExists by rememberSaveable { mutableStateOf(false) }
val subTasks = remember { mutableStateListOf<SubTask>() }
var recurring by rememberSaveable { mutableStateOf(false) }
var frequency by rememberSaveable { mutableIntStateOf(0) }
var frequencyAmount by rememberSaveable { mutableIntStateOf(0) }
val priorities = listOf(Priority.LOW, Priority.MEDIUM, Priority.HIGH)
val context = LocalContext.current
val timeState = rememberTimePickerState()
val snackState = remember { SnackbarHostState() }
val snackScope = rememberCoroutineScope()
val formatter = remember { SimpleDateFormat("hh:mm a", Locale.getDefault()) }
var showTimePicker by remember { mutableStateOf(true) }
var openDialog by remember { mutableStateOf(true) }
Column(
modifier = Modifier
.defaultMinSize(minHeight = 1.dp)
.padding(horizontal = 16.dp, vertical = 24.dp)
.verticalScroll(rememberScrollState())
) {
SheetHandle(Modifier.align(Alignment.CenterHorizontally))
Text(
text = stringResource(R.string.add_task),
style = MaterialTheme.typography.bodyMedium,
fontSize = 16.sp
)
Spacer(Modifier.height(16.dp))
OutlinedTextField(
value = title,
onValueChange = { title = it },
label = { Text(text = stringResource(R.string.title)) },
shape = RoundedCornerShape(15.dp),
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
)
Spacer(Modifier.height(12.dp))
Column {
subTasks.forEachIndexed { index, item ->
SubTaskItem(
subTask = item,
onChange = { subTasks[index] = it },
onDelete = { subTasks.removeAt(index) }
)
}
}
Row(
Modifier
.fillMaxWidth()
.clickable {
subTasks.add(
SubTask(
title = "",
isCompleted = false,
)
)
},
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(R.string.add_sub_task),
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.padding(vertical = 8.dp)
)
Icon(
modifier = Modifier.size(15.dp),
painter = painterResource(id = R.drawable.ic_add),
contentDescription = stringResource(
id = R.string.add_sub_task
)
)
}
Divider()
Spacer(Modifier.height(13.dp))
Text(
text = stringResource(R.string.priority),
style = MaterialTheme.typography.bodyMedium.copy(fontWeight = FontWeight.Bold)
)
Spacer(Modifier.height(15.dp))
PriorityTabRow(
priorities = priorities,
priority,
onChange = { priority = it }
)
Spacer(Modifier.height(12.dp))
Divider()
Spacer(Modifier.height(12.dp))
Row(
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = dueDateExists,
onCheckedChange = { dueDateExists = it },
colors = CheckboxDefaults.colors(Color.DarkGray)
)
Spacer(Modifier.width(4.dp))
Text(
text = stringResource(R.string.due_date),
style = MaterialTheme.typography.bodyMedium,
)
}
AnimatedVisibility(dueDateExists) {
Column {
Row(
Modifier
.fillMaxWidth()
.clickable {
showTimePicker = true
openDialog = true
}
.padding(8.dp),
horizontalArrangement = Arrangement.SpaceBetween,
) {
if (showTimePicker) {
TimePickerDialog(
onCancel = { showTimePicker = false },
onConfirm = {
// Construct the Calendar object with the selected time
val cal = Calendar.getInstance()
// Update the dueDate with the selected time
dueDate.set(Calendar.HOUR_OF_DAY, timeState.hour)
dueDate.set(Calendar.MINUTE, timeState.minute)
// Show Snackbar with selected time
val formattedTime = SimpleDateFormat(
"yyyy-MM-dd hh:mm a",
Locale.getDefault()
).format(cal.time)
snackScope.launch {
snackState.showSnackbar("Selected time: $formattedTime")
}
// Close the time picker
showTimePicker = false
}
) {
TimePicker(
state = timeState,
colors = TimePickerDefaults.colors(
timeSelectorSelectedContainerColor = Color(0xE18260BE),
selectorColor = Color(0xFFB79AE9),
)
)
}
}
if (openDialog) {
val datePickerState = rememberDatePickerState()
val confirmEnabled = remember {
derivedStateOf { datePickerState.selectedDateMillis != null }
}
DatePickerDialog(
onDismissRequest = {
openDialog = false
},
confirmButton = {
TextButton(
onClick = {
val selectedDateMillis = datePickerState.selectedDateMillis ?: Calendar.getInstance().timeInMillis
// Update the dueDate with the selected date
dueDate = Calendar.getInstance().apply { timeInMillis = selectedDateMillis }
openDialog = false
// Show the time picker after selecting the date
showTimePicker = true
// Show Snackbar with selected date
snackScope.launch {
snackState.showSnackbar(
context.getString(
R.string.selected_date,
dueDate.timeInMillis.formatDateDependingOnDay()
)
)
}
},
enabled = confirmEnabled.value
) {
Text("OK")
}
},
dismissButton = {
TextButton(
onClick = {
openDialog = false
}
) {
Text("Cancel")
}
}
) {
val minDate = Calendar.getInstance().apply {
// Clear the time fields to set the time to midnight
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.timeInMillis
DatePicker(
state = datePickerState,
colors = DatePickerDefaults.colors(
selectedDayContainerColor = Color(0xD78260BE)
),
dateValidator = { date ->
// Check if the date is after or equal to the minimum date
date >= minDate
},
)
}
}
Row(verticalAlignment = Alignment.CenterVertically) {
Icon(
painter = painterResource(R.drawable.ic_alarm),
stringResource(R.string.due_date)
)
Spacer(Modifier.width(8.dp))
Text(
text = stringResource(R.string.due_date),
style = MaterialTheme.typography.bodyMedium
)
}
Text(
text = dueDate.timeInMillis.formatDateDependingOnDay(),
style = MaterialTheme.typography.bodyMedium
)
}
Row(
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(checked = recurring,
colors = CheckboxDefaults.colors(Color.DarkGray),
onCheckedChange = {
recurring = it
if (!it) frequency = 0
})
Spacer(Modifier.width(4.dp))
Text(
text = stringResource(R.string.recurring),
style = MaterialTheme.typography.bodyMedium
)
}
AnimatedVisibility(recurring) {
var expanded by remember { mutableStateOf(false) }
Column {
Box {
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }) {
TaskFrequency.values().forEach { f ->
DropdownMenuItem(
text = {
Text(
text = stringResource(f.title),
style = MaterialTheme.typography.bodyMedium
)
},
onClick = {
expanded = false
frequency = f.ordinal
}
)
}
}
Row(
Modifier
.clickable { expanded = true }
.padding(8.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = stringResource(
frequency.toTaskFrequency().title
)
)
Icon(
imageVector = Icons.Default.ArrowDropDown,
contentDescription = stringResource(R.string.recurring),
modifier = Modifier.size(22.dp)
)
}
}
Spacer(Modifier.height(8.dp))
NumberPicker(
stringResource(R.string.repeats_every),
frequencyAmount
) {
if (it > 0) frequencyAmount = it
}
}
}
}
}
Spacer(Modifier.height(11.dp))
OutlinedTextField(
value = description,
onValueChange = { description = it },
label = { Text(text = stringResource(R.string.description)) },
shape = RoundedCornerShape(15.dp),
modifier = Modifier.fillMaxWidth()
)
Spacer(Modifier.height(13.dp))
Button(
colors = ButtonDefaults.buttonColors(containerColor = Color.Black),
onClick = {
onAddTask(
Task(
title = title,
description = description,
priority = priority.toInt(),
recurring = recurring,
frequency = frequency,
dueDate = if (dueDateExists) dueDate.timeInMillis else 0L,
createdDate = System.currentTimeMillis(),
updatedDate = System.currentTimeMillis(),
subTasks = subTasks.toList()
)
)
title = ""
description = ""
priority = Priority.LOW
dueDate = Calendar.getInstance()
dueDateExists = false
subTasks.clear()
},
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
shape = RoundedCornerShape(25.dp)
) {
Text(
text = stringResource(R.string.add_task),
style = MaterialTheme.typography.bodyMedium.copy(Color.White)
)
}
Spacer(modifier = Modifier.height(54.dp))
}
}
@Composable
fun PriorityTabRow(
priorities: List<Priority>,
selectedPriority: Priority,
onChange: (Priority) -> Unit
) {
val indicator = @Composable { tabPositions: List<TabPosition> ->
AnimatedTabIndicator(Modifier.tabIndicatorOffset(tabPositions[selectedPriority.toInt()]))
}
TabRow(
selectedTabIndex = selectedPriority.toInt(),
indicator = indicator,
modifier = Modifier.clip(RoundedCornerShape(14.dp)),
contentColor = Color.Black
) {
priorities.forEachIndexed { index, it ->
Tab(
text = {
Text(
stringResource(it.title),
style = MaterialTheme.typography.bodyMedium
)
},
selected = selectedPriority.toInt() == index,
onClick = {
onChange(index.toPriority())
},
modifier = Modifier.background(it.color),
)
}
}
}
@Composable
fun AnimatedTabIndicator(modifier: Modifier = Modifier) {
Box(
modifier = modifier
.padding(5.dp)
.fillMaxSize()
.border(BorderStroke(2.dp, Color.White), RoundedCornerShape(8.dp))
)
}
@Composable
fun SheetHandle(modifier: Modifier = Modifier) {
Box(
modifier = modifier
.clip(RoundedCornerShape(10.dp))
.size(width = 60.dp, height = 4.dp)
.background(Color.Gray)
.padding(5.dp)
)
}
@Preview
@Composable
fun AddTaskSheetPreview() {
AddTaskBottomSheetContent(onAddTask = {}, FocusRequester())
}
@Composable
fun TimePickerDialog(
title: String = "Select Time",
onCancel: () -> Unit,
onConfirm: () -> Unit,
toggle: @Composable () -> Unit = {},
content: @Composable () -> Unit,
) {
Dialog(
onDismissRequest = onCancel,
properties = DialogProperties(usePlatformDefaultWidth = false),
) {
Surface(
shape = MaterialTheme.shapes.extraLarge,
tonalElevation = 6.dp,
modifier = Modifier
.width(IntrinsicSize.Min)
.height(IntrinsicSize.Min)
.background(
shape = MaterialTheme.shapes.extraLarge,
color = MaterialTheme.colorScheme.surface
),
) {
Column(
modifier = Modifier.padding(24.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(bottom = 20.dp),
text = title,
style = MaterialTheme.typography.labelMedium
)
content()
Row(
modifier = Modifier
.height(40.dp)
.fillMaxWidth()
) {
toggle()
Spacer(modifier = Modifier.weight(1f))
TextButton(onClick = onCancel) {
Text("Cancel")
}
TextButton(onClick = onConfirm) {
Text("OK")
}
}
}
}
}
} | 0 | Kotlin | 0 | 2 | 3ee4ec19dec6f0c572263ef45496df53f6a98220 | 23,275 | DoodSpace-Todos.Notes.Doodles | Apache License 2.0 |
app/src/main/java/linc/com/getmeexample/fragments/StartFragment.kt | lincollincol | 262,124,997 | false | null | package linc.com.getmeexample.fragments
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import linc.com.getmeexample.ExampleGetMeActivity
import linc.com.getmeexample.MainActivity
import linc.com.getmeexample.R
class StartFragment : Fragment(), View.OnClickListener {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_start, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Button>(R.id.defaultGetMe).setOnClickListener(this)
view.findViewById<Button>(R.id.customGetMeItemLayout).setOnClickListener(this)
view.findViewById<Button>(R.id.customGetMeStyle).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeMainContent).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeExceptContent).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeOnlyDirectories).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeSingleSelection).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeFromPath).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeMaximumSelectionSize).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeAdapterAnimation).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeOverScroll).setOnClickListener(this)
view.findViewById<Button>(R.id.getMeFromActivity).setOnClickListener(this)
}
override fun onClick(p0: View?) {
when(p0?.id) {
R.id.defaultGetMe -> openFragment(ExampleGetMeFragment.DEFAULT_GETME)
R.id.customGetMeItemLayout -> openFragment(ExampleGetMeFragment.CUSTOM_ITEM_LAYOUT_GETME)
R.id.customGetMeStyle -> openFragment(ExampleGetMeFragment.CUSTOM_STYLE_GETME)
R.id.getMeMainContent -> openFragment(ExampleGetMeFragment.MAIN_CONTENT_GETME)
R.id.getMeExceptContent -> openFragment(ExampleGetMeFragment.EXCEPT_CONTENT_GETME)
R.id.getMeOnlyDirectories -> openFragment(ExampleGetMeFragment.ONLY_DIRECTORIES_GETME)
R.id.getMeSingleSelection -> openFragment(ExampleGetMeFragment.SINGLE_SELECTION_GETME)
R.id.getMeFromPath -> openFragment(ExampleGetMeFragment.FROM_PATH_GETME)
R.id.getMeMaximumSelectionSize -> openFragment(ExampleGetMeFragment.MAX_SELECTION_SIZE_GETME)
R.id.getMeAdapterAnimation -> openFragment(ExampleGetMeFragment.ADAPTER_ANIMATION_GETME)
R.id.getMeOverScroll -> openFragment(ExampleGetMeFragment.OVERSCROLL_GETME)
R.id.getMeFromActivity -> {
startActivity(Intent(this.context, ExampleGetMeActivity::class.java))
}
}
}
private fun openFragment(type: Int) {
fragmentManager?.beginTransaction()
?.replace(
R.id.fragmentContainer,
ExampleGetMeFragment.newInstance(type)
)
?.addToBackStack(null)
?.commit()
}
}
| 1 | Kotlin | 1 | 3 | a1166012cb9f64104e4b7037470f6afd9ce579ac | 3,340 | GetMe | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.