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
PrimFastKotlin/KotlinAction/app/src/main/java/com/prim/gkapp/ui/login/LoginPresenter.kt
zyl4265097
248,767,646
true
{"Markdown": 5, "Text": 1, "Shell": 8, "JSON": 13, "Ignore List": 28, "JavaScript": 8, "Java Properties": 12, "Gradle": 35, "Batchfile": 7, "XML": 200, "Proguard": 18, "Java": 150, "INI": 3, "Kotlin": 93, "CMake": 1, "YAML": 1, "Git Attributes": 1, "Starlark": 3, "OpenStep Property List": 4, "Objective-C": 4}
package com.prim.gkapp.ui.login import android.content.Context import com.prim.gkapp.BuildConfig import com.prim.gkapp.data.UserData import com.prim.lib_base.mvp.impl.BasePresenter /** * @desc * @author prim * @time 2019-05-29 - 07:32 * @version 1.0.0 */ class LoginPresenter : BasePresenter<LoginActivity>() { override fun initContext(context: Context?) { } fun login(userName: String, password: String) { UserData.username = userName UserData.password = <PASSWORD> UserData.login().subscribe({ view.onSuccessLogin() }, { view.onErrorLogin(it) }, { view.onIntent() }, { view.onStartLogin() }) } fun checkUserName(userName: String): Boolean { return true } fun checkPassword(password: String): Boolean { return password != null && password.length >= 8 } override fun onResume() { super.onResume() if (BuildConfig.DEBUG) { view.onDataInit(BuildConfig.testUserName, BuildConfig.testPassword) } else { view.onDataInit(UserData.username, UserData.password) } } }
0
Java
0
0
dba30a1b3518da41cdc5c492f70b8d3ae4146ee4
1,186
PrimFastApp
Apache License 2.0
sample/movie/ticketing/src/commonMain/kotlin/io/github/trueangle/blackbox/sample/movie/ticketing/domain/model/Cinema.kt
trueangle
687,002,862
false
{"Kotlin": 13941}
package io.github.trueangle.blackbox.sample.movie.ticketing.domain.model import kotlinx.collections.immutable.ImmutableList data class Cinema( val id: Long, val name: String, val address: String, val city: String, val showTimes: ImmutableList<ShowTime> ) data class ShowTime( val id: Long, val startTime: String, val endTime: String, val price: Double, ) { val timeRangeString = "$startTime - $endTime" }
0
Kotlin
0
6
7de102e681a92d0c417c0f50c7af30cea4b63bb3
448
Blackbox
Apache License 2.0
module-link/src/main/java/com/affise/attribution/module/link/usecase/LinkResolveUseCaseImpl.kt
affise
496,592,599
false
{"Kotlin": 816143, "JavaScript": 39328, "HTML": 33916}
package com.affise.attribution.module.link.usecase import com.affise.attribution.executors.ExecutorServiceProvider import com.affise.attribution.modules.link.AffiseLinkCallback import com.affise.attribution.network.HttpClient import com.affise.attribution.network.HttpResponse import com.affise.attribution.utils.isRedirect import java.net.URL internal class LinkResolveUseCaseImpl( private val httpClient: HttpClient, private val sendServiceProvider: ExecutorServiceProvider, ) : LinkResolveUseCase { override fun linkResolve(url: String, callback: AffiseLinkCallback) { sendServiceProvider.provideExecutorService().execute { resolve(url, callback, MAX_REDIRECT_COUNT) } } private fun resolve(url: String, callback: AffiseLinkCallback, maxSteps: Int) { //Create request val response = createRequest(url) //Has redirect status if (response.isRedirect() && maxSteps > 0) { //Get first non blank location url val redirectUrl = response.headers[HEADER_LOCATION]?.firstOrNull { it.isNotBlank() } if (!redirectUrl.isNullOrBlank()) { //Resolve redirect url resolve(redirectUrl, callback, maxSteps - 1) } else { //Return final url callback.handle(url) } } else { //Return final url callback.handle(url) } } private fun createRequest(url: String): HttpResponse { //Create request return httpClient.executeRequest( httpsUrl = URL(url), method = HttpClient.Method.GET, data = "", headers = emptyMap(), redirect = false ) } companion object { const val MAX_REDIRECT_COUNT = 10 const val HEADER_LOCATION = "Location" } }
0
Kotlin
0
3
a419ebe6c0d3b1ed601cd3b127f315fc74836161
1,878
sdk-android
MIT License
core/src/test/java/com/bed/core/domain/parameters/authentication/ResetParameterTest.kt
bed72
674,410,644
false
{"Kotlin": 151713, "Shell": 492}
package com.bed.core.domain.parameters.authentication import org.junit.Test import org.junit.Assert.assertEquals import com.bed.core.values.getFirstMessage internal class ResetParameterTest { @Test fun `Should try validate ResetParameter return valid`() { ResetParameter("code", "P@ssw0rD").map { (code, password) -> assertEquals(code(), "code") assertEquals(password(), "P@ssw0rD") } } @Test fun `Should try validate ResetParameter return failure when code is invalid`() { ResetParameter("", "P@ssw0rD").mapLeft { message -> assertEquals(message.getFirstMessage(), "Preencha um código válido.") } } @Test fun `Should try validate ResetParameter return failure when password is empty`() { ResetParameter("code", "").mapLeft { message -> assertEquals(message.getFirstMessage(), "A senha presica conter mais de 6 caracteres.") } } @Test fun `Should try validate ResetParameter return failure when password is invalid (needs a number)`() { ResetParameter("code", "password").mapLeft { message -> assertEquals(message.getFirstMessage(), "A senha presica conter caracteres numéricos.") } } @Test fun `Should try validate ResetParameter return failure when password is invalid (needs a capital character)`() { ResetParameter("code", "passw0rd").mapLeft { message -> assertEquals(message.getFirstMessage(), "A senha presica conter caracteres maiúsculos.") } } }
0
Kotlin
0
1
16e9323baf729459e7eff97881ae130d11cf3973
1,573
Hogwarts
MIT License
app/src/main/java/com/jthou/wanandroidkotlin/repository/KnowledgeSystemListRepository.kt
jthou20121212
210,117,827
false
null
package com.jthou.wanandroidkotlin.repository import androidx.lifecycle.LiveData import androidx.paging.PagedList import com.jthou.wanandroidkotlin.data.DataRepository import com.jthou.wanandroidkotlin.data.entity.Article /** * @author jthou * @version 1.0.0 * @date 22-09-2019 */ class KnowledgeSystemListRepository internal constructor(private val dataRepository: DataRepository) { fun getKnowledgeSystemArticleList(cid: Int): LiveData<PagedList<Article>> = dataRepository.getKnowledgeSystemArticleList(cid) }
0
Kotlin
0
0
7518eccff844b4c9191f69b7d9c6b72b13373f49
524
WanAndroidKotlin
Apache License 2.0
komapper-core/src/main/kotlin/org/komapper/core/DryRunResult.kt
komapper
349,909,214
false
null
package org.komapper.core data class DryRunResult( val sql: String = "", val sqlWithArgs: String = "", val args: List<Value> = emptyList(), val throwable: Throwable? = null, val description: String = "", )
6
Kotlin
0
16
7092a2bd24b609a1816bf05c89730259ff45178d
227
komapper
Apache License 2.0
app/src/main/java/org/xtimms/ridebus/ui/routes/details/stop/StopsOnRouteAdapter.kt
ridebus-by
379,109,231
false
null
package org.xtimms.ridebus.ui.routes.details.stop import org.xtimms.ridebus.ui.routes.details.RouteDetailsController import org.xtimms.ridebus.ui.routes.details.stop.base.BaseStopsAdapter class StopsOnRouteAdapter( controller: RouteDetailsController ) : BaseStopsAdapter<StopOnRouteItem>(controller) { var items: List<StopOnRouteItem> = emptyList() override fun updateDataSet(items: List<StopOnRouteItem>?) { this.items = items ?: emptyList() super.updateDataSet(items) } fun indexOf(item: StopOnRouteItem): Int { return items.indexOf(item) } }
0
Kotlin
0
7
086da0d23cdbb238c35622053568361802ebd2bc
598
ridebus
Apache License 2.0
feature-wallet-impl/src/main/java/jp/co/soramitsu/wallet/impl/data/historySource/HistorySourceProvider.kt
soramitsu
278,060,397
false
null
package jp.co.soramitsu.wallet.impl.data.historySource import jp.co.soramitsu.runtime.multiNetwork.ChainRegistry import jp.co.soramitsu.runtime.multiNetwork.chain.model.Chain import jp.co.soramitsu.wallet.impl.data.network.subquery.OperationsHistoryApi import jp.co.soramitsu.xnetworking.basic.networkclient.SoramitsuNetworkClient import jp.co.soramitsu.xnetworking.fearlesswallet.txhistory.client.TxHistoryClientForFearlessWalletFactory class HistorySourceProvider( private val walletOperationsApi: OperationsHistoryApi, private val chainRegistry: ChainRegistry, private val soramitsuNetworkClient: SoramitsuNetworkClient, private val soraTxHistoryFactory: TxHistoryClientForFearlessWalletFactory ) { operator fun invoke(historyUrl: String, historyType: Chain.ExternalApi.Section.Type): HistorySource? { return when (historyType) { Chain.ExternalApi.Section.Type.SUBQUERY -> SubqueryHistorySource(walletOperationsApi, chainRegistry, historyUrl) Chain.ExternalApi.Section.Type.SORA -> SoraHistorySource(soramitsuNetworkClient, soraTxHistoryFactory) Chain.ExternalApi.Section.Type.SUBSQUID -> SubsquidHistorySource(walletOperationsApi, historyUrl) Chain.ExternalApi.Section.Type.GIANTSQUID -> GiantsquidHistorySource(walletOperationsApi, historyUrl) Chain.ExternalApi.Section.Type.ETHERSCAN -> EtherscanHistorySource(walletOperationsApi, historyUrl) Chain.ExternalApi.Section.Type.OKLINK -> OkLinkHistorySource(walletOperationsApi, historyUrl) Chain.ExternalApi.Section.Type.ZETA -> ZetaHistorySource(walletOperationsApi, historyUrl) Chain.ExternalApi.Section.Type.REEF -> ReefHistorySource(walletOperationsApi, historyUrl) else -> null } } }
15
null
30
89
812c6ed5465d19a0616865cbba3e946d046720a1
1,792
fearless-Android
Apache License 2.0
mylib-qrcode/src/test/kotlin/QRCodeTest.kt
ismezy
140,005,112
false
null
/* * Copyright © 2020 ismezy (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import com.google.zxing.WriterException import com.zy.mylib.qrcode.QRCodeUtils.buildQrCode import org.junit.jupiter.api.Test import java.io.File import java.io.IOException import javax.imageio.ImageIO class QRCodeTest { /** * 测试生成二维码,不带logo */ @Test @Throws(WriterException::class, IOException::class) fun testBuildQrCode() { val bufferedImage = buildQrCode("hello world", 800, 800, "", null) ImageIO.write(bufferedImage, "PNG", File("/qrcode.png")) } @Test @Throws(WriterException::class, IOException::class) fun testBuildQrCodeWithLogo() { val logo = ImageIO.read(ClassLoader.getSystemResourceAsStream("logo.png")) val bufferedImage = buildQrCode( "hello world", 800, 800, "测试标题", logo ) ImageIO.write(bufferedImage, "PNG", File("/qrcode-with-logo.png")) } }
0
Kotlin
0
0
09793d3b8994839ca8a924f10b25dd131149b5dd
1,425
mylib
Apache License 2.0
server/src/main/kotlin/net/eiradir/server/culling/EntitiesUnculledEvent.kt
Eiradir
635,460,745
false
null
package net.eiradir.server.culling import com.badlogic.ashley.core.Entity import net.eiradir.server.map.ChunkDimensions import net.eiradir.server.map.EiradirMap data class EntitiesCulledEvent(private val map: EiradirMap, val chunkPos: ChunkDimensions, val entities: Collection<Entity>) { override fun toString(): String { return "EntitiesCulledEvent(map=$map, chunkPos=$chunkPos, entities=${entities.size})" } }
13
Kotlin
0
0
fd732d283c6c72bbd0d0127bb86e8daf7e5bf3cd
429
eiradir-server
MIT License
platform/external-system-impl/src/com/intellij/openapi/externalSystem/autoimport/changes/VirtualFilesChangesProvider.kt
ingokegel
284,920,751
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.externalSystem.autoimport.changes import com.intellij.openapi.Disposable import com.intellij.openapi.externalSystem.autoimport.AsyncFileChangeListenerBase import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType.EXTERNAL import com.intellij.openapi.externalSystem.autoimport.ExternalSystemModificationType.INTERNAL import com.intellij.openapi.vfs.VirtualFile import com.intellij.openapi.vfs.newvfs.events.VFileEvent import com.intellij.util.EventDispatcher class VirtualFilesChangesProvider(private val isIgnoreInternalChanges: Boolean) : FilesChangesProvider, AsyncFileChangeListenerBase() { private val eventDispatcher = EventDispatcher.create(FilesChangesListener::class.java) override fun subscribe(listener: FilesChangesListener, parentDisposable: Disposable) { eventDispatcher.addListener(listener, parentDisposable) } override val processRecursively = false override fun init() = eventDispatcher.multicaster.init() override fun apply() = eventDispatcher.multicaster.apply() override fun isRelevant(file: VirtualFile, event: VFileEvent) = !isIgnoreInternalChanges || !event.isFromSave override fun updateFile(file: VirtualFile, event: VFileEvent) { val modificationType = if (event.isFromRefresh) EXTERNAL else INTERNAL eventDispatcher.multicaster.onFileChange(file.path, file.modificationStamp, modificationType) } }
191
null
4372
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
1,563
intellij-community
Apache License 2.0
app/src/main/java/com/example/philosophyquotes/data/model/Quote.kt
WillACosta
536,141,267
false
{"Kotlin": 38147}
package com.example.philosophyquotes.data.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.example.philosophyquotes.core.constants.AppConstants import com.google.gson.annotations.SerializedName @Entity(tableName = AppConstants.DATA_SOURCE.TABLE_NAME) class Quote { @PrimaryKey(autoGenerate = true) @ColumnInfo @SerializedName("id") var id: Int = 0 @ColumnInfo @SerializedName("body") var quote: String = "" @ColumnInfo @SerializedName("author_id") var authorId: Int = 0 @ColumnInfo @SerializedName("author") var author: String = "" val authorName: String get() = buildString { append("- ") append(author) } }
0
Kotlin
0
0
6dced3869dbae7ff1deddf04c0e6903804d964e1
772
philosophy_quotes
Apache License 2.0
src/main/kotlin/jp/nephy/penicillin/models/BadgeCount.kt
7u4
162,947,832
true
{"Kotlin": 259979}
@file:Suppress("UNUSED") package jp.nephy.penicillin.models import jp.nephy.jsonkt.JsonObject import jp.nephy.jsonkt.delegation.* data class BadgeCount(override val json: JsonObject): PenicillinModel { val dmUnreadCount by int("dm_unread_count") val ntabUnreadCount by int("ntab_unread_count") val totalUnreadCount by int("total_unread_count") }
0
Kotlin
0
0
747aa281b512072d99e9b03cfe68b6c54d98b6f0
361
Penicillin
MIT License
src/main/kotlin/com/wg2/storefront/products/ProductService.kt
working-group-two
653,561,464
false
{"Kotlin": 18064, "Vue": 15432, "HTML": 842, "CSS": 270}
package com.wg2.storefront.products import com.wg2.storefront.GrpcShared import com.wgtwo.api.v0.products.ProductServiceGrpc import com.wgtwo.api.v0.products.ProductsProto import com.wgtwo.api.v0.products.ProductsProto.ListProductsForTenantRequest import org.slf4j.LoggerFactory data class Product( val id: String, val name: String, val subtitle: String, val description: String, val productUrl: String, val iconImageId: Long = 903, //TODO: Remove this ) object ProductService { private val logger by lazy { LoggerFactory.getLogger(javaClass) } private val productsStub = ProductServiceGrpc .newBlockingStub(GrpcShared.channel) .withInterceptors(GrpcShared.authInterceptor) // TODO: Should cache this fun listProducts(tenant: String): List<Product> { val request = ListProductsForTenantRequest.newBuilder().apply { this.tenant = tenant }.build() val response = productsStub.listProductsForTenant(request) return response.productsList.map { it.toProduct() } } private fun ProductsProto.Product.toProduct() = Product( id = id, name = name, subtitle = subtitle, description = description, productUrl = productUrl, ) }
0
Kotlin
0
0
04c221a418e0f1ee014a80622b782796f5b37cab
1,275
storefront-example
Apache License 2.0
andfun-kotlin-dev-bytes-starter-code/app/src/main/java/com/example/android/devbyteviewer/util/Util.kt
cpinan
202,233,134
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 * * 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 online.zhenhong.devbyteviewer.util private val PUNCTUATION = listOf(", ", "; ", ": ", " ") /** * Truncate long text with a preference for word boundaries and without trailing punctuation. */ fun String.smartTruncate(length: Int): String { val words = split(" ") var added = 0 var hasMore = false val builder = StringBuilder() for (word in words) { if (builder.length > length) { hasMore = true break } builder.append(word) builder.append(" ") added += 1 } PUNCTUATION.map { if (builder.endsWith(it)) { builder.replace(builder.length - it.length, builder.length, "") } } if (hasMore) { builder.append("...") } return builder.toString() }
1
null
1
4
c30b0eee00c88364bb5aefbcad06f6677b52df8b
1,415
Android-Associate-Developer-Training
Apache License 2.0
kodando-mobx/src/main/kotlin/kodando/mobx/ActionContext.kt
kodando
81,663,289
false
null
package kodando.mobx interface ActionContext { val actionName: String }
12
Kotlin
5
76
f1428066ca01b395c1611717fde5463ba0042b19
75
kodando
MIT License
app/src/main/java/com/codelab/theming/ui/start/theme/Shape.kt
Tonnie-Dev
404,807,035
false
{"Kotlin": 33592}
package com.codelab.theming.ui.start.theme import android.graphics.drawable.shapes.Shape import androidx.compose.foundation.shape.CutCornerShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Shapes import androidx.compose.ui.unit.dp val JetnewsShapes = Shapes( //Shape used by small components like Button or Snackbar small = CutCornerShape(topStart = 8.dp), //Shape used by medium components like Card or AlertDialog medium =CutCornerShape(topStart = 24.dp, bottomEnd = 24.dp), //Shape used by large components like ModalDrawer large = RoundedCornerShape(8.dp))
0
Kotlin
0
0
36413c3dd985e96c0a4a0337055d6dfd8245ba41
638
ComposeTheming
Apache License 2.0
sample-tencent/src/main/java/com/melody/tencentmap/myapplication/ui/RoutePlanScreen.kt
TheMelody
543,049,561
false
{"Kotlin": 1503767}
// MIT License // // Copyright (c) 2022 被风吹过的夏天 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package com.melody.tencentmap.myapplication.ui import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.runtime.* 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 com.google.accompanist.flowlayout.FlowRow import com.melody.map.tencent_compose.TXMap import com.melody.map.tencent_compose.position.rememberCameraPositionState import com.melody.sample.common.utils.showToast import com.melody.tencentmap.myapplication.contract.RoutePlanContract import com.melody.tencentmap.myapplication.model.BusRouteDataState import com.melody.tencentmap.myapplication.model.DrivingRouteDataState import com.melody.tencentmap.myapplication.model.RideRouteDataState import com.melody.tencentmap.myapplication.model.WalkRouteDataState import com.melody.tencentmap.myapplication.ui.route.BusRouteOverlayContent import com.melody.tencentmap.myapplication.ui.route.DrivingRouteOverlayContent import com.melody.tencentmap.myapplication.ui.route.RideRouteOverlayContent import com.melody.tencentmap.myapplication.ui.route.WalkingRouteOverlayContent import com.melody.tencentmap.myapplication.viewmodel.RoutePlanViewModel import com.melody.ui.components.MapMenuButton import com.melody.ui.components.RedCenterLoading import com.melody.ui.components.RoadTrafficSwitch import com.tencent.tencentmap.mapsdk.maps.CameraUpdateFactory import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.onEach /** * RoutePlanScreen * @author 被风吹过的夏天 * @email <EMAIL> * @github: https://github.com/TheMelody/OmniMap * created 2023/02/17 16:40 */ @Composable internal fun RoutePlanScreen() { val viewModel: RoutePlanViewModel = viewModel() val cameraPositionState = rememberCameraPositionState() val currentState by viewModel.uiState.collectAsState() LaunchedEffect(viewModel.effect) { viewModel.effect.onEach { if(it is RoutePlanContract.Effect.Toast) { showToast(it.msg) } }.collect() } LaunchedEffect(currentState.routePlanDataState?.latLngBounds) { currentState.routePlanDataState?.latLngBounds?.let { cameraPositionState.move(CameraUpdateFactory.newLatLngBounds(it, 100)) } } Box(modifier = Modifier.fillMaxSize()) { TXMap( modifier = Modifier.matchParentSize(), cameraPositionState = cameraPositionState, properties = currentState.mapProperties, uiSettings = currentState.uiSettings, onMapLoaded = viewModel::queryRoutePlan ) { when(currentState.routePlanDataState) { is DrivingRouteDataState -> { val dataState = currentState.routePlanDataState as DrivingRouteDataState DrivingRouteOverlayContent(dataState) } is BusRouteDataState -> { val dataState = currentState.routePlanDataState as BusRouteDataState BusRouteOverlayContent(dataState) } is WalkRouteDataState -> { val dataState = currentState.routePlanDataState as WalkRouteDataState WalkingRouteOverlayContent(dataState) } is RideRouteDataState -> { val dataState = currentState.routePlanDataState as RideRouteDataState RideRouteOverlayContent(dataState) } } } if(currentState.isLoading) { RedCenterLoading() } MenuButtonList(viewModel::queryRoutePlan) RoadTrafficSwitch( modifier = Modifier .align(Alignment.CenterEnd) .padding(end = 4.dp) .clickable(onClick = viewModel::switchRoadTraffic), isEnable = currentState.mapProperties.isTrafficEnabled ) } } @Composable private fun BoxScope.MenuButtonList(onClick:(Int) -> Unit) { val currentOnClick by rememberUpdatedState(newValue = onClick) FlowRow( modifier = Modifier .align(Alignment.TopCenter) .fillMaxWidth() .background(Color.Black.copy(alpha = 0.3F)) ) { MapMenuButton(text = "驾车", onClick = { currentOnClick.invoke(0) }) MapMenuButton(text = "公交", onClick = { currentOnClick.invoke(1) }) MapMenuButton(text = "步行", onClick = { currentOnClick.invoke(2) }) MapMenuButton(text = "骑行", onClick = { currentOnClick.invoke(3) }) } }
2
Kotlin
5
60
8a867728136bdb97f156ce57381437864c196382
5,845
OmniMap-Compose
MIT License
src/main/kotlin/com/github/weewar/mapviewer/controllers/ImageController.kt
JafarSadik
97,445,382
false
null
package com.github.weewar.mapviewer.controllers import com.github.weewar.mapviewer.dao.WeewarMapDAO import com.github.weewar.mapviewer.model.* import com.github.weewar.mapviewer.service.WeewarMapRenderer import com.github.weewar.mapviewer.utils.Images import org.springframework.http.* import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import java.awt.image.BufferedImage import java.util.concurrent.TimeUnit @Controller class ImageController(private val weewarMapRenderer: WeewarMapRenderer, private val weewarMapDAO: WeewarMapDAO) { @GetMapping("/images/maps/{map_id}.png", produces = [MediaType.IMAGE_PNG_VALUE]) fun renderWeewarMap(@PathVariable("map_id") mapId: Int): ResponseEntity<ByteArray> { return weewarMapDAO.findMapById(mapId) .map { httpOk(image(it)) } .orElse(httpNotFoundError()) } @GetMapping("/images/maps/thumbnails/{map_id}.png") fun renderMapThumbnail(@PathVariable("map_id") mapId: Int): ResponseEntity<ByteArray> { return weewarMapDAO.findMapById(mapId) .map { httpOk(thumbnail(it)) } .orElse(httpNotFoundError()) } private fun image(map: WeewarMap) = weewarMapRenderer.render(map) private fun thumbnail(map: WeewarMap) = weewarMapRenderer.renderThumbnail(map, thumbnailWidth, thumbnailHeight) private fun httpNotFoundError(): ResponseEntity<ByteArray> = ResponseEntity.notFound().build() private fun httpOk(image: BufferedImage): ResponseEntity<ByteArray> { val pngData = Images.toPNG(image) return ResponseEntity.ok() .contentType(MediaType.IMAGE_PNG) .contentLength(pngData.size.toLong()) .cacheControl(CacheControl.maxAge(365, TimeUnit.DAYS)) .body(pngData) } }
0
Kotlin
0
1
78d4104130340fda3c0c2d3ecbe578f7f524c113
1,918
weewar-map-viewer
Apache License 2.0
src/me/anno/image/ImageReader.kt
AntonioNoack
456,513,348
false
{"Kotlin": 9711019, "C": 236481, "GLSL": 9454, "Java": 7682, "Lua": 4315}
package me.anno.image import me.anno.cache.AsyncCacheData import me.anno.gpu.texture.TextureLib.blackTexture import me.anno.gpu.texture.TextureLib.whiteTexture import me.anno.image.raw.* import me.anno.io.files.BundledRef import me.anno.io.files.FileFileRef import me.anno.io.files.FileReference import me.anno.io.files.Signature import me.anno.io.zip.InnerFolder import me.anno.io.zip.SignatureFile import me.anno.maths.Maths import me.anno.utils.OS import me.anno.utils.Sleep.waitForGFXThread import me.anno.video.ffmpeg.MediaMetadata import me.anno.video.ffmpeg.FFMPEGStream import net.sf.image4j.codec.ico.ICOReader import org.apache.commons.imaging.Imaging import org.apache.logging.log4j.LogManager import java.io.IOException import javax.imageio.ImageIO /** * an easy interface to read any image as rgba and individual channels * */ object ImageReader { private val LOGGER = LogManager.getLogger(ImageReader::class) @JvmStatic fun readAsFolder(file: FileReference, callback: (InnerFolder?, Exception?) -> Unit) { // todo white with transparency, black with transparency // (overriding color) val folder = InnerFolder(file) // add the most common swizzles: r,g,b,a createComponent(file, folder, "r.png", "r", false) createComponent(file, folder, "g.png", "g", false) createComponent(file, folder, "b.png", "b", false) createComponent(file, folder, "a.png", "a", false) // bgra createComponent(file, folder, "bgra.png") { if (it is BGRAImage) it.base // bgra.bgra = rgba else BGRAImage(it) } // inverted components createComponent(file, folder, "1-r.png", "r", true) createComponent(file, folder, "1-g.png", "g", true) createComponent(file, folder, "1-b.png", "b", true) createComponent(file, folder, "1-a.png", "a", true) // grayscale, if not only a single channel createComponent(file, folder, "grayscale.png") { if (it.numChannels > 1) GrayscaleImage(it) else it } // rgb without alpha, if alpha exists createComponent(file, folder, "rgb.png") { if (it.hasAlphaChannel) OpaqueImage(it) else it } if (file.lcExtension == "ico") { Signature.findName(file) { sign -> if (sign == null || sign == "ico") { file.inputStream { it, exc -> if (it != null) { val layers = ICOReader.readAllLayers(it) for (index in layers.indices) { val layer = layers[index] folder.createImageChild("layer$index", layer) } it.close() callback(folder, null) } else { exc?.printStackTrace() callback(folder, null) } } } else callback(folder, null) } return } callback(folder, null) } @JvmStatic private fun createComponent(file: FileReference, folder: InnerFolder, name: String, createImage: (Image) -> Image) { folder.createLazyImageChild(name, lazy { val src = ImageCPUCache[file, false] ?: throw IOException("Missing image of $file") createImage(src) }, { val src = ImageGPUCache[file, false] ?: throw IOException("Missing image of $file") createImage(GPUImage(src)) }) } @JvmStatic private fun createComponent( file: FileReference, folder: InnerFolder, name: String, swizzle: String, inverse: Boolean ) { when (swizzle.length) { 1 -> createComponent(file, folder, name) { when { (swizzle == "a" && !it.hasAlphaChannel) -> GPUImage(if (inverse) blackTexture else whiteTexture) (swizzle == "b" && it.numChannels < 3) || (swizzle == "g" && it.numChannels < 2) -> GPUImage(if (inverse) whiteTexture else blackTexture) else -> ComponentImage(it, inverse, swizzle[0]) } } else -> throw NotImplementedError(swizzle) } } fun shouldUseFFMPEG(signature: String?, file: FileReference): Boolean { if (OS.isWeb) return false // uncomment, when we support FFMPEG in the browser XD return signature == "dds" || signature == "media" || file.lcExtension == "webp" } fun shouldIgnore(signature: String?): Boolean { return when (signature) { "rar", "bz2", "zip", "tar", "gzip", "xz", "lz4", "7z", "xar", "oar", "java", "text", "wasm", "ttf", "woff1", "woff2", "shell", "xml", "svg", "exe", "vox", "fbx", "gltf", "obj", "blend", "mesh-draco", "md2", "md5mesh", "dae", "yaml" -> true else -> false } } fun readImage(file: FileReference, data: AsyncCacheData<Image?>, forGPU: Boolean) { if (file is ImageReadable) { data.value = if (forGPU) file.readGPUImage() else file.readCPUImage() } else if (file is BundledRef || (file !is SignatureFile && file.length() < 10_000_000L)) { // < 10MB -> read directly file.readBytes { bytes, exc -> exc?.printStackTrace() if (bytes != null) { readImage(file, data, bytes, forGPU) } else data.value = null } } else Signature.findName(file) { signature -> readImage(file, data, signature, forGPU) } } fun readImage(file: FileReference, data: AsyncCacheData<Image?>, bytes: ByteArray, forGPU: Boolean) { val signature = Signature.findName(bytes) if (shouldIgnore(signature)) { data.value = null } else if (shouldUseFFMPEG(signature, file)) { tryFFMPEG(file, signature, forGPU) { it, e -> data.value = it e?.printStackTrace() } } else { val reader = ImageCPUCache.byteReaders[signature] ?: ImageCPUCache.byteReaders[file.lcExtension] data.value = if (reader != null) reader(bytes) else tryGeneric(file, bytes) } } fun readImage(file: FileReference, data: AsyncCacheData<Image?>, signature: String?, forGPU: Boolean) { if (shouldIgnore(signature)) { data.value = null } else if (shouldUseFFMPEG(signature, file)) { tryFFMPEG(file, signature, forGPU) { it, e -> data.value = it e?.printStackTrace() } } else { val reader = ImageCPUCache.fileReaders[signature] ?: ImageCPUCache.fileReaders[file.lcExtension] if (reader != null) reader(file) { it, e -> e?.printStackTrace() data.value = it } else tryGeneric(file) { it, e -> e?.printStackTrace() data.value = it } } } private fun frameIndex(meta: MediaMetadata): Int { return Maths.min(20, (meta.videoFrameCount - 1) / 3) } private fun tryFFMPEG(file: FileReference, signature: String?, forGPU: Boolean, callback: ImageCallback) { if (file is FileFileRef) { val meta = MediaMetadata.getMeta(file, false)!! if (forGPU) { FFMPEGStream.getImageSequenceGPU( file, signature, meta.videoWidth, meta.videoHeight, frameIndex(meta), 1, meta.videoFPS, meta.videoWidth, meta.videoFPS, meta.videoFrameCount, {}, { frames -> val frame = frames.firstOrNull() if (frame != null) { waitForGFXThread(true) { frame.isCreated || frame.isDestroyed } callback(GPUFrameImage(frame), null) } else callback(null, IOException("No frame was found")) } ) } else { FFMPEGStream.getImageSequenceCPU( file, signature, meta.videoWidth, meta.videoHeight, frameIndex(meta), 1, meta.videoFPS, meta.videoWidth, meta.videoFPS, meta.videoFrameCount, {}, { frames -> val frame = frames.firstOrNull() if (frame != null) callback(frame, null) else callback(null, IOException("No frame was found")) } ) } } else { // todo when we have native ffmpeg, don't copy the file val tmp = FileFileRef.createTempFile("4ffmpeg", file.extension) file.readBytes { bytes, e -> if (bytes != null) { tmp.writeBytes(bytes) tryFFMPEG(FileReference.getReference(tmp), signature, forGPU, callback) tmp.delete() } else callback(null, e) } } } private fun tryGeneric(file: FileReference, callback: ImageCallback) { file.inputStream { it, exc -> if (it != null) { try { val img = ImageIO.read(it) ?: throw IOException(file.toString()) it.close() callback(img.toImage(), null) } catch (e: Exception) { it.close() file.inputStream { it2, exc2 -> if (it2 != null) { try { callback(Imaging.getBufferedImage(it2).toImage(), null) } catch (e: Exception) { callback(null, e) } finally { it2.close() } } else callback(null, exc2) } } } else callback(null, exc) } } private fun tryGeneric(file: FileReference, bytes: ByteArray): Image? { var image = try { ImageIO.read(bytes.inputStream()) } catch (e: Exception) { e.printStackTrace() null } if (image == null) { LOGGER.debug("ImageIO failed for {}", file) try { image = Imaging.getBufferedImage(bytes) } catch (e: Exception) { // e.printStackTrace() } } if (image == null) { LOGGER.debug("Imaging failed for {}", file) } return image?.toImage() } }
0
Kotlin
3
17
adca85186e6781391fd2dca12067ef062d22cba4
10,861
RemsEngine
Apache License 2.0
data/models/src/main/java/com/kafka/data/model/item/Doc.kt
vipulyaara
612,950,214
false
{"Kotlin": 635130, "JavaScript": 440999, "HTML": 11959, "CSS": 7888, "Shell": 2974}
package com.kafka.data.model.item import com.kafka.data.model.StringListSerializer import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Doc( @SerialName("genre") @Serializable(with = StringListSerializer::class) val collection: List<String>? = null, @SerialName("creator") @Serializable(with = StringListSerializer::class) val creator: List<String>? = null, @SerialName("date") @Serializable(with = StringListSerializer::class) val date: List<String>? = null, @SerialName("description") @Serializable(with = StringListSerializer::class) val description: List<String>? = null, @SerialName("downloads") val downloads: Int, @SerialName("format") val format: List<String>? = null, @SerialName("identifier") val identifier: String, @SerialName("item_size") val itemSize: Long, @SerialName("language") @Serializable(with = StringListSerializer::class) val language: List<String>? = null, @SerialName("mediatype") val mediatype: String, @SerialName("month") val month: Int? = 0, @SerialName("subject") @Serializable(with = StringListSerializer::class) val subject: List<String>? = null, @SerialName("title") @Serializable(with = StringListSerializer::class) val title: List<String>, @SerialName("week") val week: Int? = 0, @SerialName("year") val year: String? = null, @SerialName("avg_rating") val rating: Double? = null, )
5
Kotlin
6
86
fa64a43602eecac8b93ae9e8b713f6d29ba90727
1,530
Kafka
Apache License 2.0
src/main/kotlin/io/beansnapper/flow/engine/Start.kt
waveskimmer
310,305,080
false
{"Kotlin": 17193}
package io.beansnapper.flow.engine
0
Kotlin
0
0
cd33834f463f12498ba559ce5e9b1fc6cb6b162b
36
snap-flow
Apache License 2.0
src/test/kotlin/unit/org/kollektions/examples/advanced/ValuesToRanges.kt
AlexCue987
203,469,269
false
null
package org.kollektions.examples.advanced import org.kollektions.consumers.* import org.kollektions.dispatchers.consumeWithResetting import java.time.LocalDateTime import java.util.* import kotlin.test.Test import kotlin.test.assertEquals class ValuesToRanges { val wednesdayMorning = LocalDateTime.of(2019, 10, 9, 8, 7) val wednesdayNoon = LocalDateTime.of(2019, 10, 9, 12, 7) val wednesdayNight = LocalDateTime.of(2019, 10, 9, 19, 7) val midnight = LocalDateTime.of(2019, 10, 9, 23, 59) val thursdayMorning = LocalDateTime.of(2019, 10, 10, 5, 7) val thursdayNight = LocalDateTime.of(2019, 10, 10, 18, 7) private val prices = listOf( TimedPrice(wednesdayMorning, 44), TimedPrice(wednesdayNoon, 44), TimedPrice(wednesdayNight, 46), TimedPrice(midnight, 48), TimedPrice(thursdayMorning, 42), TimedPrice(thursdayNight, 42) ) private data class TimedPrice(val takenAt: LocalDateTime, val price: Int) private data class PriceRange(val startAt: LocalDateTime, val endAt: LocalDateTime, val price: Int) @Test fun `coalesce prices to intervals`() { val actual = prices.consumeByOne( consumeWithResetting( intermediateConsumersFactory = { listOf(First(), Last()) }, resetTrigger = { intermediateConsumers: List<Consumer<TimedPrice>>, value: TimedPrice -> val stateResults = (intermediateConsumers[0].results() as Optional<TimedPrice>) stateResults.isPresent && stateResults.get().price != value.price }, intermediateResultsTransformer = { intermediateConsumers: List<Consumer<TimedPrice>> -> getPriceRange(intermediateConsumers) }, finalConsumer = asList(), keepValueThatTriggeredReset = true, repeatLastValueInNewSeries = true) ) println(actual) /* Output: PriceRange(startAt=2019-10-09T08:07, endAt=2019-10-09T15:07, price=44) PriceRange(startAt=2019-10-09T15:07, endAt=2019-10-09T23:59, price=46) PriceRange(startAt=2019-10-09T23:59, endAt=2019-10-10T05:07, price=48) PriceRange(startAt=2019-10-10T05:07, endAt=2019-10-10T11:07, price=42) */ val expected = listOf( PriceRange(wednesdayMorning, wednesdayNight, 44), PriceRange(wednesdayNight, midnight, 46), PriceRange(midnight, thursdayMorning, 48), PriceRange(thursdayMorning, thursdayNight, 42) ) assertEquals(expected, actual) } private fun getPriceRange(intermediateConsumers: List<Consumer<TimedPrice>>): PriceRange { val firstPrice = (intermediateConsumers[0].results() as Optional<TimedPrice>).get() val lastPrice = (intermediateConsumers[1].results() as Optional<TimedPrice>).get() return PriceRange(firstPrice.takenAt, lastPrice.takenAt, firstPrice.price) } }
0
Kotlin
1
21
126470f2126b3211bd70e8f167bd20e0f87088d9
2,968
konsumers
Apache License 2.0
src/main/kotlin/person/Person.kt
MSDNicrosoft
842,585,344
false
{"Kotlin": 7793}
package person class Person { val entity = Entity() val eyes = Eyes() val minds = mapOf<Any, Any>() val memories = Memories() val heart = Any() val dreams = listOf<Any>() val wishes = Any() val intentions = Any() val emotions = Emotions() val travelWith = listOf<Any>() val liveAlongWith = Any() val love = Any() val pain = Any() val oppositeScreen = mutableListOf<Person>() fun notice() {} fun wipe(eyes: Eyes) {} fun hug(person: Person): Collection<Emotions.Emotion> { return TODO() } fun playSound(topic: Any? = null): Unit? { return Unit } var sing: (Any?) -> Any? = {} fun understand(vararg thing: Any?) {} fun send(thing: Any, person: Person) {} fun sing(topic: Any?) {} fun hear(thing: Any) {} fun memorize(vararg things: Any?) {} fun describeShape(entity: Entity) {} fun canFeel(person: Person): Boolean = true fun makeReal(thing: Any) {} fun travelWith(thing: Any?) {} fun travelTo(thing: Any?) {} }
0
Kotlin
0
0
c84e271b1862a146156445a285a54a949a1670de
1,079
IfLoveEqualsTrue
The Unlicense
app/src/main/java/stark/android/appbase/demo/db/DbDemoActivity.kt
jhwing
67,675,497
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 3, "Proguard": 2, "Java": 16, "XML": 52, "Kotlin": 84}
package stark.android.appbase.demo.db import android.os.Bundle import stark.android.appbase.activity.BaseToolbarActivity import stark.android.appbase.activity.setBaseContentView import stark.android.appbase.activity.setToolbar class DbDemoActivity : BaseToolbarActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setBaseContentView() setToolbar("db demo", true) } }
1
null
1
1
6edac4ffb158542ee66f1911e4560ee924b99fc5
449
AndroidAppBase
Apache License 2.0
example/src/main/java/co/infinum/example/Extensions.kt
infinum
54,713,189
false
null
package co.infinum.example import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageFormat import android.graphics.YuvImage import android.media.Image import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.camera.core.ImageProxy import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import co.infinum.goldeneye.config.CameraConfig import co.infinum.goldeneye.models.AntibandingMode import co.infinum.goldeneye.models.ColorEffectMode import co.infinum.goldeneye.models.FlashMode import co.infinum.goldeneye.models.FocusMode import co.infinum.goldeneye.models.PreviewScale import co.infinum.goldeneye.models.Size import co.infinum.goldeneye.models.VideoQuality import co.infinum.goldeneye.models.WhiteBalanceMode import java.io.ByteArrayOutputStream import java.nio.ByteBuffer fun FocusMode.convertToString() = name.toLowerCase() fun FlashMode.convertToString() = name.toLowerCase() fun PreviewScale.convertToString() = name.toLowerCase() fun WhiteBalanceMode.convertToString() = name.toLowerCase() fun Size.convertToString() = "$width x $height" fun Int.toPercentage() = "%.02fx".format(this / 100f) fun Boolean.convertToString() = if (this) "Enabled" else "Disabled" fun AntibandingMode.convertToString() = name.toLowerCase() fun ColorEffectMode.convertToString() = name.toLowerCase() fun VideoQuality.convertToString() = name.toLowerCase() fun boolList() = listOf( ListItem(true, "Enabled"), ListItem(false, "Disabled") ) fun Context.toast(text: String) = Toast.makeText(this, text, Toast.LENGTH_LONG).show() fun CameraConfig.prepareItems(context: Context, adapter: SettingsAdapter) { val settingsItems = listOf( SettingsItem(name = "Basic features", type = 1), SettingsItem("Preview size:", previewSize.convertToString()) { if (previewScale == PreviewScale.MANUAL || previewScale == PreviewScale.MANUAL_FIT || previewScale == PreviewScale.MANUAL_FILL ) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Preview size", listItems = supportedPreviewSizes.map { ListItem(it, it.convertToString()) }, onClick = { previewSize = it } ) } else { context.toast("Preview scale is automatic so it picks preview size on its own.") } }, SettingsItem("Picture size:", pictureSize.convertToString()) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Picture size", listItems = supportedPictureSizes.map { ListItem(it, it.convertToString()) }, onClick = { pictureSize = it } ) }, SettingsItem("Preview scale", previewScale.convertToString()) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Preview scale", listItems = PreviewScale.values().map { ListItem(it, it.convertToString()) }, onClick = { previewScale = it } ) }, SettingsItem("Video quality:", videoQuality.convertToString()) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Video quality", listItems = supportedVideoQualities.map { ListItem(it, it.convertToString()) }, onClick = { videoQuality = it } ) }, SettingsItem("Video stabilization:", videoStabilizationEnabled.convertToString()) { if (isVideoStabilizationSupported) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Video stabilization", listItems = boolList(), onClick = { videoStabilizationEnabled = it } ) } else { context.toast("Video stabilization not supported") } }, SettingsItem("Flash mode:", flashMode.convertToString()) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Flash mode", listItems = supportedFlashModes.map { ListItem(it, it.convertToString()) }, onClick = { flashMode = it } ) }, SettingsItem("Focus mode:", focusMode.convertToString()) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Focus mode", listItems = supportedFocusModes.map { ListItem(it, it.convertToString()) }, onClick = { focusMode = it } ) }, SettingsItem("Tap to focus:", tapToFocusEnabled.convertToString()) { if (isTapToFocusSupported) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Tap to focus", listItems = boolList(), onClick = { tapToFocusEnabled = it } ) } else { context.toast("Tap to focus not supported.") } }, SettingsItem("Tap to focus - reset focus delay:", tapToFocusResetDelay.toString()) { if (isTapToFocusSupported) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Reset delay", listItems = listOf( ListItem(2_500L, "2500"), ListItem(5_000L, "5000"), ListItem(7_500L, "7500") ), onClick = { tapToFocusResetDelay = it } ) } else { context.toast("Tap to focus not supported.") } }, SettingsItem("Pinch to zoom:", pinchToZoomEnabled.convertToString()) { if (isZoomSupported) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Pinch to zoom", listItems = boolList(), onClick = { pinchToZoomEnabled = it } ) } else { context.toast("Pinch to zoom not supported.") } }, SettingsItem("Pinch to zoom friction:", "%.02f".format(pinchToZoomFriction)) { if (isZoomSupported) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Friction", listItems = listOf( ListItem(0.5f, "0.50"), ListItem(1f, "1.00"), ListItem(2f, "2.00") ), onClick = { pinchToZoomFriction = it } ) } else { context.toast("Pinch to zoom not supported.") } }, SettingsItem(name = "Advanced features", type = 1), SettingsItem("White Balance:", whiteBalanceMode.convertToString()) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "White Balance", listItems = supportedWhiteBalanceModes.map { ListItem(it, it.convertToString()) }, onClick = { whiteBalanceMode = it } ) }, SettingsItem("Color Effect:", colorEffectMode.convertToString()) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Color Effect", listItems = supportedColorEffectModes.map { ListItem(it, it.convertToString()) }, onClick = { colorEffectMode = it } ) }, SettingsItem("Antibanding:", antibandingMode.convertToString()) { displayDialog( context = context, config = this, settingsAdapter = adapter, title = "Antibanding", listItems = supportedAntibandingModes.map { ListItem(it, it.convertToString()) }, onClick = { antibandingMode = it } ) } ) adapter.updateDataSet(settingsItems) } fun <T> displayDialog( context: Context, config: CameraConfig, settingsAdapter: SettingsAdapter, title: String, listItems: List<ListItem<T>>, onClick: (T) -> Unit ) { if (listItems.isEmpty()) { context.toast("$title not supported") return } val dialog = AlertDialog.Builder(context) .setView(R.layout.list) .setCancelable(true) .setTitle(title) .show() dialog.findViewById<RecyclerView>(R.id.recyclerView)?.apply { layoutManager = LinearLayoutManager(context) adapter = ListItemAdapter(listItems) { onClick(it) dialog.dismiss() config.prepareItems(context, settingsAdapter) } } } fun Image.toBitmap(): Bitmap { val buffer: ByteBuffer = planes.first().buffer val bytes = ByteArray(buffer.remaining()) buffer.get(bytes) return BitmapFactory.decodeByteArray(bytes, 0, bytes.size) }
15
null
52
374
5f9a7106043b68013aa65c65f8e552f64a46e8c5
10,070
Android-GoldenEye
Apache License 2.0
treeview/src/main/java/com/funny/treeview/TreeActivity.kt
FunCoder0676
241,558,625
false
null
package com.funny.treeview import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.alibaba.android.arouter.facade.annotation.Route @Route(path = "/tree/tree") class TreeActivity: AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_tree) } }
0
Kotlin
0
1
2f9e3e251992659ab25a8f3a028290d113226a7d
387
WanAlpha
Apache License 2.0
library/src/main/java/io/zhuliang/photopicker/api/Action.kt
Pigcasso
125,020,235
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "INI": 3, "Proguard": 2, "XML": 38, "Kotlin": 29, "Java": 2}
package io.zhuliang.photopicker.api /** * @author Zhu Liang */ interface Action<in T> { fun onAction(requestCode: Int, result: T) }
1
null
1
1
6b13a78275948b0df6630ee0e291108766802d39
140
PhotoPicker
Apache License 2.0
app/src/main/java/com/example/theatre/features/spectacles/domain/repository/PerformanceRepository.kt
2023Constanta
601,772,348
false
null
package com.example.theatre.features.spectacles.domain.repository import com.example.theatre.core.domain.model.common.performance.Performance import com.example.theatre.core.domain.model.common.performance.PerformancePlace import com.example.theatre.core.domain.model.common.performance.PerformancePlaceLocation /** * Репозиторий для списка постановок и их детализации * * @author <NAME> */ interface PerformanceRepository { suspend fun getPerformances(): List<Performance> suspend fun getPerformancesByQuery(query: String): List<Performance> suspend fun getPerformanceById(id: Int): Performance /** * Get place by id * * @return - место проведения выбранной постановки по идентификатору */ suspend fun getPlace(id: Int): PerformancePlace /** * Get city name * * @return - город, где проходит постановка по текстовому идентификатору, пример: msk, spb */ suspend fun getCityName(slug: String): PerformancePlaceLocation }
0
Kotlin
0
0
454794e98ed30e795d769ba304ecf092c7df2582
996
Theatre
Apache License 2.0
sample/src/main/java/nz/co/trademe/konfigure/sample/examples/restart/RestartUtil.kt
Hazer
206,080,261
true
{"Kotlin": 69841}
package nz.co.trademe.konfigure.sample.examples.restart import android.content.Intent import android.view.View import androidx.appcompat.app.AppCompatActivity import com.google.android.material.snackbar.Snackbar /** * Extension function for displaying a Snackbar with a restart app action. */ @JvmOverloads fun AppCompatActivity.showRestartSnackbar(view: View = findViewById(android.R.id.content)): Snackbar = Snackbar.make(view, "You have pending config changes which require a restart", Snackbar.LENGTH_INDEFINITE) .setAction("Restart") { restartApp(this) }.also { it.show() } /** * Function for restarting a given application and returning to the activity passed in as an argument */ private fun restartApp(activity: AppCompatActivity) { val packageManager = activity.applicationContext.packageManager val intent = packageManager.getLaunchIntentForPackage(activity.applicationContext.packageName) val componentName = intent!!.component val mainIntent = Intent.makeRestartActivityTask(componentName) activity.startActivity(mainIntent) Runtime.getRuntime().exit(0) }
0
Kotlin
0
1
a0b1f323abf7220456753966f1fe321cc1a6f9d8
1,167
konfigure
MIT License
app/src/main/java/io/horizontalsystems/bankwallet/ui/extensions/SelectorDialog.kt
fahimaltinordu
312,207,740
false
null
package io.horizontalsystems.bankwallet.ui.extensions import android.content.Context import android.os.Bundle import android.view.* import android.view.inputmethod.InputMethodManager import android.widget.TextView import androidx.core.view.isVisible import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.RecyclerView import io.horizontalsystems.bankwallet.R import kotlinx.android.extensions.LayoutContainer import kotlinx.android.synthetic.main.view_holder_item_selector.* class SelectorDialog : DialogFragment(), SelectorAdapter.Listener { private var onSelectItem: ((Int) -> Unit)? = null private var items = listOf<SelectorItem>() private var title: String? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE) dialog?.window?.setBackgroundDrawableResource(R.drawable.alert_background_themed) dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_UNCHANGED) val view = inflater.inflate(R.layout.fragment_alert_dialog_single_select, container, false) val recyclerView = view.findViewById<RecyclerView>(R.id.dialogRecyclerView) val dialogTitle = view.findViewById<TextView>(R.id.dialogTitle) recyclerView.adapter = SelectorAdapter(items, this, title != null) dialogTitle.isVisible = title != null dialogTitle.text = title hideKeyBoard() return view } override fun onClick(position: Int) { onSelectItem?.invoke(position) dismiss() } private fun hideKeyBoard() { (context?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.hideSoftInputFromWindow(activity?.currentFocus?.windowToken, 0) } companion object { fun newInstance(items: List<SelectorItem>, title: String? = null, onSelectItem: ((Int) -> Unit)? = null): SelectorDialog { val dialog = SelectorDialog() dialog.onSelectItem = onSelectItem dialog.items = items dialog.title = title return dialog } } } class SelectorAdapter(private val list: List<SelectorItem>, private val listener: Listener, private val hasTitle: Boolean) : RecyclerView.Adapter<SelectorOptionViewHolder>() { interface Listener { fun onClick(position: Int) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = SelectorOptionViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.view_holder_item_selector, parent, false), listener) override fun onBindViewHolder(holder: SelectorOptionViewHolder, position: Int) { holder.bind(list[position], hasTitle || position > 0) } override fun getItemCount() = list.size } class SelectorOptionViewHolder(override val containerView: View, private val listener: SelectorAdapter.Listener) : RecyclerView.ViewHolder(containerView), LayoutContainer { init { containerView.setOnClickListener { listener.onClick(bindingAdapterPosition) } } fun bind(item: SelectorItem, showTopDivider: Boolean) { itemTitle.text = item.caption itemTitle.isSelected = item.selected topDivider.isVisible = showTopDivider } } data class SelectorItem(val caption: String, val selected: Boolean)
163
null
170
4
d3094c4afaa92a5d63ce53583bc07c8fb343f90b
3,448
WILC-wallet-android
MIT License
plugin-dotnet-agent/src/main/kotlin/jetbrains/buildServer/mono/MonoToolEnvironment.kt
JetBrains
49,584,664
false
null
/* * Copyright 2000-2021 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jetbrains.buildServer.mono import jetbrains.buildServer.agent.Environment import jetbrains.buildServer.agent.Path import jetbrains.buildServer.agent.ToolEnvironment import jetbrains.buildServer.agent.runner.BuildStepContext import jetbrains.buildServer.agent.runner.ParameterType import jetbrains.buildServer.agent.runner.ParametersService import jetbrains.buildServer.dotnet.MonoConstants import java.io.File class MonoToolEnvironment( private val _buildStepContext: BuildStepContext, private val _environment: Environment, private val _parametersService: ParametersService) : ToolEnvironment { private val _homePaths get() = when(_buildStepContext.isAvailable) { false -> _environment.tryGetVariable(MonoConstants.TOOL_HOME)?.let { sequenceOf(Path(it)) } ?: emptySequence() true -> _parametersService.tryGetParameter(ParameterType.Environment, MonoConstants.TOOL_HOME)?.let { sequenceOf(Path(it)) } ?: emptySequence() } override val homePaths: Sequence<Path> get() = extendByBin(_homePaths) override val defaultPaths: Sequence<Path> get() = emptySequence() override val environmentPaths: Sequence<Path> get() = extendByBin(_environment.paths) private fun extendByBin(paths: Sequence<Path>) = paths + paths.map { Path("${it.path}${File.separatorChar}bin") } }
3
null
25
91
a0101341b8322dce1bc27104603ff9e788892990
1,989
teamcity-dotnet-plugin
Apache License 2.0
app/src/main/java/tech/salvatore/livro_android_kotlin_paulo_salvatore/view/navigation/NavigationActivity.kt
paulosalvatore
387,030,484
false
null
package tech.salvatore.livro_android_kotlin_paulo_salvatore.view.navigation import android.os.Bundle import android.view.View import android.view.ViewTreeObserver import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.navigation.fragment.NavHostFragment import androidx.navigation.navOptions import dagger.hilt.android.AndroidEntryPoint import tech.salvatore.livro_android_kotlin_paulo_salvatore.R import tech.salvatore.livro_android_kotlin_paulo_salvatore.view.creatures.choose.CreaturesChooseFragmentDirections import tech.salvatore.livro_android_kotlin_paulo_salvatore.view.creatures.list.CreaturesListFragmentDirections import tech.salvatore.livro_android_kotlin_paulo_salvatore.viewmodel.NavigationViewModel import tech.salvatore.livro_android_kotlin_paulo_salvatore.viewmodel.UserViewModel @AndroidEntryPoint class NavigationActivity : AppCompatActivity() { private val navigationViewModel: NavigationViewModel by viewModels() private val userViewModel: UserViewModel by viewModels() private val navHostFragment by lazy { supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment } private val navController by lazy { navHostFragment.navController } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.navigation_activity) val content = findViewById<View>(android.R.id.content) content.viewTreeObserver.addOnPreDrawListener( object : ViewTreeObserver.OnPreDrawListener { override fun onPreDraw(): Boolean { val isReady = navigationViewModel.isReady.value != null if (isReady && initNavigation()) { content.viewTreeObserver.removeOnPreDrawListener(this) return true } return false } } ) userViewModel.onChooseCreature.observe(this) { if (navController.currentDestination?.id == R.id.creatures_choose_dest) { val action = CreaturesChooseFragmentDirections.creaturesChooseToCreaturesAddedAction(it.number) navController.navigate(action) } } } private fun initNavigation(): Boolean { // Add NavGraph val graphInflater = navHostFragment.navController.navInflater val navGraph = graphInflater.inflate(R.navigation.nav_graph) navController.graph = navGraph // Make sure user is available beforing releasing splash screen val user = userViewModel.user.value ?: return false // Check if any creatures are available and navigate to choose creatures screen if (user.newCreaturesAvailable > 0 && navController.currentDestination?.id != R.id.creatures_choose_dest ) { val options = navOptions { anim { enter = R.anim.slide_in_right exit = R.anim.slide_out_left popEnter = R.anim.slide_in_left popExit = R.anim.slide_out_right } } val action = CreaturesListFragmentDirections.creaturesChooseAction() navController.navigate(action, options) } // Finish navigation init return true } }
0
Kotlin
6
7
7ff57a05e57a6a09b8ca27085f9fca51c5dcbddb
3,463
Livro_Android_Kotlin_PauloSalvatore
MIT License
test-automation-feign/src/main/kotlin/com/nortal/test/feign/interceptor/LoggingInterceptor.kt
nortal
504,492,420
false
{"Kotlin": 332735, "Java": 39099, "CSS": 6064, "JavaScript": 2198, "Gherkin": 2044, "HTML": 377}
/** * Copyright (c) 2022 Nortal AS * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.nortal.test.feign.interceptor import okhttp3.Interceptor import okhttp3.Response import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import java.io.IOException @Component open class LoggingInterceptor : FeignClientInterceptor { private val log: Logger = LoggerFactory.getLogger(javaClass) @Throws(IOException::class) override fun intercept(chain: Interceptor.Chain): Response { val request = chain.request() val startTime = System.currentTimeMillis() val response = chain.proceed(request) val duration = System.currentTimeMillis() - startTime log.info("Received response with code {} for {} in {}ms.", response.code, response.request.url, duration) return response } override fun getOrder(): Int { return 110 } }
0
Kotlin
2
2
6deaf66c37d6a9cc78c49a81ea59779ad95e5c7f
1,979
test-automation
MIT License
app/src/main/java/org/wikipedia/main/MainActivity.kt
contextu-al
590,289,323
false
{"Kotlin": 2150635, "Java": 405441, "Python": 22955, "Shell": 3215, "Jinja": 533}
package org.wikipedia.main import android.annotation.SuppressLint import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.View import androidx.appcompat.view.ActionMode import androidx.appcompat.widget.Toolbar import androidx.fragment.app.Fragment import com.contextu.al.BuildConfig import com.contextu.al.Contextual import com.contextu.al.Contextual.tagStringArray import com.contextu.al.core.CtxEventObserver import com.contextu.al.debug.Log import org.wikipedia.Constants import org.wikipedia.R import org.wikipedia.WikipediaApp import org.wikipedia.activity.SingleFragmentActivity import org.wikipedia.appshortcuts.AppShortcuts.Companion.setShortcuts import org.wikipedia.databinding.ActivityMainBinding import org.wikipedia.navtab.NavTab import org.wikipedia.page.PageActivity import org.wikipedia.page.tabs.TabActivity import org.wikipedia.settings.Prefs import org.wikipedia.suggestededits.SuggestedEditsTasksFragment import org.wikipedia.util.DimenUtil import org.wikipedia.util.FeedbackUtil import org.wikipedia.util.ResourceUtil import org.wikipedia.views.TabCountsView import java.text.SimpleDateFormat import java.util.* class MainActivity : SingleFragmentActivity<MainFragment>(), MainFragment.Callback { private lateinit var binding: ActivityMainBinding private var tabCountsView: TabCountsView? = null private var controlNavTabInFragment = false private var showTabCountsAnimation = false private val guideJson = "{\n" + " \"buttons\":{\n" + " \"dismiss\":{\n" + " \"color\":\"#000000\",\n" + " \"height\":16,\n" + " \"width\":16\n" + " },\n" + " \"layout\":\"horizontal\",\n" + " \"next\":{\n" + " \"align\":\"left\",\n" + " \"border-color\":\"#2E7D32\",\n" + " \"border-width\":1,\n" + " \"button-align\":\"right\",\n" + " \"color\":\"#000000\",\n" + " \"corner-radius\":5,\n" + " \"font-size\":14,\n" + " \"margin-right\":10,\n" + " \"padding-left\":10,\n" + " \"padding-right\":10,\n" + " \"padding-top\":0,\n" + " \"placement\":\"right\",\n" + " \"text-align\":\"center\",\n" + " \"type\":\"button\"\n" + " },\n" + " \"prev\":{\n" + " \"align\":\"left\",\n" + " \"border-color\":\"#2E7D32\",\n" + " \"border-width\":1,\n" + " \"button-align\":\"left\",\n" + " \"corner-radius\":5,\n" + " \"margin-left\":10,\n" + " \"padding-left\":10,\n" + " \"padding-right\":10,\n" + " \"placement\":\"left\",\n" + " \"text-align\":\"center\",\n" + " \"type\":\"button\"\n" + " }\n" + " },\n" + " \"content\":{\n" + " \"background-color\":\"#00000000\",\n" + " \"color\":\"#000000\",\n" + " \"font-size\":\"-1\",\n" + " \"line-height\":\"120%\",\n" + " \"margin-bottom\":10,\n" + " \"margin-left\":10,\n" + " \"margin-right\":10,\n" + " \"margin-top\":10,\n" + " \"padding-bottom\":10,\n" + " \"padding-left\":1,\n" + " \"padding-right\":1,\n" + " \"padding-top\":10,\n" + " \"text\":\"this is my first popup\",\n" + " \"text-align\":\"left\"\n" + " },\n" + " \"image\":[\n" + " \n" + " ],\n" + " \"interactions\":[\n" + " \n" + " ],\n" + " \"meta\":{\n" + " \"animation\":{\n" + " \"transition-in\":{\n" + " \"type\":\"none\"\n" + " },\n" + " \"transition-out\":{\n" + " \"type\":\"none\"\n" + " }\n" + " },\n" + " \"background-color\":\"#F9F9F9\",\n" + " \"box-shadow\":0,\n" + " \"container_type\":\"modal\",\n" + " \"dismiss-params\":{\n" + " \"touch-in\":true,\n" + " \"touch-out\":true\n" + " },\n" + " \"display-params\":{\n" + " \"_height_unit\":\"px\",\n" + " \"_width_unit\":\"%\",\n" + " \"border-color\":\"#E0E0E0\",\n" + " \"border-width\":1,\n" + " \"corner-radius\":5,\n" + " \"width\":\"80%\"\n" + " },\n" + " \"dynamicUrl\":{\n" + " \"display_condition\":\"any_page\",\n" + " \"matching_condition\":{\n" + " \"conditions\":[\n" + " {\n" + " \"operator\":\"equal\"\n" + " }\n" + " ],\n" + " \"match_type\":\"any\"\n" + " }\n" + " },\n" + " \"id\":10,\n" + " \"margin-bottom\":0,\n" + " \"margin-left\":0,\n" + " \"margin-right\":0,\n" + " \"margin-top\":0,\n" + " \"padding-bottom\":10,\n" + " \"padding-left\":10,\n" + " \"padding-right\":10,\n" + " \"padding-top\":10,\n" + " \"placement\":\"center\",\n" + " \"tool\":\"modal\",\n" + " \"view\":\"_ALL_\"\n" + " },\n" + " \"overlay\":{\n" + " \n" + " },\n" + " \"screenshot\":{\n" + " \"client_version\":\"Unknown\",\n" + " \"height\":568,\n" + " \"id\":\"_ALL_\",\n" + " \"json\":[\n" + " \n" + " ],\n" + " \"model\":\"Simulator\",\n" + " \"modified\":\"Unknown\",\n" + " \"orientation\":\"portrait\",\n" + " \"view\":\"_ALL_\",\n" + " \"width\":320\n" + " },\n" + " \"templateId\":213,\n" + " \"theme\":\"popup\",\n" + " \"title\":{\n" + " \"color\":\"#000000\",\n" + " \"font-size\":20,\n" + " \"font-weight\":\"bold\",\n" + " \"text-align\":\"left\"\n" + " }\n" + "}" override fun inflateAndSetContentView() { binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val pattern = "dd-MMM-yyyy hh:mm" @SuppressLint("SimpleDateFormat") val simpleDateFormat = SimpleDateFormat(pattern) Contextual.init(this.application, getString(R.string.app_key), object : CtxEventObserver{ override fun onInstallRegistered(installId: UUID, context: Context) { val date = simpleDateFormat.format(Date()) tagStringArray(mutableMapOf("sh_email" to "<EMAIL>", "sh_first_name" to "QA", "sh_last_name" to "Contextual", "sh_cuid" to "pz-wiki-dev-user - ${BuildConfig.CTX_VERSION_NAME} - $date")) } override fun onInstallRegisterError(errorMsg: String) { Log.e("Integration", errorMsg) } }) setShortcuts(this) setImageZoomHelper() /* if (Prefs.isInitialOnboardingEnabled() && savedInstanceState == null) { // Updating preference so the search multilingual tooltip // is not shown again for first time users Prefs.setMultilingualSearchTutorialEnabled(false) // Use startActivityForResult to avoid preload the Feed contents before finishing the initial onboarding. // The ACTIVITY_REQUEST_INITIAL_ONBOARDING has not been used in any onActivityResult startActivityForResult(InitialOnboardingActivity.newIntent(this), Constants.ACTIVITY_REQUEST_INITIAL_ONBOARDING) }*/ setNavigationBarColor(ResourceUtil.getThemedColor(this, R.attr.nav_tab_background_color)) setSupportActionBar(binding.mainToolbar) supportActionBar?.title = "" supportActionBar?.setDisplayHomeAsUpEnabled(false) binding.mainToolbar.navigationIcon = null // Contextual.addGuide(guideJson) } override fun onResume() { super.onResume() invalidateOptionsMenu() } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) menuInflater.inflate(R.menu.menu_main, menu) return true } override fun onPrepareOptionsMenu(menu: Menu): Boolean { fragment.requestUpdateToolbarElevation() val tabsItem = menu.findItem(R.id.menu_tabs) if (WikipediaApp.getInstance().tabCount < 1 || fragment.currentFragment is SuggestedEditsTasksFragment) { tabsItem.isVisible = false tabCountsView = null } else { tabsItem.isVisible = true tabCountsView = TabCountsView(this, null) tabCountsView!!.setOnClickListener { if (WikipediaApp.getInstance().tabCount == 1) { startActivity(PageActivity.newIntent(this@MainActivity)) } else { startActivityForResult(TabActivity.newIntent(this@MainActivity), Constants.ACTIVITY_REQUEST_BROWSE_TABS) } } tabCountsView!!.updateTabCount(showTabCountsAnimation) tabCountsView!!.contentDescription = getString(R.string.menu_page_show_tabs) tabsItem.actionView = tabCountsView tabsItem.expandActionView() FeedbackUtil.setButtonLongPressToast(tabCountsView!!) showTabCountsAnimation = false } return true } override fun createFragment(): MainFragment { return MainFragment.newInstance() } override fun onTabChanged(tab: NavTab) { if (tab == NavTab.EXPLORE) { binding.mainToolbarWordmark.visibility = View.VISIBLE binding.mainToolbar.title = "" controlNavTabInFragment = false } else { if (tab == NavTab.SEARCH && Prefs.shouldShowSearchTabTooltip()) { FeedbackUtil.showTooltip(this, fragment.binding.mainNavTabLayout.findViewById(NavTab.SEARCH.id()), getString(R.string.search_tab_tooltip), aboveOrBelow = true, autoDismiss = false) Prefs.setShowSearchTabTooltip(false) } binding.mainToolbarWordmark.visibility = View.GONE binding.mainToolbar.setTitle(tab.text()) controlNavTabInFragment = true } fragment.requestUpdateToolbarElevation() } override fun updateTabCountsView() { showTabCountsAnimation = true invalidateOptionsMenu() } override fun onSupportActionModeStarted(mode: ActionMode) { super.onSupportActionModeStarted(mode) if (!controlNavTabInFragment) { fragment.setBottomNavVisible(false) } } override fun onSupportActionModeFinished(mode: ActionMode) { super.onSupportActionModeFinished(mode) fragment.setBottomNavVisible(true) } override fun updateToolbarElevation(elevate: Boolean) { if (elevate) { setToolbarElevationDefault() } else { clearToolbarElevation() } } override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) setIntent(intent) fragment.handleIntent(intent) } override fun onGoOffline() { fragment.onGoOffline() } override fun onGoOnline() { fragment.onGoOnline() } override fun onBackPressed() { if (fragment.onBackPressed()) { return } super.onBackPressed() } fun isCurrentFragmentSelected(f: Fragment): Boolean { return fragment.currentFragment === f } fun getToolbar(): Toolbar { return binding.mainToolbar } private fun setToolbarElevationDefault() { binding.mainToolbar.elevation = DimenUtil.dpToPx(DimenUtil.getDimension(R.dimen.toolbar_default_elevation)) } private fun clearToolbarElevation() { binding.mainToolbar.elevation = 0f } companion object { @JvmStatic fun newIntent(context: Context): Intent { return Intent(context, MainActivity::class.java) } } }
0
Kotlin
0
2
453802bf9852d3ef880beb9f73b2b1d6b4932eae
13,062
wikipedia
Apache License 2.0
src/main/kotlin/org/teamvoided/dusk_autumn/block/sapling/SaplingGenerators.kt
TeamVoided
737,359,498
false
{"Kotlin": 361125, "Java": 3800}
package org.teamvoided.dusk_autumn.block.sapling import net.minecraft.block.sapling.TreeGrower import org.teamvoided.dusk_autumn.DuskAutumns.id import org.teamvoided.dusk_autumn.data.worldgen.DuskConfiguredFeature import java.util.* object SaplingGenerators { val CASCADE = TreeGrower( id("cascade").toString(), Optional.of(DuskConfiguredFeature.CASCADE_TREE), Optional.empty(), Optional.of(DuskConfiguredFeature.CASCADE_TREE_BEES) ) val GOLDEN_BIRCH = TreeGrower( id("golden_birch").toString(), Optional.empty(), Optional.of(DuskConfiguredFeature.GOLDEN_BIRCH_TALL), Optional.of(DuskConfiguredFeature.GOLDEN_BIRCH_TALL_BEES) ) }
0
Kotlin
0
0
ad953436fb5aa692d897d635c052b646a94a5aa9
712
DuskBlocks
MIT License
lego/lego_plugins/src/main/java/com/lego/plugins/basic/utility/ContextExtension.kt
ruichard
775,792,965
false
{"Kotlin": 369040, "Java": 13237}
package com.lego.plugins.basic.utility import com.android.builder.model.BuildType import com.ktnail.x.pascalToCamel import com.ktnail.x.uriToPascal import com.lego.plugins.basic.exception.LegoProjectPathNotSetException import com.lego.plugins.context.ContextPlugin import com.lego.plugins.extension.context.ContextExtension import com.lego.plugins.extension.context.source.SourceExtension import com.lego.plugins.extension.root.model.MavenMode import com.lego.plugins.extension.root.model.Picked fun ContextExtension.firstPriorityMavenVersion(picked: Picked?, tagSource: SourceExtension?) = (picked?.mode as? MavenMode)?.maven?.version ?: tagSource?.maven?.version ?: mavenVersion fun ContextExtension.firstPriorityMavenVariant(picked: Picked?, tagSource: SourceExtension?) = (picked?.mode as? MavenMode)?.maven?.variant ?: tagSource?.maven?.variant ?: mavenVariant fun ContextExtension.firstPriorityProjectPath(tagSource: SourceExtension?) = tagSource?.project?.path ?: projectPath ?: throw LegoProjectPathNotSetException( uri ) fun ContextExtension.buildTypeName() = publishArtifactName.uriToPascal().pascalToCamel() + ContextPlugin.CONTEXT_LIB_BUILD_TYPE_NAME fun BuildType.isContextLibBuildType() = name.endsWith(ContextPlugin.CONTEXT_LIB_BUILD_TYPE_NAME) val ContextExtension.useResetCompiler: Boolean get() = lego.project.propertyOr(Ext.LEGO_USE_RESET_COMPILER, false) && !publishOriginalValue
0
Kotlin
0
1
63771a1c5c604a13964976ef81787e8fd3b41c51
1,438
Lego
Apache License 2.0
src/main/kotlin/lwaf_3D/DrawContext3D.kt
exerro
160,990,895
false
null
package lwaf_3D import lwaf_core.* import org.lwjgl.opengl.GL11 import org.lwjgl.opengl.GL14 import org.lwjgl.opengl.GL30 open class DrawContext3D( val view: GLView, val camera: Camera = Camera() ): GLResource { private val framebuffer = GLFramebuffer(view.size.x.toInt(), view.size.y.toInt()) val buffer = GBuffer(view.size.x.toInt(), view.size.y.toInt()) val texture = createEmptyTexture(view.size.x.toInt(), view.size.y.toInt()) val aspectRatio = view.size.x / view.size.y val DEFAULT_VERTEX_SHADER_PATH = "/res/shader/vertex-3D.glsl" val DEFAULT_FRAGMENT_SHADER_PATH = "/res/shader/draw-to-gbuffer.glsl" val DEFAULT_SHADER_DELEGATE = lazy { val vertexShaderContent = String(Light::class.java.getResourceAsStream(DEFAULT_VERTEX_SHADER_PATH).readBytes()) val fragmentShaderContent = String(Light::class.java.getResourceAsStream(DEFAULT_FRAGMENT_SHADER_PATH).readBytes()) loadShaderProgram(vertexShaderContent, fragmentShaderContent) } val DEFAULT_SHADER: GLShaderProgram by DEFAULT_SHADER_DELEGATE init { framebuffer.attachTexture(texture, GL30.GL_COLOR_ATTACHMENT0) framebuffer.setDrawBuffers(GL30.GL_COLOR_ATTACHMENT0) } fun begin() { buffer.bind() GL11.glDepthMask(true) GL11.glClearColor(0f, 0f, 0f, 0.0f) GL11.glClear(GL11.GL_COLOR_BUFFER_BIT or GL11.GL_DEPTH_BUFFER_BIT) buffer.unbind() framebuffer.bind() GL11.glClearColor(0f, 0f, 0f, 1f) GL11.glClear(GL11.GL_COLOR_BUFFER_BIT) framebuffer.unbind() } fun drawToGBuffer(shader: GLShaderProgram, objects: List<Object3D>) { val viewMatrix = camera.viewMatrix val projectionMatrix = camera.projectionMatrix buffer.bind() view.setViewport() GL11.glEnable(GL11.GL_CULL_FACE) GL11.glEnable(GL11.GL_DEPTH_TEST) GL11.glDisable(GL11.GL_BLEND) GL11.glDepthMask(true) shader.start() shader.setUniform("projectionTransform", projectionMatrix) shader.setUniform("viewTransform", viewMatrix) shader.setUniform("screenSize", view.size) for (o in objects) o.draw(this, shader) shader.stop() buffer.unbind() } fun drawToGBuffer(shader: GLShaderProgram, vararg objects: Object3D) { drawToGBuffer(shader, objects.toList()) } fun renderToTexture(vararg renderers: () -> Unit) { framebuffer.bind() buffer.bindReading() GL11.glDepthMask(false) GL11.glDisable(GL11.GL_CULL_FACE) GL11.glDisable(GL11.GL_DEPTH_TEST) GL11.glEnable(GL11.GL_BLEND) GL14.glBlendEquation(GL14.GL_FUNC_ADD) GL11.glBlendFunc(GL11.GL_ONE, GL11.GL_ONE) for (renderer in renderers) renderer() framebuffer.unbind() buffer.unbindReading() GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA) } fun light(light: Light) { renderToTexture({ light.shader.start() light.shader.setUniform("screenSize", view.size) light.shader.setUniform("viewTransform", camera.viewMatrix) light.shader.setUniform("projectionTransform", camera.projectionMatrix) light.render(light.shader, this) light.shader.stop() }) } fun ambientLight(intensity: Float = 0.1f, colour: vec3 = vec3(1f)) { light(AmbientLight(intensity, colour)) } fun directionalLight(direction: vec3, intensity: Float = 0.7f, colour: vec3 = vec3(1f)) { light(DirectionalLight(direction, intensity, colour)) } fun pointLight(position: vec3, intensity: Float = 4f, attenuation: vec3 = PointLight.ATTENUATION, colour: vec3 = vec3(1f)) { light(PointLight(position, intensity, attenuation, colour)) } fun spotLight(position: vec3, direction: vec3, intensity: Float = 4f, spread: vec2 = vec2(0.5f, 0.6f), attenuation: vec3 = PointLight.ATTENUATION, colour: vec3 = vec3(1f)) { light(SpotLight(position, direction, spread, intensity, attenuation, colour)) } fun drawIndexedVAO(vao: GLVAO) { view.setViewport() vao.load() GL11.glDrawElements(GL11.GL_TRIANGLES, vao.vertexCount, GL11.GL_UNSIGNED_INT, 0) vao.unload() } override fun destroy() { buffer.destroy() framebuffer.destroy() texture.destroy() if (DEFAULT_SHADER_DELEGATE.isInitialized()) { DEFAULT_SHADER.destroy() } } }
1
Kotlin
0
0
732f76f981fcb00ba486708965be2944a9d82b4d
4,545
LWAF
MIT License
compiler/testData/psi/recovery/unnamedParameter/firstInLambda.kt
JakeWharton
99,388,807
true
null
val foo = { : Int -> 0 }
179
Kotlin
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
24
kotlin
Apache License 2.0
zenet/request/src/main/kotlin/br/com/khomdrake/request/RequestHandler.kt
KhomDrake
776,191,044
false
{"Kotlin": 92853}
package br.com.khomdrake.request import android.content.Context import androidx.annotation.VisibleForTesting import br.com.arch.toolkit.livedata.response.MutableResponseLiveData import br.com.arch.toolkit.livedata.response.ResponseLiveData import br.com.khomdrake.request.cache.DiskVault import br.com.khomdrake.request.data.Response import br.com.khomdrake.request.data.flow.MutableResponseStateFlow import br.com.khomdrake.request.data.flow.ResponseStateFlow import br.com.khomdrake.request.data.responseData import br.com.khomdrake.request.data.responseError import br.com.khomdrake.request.data.responseLoading import br.com.khomdrake.request.data.toDataResult import br.com.khomdrake.request.log.LogHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.launch private val requestScope = CoroutineScope(SupervisorJob() + Dispatchers.IO) class RequestHandler<Data>( private val scope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.IO), private val key: String = "" ) { private val lock = object {} private var config: Config<Data> = Config(key) private val _responseLiveData = MutableResponseLiveData<Data>() private val _responseStateFlow = MutableResponseStateFlow<Data>(Response()) val responseLiveData: ResponseLiveData<Data> get() = _responseLiveData val responseStateFlow: ResponseStateFlow<Data> get() = _responseStateFlow .shareIn( requestScope, SharingStarted.WhileSubscribed(), replay = 0 ) fun config(func: Config<Data>.() -> Unit) = apply { config = Config<Data>(key).apply(func) } fun logInfo(info: String) { LogHandler.logInfo(key, info) } fun execute() = synchronized(lock) { scope.launch { runCatching { createExecution().start() }.onFailure { _responseStateFlow.emitError(it) _responseLiveData.postError(it) } } return@synchronized this } @VisibleForTesting fun setData(data: Data) = apply { requestScope.launch { _responseLiveData.postData(data) _responseStateFlow.emit(responseData(data)) } } @VisibleForTesting fun setLoading() { requestScope.launch { _responseLiveData.postLoading() _responseStateFlow.emit(responseLoading()) } } @VisibleForTesting fun setError(throwable: Throwable = Throwable()) { requestScope.launch { _responseLiveData.postError(throwable) _responseStateFlow.emit(responseError(throwable)) } } private fun createExecution() = scope.launch { logInfo("[Execution] creating execution") flow { config.execute( this, this@RequestHandler ) } .onEach { _responseLiveData.postValue(it.toDataResult()) } .catch { _responseStateFlow.emitError(it) } .collect { _responseStateFlow.emit(it) } } companion object { fun init(context: Context, cleanCacheTimeout: Boolean = false) { DiskVault.init(context) if(cleanCacheTimeout) DiskVault.clearCache() } } } fun <T>requestHandler( tag: String = "", scope: CoroutineScope = requestScope ) : RequestHandler<T> { return RequestHandler(scope, tag) }
0
Kotlin
0
0
cee648d765ca6c18a3be00160da00c1a73cb7545
3,810
Zenet
Apache License 2.0
payment-sdk-core/src/main/java/payment/sdk/android/core/api/CoroutinesGatewayHttpClient.kt
network-international
187,156,001
false
{"Kotlin": 375118, "Java": 39575}
package payment.sdk.android.core.api import android.os.Build import androidx.annotation.UiThread import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import org.json.JSONObject import java.io.BufferedReader import java.io.BufferedWriter import java.net.HttpURLConnection import java.net.URL import javax.net.ssl.HttpsURLConnection import javax.net.ssl.SSLSocketFactory class CoroutinesGatewayHttpClient : HttpClient { private val sslSocketFactoryDelegate: SSLSocketFactory by lazy { TLSSocketFactoryDelegate() } @UiThread override fun get( url: String, headers: Map<String, String>, success: (Pair<Map<String, List<String>>, JSONObject>) -> Unit, error: (Exception) -> Unit ) { httpMethodCall("GET", url, headers, Body.Empty(), success, error, doOutput = false) } override suspend fun get( url: String, headers: Map<String, String>, body: Body ): SDKHttpResponse { return try { val response = call("GET", url, headers, body, doOutput = false) SDKHttpResponse.Success(response.first, response.second.toString()) } catch (e: java.lang.Exception) { SDKHttpResponse.Failed(e) } } @UiThread override fun post( url: String, headers: Map<String, String>, body: Body, success: (Pair<Map<String, List<String>>, JSONObject>) -> Unit, error: (Exception) -> Unit ) { httpMethodCall("POST", url, headers, body, success, error) } override suspend fun post( url: String, headers: Map<String, String>, body: Body ): SDKHttpResponse { return try { val response = call( method = "POST", url = url, headers = headers, body = body, doOutput = true ) SDKHttpResponse.Success(response.first, response.second.toString()) } catch (e: java.lang.Exception) { SDKHttpResponse.Failed(e) } } @UiThread override fun put( url: String, headers: Map<String, String>, body: Body, success: (Pair<Map<String, List<String>>, JSONObject>) -> Unit, error: (Exception) -> Unit ) { httpMethodCall("PUT", url, headers, body, success, error) } override suspend fun put( url: String, headers: Map<String, String>, body: Body ): SDKHttpResponse { return try { val response = call( "PUT", url, headers, body, doOutput = true ) SDKHttpResponse.Success(response.first, response.second.toString()) } catch (e: java.lang.Exception) { SDKHttpResponse.Failed(e) } } private fun httpMethodCall( method: String, url: String, headers: Map<String, String>, body: Body, success: (Pair<Map<String, List<String>>, JSONObject>) -> Unit, error: (Exception) -> Unit, doOutput: Boolean = true ) = GlobalScope.launch(Dispatchers.Main) { try { val data = withContext(Dispatchers.IO) { call(method, url, headers, body, doOutput) } success(data) } catch (e: java.lang.Exception) { error(e) } } private suspend fun call( method: String, url: String, headers: Map<String, String>, body: Body, doOutput: Boolean ) : Pair<Map<String, List<String>>, JSONObject> { var connection: HttpURLConnection? = null var writer: BufferedWriter? = null var reader: BufferedReader? = null try { connection = (withContext(Dispatchers.IO) { URL(url).openConnection() } as HttpURLConnection).apply { initConnection(this, headers, doOutput).requestMethod = method } // Write content body if (doOutput && body.isNotEmpty()) { writer = connection.outputStream.bufferedWriter() withContext(Dispatchers.IO) { writer.write(body.encode()) writer.flush() } } val responseCode = connection.responseCode when (responseCode) { // Success HttpURLConnection.HTTP_OK, HttpURLConnection.HTTP_CREATED -> { reader = connection.inputStream.bufferedReader() return Pair(connection.headerFields, JSONObject(reader.readText())) } // Not Discerned -1 -> throw IllegalStateException("Http response code can't be discerned: -1") // Other HTTP Codes else -> throw IllegalStateException("HTTP: $responseCode") } } catch (e: Exception) { throw e } finally { withContext(Dispatchers.IO) { writer?.close() reader?.close() } connection?.disconnect() } } private fun initConnection( connection: HttpURLConnection, headers: Map<String, String>, isDoOutput: Boolean ) = connection.apply { readTimeout = 30000 connectTimeout = 30000 doOutput = isDoOutput useCaches = false val device = "${Build.MANUFACTURER}-${Build.MODEL}" val os = "OS-${Build.VERSION.SDK_INT}" setRequestProperty("Accept-Language", "UTF-8") setRequestProperty("User-Agent", "Android Pay Page $device $os") headers.forEach { (key, value) -> setRequestProperty(key, value) } if (this is HttpsURLConnection) { sslSocketFactory = sslSocketFactoryDelegate } } }
3
Kotlin
7
5
dea297485b5bc45c1f1263a9c406abec3d72f497
6,169
payment-sdk-android
MIT No Attribution
kotlin-mui-icons/src/main/generated/mui/icons/material/BrandingWatermarkSharp.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/BrandingWatermarkSharp") @file:JsNonModule package mui.icons.material @JsName("default") external val BrandingWatermarkSharp: SvgIconComponent
10
Kotlin
5
983
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
226
kotlin-wrappers
Apache License 2.0
backend.native/tests/serialization/vararg.kt
mano7onam
122,908,795
true
{"Kotlin": 4630329, "C++": 803727, "Groovy": 137600, "C": 119742, "Objective-C++": 66838, "Swift": 29084, "JavaScript": 19411, "Shell": 11621, "Batchfile": 7004, "Python": 4775, "Objective-C": 3532, "Pascal": 1698, "Java": 782, "HTML": 185}
fun bar(vararg x: Int) { x.forEach { println(it) } println("size: ${x.size}") } inline fun foo() = bar(17, 19, 23, *intArrayOf(29, 31))
0
Kotlin
0
12
d5169f2370a6b20ae91fc31999fe5ebefcb4344d
158
kotlin-native
Apache License 2.0
db-objekts-postgresql/src/generated-sources/kotlin/com/dbobjekts/postgresql/testdb/core/Core.kt
jaspersprengers
576,889,038
false
null
package com.dbobjekts.postgresql.testdb.core import com.dbobjekts.metadata.Schema object Core : Schema("core", listOf(Address, AllTypesNil, Composite, CompositeForeignKey, Country, Department, Employee, EmployeeAddress, EmployeeDepartment))
0
Kotlin
1
3
d744e819a566ec0a3dbf6d2ff95feee4f58bbea6
240
db-objekts
Apache License 2.0
library/src/main/java/cloud/pace/sdk/api/pay/generated/request/paymentTokens/GetPaymentTokensAPI.kt
pace
303,641,261
false
null
/* * PLEASE DO NOT EDIT! * * Generated by SwagGen with Kotlin template. * https://github.com/pace/SwagGen */ package cloud.pace.sdk.api.pay.generated.request.paymentTokens import cloud.pace.sdk.api.pay.PayAPI import cloud.pace.sdk.api.pay.generated.model.* import cloud.pace.sdk.api.utils.EnumConverterFactory import cloud.pace.sdk.api.utils.InterceptorUtils import cloud.pace.sdk.utils.toIso8601 import com.google.gson.annotations.SerializedName import com.squareup.moshi.Json import com.squareup.moshi.Moshi import com.squareup.moshi.adapters.Rfc3339DateJsonAdapter import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import moe.banana.jsonapi2.JsonApi import moe.banana.jsonapi2.JsonApiConverterFactory import moe.banana.jsonapi2.Resource import moe.banana.jsonapi2.ResourceAdapterFactory import okhttp3.OkHttpClient import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.* import java.io.File import java.util.* import java.util.concurrent.TimeUnit object GetPaymentTokensAPI { interface GetPaymentTokensService { /* Get all valid payment tokens for user */ /* Get all valid payment tokens for user. Valid means that a token was successfully created and is not expired. It might be unusable, for example if it is used in a transaction already. */ @GET("payment-tokens") fun getPaymentTokens( @Query("filter[valid]") filtervalid: Filtervalid ): Call<PaymentTokens> } /* Get all valid payment tokens for user. Valid means that a token was successfully created and is not expired. It might be unusable, for example if it is used in a transaction already. */ enum class Filtervalid(val value: String) { @SerializedName("true") @Json(name = "true") `TRUE`("true") } fun PayAPI.PaymentTokensAPI.getPaymentTokens(filtervalid: Filtervalid, readTimeout: Long? = null): Call<PaymentTokens> { val client = OkHttpClient.Builder() .addNetworkInterceptor(InterceptorUtils.getInterceptor("application/vnd.api+json", "application/vnd.api+json", true)) .authenticator(InterceptorUtils.getAuthenticator()) if (readTimeout != null) { client.readTimeout(readTimeout, TimeUnit.SECONDS) } val service: GetPaymentTokensService = Retrofit.Builder() .client(client.build()) .baseUrl(PayAPI.baseUrl) .addConverterFactory(EnumConverterFactory()) .addConverterFactory( JsonApiConverterFactory.create( Moshi.Builder() .add(ResourceAdapterFactory.builder() .build() ) .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .add(KotlinJsonAdapterFactory()) .build() ) ) .addConverterFactory( MoshiConverterFactory.create( Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .add(KotlinJsonAdapterFactory()) .build() ) ) .build() .create(GetPaymentTokensService::class.java) return service.getPaymentTokens(filtervalid) } }
0
Kotlin
0
3
ed4d7b1e2e0d72f9d5f7ffc8c9ccf3df6940eefe
3,567
cloud-sdk-android
MIT License
src/main/kotlin/com/example/controller/time/LastFetchTimeManager.kt
Huythanh0x
629,448,338
false
null
package com.example.controller.time import com.example.data.dao.CouponDAO import com.example.utils.Constants import org.json.JSONObject import java.io.File import java.io.FileWriter import java.time.LocalDateTime import java.time.ZoneId import java.time.format.DateTimeFormatter class LastFetchTimeManager { companion object { private val couponDAO = CouponDAO fun dumpFetchedTimeJsonToFile(jsonFilePath: String = "fetched_time.json") { val resultJson = JSONObject() resultJson.put("localTime", LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)) FileWriter(jsonFilePath).use { it.write(resultJson.toString()) } } fun loadLasFetchedTimeInMilliSecond(): Long { return try { val couponsJson = File("fetched_time.json").readText() val responseJsonObject = JSONObject(couponsJson) val dateTimeString = responseJsonObject.getString("localTime") val formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME val localDateTime = LocalDateTime.parse(dateTimeString, formatter) localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli() } catch (e: Exception) { System.currentTimeMillis() - Constants.INTERVAL } } } }
0
Kotlin
0
0
67bfc607779bfa0cf5e39248cd81bc28c369bd81
1,364
UdemyCouponKtorServer
MIT License
src/main/kotlin/com/between_freedom_and_space/mono_backend/posts/api/routing/PostsInformationRouting.kt
Between-Freedom-and-Space
453,797,438
false
{"Kotlin": 614504, "HTML": 8733, "Dockerfile": 503, "Shell": 166}
package com.between_freedom_and_space.mono_backend.posts.api.routing import com.between_freedom_and_space.mono_backend.common.api.PageParams import com.between_freedom_and_space.mono_backend.common.api.Response import com.between_freedom_and_space.mono_backend.common.components.ModelMapper import com.between_freedom_and_space.mono_backend.posts.api.models.PostCommentsCountResponse import com.between_freedom_and_space.mono_backend.posts.api.models.PostModel import com.between_freedom_and_space.mono_backend.posts.api.models.PostReactionsCountResponse import com.between_freedom_and_space.mono_backend.posts.internal.comments.api.models.CommentModel import com.between_freedom_and_space.mono_backend.posts.internal.comments.modules.qualifiers.CommentsMappersQualifiers import com.between_freedom_and_space.mono_backend.posts.internal.comments.services.models.BaseCommentModel import com.between_freedom_and_space.mono_backend.posts.internal.reactions.api.models.ReactionModel import com.between_freedom_and_space.mono_backend.posts.internal.reactions.modules.qualifiers.ReactionsMappersQualifiers import com.between_freedom_and_space.mono_backend.posts.internal.reactions.service.model.BasePostReactionModel import com.between_freedom_and_space.mono_backend.posts.internal.tags.api.models.TagModel import com.between_freedom_and_space.mono_backend.posts.internal.tags.modules.qualifiers.TagsMappersQualifiers import com.between_freedom_and_space.mono_backend.posts.internal.tags.services.model.BaseTagModel import com.between_freedom_and_space.mono_backend.posts.modules.qualifiers.PostMappersQualifiers import com.between_freedom_and_space.mono_backend.posts.services.InformationPostsService import com.between_freedom_and_space.mono_backend.posts.services.exceptions.InvalidPostException import com.between_freedom_and_space.mono_backend.posts.services.models.BasePostModel import com.between_freedom_and_space.mono_backend.posts.services.models.PostCommentsCountModel import com.between_freedom_and_space.mono_backend.posts.services.models.PostReactionsCountModel import com.between_freedom_and_space.mono_backend.util.extensions.getPathParameter import com.between_freedom_and_space.mono_backend.util.extensions.inject import com.between_freedom_and_space.mono_backend.util.extensions.sendResponse import com.between_freedom_and_space.mono_backend.util.extensions.validateAndReceiveRequest import io.ktor.server.application.* import io.ktor.server.routing.* import org.koin.core.qualifier.named internal fun Application.postsInformationRouting() { val basePath = "/post" val informationService by inject<InformationPostsService>() val baseModelMapper by inject<ModelMapper<BasePostModel, PostModel>>( named(PostMappersQualifiers.BASE_POST_MODEL_TO_POST_MODEL) ) routing { get("$basePath/all") { val pageParams = validateAndReceiveRequest<PageParams>() val pageNumber = pageParams.pageNumber val pageSize = pageParams.pageSize val posts = informationService.getAllPosts(pageNumber, pageSize) val postsResponse = posts.map { baseModelMapper.map(it) } val response = Response.ok(postsResponse) sendResponse(response) } get("$basePath/{id}") { val postId = getPathParameter("id")?.toLong() ?: throw InvalidPostException("Post id is not presented") val post = informationService.getPostById(postId) val postResponse = baseModelMapper.map(post) val response = Response.ok(postResponse) sendResponse(response) } get("$basePath/{id}/comments") { val commentMapper by inject<ModelMapper<BaseCommentModel, CommentModel>>( named(CommentsMappersQualifiers.BASE_COMMENT_TO_COMMENT_MODEL) ) val pageParams = validateAndReceiveRequest<PageParams>() val pageNumber = pageParams.pageNumber val pageSize = pageParams.pageSize val postId = getPathParameter("id")?.toLong() ?: throw InvalidPostException("Post id is not presented") val comments = informationService.getPostComments(postId, pageNumber, pageSize) val commentsResponse = comments.map { commentMapper.map(it) } val response = Response.ok(commentsResponse) sendResponse(response) } get("$basePath/{id}/reactions") { val reactionMapper by inject<ModelMapper<BasePostReactionModel, ReactionModel>>( named(ReactionsMappersQualifiers.BASE_POST_REACTION_TO_MODEL) ) val pageParams = validateAndReceiveRequest<PageParams>() val pageNumber = pageParams.pageNumber val pageSize = pageParams.pageSize val postId = getPathParameter("id")?.toLong() ?: throw InvalidPostException("Post id is not presented") val reactions = informationService.getPostReactions(postId, pageNumber, pageSize) val reactionsResponse = reactions.map { reactionMapper.map(it) } val response = Response.ok(reactionsResponse) sendResponse(response) } get("$basePath/{id}/reactions/count") { val countMapper by inject<ModelMapper<PostReactionsCountModel, PostReactionsCountResponse>>( named(PostMappersQualifiers.POST_REACTIONS_COUNT_MODEL_TO_POST_REACTIONS_COUNT_RESPONSE) ) val postId = getPathParameter("id")?.toLong() ?: throw InvalidPostException("Post id is not presented") val countModel = informationService.getPostReactionsCount(postId) val countResponse = countMapper.map(countModel) val response = Response.ok(countResponse) sendResponse(response) } get("$basePath/{id}/comments/count") { val countMapper by inject<ModelMapper<PostCommentsCountModel, PostCommentsCountResponse>>( named(PostMappersQualifiers.POST_COMMENTS_COUNT_MODEL_TO_POST_COMMENTS_COUNT_RESPONSE) ) val postId = getPathParameter("id")?.toLong() ?: throw InvalidPostException("Post id is not presented") val countModel = informationService.getPostCommentsCount(postId) val countResponse = countMapper.map(countModel) val response = Response.ok(countResponse) sendResponse(response) } get("$basePath/{id}/tags") { val tagMapper by inject<ModelMapper<BaseTagModel, TagModel>>( named(TagsMappersQualifiers.BASE_TAG_MODEL_TO_MODEL) ) val pageParams = validateAndReceiveRequest<PageParams>() val pageNumber = pageParams.pageNumber val pageSize = pageParams.pageSize val postId = getPathParameter("id")?.toLong() ?: throw InvalidPostException("Post id is not presented") val tags = informationService.getPostTags(postId, pageNumber, pageSize) val tagResponse = tags.map { tagMapper.map(it) } val response = Response.ok(tagResponse) sendResponse(response) } } }
0
Kotlin
0
1
812d8257e455e7d5b1d0c703a66b55ed2e1dcd35
7,274
Mono-Backend
Apache License 2.0
modules/module-compose/src/main/java/com/bbgo/module_compose/activity/ComposeActivity.kt
bbggo
371,705,786
false
null
package com.bbgo.module_compose import android.app.Activity import android.os.Bundle import android.text.Html import androidx.activity.compose.setContent import androidx.activity.viewModels import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.Image import androidx.compose.foundation.border import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.dimensionResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.compose.rememberNavController import com.alibaba.android.arouter.facade.annotation.Route import com.bbgo.common_base.base.BaseActivity import com.bbgo.common_base.constants.Constants import com.bbgo.common_base.ext.logD import com.bbgo.module_compose.theme.* import com.bbgo.module_compose.util.InjectorUtil import com.bbgo.module_compose.viewmodel.ComposeViewModel import com.bbgo.module_compose.bean.ArticleDetail @Route(path = Constants.NAVIGATION_TO_COLLECT) class ComposeActivity : BaseActivity() { @ExperimentalFoundationApi val composeViewModel: ComposeViewModel by viewModels { InjectorUtil.getComposeViewModelFactory() } @ExperimentalFoundationApi lateinit var context: Activity @ExperimentalFoundationApi override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) context = this composeViewModel.getArticles(0) setContent { WanAndroidTheme { RenderTopAppBar(composeViewModel) } } } } @ExperimentalFoundationApi @Composable fun RenderTopAppBar(composeViewModel: ComposeViewModel) { Scaffold( topBar = { TopAppBar( title = { Text( text = stringResource(id = R.string.nav_my_collect), color = Color.White, fontSize = 18.sp ) }, navigationIcon = { IconButton(onClick = { }) { Icon(Icons.Filled.ArrowBack, null, tint = Color.White) } }, backgroundColor = colorResource(id = R.color.colorPrimary) ) }, ){ Request(composeViewModel) } } @ExperimentalFoundationApi @Composable fun Request(composeViewModel: ComposeViewModel) { val liveData by composeViewModel.articleLiveData.observeAsState() logD("======================") logD(liveData?.data) liveData?.data?.let { RenderArticleList(it) } } @ExperimentalFoundationApi @Composable fun RenderArticleList(articles: List<ArticleDetail>) { LazyColumn { items(articles.size) { articles.forEach { ItemCard(articleDetail = it) } } } /*LazyColumn { items(articles) { articleDetail -> ItemCard(articleDetail = articleDetail) } }*/ } @ExperimentalFoundationApi @Composable fun ItemCard(articleDetail: ArticleDetail) { val dp2 = dimensionResource(id = R.dimen.dp_2) val dp5 = dimensionResource(id = R.dimen.dp_5) val dp10 = dimensionResource(id = R.dimen.dp_10) Surface(elevation = dimensionResource(id = R.dimen.dp_1), ) { Column() { Spacer(modifier = Modifier.padding(vertical = dp5)) Row { Row(modifier = Modifier.weight(1f)) { if (articleDetail.top == "1") { Spacer(modifier = Modifier.padding(horizontal = dp5)) Text( text = "置顶", color = Color.Red, fontSize = sp10, modifier = Modifier .border(dp05, Color.Red, shape = RoundedCornerShape(dp2)) .padding(start = dp4, end = dp4, top = dp2, bottom = dp2) ) } if (articleDetail.fresh) { Spacer(modifier = Modifier.padding(horizontal = dp5)) Text( text = "新", color = Color.Red, fontSize = sp10, modifier = Modifier .border(dp05, Color.Red, shape = RoundedCornerShape(dp2)) .padding(start = dp4, end = dp4, top = dp2, bottom = dp2) ) } if (articleDetail.tags.isNotEmpty()) { Spacer(modifier = Modifier.padding(horizontal = dp5)) Text( text = articleDetail.tags[0].name, color = Color.Red, fontSize = sp12, modifier = Modifier .border(dp05, Color.Red, shape = RoundedCornerShape(dp2)) .padding(start = dp4, end = dp4, top = dp2, bottom = dp2) ) } Spacer(modifier = Modifier.padding(horizontal = dp5)) Text( text = articleDetail.author, color = colorResource(id = R.color.Grey600), fontSize = sp12, modifier = Modifier .padding(start = dp4, end = dp4, top = dp2, bottom = dp2) ) } Row(modifier = Modifier.padding(end = dp5)) { Text( text = articleDetail.niceDate, color = colorResource(id = R.color.Grey600), fontSize = sp12, modifier = Modifier .padding(start = dp4, end = dp4, top = dp2, bottom = dp2) ) } } Spacer(modifier = Modifier.padding(vertical = dp2)) Row(horizontalArrangement = Arrangement.Start) { Spacer(modifier = Modifier.padding(horizontal = dp5)) Text( text = Html.fromHtml(articleDetail.title).toString(), color = colorResource(id = R.color.item_title), fontSize = sp16, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(end = dp5), textAlign = TextAlign.Start ) } Spacer(modifier = Modifier.padding(vertical = dp5)) val chapterName = when { articleDetail.superChapterName.isNotEmpty() and articleDetail.chapterName.isNotEmpty() -> "${articleDetail.superChapterName} / ${articleDetail.chapterName}" articleDetail.superChapterName.isNotEmpty() -> articleDetail.superChapterName articleDetail.chapterName.isNotEmpty() -> articleDetail.chapterName else -> "" } Row(verticalAlignment = Alignment.Bottom) { Text( text = chapterName, color = colorResource(id = R.color.item_title), fontSize = sp12, textAlign = TextAlign.Start, modifier = Modifier .weight(1f) .padding(start = dp10) ) val imgId = if (articleDetail.collect) { R.drawable.ic_like } else { R.drawable.ic_like_not } Image( painter = painterResource(id = imgId), contentDescription = null, alignment = Alignment.CenterEnd, modifier = Modifier .weight(0.1f) .size(26.dp) .padding(end = dp5) .clickable { } ) } Spacer(modifier = Modifier.padding(vertical = dp5)) Divider(thickness = 0.2.dp) } } } @Composable fun TestItemCard() { val dp2 = dimensionResource(id = R.dimen.dp_2) val dp5 = dimensionResource(id = R.dimen.dp_5) Surface(shape = MaterialTheme.shapes.medium, elevation = dimensionResource(id = R.dimen.dp_1), ) { Column() { Spacer(modifier = Modifier.padding(vertical = dp2)) Row { Row(modifier = Modifier.weight(1f)) { Spacer(modifier = Modifier.padding(horizontal = dp5)) Text( text = "置顶", color = Color.Red, fontSize = sp10, modifier = Modifier .border(dp05, Color.Red, shape = RectangleShape) .padding(start = dp4, end = dp4, top = dp2, bottom = dp2) ) Spacer(modifier = Modifier.padding(horizontal = dp5)) Text( text = "新", color = Color.Red, fontSize = sp10, modifier = Modifier .border(dp05, Color.Red, shape = RectangleShape) .padding(start = dp4, end = dp4, top = dp2, bottom = dp2) ) Spacer(modifier = Modifier.padding(horizontal = dp5)) Text( text = "玩安卓TAG", color = Color.Red, fontSize = sp10, modifier = Modifier .border(dp05, Color.Red, shape = RectangleShape) .padding(start = dp4, end = dp4, top = dp2, bottom = dp2) ) Spacer(modifier = Modifier.padding(horizontal = dp5)) Text( text = "玩安卓", color = colorResource(id = R.color.Grey600), fontSize = sp12, modifier = Modifier .padding(start = dp4, end = dp4, top = dp2, bottom = dp2) ) } Row { Spacer(modifier = Modifier.padding(horizontal = dp20)) Text( text = "玩安卓", color = colorResource(id = R.color.Grey600), fontSize = sp12, modifier = Modifier .padding(start = dp4, end = dp4, top = dp2, bottom = dp2) ) } } Spacer(modifier = Modifier.padding(vertical = dp2)) Row(horizontalArrangement = Arrangement.Start) { Spacer(modifier = Modifier.padding(horizontal = dp5)) Text( text = "Compose 有效地处理嵌套布局,使其成为设计复杂UI的好方法。这是对 Android Views 的改进,在 Android Views 中,出于性能原因,您需要避免嵌套布局。你好呀陌生人,这是一个标题,不是很长,因为我想不出其他什么比较好的标题了", color = colorResource(id = R.color.item_title), fontSize = sp16, maxLines = 2, overflow = TextOverflow.Ellipsis, modifier = Modifier.padding(end = dp5), textAlign = TextAlign.Start ) } Spacer(modifier = Modifier.padding(vertical = dp2)) /*Scaffold( topBar = { TopAppBar( title = { Text( text = "问答 / 官方", color = colorResource(id = R.color.item_title), fontSize = sp8, textAlign = TextAlign.Center, ) }, actions = { Image( painter = painterResource(id = R.drawable.ic_like_not), contentDescription = null, modifier = Modifier.padding(end = 10.dp) ) }, backgroundColor = Color.White ) }, ) {}*/ Row { Text( text = "问答 / 官方", color = colorResource(id = R.color.item_title), fontSize = sp12, textAlign = TextAlign.Start, modifier = Modifier .weight(1f) .padding(start = dp10) ) Image( painter = painterResource(id = R.drawable.ic_like_not), contentDescription = null, alignment = Alignment.CenterEnd, modifier = Modifier .weight(0.1f) .size(20.dp) .padding(end = dp5) .clickable { } ) } } } } @Preview @Composable fun DefaultPreview() { // ArticleList(articleList = mutableListOf()) TestItemCard() }
3
null
9
8
9c983af26f5bd9cd5e08b7a6080190305738b435
14,556
WanAndroid
Apache License 2.0
Session 12 - Firabase II/Exercise 1/app/src/main/java/com/harbourspace/unsplash/data/UnsplashCollection.kt
m-4-s-h-4
670,582,935
false
null
package com.harbourspace.unsplash.data import android.os.Parcelable import androidx.room.Entity import kotlinx.parcelize.Parcelize @Entity @Parcelize data class UnsplashCollection( val cover_photo: CoverPhoto, val description: String?, val id: String, val last_collected_at: String, val links: Links, val `private`: Boolean, val published_at: String, val share_key: String, val title: String, val total_photos: Int, val updated_at: String, val user: User ): Parcelable
1
Kotlin
2
0
a18e9f68eed9eed28997a824abca1201d189a2b3
518
hw10
Apache License 2.0
reactive/kotlinx-coroutines-rx2/src/RxMaybe.kt
weverb2
183,635,586
false
{"Shell": 6, "Gradle": 44, "Markdown": 45, "Java Properties": 9, "Ignore List": 2, "Batchfile": 4, "Text": 28, "Kotlin": 692, "Gemfile.lock": 1, "YAML": 2, "Ruby": 1, "SCSS": 5, "HTML": 4, "JavaScript": 3, "Proguard": 4, "XML": 20, "JSON": 2, "CSS": 1, "Java": 1}
/* * Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.rx2 import io.reactivex.* import kotlinx.coroutines.* import kotlin.coroutines.* /** * Creates cold [maybe][Maybe] that will run a given [block] in a coroutine. * Every time the returned observable is subscribed, it starts a new coroutine. * Coroutine returns a single, possibly null value. Unsubscribing cancels running coroutine. * * | **Coroutine action** | **Signal to subscriber** * | ------------------------------------- | ------------------------ * | Returns a non-null value | `onSuccess` * | Returns a null | `onComplete` * | Failure with exception or unsubscribe | `onError` * * Coroutine context is inherited from a [CoroutineScope], additional context elements can be specified with [context] argument. * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used. * The parent job is inherited from a [CoroutineScope] as well, but it can also be overridden * with corresponding [coroutineContext] element. * * @param context context of the coroutine. * @param block the coroutine code. */ public fun <T> CoroutineScope.rxMaybe( context: CoroutineContext = EmptyCoroutineContext, block: suspend CoroutineScope.() -> T? ): Maybe<T> = Maybe.create { subscriber -> val newContext = newCoroutineContext(context) val coroutine = RxMaybeCoroutine(newContext, subscriber) subscriber.setCancellable(RxCancellable(coroutine)) coroutine.start(CoroutineStart.DEFAULT, coroutine, block) } private class RxMaybeCoroutine<T>( parentContext: CoroutineContext, private val subscriber: MaybeEmitter<T> ) : AbstractCoroutine<T>(parentContext, true) { override fun onCompleted(value: T) { if (!subscriber.isDisposed) { if (value == null) subscriber.onComplete() else subscriber.onSuccess(value) } } override fun onCancelled(cause: Throwable, handled: Boolean) { if (!subscriber.isDisposed) { subscriber.onError(cause) } else if (!handled) { handleCoroutineException(context, cause) } } }
1
null
1
1
4d5246a31e67e02c29e86f0e40f10fd307bdf673
2,280
kotlinx.coroutines
Apache License 2.0
base/src/main/java/jp/juggler/util/data/BinPack.kt
tateisu
89,120,200
false
null
package jp.juggler.util import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.InputStream import java.io.OutputStream /** * BinPack format * * アプリサーバからプッシュサービス経由で受け取るデータを包む。 * - 構造的にはJSONに似ている。階層を持つデータをエンコードできる。 * * Pros: * - バイト配列をエンコードできる。 * - 整数、浮動少数をエンコードできる。 * - エンコードされたデータは外部ライブラリの仕様変更に影響されない。 * - 内部実装のenumの名前やorderに依存しない。 * * Cons: * - ORMをサポートしない。 * - デコード結果の解読は生jsonと同程度に面倒。 * - ByteArray以外のプリミティブ配列をサポートしない。 * * Usage: * ListやMap をエンコード/デコードしたら BinPackMap や BinPackList になる。 * 利便性のために string(k), bytes(k), map(k) などのメソッドがある。 * * Background: * WebPushで暗号化されたバイト配列とHTTPヘッダ情報と宛先ハッシュを送るため * バイナリの汎用データフォーマットが欲しかった。 * 既存のものをいくつか検討した結果、300行程度で済むなら自前実装 * * */ fun Any?.encodeBinPack(): ByteArray = ByteArrayOutputStream().use { BinPackWriter(it).writeValue(this) it.flush() it.toByteArray() } fun ByteArray.decodeBinPack(): Any? = ByteArrayInputStream(this).use { BinPackReader(it).readValue() } fun ByteArray.decodeBinPackMap() = decodeBinPack() as? BinPackMap @Suppress("unused") fun ByteArray.decodeBinPackList() = decodeBinPack() as? BinPackList class BinPackMap() : HashMap<Any?, Any?>() { constructor(vararg pairs: Pair<Any?, Any?>) : this() { putAll(pairs) } fun string(k: Any?) = get(k) as? String fun bytes(k: Any?) = get(k) as? ByteArray fun map(k: Any?) = get(k) as? BinPackMap } class BinPackList() : ArrayList<Any?>() { constructor(vararg args: Any?) : this() { addAll(args) } fun string(k: Int) = elementAtOrNull(k) as? String @Suppress("unused") fun bytes(k: Int) = elementAtOrNull(k) as? ByteArray fun map(k: Int) = elementAtOrNull(k) as? BinPackMap } private enum class ValueType(val id: Int) { VNull(0), VTrue(1), VFalse(2), VBytes(3), VString(4), VList(5), VMap(6), VDouble(7), VFloat(8), @Suppress("unused") VInt8(10), // Byte, signed VInt16(11), VInt32(12), VInt64(13), VUInt16(15), // Char, unsigned ; companion object { val valuesCache = values() val idMap = valuesCache.associateBy { it.id } } } private class BinPackWriter( private val out: OutputStream, ) { private fun writeInt16(n: Int) { out.write(n) out.write(n.ushr(8)) } private fun writeInt32(n: Int) { out.write(n) out.write(n.ushr(8)) out.write(n.ushr(16)) out.write(n.ushr(24)) } private fun writeInt64(n: Long) { writeInt32(n.toInt()) writeInt32(n.ushr(32).toInt()) } private fun writeDouble(n: Double) = writeInt64(n.toRawBits()) private fun writeFloat(n: Float) = writeInt32(n.toRawBits()) private fun writeVType(t: ValueType) = out.write(t.id) private fun writeSize(n: Int) = writeInt32(n) fun writeValue(value: Any?) { when (value) { null -> writeVType(ValueType.VNull) true -> writeVType(ValueType.VTrue) false -> writeVType(ValueType.VFalse) is ByteArray -> { writeVType(ValueType.VBytes) writeSize(value.size) out.write(value) } is String -> { writeVType(ValueType.VString) val encoded = value.encodeUTF8() writeSize(encoded.size) out.write(encoded) } is Collection<*> -> { writeVType(ValueType.VList) writeSize(value.size) for (x in value) { writeValue(x) } } is Array<*> -> { writeVType(ValueType.VList) writeSize(value.size) for (x in value) { writeValue(x) } } is Map<*, *> -> { writeVType(ValueType.VMap) val entries = value.entries writeSize(entries.size) for (entry in value.entries) { writeValue(entry.key) writeValue(entry.value) } } is Double -> { writeVType(ValueType.VDouble) writeDouble(value) } is Float -> { writeVType(ValueType.VFloat) writeFloat(value) } is Long -> { writeVType(ValueType.VInt64) writeInt64(value) } is Int -> { writeVType(ValueType.VInt32) writeInt32(value) } is Short -> { writeVType(ValueType.VInt16) writeInt16(value.toInt()) } is Char -> { writeVType(ValueType.VUInt16) writeInt16(value.code) } is Byte -> { writeVType(ValueType.VInt8) out.write(value.toInt()) } else -> error("unsupported type ${value.javaClass.simpleName}") } } } private class BinPackReader( private val ins: InputStream, ) { private fun readUInt8(): Int { val n = ins.read().and(255) if (n == -1) error("unexpected end") return n } private fun readUInt16(): Int { val b0 = readUInt8() val b1 = readUInt8().shl(8) return b0.or(b1) } private fun readInt32(): Int { val b0 = readUInt8() val b1 = readUInt8().shl(8) val b2 = readUInt8().shl(16) val b3 = readUInt8().shl(24) return b0.or(b1).or(b2).or(b3) } private fun readInt64(): Long { val low = readInt32().toLong().and(0xFFFFFFFFL) val high = readInt32().toLong().shl(32) return low.or(high) } private fun readFloat() = Float.fromBits(readInt32()) private fun readDouble() = Double.fromBits(readInt64()) private fun readBytes(size: Int) = ByteArray(size).also { dst -> var nRead = 0 while (nRead < size) { val delta = ins.read(dst, nRead, size - nRead) if (delta < 0) error("unexpected end.") if (delta > 0) nRead += delta } } private fun readSize() = readInt32() fun readValue(): Any? { val id = readUInt8() return when (ValueType.idMap[id]) { null -> error("unknown type id=$id") ValueType.VNull -> null ValueType.VTrue -> true ValueType.VFalse -> false ValueType.VBytes -> readBytes(readSize()) ValueType.VString -> readBytes(readSize()).decodeUTF8() ValueType.VList -> BinPackList().apply { val size = readSize() ensureCapacity(size) repeat(size) { add(readValue()) } } ValueType.VMap -> BinPackMap().apply { repeat(readSize()) { val k = readValue() val v = readValue() put(k, v) } } ValueType.VDouble -> readDouble() ValueType.VFloat -> readFloat() ValueType.VInt8 -> readUInt8().toByte() ValueType.VInt16 -> readUInt16().toShort() ValueType.VInt32 -> readInt32() ValueType.VInt64 -> readInt64() ValueType.VUInt16 -> readUInt16().toChar() } } }
37
null
23
238
f20f9fee8ef29bfcbba0f4c610ca8c2fb1c29d4f
7,503
SubwayTooter
Apache License 2.0
composeApp/src/desktopMain/kotlin/org/openswim/database/dao/RelayTypes.kt
Grufoony
856,821,082
false
{"Kotlin": 22774}
package org.openswim.database.dao import org.jetbrains.exposed.dao.IntEntity import org.jetbrains.exposed.dao.IntEntityClass import org.jetbrains.exposed.dao.id.EntityID import org.jetbrains.exposed.dao.id.IntIdTable object RelayTypes : IntIdTable("relay_types") { val name = varchar("name", 255) } class RelayType(id: EntityID<Int>) : IntEntity(id) { companion object : IntEntityClass<RelayType>(RelayTypes) var name by RelayTypes.name }
5
Kotlin
0
0
48eefb6253bd150599f2dfa9d88a90ea8d795df6
454
OpenSwim
MIT License
src/main/kotlin/nest/Spawning.kt
Seveen
288,517,608
false
null
package nest import creature.Role import creature.roleToEssence import screeps.api.* import screeps.api.structures.StructureSpawn fun spawn(spawn: StructureSpawn, role: Role, energy: Int) { val essence = roleToEssence(role) val body: Array<BodyPartConstant> = essence.createBody(energy) val newName = "${role.name}_${Game.time}" val code = spawn.spawnCreep( body, newName, options { memory = essence.createMemory(spawn.room) }) when (code) { OK -> console.log("spawning $newName with body $body") ERR_BUSY, ERR_NOT_ENOUGH_ENERGY -> run { } else -> console.log("unhandled error code $code") } }
0
Kotlin
0
0
ed959ae2b2e6d6d1195a338de3cbf45e700f8a6c
685
screeps-ai
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Bucket.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.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.straight.Icons public val Icons.Outline.Bucket: ImageVector get() { if (_bucket != null) { return _bucket!! } _bucket = Builder(name = "Bucket", 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(21.381f, 8.0f) curveToRelative(-0.503f, -3.159f, -2.572f, -5.8f, -5.381f, -7.111f) verticalLineToRelative(-0.889f) horizontalLineToRelative(-8.0f) verticalLineToRelative(0.889f) curveToRelative(-2.809f, 1.31f, -4.878f, 3.951f, -5.381f, 7.111f) horizontalLineToRelative(-1.619f) verticalLineToRelative(2.0f) horizontalLineToRelative(1.692f) lineToRelative(3.0f, 14.0f) horizontalLineToRelative(12.617f) lineToRelative(3.0f, -14.0f) horizontalLineToRelative(1.692f) verticalLineToRelative(-2.0f) horizontalLineToRelative(-1.619f) close() moveTo(16.691f, 22.0f) lineTo(7.309f, 22.0f) lineToRelative(-1.714f, -8.0f) horizontalLineToRelative(10.767f) lineToRelative(0.429f, -2.0f) lineTo(5.166f, 12.0f) lineToRelative(-0.429f, -2.0f) horizontalLineToRelative(14.526f) lineToRelative(-2.572f, 12.0f) close() moveTo(4.651f, 8.0f) curveToRelative(0.414f, -2.031f, 1.654f, -3.76f, 3.349f, -4.834f) verticalLineToRelative(0.834f) horizontalLineToRelative(8.0f) verticalLineToRelative(-0.834f) curveToRelative(1.695f, 1.074f, 2.935f, 2.804f, 3.349f, 4.834f) lineTo(4.651f, 8.0f) close() } } .build() return _bucket!! } private var _bucket: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,831
icons
MIT License
app/src/main/java/dev/albertus/expensms/ui/components/GroupedTransactionList.kt
albertusdev
864,469,705
false
null
package dev.albertus.expensms.ui.components import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp import dev.albertus.expensms.data.model.Transaction import java.time.LocalDate @Composable fun GroupedTransactionList( groupedTransactions: Map<LocalDate, List<Transaction>>, modifier: Modifier = Modifier, isAmountVisible: Boolean = true, onTransactionClick: (String) -> Unit, lazyListState: LazyListState = rememberLazyListState() ) { LazyColumn(modifier = modifier, state = lazyListState) { groupedTransactions.forEach { (date, transactions) -> item { DayHeader(date) } item { DailyTotal(transactions, isAmountVisible = isAmountVisible) } items(transactions) { transaction -> TransactionItem( transaction = transaction, isAmountVisible = isAmountVisible, onClick = { onTransactionClick(transaction.id) } ) } item { HorizontalDivider(Modifier.padding(vertical = 8.dp)) } } } }
5
null
1
8
f13b993dded9342fd89678e9e26e43fa3e390917
1,512
expensms
MIT License
src/main/kotlin/playground/common/messaging/logging/DragonMessagingErrorHandler.kt
dtkmn
596,118,171
false
{"Kotlin": 333222, "Dockerfile": 763}
package playground.common.messaging.logging import playground.common.observability.logging.MDC_KEY_LOG_EVENT import playground.common.observability.logging.kv import playground.common.messaging.consumer.MessageListenerContainerStartHelper import io.sentry.Sentry import org.apache.kafka.clients.consumer.Consumer import org.apache.kafka.clients.consumer.ConsumerRecord import org.apache.kafka.common.KafkaException import org.apache.kafka.common.errors.InvalidPidMappingException import org.apache.kafka.common.errors.ProducerFencedException import org.apache.kafka.common.errors.UnknownProducerIdException import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.core.task.SimpleAsyncTaskExecutor import org.springframework.kafka.listener.ErrorHandler import org.springframework.kafka.listener.ListenerExecutionFailedException import org.springframework.kafka.listener.MessageListenerContainer import org.springframework.transaction.CannotCreateTransactionException import java.util.concurrent.Executor import org.apache.commons.lang3.exception.ExceptionUtils /** * Contains two error handlers: * * handle(Exception, ConsumerRecord) - used by when listener fails on record * handle(Exception, List, consumer, container) - used when rollback processing fails - for some unrecoverable * exceptions restarts container. * */ class DragonMessagingErrorHandler(private val messageListenerContainerStartHelper: MessageListenerContainerStartHelper) : ErrorHandler { private val log: Logger = LoggerFactory.getLogger(javaClass)!! private val executor: Executor = SimpleAsyncTaskExecutor() // used by when listener fails on record override fun handle(ex: Exception, data: ConsumerRecord<*, *>?) { Sentry.captureException(unwrap(ex)) throw ex } // used when rollback processing fails - for some unrecoverable exceptions restarts container override fun handle( ex: java.lang.Exception, records: MutableList<ConsumerRecord<*, *>>, consumer: Consumer<*, *>, container: MessageListenerContainer ) { if (exceptionQualifyForContainerRestart(ex)) { restartContainer(container) } Sentry.captureException(unwrap(ex)) throw ex } private fun exceptionQualifyForContainerRestart(ex: Exception): Boolean { // any transactional exceptions are thrown by rollback processing only // because error handler for listener errors is called from inside transaction // we do not want to restart container for ProducerFencedException as it is not needed for this error // or // any transient producer exception which means that message could not be sent to DLT return isKafkaTransactionalNotFencedException(ex) || isKafkaProducerException(ex) } private fun isKafkaProducerException(ex: Exception): Boolean { return when { ExceptionUtils.getRootCause(ex) is UnknownProducerIdException -> true ExceptionUtils.getRootCause(ex) is InvalidPidMappingException -> true ex is KafkaException && ex.message == "The producer closed forcefully" -> true else -> false } } private fun isKafkaTransactionalNotFencedException(ex: Exception) = ex is CannotCreateTransactionException && (ex.cause == null || ex.cause !is ProducerFencedException) private fun restartContainer(container: MessageListenerContainer) { log.warn("Stopping and restarting container", kv(MDC_KEY_LOG_EVENT, LOG_EVENT_RESTARTING_CONTAINER_DUE_TO_ERROR)) this.executor.execute { container.stop() messageListenerContainerStartHelper.startContainer(container) log.warn("Restarted container because of not recoverable error for listener", kv(MDC_KEY_LOG_EVENT, LOG_EVENT_CONTAINER_RESTARTED_DUE_TO_ERROR)) } } private fun unwrap(thrownException: Exception): Throwable { return if (thrownException is ListenerExecutionFailedException && thrownException.cause != null) { thrownException.cause!! } else { thrownException } } }
0
Kotlin
0
0
49b517c2197a6fa79a8532225ce294b213f2356a
4,177
kotlin-playground
MIT License
src/test/kotlin/no/nav/eessi/pensjon/prefill/sed/krav/PrefillP2000_AP_LOP_UTLANDTest.kt
navikt
358,172,246
false
null
package no.nav.eessi.pensjon.prefill.sed.krav import io.mockk.every import io.mockk.mockk import no.nav.eessi.pensjon.eux.model.SedType import no.nav.eessi.pensjon.eux.model.sed.Nav import no.nav.eessi.pensjon.eux.model.sed.SED import no.nav.eessi.pensjon.personoppslag.Fodselsnummer import no.nav.eessi.pensjon.personoppslag.FodselsnummerGenerator import no.nav.eessi.pensjon.prefill.ApiRequest import no.nav.eessi.pensjon.prefill.InnhentingService import no.nav.eessi.pensjon.prefill.PersonPDLMock import no.nav.eessi.pensjon.prefill.models.EessiInformasjon import no.nav.eessi.pensjon.prefill.models.InstitusjonItem import no.nav.eessi.pensjon.prefill.models.PensjonCollection import no.nav.eessi.pensjon.prefill.models.PersonDataCollection import no.nav.eessi.pensjon.prefill.models.PrefillDataModel import no.nav.eessi.pensjon.prefill.models.PrefillDataModelMother.initialPrefillDataModel import no.nav.eessi.pensjon.prefill.person.PrefillPDLAdresse import no.nav.eessi.pensjon.prefill.person.PrefillPDLNav import no.nav.eessi.pensjon.prefill.sed.PrefillSEDService import no.nav.eessi.pensjon.prefill.sed.PrefillTestHelper.lesPensjonsdataFraFil import no.nav.eessi.pensjon.prefill.sed.PrefillTestHelper.readJsonResponse import no.nav.eessi.pensjon.utils.mapAnyToJson import no.nav.eessi.pensjon.utils.toJson import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test class PrefillP2000_AP_LOP_UTLANDTest { private val personFnr = FodselsnummerGenerator.generateFnrForTest(68) private val ekteFnr = FodselsnummerGenerator.generateFnrForTest(70) private val pesysSaksnummer = "21644722" private lateinit var prefillData: PrefillDataModel lateinit var prefillSEDService: PrefillSEDService lateinit var persondataCollection: PersonDataCollection lateinit var pensjonCollection: PensjonCollection @BeforeEach fun setup() { persondataCollection = PersonPDLMock.createEnkelFamilie(personFnr, ekteFnr) val prefillNav = PrefillPDLNav( prefillAdresse = mockk<PrefillPDLAdresse> { every { hentLandkode(any()) } returns "NO" every { createPersonAdresse(any()) } returns mockk(relaxed = true) }, institutionid = "NO:noinst002", institutionnavn = "NOINST002, NO INST002, NO" ) val dataFromPEN = lesPensjonsdataFraFil("/pensjonsinformasjon/krav/AP-LOP-21644722.xml") prefillData = initialPrefillDataModel(SedType.P2000, personFnr, penSaksnummer = pesysSaksnummer).apply { partSedAsJson["PersonInfo"] = readJsonResponse("/json/nav/other/person_informasjon_selvb.json") partSedAsJson["P4000"] = readJsonResponse("/json/nav/other/p4000_trygdetid_part.json") } val innhentingService = InnhentingService(mockk(), pensjonsinformasjonService = dataFromPEN) pensjonCollection = innhentingService.hentPensjoninformasjonCollection(prefillData) prefillSEDService = PrefillSEDService(EessiInformasjon(), prefillNav) } @Test fun `forventet korrekt utfylt P2000 alderpensjon med kap4 og 9`() { val P2000 = prefillSEDService.prefill(prefillData, persondataCollection,pensjonCollection) val P2000pensjon = SED( type = SedType.P2000, pensjon = P2000.pensjon, nav = Nav(krav = P2000.nav?.krav) ) assertNotNull(P2000pensjon.nav?.krav) assertEquals("2014-01-13", P2000pensjon.nav?.krav?.dato) } @Test fun `forventet korrekt utfylt P2000 alderpersjon med mockdata fra testfiler`() { val p2000 = prefillSEDService.prefill(prefillData, persondataCollection,pensjonCollection) assertEquals(null, p2000.nav?.barn) assertEquals("", p2000.nav?.bruker?.arbeidsforhold?.get(0)?.yrke) assertEquals("2018-11-11", p2000.nav?.bruker?.arbeidsforhold?.get(0)?.planlagtstartdato) assertEquals("2018-11-13", p2000.nav?.bruker?.arbeidsforhold?.get(0)?.planlagtpensjoneringsdato) assertEquals("07", p2000.nav?.bruker?.arbeidsforhold?.get(0)?.type) assertEquals("foo", p2000.nav?.bruker?.bank?.navn) assertEquals("bar", p2000.nav?.bruker?.bank?.konto?.sepa?.iban) assertEquals("baz", p2000.nav?.bruker?.bank?.konto?.sepa?.swift) assertEquals("ODIN ETTØYE", p2000.nav?.bruker?.person?.fornavn) assertEquals("BALDER", p2000.nav?.bruker?.person?.etternavn) val navfnr1 = Fodselsnummer.fra(p2000.nav?.bruker?.person?.pin?.get(0)?.identifikator!!) assertEquals(68, navfnr1?.getAge()) assertNotNull(p2000.nav?.bruker?.person?.pin) val pinlist = p2000.nav?.bruker?.person?.pin val pinitem = pinlist?.get(0) assertEquals(null, pinitem?.sektor) assertEquals("NOINST002, NO INST002, NO", pinitem?.institusjonsnavn) assertEquals("NO:noinst002", pinitem?.institusjonsid) assertEquals(personFnr, pinitem?.identifikator) assertEquals("THOR-DOPAPIR", p2000.nav?.ektefelle?.person?.fornavn) assertEquals("RAGNAROK", p2000.nav?.ektefelle?.person?.etternavn) val navfnr = Fodselsnummer.fra(p2000.nav?.ektefelle?.person?.pin?.get(0)?.identifikator!!) assertEquals(70, navfnr?.getAge()) } @Test fun `testing av komplett P2000 med utskrift og testing av innsending`() { val P2000 = prefillSEDService.prefill(prefillData, persondataCollection,pensjonCollection) val json = mapAnyToJson(createMockApiRequest("P2000", "P_BUC_01", P2000.toJson())) assertNotNull(json) } private fun createMockApiRequest(sedName: String, buc: String, payload: String): ApiRequest { val items = listOf(InstitusjonItem(country = "NO", institution = "NAVT003")) return ApiRequest( institutions = items, sed = sedName, sakId = "01234567890", euxCaseId = "99191999911", aktoerId = "1000060964183", buc = buc, subjectArea = "Pensjon", payload = payload ) } }
2
Kotlin
0
4
b5d65bb8df9a82e0640e5ba0eaec85e338501802
6,228
eessi-pensjon-prefill
MIT License
app/src/main/java/com/aaron/yespdf/filepicker/IViewAllContract.kt
aaronzzx
206,055,620
false
null
package com.aaron.yespdf.filepicker import androidx.annotation.StringRes import com.aaron.yespdf.common.IModel import com.aaron.yespdf.common.IPresenter import com.aaron.yespdf.common.IView import com.blankj.utilcode.util.SDCardUtils.SDCardInfo import java.io.File import java.util.* import kotlin.collections.ArrayList /** * @author Aaron <EMAIL> */ interface IViewAllModel : IModel { fun listStorage(callback: (List<SDCardInfo>?) -> Unit) fun listFile(path: String?, callback: (List<File>?) -> Unit) fun saveLastPath(path: String?) fun queryLastPath(): String? companion object { const val SP_LAST_PATH = "SP_LAST_PATH" // 使用首选项存放退出之前的路径 } } interface IViewAllView : IView { fun onShowMessage(@StringRes stringId: Int) fun onShowFileList(fileList: List<File>?) fun onShowPath(pathList: List<String>) } abstract class IViewAllPresenter(view: IViewAllView) : IPresenter<IViewAllView>(view) { protected abstract val model: IViewAllModel protected var fileList: MutableList<File> = ArrayList() abstract fun canFinish(): Boolean abstract fun goBack() abstract fun listStorage() abstract fun listFile(path: String?) abstract fun detach() companion object { const val ROOT_PATH = "/storage/emulated" } }
4
Java
7
41
c2428c2984968b2d4feb23e69a4b82379f90d893
1,295
YESPDF
Apache License 2.0
test/org/jetbrains/r/classes/s4/RS4IdentifierCompletionTest.kt
Mervap
368,684,017
true
{"Kotlin": 2985484, "Java": 794911, "R": 35713, "CSS": 23692, "Lex": 14254, "HTML": 6049, "Rebol": 19}
/* * Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package org.jetbrains.r.classes.s4 import org.jetbrains.r.completion.IdentifierBaseCompletionTest class RS4IdentifierCompletionTest : IdentifierBaseCompletionTest() { override fun setUp() { super.setUp() addLibraries() } fun testLibS4Generic() { doTest("sho<caret>", "show") } fun testUserS4Generic() { doTest(""" setGeneric("myShow", "obj", function(obj) standartGeneric("myShow")) setGeneric("myShow1", "obj1", function(obj1) standartGeneric("myShow1")) mySho<caret> """.trimIndent(), "myShow", "myShow1") } }
0
Kotlin
0
0
f6fc7683881127e1b8033786447ebce683659ea3
716
Rplugin
Apache License 2.0
serialization/src/test/kotlin/io/github/airflux/serialization/dsl/reader/array/item/specification/ArrayNullableItemSpecTest.kt
airflux
336,002,943
false
null
/* * Copyright 2021-2022 <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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.airflux.serialization.dsl.reader.array.item.specification import io.github.airflux.serialization.common.JsonErrors import io.github.airflux.serialization.common.dummyIntReader import io.github.airflux.serialization.common.dummyStringReader import io.github.airflux.serialization.common.shouldBeFailure import io.github.airflux.serialization.common.shouldBeSuccess import io.github.airflux.serialization.core.location.Location import io.github.airflux.serialization.core.reader.env.ReaderEnv import io.github.airflux.serialization.core.reader.error.InvalidTypeErrorBuilder import io.github.airflux.serialization.core.reader.result.ReaderResult import io.github.airflux.serialization.core.value.BooleanNode import io.github.airflux.serialization.core.value.NullNode import io.github.airflux.serialization.core.value.NumericNode import io.github.airflux.serialization.core.value.StringNode import io.github.airflux.serialization.core.value.valueOf import io.github.airflux.serialization.std.validator.condition.applyIfNotNull import io.github.airflux.serialization.std.validator.string.IsNotEmptyStringValidator import io.github.airflux.serialization.std.validator.string.StdStringValidator import io.kotest.core.spec.style.FreeSpec internal class ArrayNullableItemSpecTest : FreeSpec() { companion object { private const val ID_VALUE_AS_UUID = "91a10692-7430-4d58-a465-633d45ea2f4b" private const val ID_VALUE_AS_INT = "10" private val ENV = ReaderEnv(EB(), Unit) private val CONTEXT = Unit private val LOCATION = Location.empty private val StringReader = dummyStringReader<EB, Unit, Unit>() private val IntReader = dummyIntReader<EB, Unit, Unit>() } init { "The ArrayItemSpec#Nullable type" - { "when creating the instance of the spec" - { val spec = nullable(reader = StringReader) "when the reader has read an item" - { "when the reader has successfully read" - { "if the property value is not the null type" - { val source = StringNode(ID_VALUE_AS_UUID) val result = spec.reader.read(ENV, CONTEXT, LOCATION, source) "then the not-null value should be returned" { result shouldBeSuccess ReaderResult.Success( location = LOCATION, value = ID_VALUE_AS_UUID ) } } "if the property value is the null type" - { val source = NullNode val result = spec.reader.read(ENV, CONTEXT, LOCATION, source) "then the null value should be returned" { result shouldBeSuccess ReaderResult.Success( location = LOCATION, value = null ) } } } "when a read error occurred" - { val source = NumericNode.Integer.valueOf(10) val result = spec.reader.read(ENV, CONTEXT, LOCATION, source) "then should be returned a read error" { result shouldBeFailure ReaderResult.Failure( location = LOCATION, error = JsonErrors.InvalidType( expected = listOf(StringNode.nameOfType), actual = NumericNode.Integer.nameOfType ) ) } } } } "when the validator was added to the spec" - { val spec = nullable(reader = StringReader) val specWithValidator = spec.validation(StdStringValidator.isNotEmpty<EB, Unit, Unit>().applyIfNotNull()) "when the reader has successfully read" - { "then a value should be returned if validation is a success" { val source = StringNode(ID_VALUE_AS_UUID) val result = specWithValidator.reader.read(ENV, CONTEXT, LOCATION, source) result shouldBeSuccess ReaderResult.Success( location = LOCATION, value = ID_VALUE_AS_UUID ) } "then a validation error should be returned if validation is a failure" { val source = StringNode("") val result = specWithValidator.reader.read(ENV, CONTEXT, LOCATION, source) result shouldBeFailure ReaderResult.Failure( location = LOCATION, error = JsonErrors.Validation.Strings.IsEmpty ) } } "when an error occurs while reading" - { "then should be returned a read error" { val source = NumericNode.Integer.valueOf(10) val result = specWithValidator.reader.read(ENV, CONTEXT, LOCATION, source) result shouldBeFailure ReaderResult.Failure( location = LOCATION, error = JsonErrors.InvalidType( expected = listOf(StringNode.nameOfType), actual = NumericNode.Integer.nameOfType ) ) } } } "when an alternative spec was added" - { val spec = nullable(reader = StringReader) val alt = nullable(reader = IntReader.map { it.toString() }) val specWithAlternative = spec or alt "when the main reader has successfully read" - { val source = StringNode(ID_VALUE_AS_UUID) val result = specWithAlternative.reader.read(ENV, CONTEXT, LOCATION, source) "then a value should be returned" { result shouldBeSuccess ReaderResult.Success( location = LOCATION, value = ID_VALUE_AS_UUID ) } } "when the main reader has failure read" - { val source = NumericNode.Integer.valueOrNullOf(ID_VALUE_AS_INT)!! val result = specWithAlternative.reader.read(ENV, CONTEXT, LOCATION, source) "then a value should be returned from the alternative reader" { result shouldBeSuccess ReaderResult.Success( location = LOCATION, value = ID_VALUE_AS_INT ) } } "when the alternative reader has failure read" - { val source = BooleanNode.True val result = specWithAlternative.reader.read(ENV, CONTEXT, LOCATION, source) "then should be returned all read errors" { result shouldBeFailure listOf( ReaderResult.Failure.Cause( location = LOCATION, error = JsonErrors.InvalidType( expected = listOf(StringNode.nameOfType), actual = BooleanNode.nameOfType ) ), ReaderResult.Failure.Cause( location = LOCATION, error = JsonErrors.InvalidType( expected = listOf(NumericNode.Integer.nameOfType), actual = BooleanNode.nameOfType ) ) ) } } } } } internal class EB : InvalidTypeErrorBuilder, IsNotEmptyStringValidator.ErrorBuilder { override fun invalidTypeError(expected: Iterable<String>, actual: String): ReaderResult.Error = JsonErrors.InvalidType(expected = expected, actual = actual) override fun isNotEmptyStringError(): ReaderResult.Error = JsonErrors.Validation.Strings.IsEmpty } }
0
Kotlin
3
3
9dfcfe4ec288e27f150beeef12dff45f131d0805
9,530
airflux-serialization
Apache License 2.0
kgl-vulkan/src/nativeMain/kotlin/com/kgl/vulkan/structs/FormatProperties.kt
BrunoSilvaFreire
223,607,080
true
{"Kotlin": 1880529, "C": 10037}
/** * Copyright [2019] [<NAME>] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kgl.vulkan.structs import com.kgl.vulkan.enums.FormatFeature import cvulkan.VkFormatProperties fun FormatProperties.Companion.from(ptr: VkFormatProperties): FormatProperties = FormatProperties( FormatFeature.fromMultiple(ptr.linearTilingFeatures), FormatFeature.fromMultiple(ptr.optimalTilingFeatures), FormatFeature.fromMultiple(ptr.bufferFeatures) )
0
null
0
0
74de23862c29404e7751490331cbafbef310bd63
963
kgl
Apache License 2.0
lib/src/main/kotlin/com/aballano/mnemonik/Memoize.kt
aballano
85,889,713
false
null
package com.aballano.mnemonik import com.aballano.mnemonik.tuples.Quadruple import com.aballano.mnemonik.tuples.Quintuple import java.util.concurrent.ConcurrentHashMap import java.util.concurrent.ConcurrentMap private const val DEFAULT_CAPACITY = 256 /** * Functions must be pure for the caching technique to work. * * A pure function is one that has no side effects: it references no other mutable class fields, * doesn't set any values other than the return value, and relies only on the parameters for input. * In other words, you can reuse cached results successfully only if the function reliably returns the * same values for a given set of parameters. * * Also, when passing or returning Objects, make sure to implement both equals and hashcode for the cache to work properly. */ fun <A, R> ((A) -> R).memoize( initialCapacity: Int = DEFAULT_CAPACITY ): (A) -> R = memoize(HashMap(initialCapacity)) fun <A, R> ((A) -> R).memoize( cache: MutableMap<A, R> ): (A) -> R = { a: A -> cache.getOrPut(a) { this(a) } } fun <A, B, R> ((A, B) -> R).memoize( initialCapacity: Int = DEFAULT_CAPACITY ): (A, B) -> R = memoize(HashMap(initialCapacity)) fun <A, B, R> ((A, B) -> R).memoize( cache: MutableMap<Pair<A, B>, R> ): (A, B) -> R = { a: A, b: B -> cache.getOrPut(a to b) { this(a, b) } } fun <A, B, C, R> ((A, B, C) -> R).memoize( initialCapacity: Int = DEFAULT_CAPACITY ): (A, B, C) -> R = memoize(HashMap(initialCapacity)) fun <A, B, C, R> ((A, B, C) -> R).memoize( cache: MutableMap<Triple<A, B, C>, R> ): (A, B, C) -> R = { a: A, b: B, c: C -> cache.getOrPut(Triple(a, b, c)) { this(a, b, c) } } fun <A, B, C, D, R> ((A, B, C, D) -> R).memoize( initialCapacity: Int = DEFAULT_CAPACITY ): (A, B, C, D) -> R = memoize(HashMap(initialCapacity)) fun <A, B, C, D, R> ((A, B, C, D) -> R).memoize( cache: MutableMap<Quadruple<A, B, C, D>, R> ): (A, B, C, D) -> R = { a: A, b: B, c: C, d: D -> cache.getOrPut(Quadruple(a, b, c, d)) { this(a, b, c, d) } } fun <A, B, C, D, E, R> ((A, B, C, D, E) -> R).memoize( initialCapacity: Int = DEFAULT_CAPACITY ): (A, B, C, D, E) -> R = memoize(HashMap(initialCapacity)) fun <A, B, C, D, E, R> ((A, B, C, D, E) -> R).memoize( cache: MutableMap<Quintuple<A, B, C, D, E>, R> ): (A, B, C, D, E) -> R = { a: A, b: B, c: C, d: D, e: E -> cache.getOrPut(Quintuple(a, b, c, d, e)) { this(a, b, c, d, e) } } fun <A, R> (suspend (A) -> R).memoizeSuspend( initialCapacity: Int = DEFAULT_CAPACITY ): suspend (A) -> R = memoizeSuspend(ConcurrentHashMap(initialCapacity)) fun <A, R> (suspend (A) -> R).memoizeSuspend( cache: ConcurrentMap<A, R> ): suspend (A) -> R = { a: A -> cache.getOrPut(a) { this(a) } } fun <A, B, R> (suspend (A, B) -> R).memoizeSuspend( initialCapacity: Int = DEFAULT_CAPACITY ): suspend (A, B) -> R = memoizeSuspend(ConcurrentHashMap(initialCapacity)) fun <A, B, R> (suspend (A, B) -> R).memoizeSuspend( cache: ConcurrentMap<Pair<A, B>, R> ): suspend (A, B) -> R = { a: A, b: B -> cache.getOrPut(a to b) { this(a, b) } } fun <A, B, C, R> (suspend (A, B, C) -> R).memoizeSuspend( initialCapacity: Int = DEFAULT_CAPACITY ): suspend (A, B, C) -> R = memoizeSuspend(ConcurrentHashMap(initialCapacity)) fun <A, B, C, R> (suspend (A, B, C) -> R).memoizeSuspend( cache: ConcurrentMap<Triple<A, B, C>, R> ): suspend (A, B, C) -> R = { a: A, b: B, c: C -> cache.getOrPut(Triple(a, b, c)) { this(a, b, c) } } fun <A, B, C, D, R> (suspend (A, B, C, D) -> R).memoizeSuspend( initialCapacity: Int = DEFAULT_CAPACITY ): suspend (A, B, C, D) -> R = memoizeSuspend(ConcurrentHashMap(initialCapacity)) fun <A, B, C, D, R> (suspend (A, B, C, D) -> R).memoizeSuspend( cache: ConcurrentMap<Quadruple<A, B, C, D>, R> ): suspend (A, B, C, D) -> R = { a: A, b: B, c: C, d: D -> cache.getOrPut(Quadruple(a, b, c, d)) { this(a, b, c, d) } } fun <A, B, C, D, E, R> (suspend (A, B, C, D, E) -> R).memoizeSuspend( initialCapacity: Int = DEFAULT_CAPACITY ): suspend (A, B, C, D, E) -> R = memoizeSuspend(ConcurrentHashMap(initialCapacity)) fun <A, B, C, D, E, R> (suspend (A, B, C, D, E) -> R).memoizeSuspend( cache: ConcurrentMap<Quintuple<A, B, C, D, E>, R> ): suspend (A, B, C, D, E) -> R = { a: A, b: B, c: C, d: D, e: E -> cache.getOrPut(Quintuple(a, b, c, d, e)) { this(a, b, c, d, e) } }
0
Kotlin
2
42
943d4b0a59b2ee273bda7fc64c67c2bb10c03ebf
4,366
mnemonik
Apache License 2.0
app/src/main/java/com/ahmedtikiwa/fxapp/MainActivity.kt
akitikkx
371,123,034
false
null
package com.ahmedtikiwa.fxapp import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import androidx.navigation.findNavController import androidx.navigation.fragment.NavHostFragment import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.ahmedtikiwa.fxapp.databinding.ActivityMainBinding import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) val navHostFragment = supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment val navController = navHostFragment.navController val appBarConfiguration = AppBarConfiguration.Builder( R.id.converterFragment, R.id.graphFragment ).build() setupActionBarWithNavController(navController, appBarConfiguration) binding.bottomNavigation.setupWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp() || super.onSupportNavigateUp() } }
0
Kotlin
0
0
a782a5a5f6960b3926e670faa37d8f9b5f4355e1
1,478
fx-app
MIT License
src/test/kotlin/no/nav/familie/ef/sak/felles/util/FeatureToggleTestUtil.kt
navikt
206,805,010
false
{"Kotlin": 3922371, "Gherkin": 163948, "Dockerfile": 187}
package no.nav.familie.ef.sak.felles.util import io.mockk.every import io.mockk.mockk import no.nav.familie.ef.sak.infrastruktur.featuretoggle.FeatureToggleService import no.nav.familie.ef.sak.infrastruktur.featuretoggle.Toggle fun mockFeatureToggleService(enabled: Boolean = true): FeatureToggleService { val mockk = mockk<FeatureToggleService>() every { mockk.isEnabled(any()) } returns enabled every { mockk.isEnabled(Toggle.SATSENDRING_BRUK_IKKE_VEDTATT_MAXSATS) } returns false return mockk }
5
Kotlin
2
0
28d379f72763347782d5afd01fa7639caff7b011
516
familie-ef-sak
MIT License
app/src/main/java/com/delishstudio/delish/model/UserManager.kt
evangelionmanuhutu
737,305,479
false
null
package com.delishstudio.delish.model import com.delishstudio.delish.system.DatabaseStrRef import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener class UserManager { companion object { var Main: UserModel = UserModel("", "", "", "") fun Update() { val firebaseRef = FirebaseDatabase.getInstance().getReference(DatabaseStrRef.USERS) val query = firebaseRef.orderByChild(DatabaseStrRef.EMAIL).equalTo(Main.email) query.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { for (userSnapshot in dataSnapshot.children) { val userKey = userSnapshot.key userKey?.let { firebaseRef.child(it).setValue(Main) } } } override fun onCancelled(databaseError: DatabaseError) { } }) } fun Available(callback: (Boolean) -> Unit) = if (Main.userName!!.isEmpty()) { val email = FirebaseAuth.getInstance().currentUser!!.email.toString() val userListRef = FirebaseDatabase.getInstance().getReference(DatabaseStrRef.USERS) val query = userListRef.orderByChild(DatabaseStrRef.EMAIL).equalTo(email) query.addListenerForSingleValueEvent(object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { var userFound = false for (userSnapshot in dataSnapshot.children) { val user = userSnapshot.getValue(UserModel::class.java) if (user != null) { Main = user val addressListRef = userSnapshot.child("AddressList") val addressList = ArrayList<AddressModel>() addressListRef.children.forEach { addressSnapshot -> val address = addressSnapshot.getValue(AddressModel::class.java) address?.let { addressList.add(it) } } Main.addressList = addressList userFound = true } } callback(userFound) } override fun onCancelled(error: DatabaseError) = callback(false) }) } else callback(true) } }
0
null
0
1
c2dd1febdb285d96f9f8d472e20580426f42bb73
2,870
Delish
Apache License 2.0
app/src/main/java/com/socketmobile/stockcount/helper/PreferenceHelper.kt
hightop0924
638,576,997
false
null
/** Copyright © 2018 Socket Mobile, Inc. */ package com.socketmobile.stockcount.helper import android.content.Context import android.preference.PreferenceManager const val SHOW_INSTRUCTION_KEY = "HaveToShowInstruction" const val AUTO_ADD_QUANTITY_KEY = "AutoAddQuantity" const val D600_SUPPORT_KEY = "D600Support" const val DELINEATOR_COMMA_SET_KEY = "DelineatorCommaSet" const val DEFAULT_QUANTITY_KEY = "DefaultQuantity" const val NEW_LINE_KEY = "NewLineForNewScan" const val VIBRATION_KEY = "VibrationOnScan" const val SCAN_DATE_KEY = "ScanDate" const val SCAN_COUNT_KEY = "ScanCount" const val CONSOLIDATING_COUNTS = "ConsolidatingCounts" const val DEFAULT_AUTO_ADD_QUANTITY = true const val DEFAULT_D600_SUPPORT = false const val DEFAULT_DELINEATOR_COMMA_SET = true const val DEFAULT_QUANTITY = 1 const val DEFAULT_NEW_LINE = true const val DEFAULT_VIBRATION_ON_SCAN = false const val DEFAULT_SCAN_DATE = "" const val DEFAULT_SCAN_COUNT = 0 const val DEFAULT_CONSOLIDATING_COUNTS = true fun autoAddQuantity(c: Context): Boolean { val sp = PreferenceManager.getDefaultSharedPreferences(c) return sp.getBoolean(AUTO_ADD_QUANTITY_KEY, DEFAULT_AUTO_ADD_QUANTITY) } fun isDelineatorComma(c: Context): Boolean { return PreferenceManager.getDefaultSharedPreferences(c).getBoolean(DELINEATOR_COMMA_SET_KEY, DEFAULT_DELINEATOR_COMMA_SET) } fun getDefaultQuantity(c: Context): Int { return PreferenceManager.getDefaultSharedPreferences(c).getInt(DEFAULT_QUANTITY_KEY, DEFAULT_QUANTITY) } fun isAddNewLine(c: Context): Boolean { return PreferenceManager.getDefaultSharedPreferences(c).getBoolean(NEW_LINE_KEY, DEFAULT_NEW_LINE) } fun isVibrationOnScan(c: Context): Boolean { return PreferenceManager.getDefaultSharedPreferences(c).getBoolean(VIBRATION_KEY, DEFAULT_VIBRATION_ON_SCAN) } fun getLineForBarcode(c: Context, barcode: String? = null): String { var retValue = if (barcode.isNullOrEmpty()) "Invalid barcode" else barcode return retValue }
0
Kotlin
0
0
b2dfabf0ace9c802880732ecb608e03adb61f265
1,985
code_scanner_demo
Apache License 2.0
core/src/com/elementalg/minigame/ILeaderboard.kt
simple0x47
294,504,550
false
null
package com.elementalg.minigame interface ILeaderboard { fun addScore(score: Float) fun getHighScore(): Float fun getWorldHighScore(): Float fun showLeaderboard() }
0
Kotlin
0
0
2a5580033c278905a5b1665afe6b34a72993602b
182
drop-the-finger
MIT License
src/test/kotlin/dev/monosoul/jooq/container/GenericDatabaseContainerTest.kt
monosoul
497,003,599
false
null
package dev.monosoul.jooq.container import dev.monosoul.jooq.settings.Database import dev.monosoul.jooq.settings.Image import io.mockk.every import io.mockk.impl.annotations.MockK import io.mockk.junit5.MockKExtension import io.mockk.mockk import io.mockk.verify import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.DynamicTest.dynamicTest import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestFactory import org.junit.jupiter.api.extension.ExtendWith import org.testcontainers.containers.JdbcDatabaseContainer.NoDriverFoundException import strikt.api.expectThat import strikt.api.expectThrows import strikt.assertions.isEqualTo import strikt.assertions.message import java.sql.Driver import java.util.concurrent.CountDownLatch import java.util.concurrent.Executors import kotlin.streams.asStream @ExtendWith(MockKExtension::class) class GenericDatabaseContainerTest { private lateinit var image: Image private lateinit var database: Database.Internal @MockK private lateinit var jdbcAwareClassLoader: ClassLoader private lateinit var container: GenericDatabaseContainer @BeforeEach fun setUp() { database = Database.Internal() image = Image() container = GenericDatabaseContainer( image = image, database = database, jdbcAwareClassLoader = jdbcAwareClassLoader, ) } @Test fun `should only load driver class once`() { // given every { jdbcAwareClassLoader.loadClass(any()) } returns TestDriver::class.java // when container.jdbcDriverInstance container.jdbcDriverInstance // then verify(exactly = 1) { jdbcAwareClassLoader.loadClass(database.jdbc.driverClassName) } } @TestFactory fun `should rethrow expected exceptions as no driver found exception`() = sequenceOf( InstantiationException(), IllegalAccessException(), ClassNotFoundException(), ).map { exception -> dynamicTest("should rethrow ${exception::class.simpleName} as no driver found exception") { // given every { jdbcAwareClassLoader.loadClass(any()) } throws exception // when && then expectThrows<NoDriverFoundException> { container.jdbcDriverInstance }.message isEqualTo "Could not get Driver" } }.asStream() @Test fun `should rethrow unexpected exceptions as is`() { // given val unexpectedException = RuntimeException() every { jdbcAwareClassLoader.loadClass(any()) } throws unexpectedException // when && then expectThrows<RuntimeException> { container.jdbcDriverInstance } isEqualTo unexpectedException } @Test fun `should prevent asynchronous driver instantiation`() { // given val startLatch = CountDownLatch(2) val driverGetLatch = CountDownLatch(2) val threadPool = Executors.newFixedThreadPool(2) every { jdbcAwareClassLoader.loadClass(any()) } answers { driverGetLatch.countDown() TestDriver::class.java } // when val futures = (1..2).map { threadPool.submit { startLatch.countDown() container.jdbcDriverInstance } } driverGetLatch.countDown() futures.forEach { it.get() } threadPool.shutdown() // then verify(exactly = 1) { jdbcAwareClassLoader.loadClass(database.jdbc.driverClassName) } } @Test fun `should delegate getDatabaseName method to the database object as is`() { // when val actual = container.databaseName // then expectThat(actual) isEqualTo database.name } @Test fun `should delegate getDriverClassName method to the jdbc object as is`() { // when val actual = container.driverClassName // then expectThat(actual) isEqualTo database.jdbc.driverClassName } @Test fun `should delegate getUsername method to the database object as is`() { // when val actual = container.username // then expectThat(actual) isEqualTo database.username } @Test fun `should delegate getPassword method to the database object as is`() { // when val actual = container.password // then expectThat(actual) isEqualTo database.password } private class TestDriver(val mockDriver: Driver = mockk()) : Driver by mockDriver }
4
Kotlin
5
9
f3cc5cbaf77e3a2a22c767fee75de4f809cea477
4,755
jooq-gradle-plugin
Apache License 2.0
language-server/src/test/kotlin/tools/samt/ls/SymbolsTest.kt
samtkit
602,288,830
false
{"Kotlin": 612474, "Batchfile": 1420, "Shell": 1226}
package tools.samt.ls import org.eclipse.lsp4j.DocumentSymbol import org.eclipse.lsp4j.Position import org.eclipse.lsp4j.Range import org.eclipse.lsp4j.SymbolKind import tools.samt.common.SourceFile import kotlin.test.Test import kotlin.test.assertEquals class SymbolsTest { @Test fun `getSymbols returns correct symbols`() { val source = """ package foo.bar enum Foo { A } record Bar { a: Int } service Baz { a() } provide BazProvider { implements Baz transport http } consume BazProvider { uses Baz } """.trimIndent() val sourceFile = SourceFile("file:///tmp/test/src/model.samt".toPathUri(), source) val fileInfo = parseFile(sourceFile) val symbols = fileInfo.fileNode?.getSymbols() assertEquals( listOf( DocumentSymbol( "foo.bar", SymbolKind.Package, Range(Position(0, 0), Position(0, 15)), Range(Position(0, 8), Position(0, 15)) ), DocumentSymbol( "Foo", SymbolKind.Enum, Range(Position(1, 0), Position(3, 1)), Range(Position(1, 5), Position(1, 8)) ).apply { children = listOf( DocumentSymbol( "A", SymbolKind.EnumMember, Range(Position(2, 4), Position(2, 5)), Range(Position(2, 4), Position(2, 5)) ) ) }, DocumentSymbol( "Bar", SymbolKind.Struct, Range(Position(4, 0), Position(6, 1)), Range(Position(4, 7), Position(4, 10)) ).apply { children = listOf( DocumentSymbol( "a", SymbolKind.Property, Range(Position(5, 4), Position(5, 10)), Range(Position(5, 4), Position(5, 5)) ) ) }, DocumentSymbol( "Baz", SymbolKind.Interface, Range(Position(7, 0), Position(9, 1)), Range(Position(7, 8), Position(7, 11)) ).apply { children = listOf( DocumentSymbol( "a", SymbolKind.Method, Range(Position(8, 4), Position(8, 7)), Range(Position(8, 4), Position(8, 5)) ) ) }, DocumentSymbol( "BazProvider", SymbolKind.Class, Range(Position(10, 0), Position(14, 1)), Range(Position(10, 8), Position(10, 19)) ).apply { children = emptyList() }, DocumentSymbol( "Consumer for BazProvider", SymbolKind.Class, Range(Position(15, 0), Position(17, 1)), Range(Position(15, 8), Position(15, 19)) ) ), symbols ) } }
0
Kotlin
0
8
fbb3ed090f5c3f72a7330a4dd687345c67d6e786
3,665
core
MIT License
store/src/commonMain/kotlin/org/mobilenativefoundation/store/store5/StoreBuilder.kt
MobileNativeFoundation
226,169,258
false
null
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mobilenativefoundation.store.store5 import kotlinx.coroutines.CoroutineScope import org.mobilenativefoundation.store.cache5.Cache import org.mobilenativefoundation.store.store5.impl.storeBuilderFromFetcher import org.mobilenativefoundation.store.store5.impl.storeBuilderFromFetcherAndSourceOfTruth import org.mobilenativefoundation.store.store5.impl.storeBuilderFromFetcherSourceOfTruthAndMemoryCache import org.mobilenativefoundation.store.store5.impl.storeBuilderFromFetcherSourceOfTruthMemoryCacheAndConverter /** * Main entry point for creating a [Store]. */ interface StoreBuilder<Key : Any, Output : Any> { fun build(): Store<Key, Output> fun <Network : Any, Local : Any> toMutableStoreBuilder(converter: Converter<Network, Local, Output>): MutableStoreBuilder<Key, Network, Local, Output> /** * A store multicasts same [Output] value to many consumers (Similar to RxJava.share()), by default * [Store] will open a global scope for management of shared responses, if instead you'd like to control * the scope that sharing/multicasting happens in you can pass a @param [scope] * * @param scope - scope to use for sharing */ fun scope(scope: CoroutineScope): StoreBuilder<Key, Output> /** * controls eviction policy for a store cache, use [MemoryPolicy.MemoryPolicyBuilder] to configure a TTL * or size based eviction * Example: MemoryPolicy.builder().setExpireAfterWrite(10.seconds).build() */ fun cachePolicy(memoryPolicy: MemoryPolicy<Key, Output>?): StoreBuilder<Key, Output> /** * by default a Store caches in memory with a default policy of max items = 100 */ fun disableCache(): StoreBuilder<Key, Output> fun validator(validator: Validator<Output>): StoreBuilder<Key, Output> companion object { /** * Creates a new [StoreBuilder] from a [Fetcher]. * * @param fetcher a [Fetcher] flow of network records. */ fun <Key : Any, Input : Any> from( fetcher: Fetcher<Key, Input>, ): StoreBuilder<Key, Input> = storeBuilderFromFetcher(fetcher = fetcher) /** * Creates a new [StoreBuilder] from a [Fetcher] and a [SourceOfTruth]. * * @param fetcher a function for fetching a flow of network records. * @param sourceOfTruth a [SourceOfTruth] for the store. */ fun <Key : Any, Input : Any, Output : Any> from( fetcher: Fetcher<Key, Input>, sourceOfTruth: SourceOfTruth<Key, Input, Output> ): StoreBuilder<Key, Output> = storeBuilderFromFetcherAndSourceOfTruth(fetcher = fetcher, sourceOfTruth = sourceOfTruth) fun <Key : Any, Network : Any, Output : Any> from( fetcher: Fetcher<Key, Network>, sourceOfTruth: SourceOfTruth<Key, Network, Output>, memoryCache: Cache<Key, Output>, ): StoreBuilder<Key, Output> = storeBuilderFromFetcherSourceOfTruthAndMemoryCache( fetcher, sourceOfTruth, memoryCache ) fun <Key : Any, Network : Any, Output : Any, Local : Any> from( fetcher: Fetcher<Key, Network>, sourceOfTruth: SourceOfTruth<Key, Local, Output>, converter: Converter<Network, Local, Output> ): StoreBuilder<Key, Output> = storeBuilderFromFetcherSourceOfTruthMemoryCacheAndConverter( fetcher, sourceOfTruth, null, converter ) fun <Key : Any, Network : Any, Output : Any, Local : Any> from( fetcher: Fetcher<Key, Network>, sourceOfTruth: SourceOfTruth<Key, Local, Output>, memoryCache: Cache<Key, Output>, converter: Converter<Network, Local, Output> ): StoreBuilder<Key, Output> = storeBuilderFromFetcherSourceOfTruthMemoryCacheAndConverter( fetcher, sourceOfTruth, memoryCache, converter ) } }
57
null
202
3,174
f9072fc59cc8bfe95cfe008cc8a9ce999301b242
4,624
Store
Apache License 2.0
example/shared/src/androidMain/kotlin/com/splendo/kaluga/example/shared/di/DependencyInjection.kt
splendo
191,371,940
false
{"Kotlin": 6494822, "Swift": 172024, "Shell": 1514}
/* Copyright 2022 Splendo Consulting B.V. The Netherlands Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @file:JvmName("AndroidDependencyInjection") package com.splendo.kaluga.example.shared.di import com.splendo.kaluga.alerts.AlertPresenter import com.splendo.kaluga.architecture.navigation.Navigator import com.splendo.kaluga.base.ApplicationHolder import com.splendo.kaluga.bluetooth.BluetoothBuilder import com.splendo.kaluga.datetimepicker.DateTimePickerPresenter import com.splendo.kaluga.example.shared.viewmodel.ExampleTabNavigation import com.splendo.kaluga.example.shared.viewmodel.ExampleViewModel import com.splendo.kaluga.example.shared.viewmodel.alert.AlertViewModel import com.splendo.kaluga.example.shared.viewmodel.architecture.ArchitectureDetailsNavigationAction import com.splendo.kaluga.example.shared.viewmodel.architecture.ArchitectureDetailsViewModel import com.splendo.kaluga.example.shared.viewmodel.architecture.ArchitectureNavigationAction import com.splendo.kaluga.example.shared.viewmodel.architecture.ArchitectureViewModel import com.splendo.kaluga.example.shared.viewmodel.architecture.BottomSheetNavigation import com.splendo.kaluga.example.shared.viewmodel.architecture.BottomSheetSubPageNavigation import com.splendo.kaluga.example.shared.viewmodel.architecture.BottomSheetSubPageViewModel import com.splendo.kaluga.example.shared.viewmodel.architecture.BottomSheetViewModel import com.splendo.kaluga.example.shared.viewmodel.architecture.InputDetails import com.splendo.kaluga.example.shared.viewmodel.beacons.BeaconsListViewModel import com.splendo.kaluga.example.shared.viewmodel.bluetooth.BluetoothDeviceDetailViewModel import com.splendo.kaluga.example.shared.viewmodel.bluetooth.BluetoothListViewModel import com.splendo.kaluga.example.shared.viewmodel.bluetooth.DeviceDetails import com.splendo.kaluga.example.shared.viewmodel.compose.ComposeOrXMLNavigationAction import com.splendo.kaluga.example.shared.viewmodel.compose.ComposeOrXMLSelectionViewModel import com.splendo.kaluga.example.shared.viewmodel.datetime.TimerViewModel import com.splendo.kaluga.example.shared.viewmodel.datetimepicker.DateTimePickerViewModel import com.splendo.kaluga.example.shared.viewmodel.featureList.FeatureListNavigationAction import com.splendo.kaluga.example.shared.viewmodel.featureList.FeatureListViewModel import com.splendo.kaluga.example.shared.viewmodel.hud.HudViewModel import com.splendo.kaluga.example.shared.viewmodel.info.InfoNavigation import com.splendo.kaluga.example.shared.viewmodel.info.InfoViewModel import com.splendo.kaluga.example.shared.viewmodel.link.BrowserNavigationActions import com.splendo.kaluga.example.shared.viewmodel.link.LinksViewModel import com.splendo.kaluga.example.shared.viewmodel.location.LocationViewModel import com.splendo.kaluga.example.shared.viewmodel.media.MediaNavigationAction import com.splendo.kaluga.example.shared.viewmodel.media.MediaViewModel import com.splendo.kaluga.example.shared.viewmodel.permissions.NotificationPermissionViewModel import com.splendo.kaluga.example.shared.viewmodel.permissions.PermissionViewModel import com.splendo.kaluga.example.shared.viewmodel.permissions.PermissionsListNavigationAction import com.splendo.kaluga.example.shared.viewmodel.permissions.PermissionsListViewModel import com.splendo.kaluga.example.shared.viewmodel.resources.ButtonViewModel import com.splendo.kaluga.example.shared.viewmodel.resources.ColorViewModel import com.splendo.kaluga.example.shared.viewmodel.resources.ImagesViewModel import com.splendo.kaluga.example.shared.viewmodel.resources.LabelViewModel import com.splendo.kaluga.example.shared.viewmodel.resources.ResourcesListNavigationAction import com.splendo.kaluga.example.shared.viewmodel.resources.ResourcesListViewModel import com.splendo.kaluga.example.shared.viewmodel.scientific.ScientificViewModel import com.splendo.kaluga.example.shared.viewmodel.scientific.ScientificConverterNavigationAction import com.splendo.kaluga.example.shared.viewmodel.scientific.ScientificConverterViewModel import com.splendo.kaluga.example.shared.viewmodel.scientific.ScientificNavigationAction import com.splendo.kaluga.example.shared.viewmodel.scientific.ScientificUnitSelectionAction import com.splendo.kaluga.example.shared.viewmodel.scientific.ScientificUnitSelectionViewModel import com.splendo.kaluga.example.shared.viewmodel.system.SystemNavigationActions import com.splendo.kaluga.example.shared.viewmodel.system.SystemViewModel import com.splendo.kaluga.example.shared.viewmodel.system.network.NetworkViewModel import com.splendo.kaluga.hud.HUD import com.splendo.kaluga.links.DefaultLinksManager import com.splendo.kaluga.location.LocationStateRepoBuilder import com.splendo.kaluga.location.DefaultLocationManager import com.splendo.kaluga.location.GoogleLocationProvider import com.splendo.kaluga.media.DefaultMediaManager import com.splendo.kaluga.media.MediaSurfaceProvider import com.splendo.kaluga.permissions.base.Permission import com.splendo.kaluga.permissions.location.LocationPermission import com.splendo.kaluga.resources.StyledStringBuilder import com.splendo.kaluga.review.ReviewManager import com.splendo.kaluga.scientific.PhysicalQuantity import com.splendo.kaluga.system.network.state.NetworkStateRepoBuilder import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.core.module.Module import org.koin.dsl.KoinAppDeclaration import org.koin.dsl.module internal val androidModule = module { viewModel { (navigator: Navigator<ExampleTabNavigation>) -> ExampleViewModel(navigator) } viewModel { (navigator: Navigator<FeatureListNavigationAction>) -> FeatureListViewModel(navigator) } viewModel { (navigator: Navigator<InfoNavigation<*>>) -> InfoViewModel( ReviewManager.Builder(), navigator, ) } viewModel { (navigator: Navigator<ComposeOrXMLNavigationAction>) -> ComposeOrXMLSelectionViewModel(navigator) } viewModel { (navigator: Navigator<PermissionsListNavigationAction>) -> PermissionsListViewModel(navigator) } viewModel { (permission: Permission) -> PermissionViewModel(permission) } viewModel { (permission: LocationPermission) -> LocationViewModel(permission) } viewModel { NotificationPermissionViewModel() } viewModel { (navigator: Navigator<ArchitectureNavigationAction<*>>) -> ArchitectureViewModel(navigator) } viewModel { (initialDetail: InputDetails, navigator: Navigator<ArchitectureDetailsNavigationAction<*>>) -> ArchitectureDetailsViewModel( initialDetail, navigator, ) } viewModel { (navigator: Navigator<BottomSheetNavigation>) -> BottomSheetViewModel(navigator) } viewModel { (navigator: Navigator<BottomSheetSubPageNavigation>) -> BottomSheetSubPageViewModel(navigator) } viewModel { AlertViewModel(AlertPresenter.Builder()) } viewModel { TimerViewModel() } viewModel { DateTimePickerViewModel(DateTimePickerPresenter.Builder()) } viewModel { HudViewModel(HUD.Builder()) } viewModel { (navigator: Navigator<BrowserNavigationActions<*>>) -> LinksViewModel( DefaultLinksManager.Builder(), AlertPresenter.Builder(), navigator, ) } viewModel { (mediaSurfaceProvider: MediaSurfaceProvider, navigator: Navigator<MediaNavigationAction>) -> MediaViewModel(mediaSurfaceProvider, DefaultMediaManager.Builder(), AlertPresenter.Builder(), navigator) } viewModel { (navigator: Navigator<SystemNavigationActions>) -> SystemViewModel( navigator, ) } viewModel { NetworkViewModel(NetworkStateRepoBuilder()) } viewModel { (navigator: Navigator<DeviceDetails>) -> BluetoothListViewModel(AlertPresenter.Builder(), navigator) } viewModel { (identifier: com.splendo.kaluga.bluetooth.device.Identifier) -> BluetoothDeviceDetailViewModel(identifier) } viewModel { BeaconsListViewModel() } viewModel { (navigator: Navigator<ResourcesListNavigationAction>) -> ResourcesListViewModel(navigator) } viewModel { ColorViewModel(AlertPresenter.Builder()) } viewModel { ImagesViewModel() } viewModel { LabelViewModel(StyledStringBuilder.Provider()) } viewModel { ButtonViewModel(StyledStringBuilder.Provider(), AlertPresenter.Builder()) } viewModel { (navigator: Navigator<ScientificNavigationAction<*>>) -> ScientificViewModel(AlertPresenter.Builder(), navigator) } viewModel { (quantity: PhysicalQuantity, navigator: Navigator<ScientificUnitSelectionAction<*>>) -> ScientificUnitSelectionViewModel(quantity, navigator) } viewModel { (arguments: ScientificConverterViewModel.Arguments, navigator: Navigator<ScientificConverterNavigationAction<*>>) -> ScientificConverterViewModel(arguments, navigator) } } fun initKoin(customModules: List<Module> = emptyList()) = initKoin( androidModule, { LocationStateRepoBuilder( locationManagerBuilder = DefaultLocationManager.Builder( googleLocationProviderSettings = GoogleLocationProvider.Settings(), ), permissionsBuilder = it, ) }, { BluetoothBuilder(permissionsBuilder = it) }, customModules, ) internal actual val appDeclaration: KoinAppDeclaration = { androidContext(ApplicationHolder.applicationContext) }
87
Kotlin
7
315
4094d5625a4cacb851b313d4e96bce6faac1c81f
10,191
kaluga
Apache License 2.0
node-kotlin/src/jsMain/kotlin/node/fs/writeFileSync.kt
karakum-team
393,199,102
false
null
// Automatically generated - do not modify! @file:JsModule("node:fs") package node.fs /** * Returns `undefined`. * * The `mode` option only affects the newly created file. See {@link open} for more details. * * For detailed information, see the documentation of the asynchronous version of * this API: {@link writeFile}. * @since v0.1.29 * @param file filename or file descriptor */ external fun writeFileSync( file: PathOrFileDescriptor, data: Any, /* string | NodeJS.ArrayBufferView */ options: WriteFileOptions = definedExternally, )
0
null
6
26
3ca49a8f44fc8b46e393ffe66fbd81f8b4943c18
561
types-kotlin
Apache License 2.0
app/src/main/java/com/JRobertFinal/footballapp/data/team/TeamDataSource.kt
TTVBlu
786,035,434
false
{"Kotlin": 102209}
package com.JRobertFinal.footballapp.data.team import com.JRobertFinal.footballapp.data.team.remote.response.Team import io.reactivex.Observable interface TeamDataSource { fun getTeamList(id : String): Observable<List<Team>> fun getTeamDetail(id : String): Observable<List<Team>> fun getSearchTeam(query : String): Observable<List<Team>> }
0
Kotlin
0
0
7f46c5a151920020e0c7febdeae15bfd6e34cdc7
353
Footballapp
MIT License
compiler/testData/multiplatform/regressions/incompatibleClassScopesWithImplTypeAlias/jvm.kt
JakeWharton
99,388,807
true
null
package test actual typealias Writer = java.io.Writer
179
Kotlin
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
55
kotlin
Apache License 2.0
src/jvm/src/aws/sdk/kotlin/crt/auth/credentials/StsAssumeRoleCredentialsProviderJVM.kt
awslabs
267,704,046
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package aws.sdk.kotlin.crt.auth.credentials import kotlinx.coroutines.* import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.future.asCompletableFuture import kotlinx.coroutines.runBlocking import java.util.concurrent.CompletableFuture import software.amazon.awssdk.crt.auth.credentials.Credentials as CredentialsJni import software.amazon.awssdk.crt.auth.credentials.CredentialsProvider as CredentialsProviderJni import software.amazon.awssdk.crt.auth.credentials.StsCredentialsProvider as StsCredentialsProviderJni // Based from the Java SDK default // https://sdk.amazonaws.com/java/api/latest/software/amazon/awssdk/services/sts/model/AssumeRoleRequest.html#durationSeconds private const val DEFAULT_DURATION_SECONDS = 3600 public actual class StsAssumeRoleCredentialsProvider internal actual constructor(builder: StsAssumeRoleCredentialsProviderBuilder) : CredentialsProvider, JniCredentialsProvider() { public actual companion object {} override val jniCredentials: CredentialsProviderJni = StsCredentialsProviderJni .builder() .withClientBootstrap(builder.clientBootstrap?.jniBootstrap) .withTlsContext(builder.tlsContext?.jniCtx) .withCredsProvider(adapt(builder.credentialsProvider)) .withDurationSeconds(builder.durationSeconds ?: DEFAULT_DURATION_SECONDS) .withRoleArn(builder.roleArn) .withSessionName(builder.sessionName) .build() } // Convert the SDK version of CredentialsProvider type to the CRT version internal fun adapt(credentialsProvider: CredentialsProvider?): CredentialsProviderJni? { return if (credentialsProvider == null) { null } else { toCrtCredentialsProvider(credentialsProvider) } } private fun toCrtCredentialsProvider(sdkCredentialsProvider: CredentialsProvider): CredentialsProviderJni { return object : CredentialsProviderJni() { override fun getCredentials(): CompletableFuture<CredentialsJni> = runBlocking { val deferred = async(start = CoroutineStart.UNDISPATCHED) { toCrtCredentials(sdkCredentialsProvider.getCredentials()) } deferred.asCompletableFuture() } } } private fun toCrtCredentials(sdkCredentials: Credentials): CredentialsJni { return object : CredentialsJni() { override fun getAccessKeyId(): ByteArray { return sdkCredentials.accessKeyId.encodeToByteArray() } override fun getSecretAccessKey(): ByteArray { return sdkCredentials.secretAccessKey.encodeToByteArray() } override fun getSessionToken(): ByteArray { return sdkCredentials.sessionToken?.encodeToByteArray() ?: ByteArray(0) } } }
5
Kotlin
3
1
c93e78ae4bf73c99384a253febca917c6aa7dd40
2,897
aws-crt-kotlin
Apache License 2.0
data/src/main/java/dev/mslalith/focuslauncher/data/database/dao/HiddenAppsDao.kt
mslalith
453,114,601
false
null
package dev.mslalith.focuslauncher.data.database.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import dev.mslalith.focuslauncher.data.database.entities.HiddenAppRoom import dev.mslalith.focuslauncher.data.utils.Constants.Database.HIDDEN_APPS_TABLE_NAME import kotlinx.coroutines.flow.Flow @Dao interface HiddenAppsDao { @Query("SELECT * FROM $HIDDEN_APPS_TABLE_NAME") fun getHiddenAppsFlow(): Flow<List<HiddenAppRoom>> @Query("SELECT * FROM $HIDDEN_APPS_TABLE_NAME WHERE packageName = :packageName LIMIT 1") suspend fun getHiddenAppBy(packageName: String): HiddenAppRoom? @Query("DELETE FROM $HIDDEN_APPS_TABLE_NAME") suspend fun clearHiddenApps() @Query("SELECT COUNT(*) $HIDDEN_APPS_TABLE_NAME") suspend fun getHiddenAppsSize(): Int @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun hideApp(hiddenAppRoom: HiddenAppRoom) @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun hideApps(hiddenAppRoomList: List<HiddenAppRoom>) @Delete suspend fun unHideApp(hiddenAppRoom: HiddenAppRoom) }
8
Kotlin
5
40
3298e2505e9f3eb6f8760b603586bd8c60d065e4
1,177
focus_launcher
Apache License 2.0
sample/src/main/java/com/expresspay/sample/ui/ExpresspaySaleActivity.kt
ExpresspaySa
601,645,134
false
{"Kotlin": 432395, "Java": 48886}
/* * Property of Expresspay (https://expresspay.sa). */ package com.expresspay.sample.ui import android.app.DatePickerDialog import android.content.Intent import android.os.Bundle import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.view.children import com.expresspay.sample.app.ExpresspayTransactionStorage import com.expresspay.sample.app.preattyPrint import com.expresspay.sample.databinding.ActivitySaleBinding import com.expresspay.sdk.core.ExpresspaySdk import com.expresspay.sdk.model.request.card.ExpresspayTestCard import com.expresspay.sdk.model.request.options.ExpresspaySaleOptions import com.expresspay.sdk.model.request.order.ExpresspaySaleOrder import com.expresspay.sdk.model.request.payer.ExpresspayPayer import com.expresspay.sdk.model.request.payer.ExpresspayPayerOptions import com.expresspay.sdk.model.response.base.error.ExpresspayError import com.expresspay.sdk.model.response.sale.ExpresspaySaleCallback import com.expresspay.sdk.model.response.sale.ExpresspaySaleResponse import com.expresspay.sdk.model.response.sale.ExpresspaySaleResult import com.expresspay.sample.R import io.kimo.lib.faker.Faker import java.text.DecimalFormat import java.util.* class ExpresspaySaleActivity : AppCompatActivity(R.layout.activity_sale) { private lateinit var binding: ActivitySaleBinding private lateinit var expresspayTransactionStorage: ExpresspayTransactionStorage private val random = Random() private var payerBirthdate: Calendar? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) expresspayTransactionStorage = ExpresspayTransactionStorage(this) binding = ActivitySaleBinding.inflate(layoutInflater) setContentView(binding.root) configureView() } private fun configureView() { binding.btnClearTransactions.setOnClickListener { expresspayTransactionStorage.clearTransactions() } binding.btnRandomizeRequired.setOnClickListener { randomize(false) } binding.btnRandomizeAll.setOnClickListener { randomize(true) } binding.etxtPayerBirthdate.setOnClickListener { val nowCalendar = Calendar.getInstance() DatePickerDialog( this, { _, year, month, dayOfMonth -> payerBirthdate = Calendar.getInstance() payerBirthdate?.set(year, month, dayOfMonth) binding.etxtPayerBirthdate.setText(payerBirthdate?.time.toString()) }, nowCalendar.get(Calendar.YEAR), nowCalendar.get(Calendar.MONTH), nowCalendar.get(Calendar.DAY_OF_MONTH) ) } binding.btnAuth.setOnClickListener { executeRequest(true) } binding.btnSale.setOnClickListener { executeRequest(false) } } private fun randomize(isAll: Boolean) { binding.etxtOrderId.setText(UUID.randomUUID().toString()) binding.etxtOrderAmount.setText(DecimalFormat("#.##").format(random.nextDouble() * 10_000).replace(",", ".")) binding.etxtOrderDescription.setText(Faker.Lorem.sentences()) binding.etxtOrderCurrencyCode.setText("SAR") binding.etxtPayerFirstName.setText(Faker.Name.firstName()) binding.etxtPayerLastName.setText(Faker.Name.lastName()) binding.etxtPayerAddress.setText(Faker.Address.secondaryAddress()) binding.etxtPayerCountryCode.setText(Faker.Address.countryAbbreviation()) binding.etxtPayerCity.setText(Faker.Address.city()) binding.etxtPayerZip.setText(Faker.Address.zipCode()) binding.etxtPayerEmail.setText(Faker.Internet.email()) binding.etxtPayerPhone.setText(Faker.Phone.phoneWithAreaCode()) binding.etxtPayerIpAddress.setText( "${random.nextInt(256)}.${random.nextInt(256)}.${random.nextInt(256)}.${random.nextInt( 256 )}" ) binding.rgCard.check(binding.rgCard.children.toList().random().id) binding.txtResponse.text = "" if (isAll) { binding.etxtPayerMiddleName.setText(Faker.Name.lastName()) binding.etxtPayerAddress2.setText(Faker.Address.streetWithNumber()) binding.etxtPayerState.setText(Faker.Address.state()) payerBirthdate?.set(1000 + random.nextInt(2000), random.nextInt(12), random.nextInt(31)) binding.etxtPayerBirthdate.setText(payerBirthdate?.time.toString()) binding.cbRecurringInit.isChecked = random.nextBoolean() binding.etxtChannelId.setText(UUID.randomUUID().toString().take(16)) } else { binding.etxtPayerMiddleName.setText("") binding.etxtPayerAddress2.setText("") binding.etxtPayerState.setText("") binding.etxtPayerBirthdate.setText("") binding.cbRecurringInit.isChecked = false binding.etxtChannelId.setText("") } } private fun onRequestStart() { binding.progressBar.show() binding.txtResponse.text = "" } private fun onRequestFinish() { binding.progressBar.hide() } private fun executeRequest(isAuth: Boolean) { val amount = try { binding.etxtOrderAmount.text.toString().toDouble() } catch (e: Exception) { 0.0 } val order = ExpresspaySaleOrder( id = binding.etxtOrderId.text.toString(), amount = amount, currency = binding.etxtOrderCurrencyCode.text.toString(), description = binding.etxtOrderDescription.text.toString() ) val card = when (binding.rgCard.checkedRadioButtonId) { R.id.rb_card_success -> ExpresspayTestCard.SALE_SUCCESS R.id.rb_card_failure -> ExpresspayTestCard.SALE_FAILURE R.id.rb_card_capture_failure -> ExpresspayTestCard.CAPTURE_FAILURE R.id.rb_card_3ds_success -> ExpresspayTestCard.SECURE_3D_SUCCESS R.id.rb_card_3ds_failure -> ExpresspayTestCard.SECURE_3D_FAILURE else -> ExpresspayTestCard.SALE_SUCCESS } val payerOptions = ExpresspayPayerOptions( middleName = binding.etxtPayerMiddleName.text.toString(), address2 = binding.etxtPayerAddress2.text.toString(), state = binding.etxtPayerState.text.toString(), birthdate = payerBirthdate?.time, ) val payer = ExpresspayPayer( firstName = binding.etxtPayerFirstName.text.toString(), lastName = binding.etxtPayerLastName.text.toString(), address = binding.etxtPayerAddress.text.toString(), country = binding.etxtPayerCountryCode.text.toString(), city = binding.etxtPayerCity.text.toString(), zip = binding.etxtPayerZip.text.toString(), email = binding.etxtPayerEmail.text.toString(), phone = binding.etxtPayerPhone.text.toString(), ip = binding.etxtPayerIpAddress.text.toString(), options = payerOptions ) val saleOptions:ExpresspaySaleOptions? = when (binding.cbRecurringInit.isChecked) { true -> ExpresspaySaleOptions( channelId = binding.etxtChannelId.text.toString(), recurringInit = binding.cbRecurringInit.isChecked ) false -> null } val transaction = ExpresspayTransactionStorage.Transaction( payerEmail = payer.email, cardNumber = card.number ) val termUrl3ds = "https://pay.expresspay.sa/" onRequestStart() ExpresspaySdk.Adapter.SALE.execute( order = order, card = card, payer = payer, termUrl3ds = termUrl3ds, options = saleOptions, auth = isAuth, callback = object : ExpresspaySaleCallback { override fun onResponse(response: ExpresspaySaleResponse) { super.onResponse(response) onRequestFinish() binding.txtResponse.text = response.preattyPrint() } override fun onResult(result: ExpresspaySaleResult) { transaction.fill(result.result) transaction.isAuth = isAuth if (result is ExpresspaySaleResult.Recurring) { transaction.recurringToken = result.result.recurringToken } else if (result is ExpresspaySaleResult.Secure3d) { ExpresspayRedirect3dsActivity.open( this@ExpresspaySaleActivity, result.result.redirectParams.termUrl, result.result.redirectUrl, result.result.redirectParams.paymentRequisites, termUrl3ds ) } expresspayTransactionStorage.addTransaction(transaction) } override fun onError(error: ExpresspayError) = Unit override fun onFailure(throwable: Throwable) { super.onFailure(throwable) onRequestFinish() binding.txtResponse.text = throwable.preattyPrint() } } ) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (ExpresspayRedirect3dsActivity.isOk(requestCode, resultCode)) { Toast.makeText(this, "The 3ds operation has been completed.", Toast.LENGTH_SHORT).show() } } }
0
Kotlin
2
0
8526a6a83fd0cdc5d11260521faf19c08260217d
9,862
expresspay-android-sdk-code
MIT License
app/src/main/java/com/selin/rickandmortycomposeapp/ui/theme/main/MainActivity.kt
selinihtyr
726,901,132
false
{"Kotlin": 72229}
package com.selin.rickandmortycomposeapp.ui.theme.main import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row 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.lazy.LazyColumn import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.Surface 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.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import com.google.gson.Gson import com.selin.rickandmortycomposeapp.R import com.selin.rickandmortycomposeapp.data.retrofit.model.CharacterHomePage import com.selin.rickandmortycomposeapp.ui.theme.RickAndMortyComposeAppTheme import com.selin.rickandmortycomposeapp.ui.theme.character.CharacterScreen import com.selin.rickandmortycomposeapp.ui.theme.character.DetailScreen import com.selin.rickandmortycomposeapp.ui.theme.episode.EpisodeDetailScreen import com.selin.rickandmortycomposeapp.ui.theme.episode.EpisodesFromDetailScreen import com.selin.rickandmortycomposeapp.ui.theme.episode.EpisodesScreen import com.selin.rickandmortycomposeapp.ui.theme.location.LocationDetailScreen import com.selin.rickandmortycomposeapp.ui.theme.location.LocationScreen import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { RickAndMortyComposeAppTheme { Surface( modifier = Modifier.fillMaxSize(), color = colorResource(id = R.color.mainBackground) ) { ScreenTransition() } } } } } @Composable fun ScreenTransition() { val navController = rememberNavController() NavHost(navController = navController, startDestination = "home") { composable("home") { HomeScreen(navController = navController) } composable( "character/{character}", arguments = listOf(navArgument("character") { type = NavType.StringType }) ) { it.arguments?.getString("character") CharacterScreen(navController = navController) } composable( "characterDetailScreen/{id}", arguments = listOf(navArgument("id") { type = NavType.IntType }) ) { it.arguments?.getInt("id") DetailScreen( characterId = it.arguments?.getInt("id") ?: 0, navController = navController ) } composable( "episodesFromCharacter/{ids}", arguments = listOf(navArgument("ids") { type = NavType.StringType }) ) { it.arguments?.getString("ids")?.let { episodeIds -> EpisodesFromDetailScreen( navController = navController, ids = episodeIds.split(",").map { it.toInt() }, viewModel = hiltViewModel() ) } } composable( "episode/{episode}", arguments = listOf(navArgument("episode") { type = NavType.StringType }) ) { it.arguments?.getString("episode") EpisodesScreen(navController) } composable( "episodeDetail/{id}", arguments = listOf(navArgument("id") { type = NavType.IntType }) ) { it.arguments?.getInt("id") EpisodeDetailScreen( episodeId = it.arguments?.getInt("id") ?: 0, navController = navController, viewModel = hiltViewModel() ) } composable( "location/{location}", arguments = listOf(navArgument("location") { type = NavType.StringType }) ) { it.arguments?.getString("location") LocationScreen(navController) } composable( "locationDetail/{id}", arguments = listOf(navArgument("id") { type = NavType.IntType }) ) { it.arguments?.getInt("id") LocationDetailScreen( locationId = it.arguments?.getInt("id") ?: 0, navController = navController, viewModel = hiltViewModel() ) } } } @Composable fun HomeScreen(navController: NavController) { val cartList = listOf( CharacterHomePage(1, "Characters", R.drawable.character), CharacterHomePage(2, "Episodes", R.drawable.episodes), CharacterHomePage(3, "Locations", R.drawable.location) ) LazyColumn( modifier = Modifier.fillMaxSize(), verticalArrangement = Arrangement.SpaceEvenly, horizontalAlignment = Alignment.CenterHorizontally ) { items( count = cartList.size, itemContent = { val character = cartList[it] Card( elevation = CardDefaults.cardElevation(5.dp), modifier = Modifier .padding(15.dp) .fillMaxWidth() .clickable { handleItemClick(character, navController) }, colors = CardDefaults.cardColors( containerColor = Color.White, ) ) { Row( modifier = Modifier .fillMaxWidth() .padding(15.dp), verticalAlignment = Alignment.Bottom, horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = character.name, fontSize = 32.sp, color = Color.Black, fontWeight = FontWeight.Bold, modifier = Modifier.padding(top = 120.dp) ) Image( painter = painterResource(id = character.image), contentDescription = null, modifier = Modifier.height(120.dp) ) } } } ) } } fun handleItemClick(screen: CharacterHomePage, navController: NavController) { val json = Gson().toJson(screen) when (screen.id) { 1 -> { navController.navigate("character/$json") } 2 -> { navController.navigate("episode/$json") } 3 -> { navController.navigate("location/$json") } } }
0
Kotlin
0
1
2a9d01fc368aae352610c9565e4dd713e1195dd6
7,828
RickAndMortyComposeApp
MIT License
src/main/kotlin/com/codeperfection/shipit/dto/common/PageDto.kt
codeperfection
730,719,882
false
{"Kotlin": 106653, "Dockerfile": 567}
package com.codeperfection.shipit.dto.common data class PageDto<T>( val totalElements: Long, val totalPages: Int, val elements: List<T> )
0
Kotlin
0
0
fbc1dc3aed31cf83d40fff3f988ca53b4033e0ac
151
ship-it
MIT License
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/apptest/BatchPropertyDsl.kt
F43nd1r
643,016,506
false
{"Kotlin": 5468147}
package com.faendir.awscdkkt.generated.services.apptest import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.apptest.CfnTestCase @Generated public fun buildBatchProperty(initializer: @AwsCdkDsl CfnTestCase.BatchProperty.Builder.() -> Unit = {}): CfnTestCase.BatchProperty = CfnTestCase.BatchProperty.Builder().apply(initializer).build()
1
Kotlin
0
4
c4f13bc5f85f50a5e554f90571a36ff62308c035
422
aws-cdk-kt
Apache License 2.0
news-mobile/android/app/src/main/kotlin/com/news/mobile/MainActivity.kt
PkayJava
263,666,006
false
{"Dart": 107886, "Java": 78760, "TSQL": 25214, "Swift": 404, "HTML": 314, "Kotlin": 120, "Objective-C": 38}
package com.news.mobile import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
9
Dart
0
1
e73cd30430aaa037b10d638eef9b969b870f9d0a
120
news-master
Apache License 2.0
ListaUsuario/app/src/main/java/com/rodrigo/listausuario/MainActivity.kt
cassiofm
382,967,684
false
null
package com.rodrigo.listausuario import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val rv = findViewById<RecyclerView>(R.id.rvUsuarios) val lista = mutableListOf<Usuario>( Usuario(nome="Joseffe", email="<EMAIL>", stack= Stack.BACKEND, senioridade= Senioridade.SENIOR, foto=resources.getDrawable(R.drawable.robo)), Usuario(nome="Macgyver", email="<EMAIL>", stack= Stack.BACKEND, senioridade= Senioridade.PLENO), Usuario(nome="Rodrigo", email="<EMAIL>", stack= Stack.FULLSTACK, senioridade= Senioridade.JUNIOR, foto=resources.getDrawable(R.drawable.avatar)) ) rv.adapter = UsuarioAdapter(lista) // Exibe os itens em uma coluna única no padrão vertical rv.layoutManager = LinearLayoutManager(this) // Exibe os itens em uma coluna única no padrão horizontal // rv.layoutManager = LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false) // Exibe os itens em uma tabela com x colunas // rv.layoutManager = GridLayoutManager(this, 2) // Exibe os itens em uma tabela porém as células são ajustadas automaticamente de acordo com o conteúdo (Google Keep, Pintrest) // rv.layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) } }
0
Kotlin
0
0
ee75a080ae06c2ddd4ab1a0ed26bed81c08dc293
1,620
mobile
MIT License
app/src/main/java/com/torr/coroutinesplayground/MainActivity.kt
21TORR
186,792,097
false
null
package com.torr.coroutinesplayground import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) supportFragmentManager.beginTransaction() .replace(R.id.fragment_container, Example_11_With_Context(), null) .commit() } }
0
Kotlin
0
0
3923c45a7a2e4cf2feb92bfdd012af33f75f632d
464
mmm-kotlin-coroutines
MIT License
app/src/main/java/com/nsk/app/widget/MainCateAdapterWithBinding.kt
StephenGiant
230,359,216
false
null
package com.nsk.app.widget import com.nsk.app.base.BaseAdapterWithBinding import com.nsk.app.base.BaseViewHolder import com.nsk.app.caikangyu.R class MainCateAdapterWithBinding(listData: List<Any>) : BaseAdapterWithBinding<Any>(listData) { var selectPosition = 0 override fun getLayoutResource(viewType: Int): Int { return R.layout.item_health_topcate } override fun setVariableID(): Int { return 0 } override fun getItemCount(): Int { return 0 } override fun onBindViewHolder(holder: BaseViewHolder, position: Int) { super.onBindViewHolder(holder, position) } }
1
null
1
1
d4bd736b90989a2a8b774dafcc57ab8aa42aabae
631
fuckcky
Apache License 2.0
compiler/testData/diagnostics/testsWithJsStdLib/jsCode/badAssignment.kt
JakeWharton
99,388,807
true
null
// !DIAGNOSTICS: -UNUSED_PARAMETER fun Int.foo(x: Int) { js("this = x<!JSCODE_ERROR!><!>;") }
0
Kotlin
28
83
4383335168338df9bbbe2a63cb213a68d0858104
97
kotlin
Apache License 2.0
app/src/main/kotlin/com/rajankali/plasma/compose/layout/MovieComposables.kt
rajandev17
308,975,838
false
null
/* * MIT License * * Copyright (c) 2020 rajandev17 * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.rajankali.plasma.composable import androidx.compose.foundation.Text import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.material.AmbientEmphasisLevels import androidx.compose.material.Card import androidx.compose.material.MaterialTheme import androidx.compose.material.ProvideEmphasis import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.annotatedString import androidx.compose.ui.text.withStyle import androidx.compose.ui.unit.dp import com.rajankali.core.data.Cast import com.rajankali.core.data.Movie import java.util.* @Composable fun MovieListItem(movie: Movie, isFirstCard: Boolean = false, onClick: () -> Unit) { Card( elevation = 4.dp, modifier = Modifier .padding( start = 16.dp, bottom = 8.dp, end = 16.dp, top = if (isFirstCard) 16.dp else 8.dp ), shape = MaterialTheme.shapes.medium ) { Column( modifier = Modifier .fillMaxWidth() .clickable { onClick() } ) { GlideImage( model = movie.thumbnail, modifier = Modifier.fillMaxWidth().aspectRatio(16 / 9F) ) { centerCrop() } columnSpacer(16) val padding = Modifier.padding(horizontal = 16.dp) Text( text = movie.originalTitle, style = MaterialTheme.typography.h6, modifier = padding ) columnSpacer(8) ProvideEmphasis(AmbientEmphasisLevels.current.medium) { Text( text = movie.overview, style = MaterialTheme.typography.body2, maxLines = 2, modifier = padding ) } Spacer(Modifier.preferredHeight(8.dp)) MovieMetadata(movie = movie, modifier = Modifier.padding(horizontal = 16.dp)) Spacer(Modifier.preferredHeight(16.dp)) } } } @Composable fun MovieCard(movie: Movie, isFirstCard: Boolean = false, onClick: () -> Unit) { rowSpacer(value = if(isFirstCard) 16 else 4) Column(modifier = Modifier.width(120.dp).padding(vertical = 8.dp) ) { Card( elevation = 4.dp, modifier = Modifier.clickable { onClick() }, shape = MaterialTheme.shapes.medium ) { GlideImage( model = movie.thumbnail, modifier = Modifier.fillMaxWidth().aspectRatio(3 / 4F) ) { centerCrop() } } columnSpacer(8) val padding = Modifier.padding(horizontal = 8.dp) Text( text = movie.originalTitle, style = MaterialTheme.typography.body2, maxLines = 2, modifier = padding ) columnSpacer(4) ProvideEmphasis(AmbientEmphasisLevels.current.medium) { Text( text = movie.date, style = MaterialTheme.typography.overline, modifier = padding ) } Spacer(Modifier.preferredHeight(8.dp)) } rowSpacer(value = 4) } @Composable fun GridItem(movie: Movie, onClick: () -> Unit) { GridItem(thumbnail = movie.thumbnail, title = movie.originalTitle, desc = movie.date, onClick = onClick) } @Composable fun GridItem(cast: Cast, onClick: () -> Unit){ GridItem(thumbnail = cast.thumbnail, title = cast.name, desc = cast.character, onClick = onClick) } @Composable fun GridItem(thumbnail: String, title: String, desc: String, onClick: () -> Unit){ Column(modifier = Modifier.fillMaxWidth() ) { Card( elevation = 4.dp, modifier = Modifier.clickable { onClick() }, shape = MaterialTheme.shapes.medium ) { GlideImage( model = thumbnail, modifier = Modifier.fillMaxWidth().aspectRatio(3 / 4F) ) { centerCrop() } } columnSpacer(8) val padding = Modifier.padding(horizontal = 8.dp) Text( text = title, style = MaterialTheme.typography.body2, maxLines = 2, modifier = padding ) if(desc.isNotEmpty()) { columnSpacer(4) ProvideEmphasis(AmbientEmphasisLevels.current.medium) { Text( text = desc, style = MaterialTheme.typography.overline, modifier = padding ) } } Spacer(Modifier.preferredHeight(8.dp)) } } @Composable fun MovieMetadata( movie: Movie, modifier: Modifier = Modifier ) { val divider = " • " val text = annotatedString { val tagStyle = MaterialTheme.typography.overline.toSpanStyle().copy( background = MaterialTheme.colors.primary.copy(alpha = 0.8f) ) withStyle(tagStyle) { append(" ${movie.mediaType.toUpperCase(Locale.ENGLISH)} ") } append(divider) append(movie.originalLanguage.language()) append(divider) append("${movie.voteAverage}") } ProvideEmphasis(AmbientEmphasisLevels.current.medium) { Text( text = text, style = MaterialTheme.typography.body2, modifier = modifier ) } } fun String.language(): String { val loc = Locale(this) return loc.getDisplayLanguage(loc) }
1
Kotlin
26
99
7d1db3a5c186d099a33ef6c9bef7596b3d0e1edf
7,007
Plasma
MIT License
src/main/kotlin/com/wynnlab/minestom/listeners/player inventory click listeners.kt
WynnLab
389,421,865
false
null
package com.wynnlab.minestom.listeners import com.wynnlab.minestom.core.player.checkPlayerItems import com.wynnlab.minestom.core.player.modifiedSkills import com.wynnlab.minestom.items.ItemTypeId import com.wynnlab.minestom.items.itemTypeIdTag import com.wynnlab.minestom.items.skillRequirementsTag import com.wynnlab.minestom.players.snowForSlot import com.wynnlab.minestom.util.listen import net.minestom.server.entity.GameMode import net.minestom.server.event.EventFilter import net.minestom.server.event.EventNode import net.minestom.server.event.inventory.InventoryPreClickEvent import net.minestom.server.inventory.click.ClickType import net.minestom.server.item.ItemStack import net.minestom.server.item.Material val playerInventoryClickListenersNode = EventNode.event("player-inventory-click-listeners", EventFilter.PLAYER) { e -> e is InventoryPreClickEvent && e.inventory == null && e.player.gameMode == GameMode.ADVENTURE } private fun onPlayerInventoryClick(e: InventoryPreClickEvent) { val player = e.player if (e.slot in 6..8 && e.clickType != ClickType.START_SHIFT_CLICK) { e.isCancelled = true return } if (e.slot == 13) { e.isCancelled = true return } if (e.slot == 45 || e.clickType == ClickType.CHANGE_HELD) { // Disable offhand e.isCancelled = true return } /*println(""" ===== Slot: ${e.slot} Type: ${e.clickType} Cursor: ${e.cursorItem.material} Clicked: ${e.clickedItem.material} """.trimIndent())*/ run clickType@ { when (e.clickType) { ClickType.START_SHIFT_CLICK -> { if (e.slot in 5..8) checkPlayerItems(player) if (e.slot in 9..12) { player.inventory.setItemStack(e.slot, snowForSlot(e.slot)) e.isCancelled = true if (!player.inventory.addItemStack(e.clickedItem)) e.isCancelled = false if (e.isCancelled) checkPlayerItems(player) return } else if (e.slot in 0..8) return val shiftTo = when (e.clickedItem.getTag(itemTypeIdTag)) { null -> return@clickType ItemTypeId.HELMET -> 41 ItemTypeId.CHESTPLATE -> 42 ItemTypeId.LEGGINGS -> 43 ItemTypeId.BOOTS -> 44 ItemTypeId.RING -> if (player.inventory.getItemStack(9).material == Material.SNOW) 9 else 10 ItemTypeId.BRACELET -> 11 ItemTypeId.NECKLACE -> 12 else -> return@clickType } if (!checkItem(shiftTo, e.clickedItem, player.modifiedSkills)) { if (shiftTo >= 41) e.isCancelled = true } else if (player.inventory.getItemStack(shiftTo).let { it.isAir || it.material == Material.SNOW }) { player.inventory.setItemStack(shiftTo, e.clickedItem) player.inventory.setItemStack(e.slot.let { if (it >= 36) it - 36 else it }, ItemStack.AIR) e.isCancelled = true checkPlayerItems(player) } } ClickType.SHIFT_CLICK -> return else -> return@clickType } } if (e.slot in 9..12 || e.slot in 41..44) { if (e.cursorItem.isAir) { if (e.slot < 41) { if (e.clickedItem.material != Material.SNOW) e.cursorItem = snowForSlot(e.slot) else e.isCancelled = true } } else { if (!checkItem(e.slot, e.cursorItem, player.modifiedSkills)) e.isCancelled = true else if (e.clickedItem.material == Material.SNOW) e.clickedItem = ItemStack.AIR } if (!e.isCancelled) checkPlayerItems(player) } } private fun checkItem(slot: Int, item: ItemStack, modifiedSkills: IntArray): Boolean { if (item.getTag(itemTypeIdTag) != when (slot) { 41 -> ItemTypeId.HELMET 42 -> ItemTypeId.CHESTPLATE 43 -> ItemTypeId.LEGGINGS 44 -> ItemTypeId.BOOTS 9, 10 -> ItemTypeId.RING 11 -> ItemTypeId.BRACELET 12 -> ItemTypeId.NECKLACE else -> return false }.toByte()) return false val skillRequirements = item.getTag(skillRequirementsTag) ?: return false for (i in 0..4) { if (modifiedSkills[i] < skillRequirements[i]) return false } return true } fun initPlayerInventoryClickListeners() { //playerSpellClickListenersNode.listen { } playerInventoryClickListenersNode.listen(::onPlayerInventoryClick) wynnLabPlayerListenersNode.addChild(playerInventoryClickListenersNode) }
0
Kotlin
0
5
96d970229f94503986bec40cc997b188427aae74
4,803
WynnLab-Minestom
MIT License
kandy-lets-plot/src/main/kotlin/org/jetbrains/kotlinx/kandy/letsplot/layers/context/aes/WithYEnd.kt
Kotlin
502,039,936
false
null
/* * Copyright 2020-2023 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package org.jetbrains.kotlinx.kandy.letsplot.layers.context.aes import org.jetbrains.kotlinx.dataframe.DataColumn import org.jetbrains.kotlinx.dataframe.columns.ColumnReference import org.jetbrains.kotlinx.kandy.dsl.internal.BindingContext import org.jetbrains.kotlinx.kandy.ir.bindings.PositionalMapping import org.jetbrains.kotlinx.kandy.letsplot.internal.Y_END import kotlin.reflect.KProperty public interface WithYEnd : BindingContext { public val yEnd: ConstantSetter get() = ConstantSetter(Y_END, bindingCollector) /* public fun <T> xMin(value: T): PositionalSetting<T> { return addPositionalSetting(X_MIN, value) } */ public fun <T> yEnd( column: ColumnReference<T>, ): PositionalMapping<T> { return addPositionalMapping<T>(Y_END, column.name(), null) } public fun <T> yEnd( column: KProperty<T>, ): PositionalMapping<T> { return addPositionalMapping<T>(Y_END, column.name, null) } public fun <T> yEnd( column: String, ): PositionalMapping<T> { return addPositionalMapping<T>(Y_END, column, null) } public fun <T> yEnd( values: Iterable<T>, ): PositionalMapping<T> { return addPositionalMapping<T>( Y_END, values.toList(), null, null ) } public fun <T> yEnd( values: DataColumn<T>, ): PositionalMapping<T> { return addPositionalMapping<T>( Y_END, values, null ) } }
78
Kotlin
0
98
0e54a419c188b5e6dbee8a95af5213c7ac978bb6
1,667
kandy
Apache License 2.0
ground/src/test/java/com/google/android/ground/repository/UserMediaRepositoryTest.kt
google
127,777,820
false
{"Kotlin": 1400241}
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.ground.repository import com.google.android.ground.BaseHiltTest import com.google.common.truth.Truth.assertThat import dagger.hilt.android.testing.HiltAndroidTest import javax.inject.Inject import org.junit.Assert.assertThrows import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner @HiltAndroidTest @RunWith(RobolectricTestRunner::class) class UserMediaRepositoryTest : BaseHiltTest() { @Inject lateinit var userMediaRepository: UserMediaRepository @Test fun getLocalFileFromRemotePath_invalidImageFilename() { for (path in listOf( "(/some/path/filename.png)", "/some/path/filename.", "/some/path/filename", "/some/path/filename.txt", "/some/path/filename$.png", )) { assertThrows(IllegalArgumentException::class.java) { userMediaRepository.getLocalFileFromRemotePath(path) } } } @Test fun getLocalFileFromRemotePath_validImageFilename() { for (path in listOf( "/some/path/filename.png", "/some/path/filename.jpg", )) { val localFile = userMediaRepository.getLocalFileFromRemotePath(path) assertThat(localFile).isNotNull() } } }
235
Kotlin
115
245
bb5229149eb3687923a8391f30f7279e477562a8
1,842
ground-android
Apache License 2.0
src/test/kotlin/org/wfanet/measurement/integration/k8s/EmptyClusterCorrectnessTest.kt
world-federation-of-advertisers
349,561,061
false
null
/* * Copyright 2022 The Cross-Media Measurement Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wfanet.measurement.integration.k8s import io.grpc.Channel import io.grpc.ManagedChannel import io.grpc.StatusException import io.kubernetes.client.common.KubernetesObject import io.kubernetes.client.openapi.Configuration import io.kubernetes.client.openapi.models.V1Deployment import io.kubernetes.client.openapi.models.V1Pod import io.kubernetes.client.util.ClientBuilder import java.io.File import java.net.InetSocketAddress import java.nio.charset.StandardCharsets import java.nio.file.Paths import java.security.Security import java.time.Duration import java.util.UUID import java.util.logging.Logger import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.isActive import kotlinx.coroutines.runBlocking import kotlinx.coroutines.time.delay import kotlinx.coroutines.time.withTimeout import kotlinx.coroutines.withContext import org.jetbrains.annotations.Blocking import org.junit.ClassRule import org.junit.rules.TemporaryFolder import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.junit.runners.model.Statement import org.wfanet.measurement.api.v2alpha.ApiKeysGrpcKt import org.wfanet.measurement.api.v2alpha.CertificatesGrpcKt import org.wfanet.measurement.api.v2alpha.DataProvidersGrpcKt import org.wfanet.measurement.api.v2alpha.EventGroupsGrpcKt import org.wfanet.measurement.api.v2alpha.ListEventGroupsRequestKt import org.wfanet.measurement.api.v2alpha.MeasurementConsumersGrpcKt import org.wfanet.measurement.api.v2alpha.MeasurementsGrpcKt import org.wfanet.measurement.api.v2alpha.ProtocolConfig import org.wfanet.measurement.api.v2alpha.listEventGroupsRequest import org.wfanet.measurement.api.withAuthenticationKey import org.wfanet.measurement.common.crypto.jceProvider import org.wfanet.measurement.common.crypto.tink.TinkPrivateKeyHandle import org.wfanet.measurement.common.grpc.buildMutualTlsChannel import org.wfanet.measurement.common.grpc.withDefaultDeadline import org.wfanet.measurement.common.k8s.KubernetesClient import org.wfanet.measurement.common.k8s.testing.PortForwarder import org.wfanet.measurement.common.k8s.testing.Processes import org.wfanet.measurement.common.testing.chainRulesSequentially import org.wfanet.measurement.integration.common.ALL_DUCHY_NAMES import org.wfanet.measurement.integration.common.MC_DISPLAY_NAME import org.wfanet.measurement.integration.common.SyntheticGenerationSpecs import org.wfanet.measurement.integration.common.createEntityContent import org.wfanet.measurement.integration.common.loadEncryptionPrivateKey import org.wfanet.measurement.integration.common.loadTestCertDerFile import org.wfanet.measurement.internal.kingdom.AccountsGrpcKt import org.wfanet.measurement.loadtest.measurementconsumer.MeasurementConsumerData import org.wfanet.measurement.loadtest.measurementconsumer.MeasurementConsumerSimulator import org.wfanet.measurement.loadtest.measurementconsumer.MetadataSyntheticGeneratorEventQuery import org.wfanet.measurement.loadtest.resourcesetup.DuchyCert import org.wfanet.measurement.loadtest.resourcesetup.EntityContent import org.wfanet.measurement.loadtest.resourcesetup.ResourceSetup import org.wfanet.measurement.loadtest.resourcesetup.Resources /** * Test for correctness of the CMMS on a single "empty" Kubernetes cluster using the `local` * configuration. * * This will push the images to the container registry and populate the K8s cluster prior to running * the test methods. The cluster must already exist with the `KUBECONFIG` environment variable * pointing to its kubeconfig. * * This assumes that the `tar` and `kubectl` executables are the execution path. The latter is only * used for `kustomize`, as the Kubernetes API is used to interact with the cluster. */ @RunWith(JUnit4::class) class EmptyClusterCorrectnessTest : AbstractCorrectnessTest(measurementSystem) { private class Images : TestRule { override fun apply(base: Statement, description: Description): Statement { return object : Statement() { override fun evaluate() { pushImages() base.evaluate() } } } private fun pushImages() { val pusherRuntimePath = getRuntimePath(IMAGE_PUSHER_PATH) Processes.runCommand(pusherRuntimePath.toString()) } } private data class ResourceInfo( val aggregatorCert: String, val worker1Cert: String, val worker2Cert: String, val measurementConsumer: String, val apiKey: String, val dataProviders: Map<String, Resources.Resource> ) { companion object { fun from(resources: Iterable<Resources.Resource>): ResourceInfo { var aggregatorCert: String? = null var worker1Cert: String? = null var worker2Cert: String? = null var measurementConsumer: String? = null var apiKey: String? = null val dataProviders = mutableMapOf<String, Resources.Resource>() for (resource in resources) { @Suppress("WHEN_ENUM_CAN_BE_NULL_IN_JAVA") // Proto enum fields cannot be null. when (resource.resourceCase) { Resources.Resource.ResourceCase.MEASUREMENT_CONSUMER -> { measurementConsumer = resource.name apiKey = resource.measurementConsumer.apiKey } Resources.Resource.ResourceCase.DATA_PROVIDER -> { val displayName = resource.dataProvider.displayName require(dataProviders.putIfAbsent(displayName, resource) == null) { "Entry already exists for DataProvider $displayName" } } Resources.Resource.ResourceCase.DUCHY_CERTIFICATE -> { when (val duchyId = resource.duchyCertificate.duchyId) { "aggregator" -> aggregatorCert = resource.name "worker1" -> worker1Cert = resource.name "worker2" -> worker2Cert = resource.name else -> error("Unhandled Duchy $duchyId") } } Resources.Resource.ResourceCase.RESOURCE_NOT_SET -> error("Unhandled type") } } return ResourceInfo( requireNotNull(aggregatorCert), requireNotNull(worker1Cert), requireNotNull(worker2Cert), requireNotNull(measurementConsumer), requireNotNull(apiKey), dataProviders ) } } } /** [TestRule] which populates a K8s cluster with the components of the CMMS. */ class LocalMeasurementSystem( k8sClient: Lazy<KubernetesClient>, tempDir: Lazy<TemporaryFolder>, runId: Lazy<String> ) : TestRule, MeasurementSystem { private val portForwarders = mutableListOf<PortForwarder>() private val channels = mutableListOf<ManagedChannel>() private val k8sClient: KubernetesClient by k8sClient private val tempDir: TemporaryFolder by tempDir override val runId: String by runId private lateinit var _testHarness: MeasurementConsumerSimulator override val testHarness: MeasurementConsumerSimulator get() = _testHarness override fun apply(base: Statement, description: Description): Statement { return object : Statement() { override fun evaluate() { try { runBlocking { withTimeout(Duration.ofMinutes(5)) { val measurementConsumerData = populateCluster() _testHarness = createTestHarness(measurementConsumerData) } } base.evaluate() } finally { stopPortForwarding() } } } } private suspend fun populateCluster(): MeasurementConsumerData { val apiClient = k8sClient.apiClient apiClient.httpClient = apiClient.httpClient.newBuilder().readTimeout(Duration.ofHours(1L)).build() Configuration.setDefaultApiClient(apiClient) val duchyCerts = ALL_DUCHY_NAMES.map { DuchyCert(it, loadTestCertDerFile("${it}_cs_cert.der")) } val edpEntityContents = EDP_DISPLAY_NAMES.map { createEntityContent(it) } val measurementConsumerContent = withContext(Dispatchers.IO) { createEntityContent(MC_DISPLAY_NAME) } // Wait until default service account has been created. See // https://github.com/kubernetes/kubernetes/issues/66689. k8sClient.waitForServiceAccount("default", timeout = READY_TIMEOUT) loadKingdom() val resourceSetupOutput = runResourceSetup(duchyCerts, edpEntityContents, measurementConsumerContent) val resourceInfo = ResourceInfo.from(resourceSetupOutput.resources) loadFullCmms(resourceInfo, resourceSetupOutput.akidPrincipalMap) val encryptionPrivateKey: TinkPrivateKeyHandle = withContext(Dispatchers.IO) { loadEncryptionPrivateKey("${MC_DISPLAY_NAME}_enc_private.tink") } return MeasurementConsumerData( resourceInfo.measurementConsumer, measurementConsumerContent.signingKey, encryptionPrivateKey, resourceInfo.apiKey ) } private suspend fun createTestHarness( measurementConsumerData: MeasurementConsumerData ): MeasurementConsumerSimulator { val kingdomPublicPod: V1Pod = k8sClient .listPodsByMatchLabels(k8sClient.waitUntilDeploymentReady(KINGDOM_PUBLIC_DEPLOYMENT_NAME)) .items .first() val publicApiForwarder = PortForwarder(kingdomPublicPod, SERVER_PORT) portForwarders.add(publicApiForwarder) val publicApiAddress: InetSocketAddress = withContext(Dispatchers.IO) { publicApiForwarder.start() } val publicApiChannel: Channel = buildMutualTlsChannel(publicApiAddress.toTarget(), MEASUREMENT_CONSUMER_SIGNING_CERTS) .also { channels.add(it) } .withDefaultDeadline(DEFAULT_RPC_DEADLINE) val eventGroupsClient = EventGroupsGrpcKt.EventGroupsCoroutineStub(publicApiChannel) return MeasurementConsumerSimulator( measurementConsumerData, OUTPUT_DP_PARAMS, DataProvidersGrpcKt.DataProvidersCoroutineStub(publicApiChannel), eventGroupsClient, MeasurementsGrpcKt.MeasurementsCoroutineStub(publicApiChannel), MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineStub(publicApiChannel), CertificatesGrpcKt.CertificatesCoroutineStub(publicApiChannel), Duration.ofSeconds(10L), MEASUREMENT_CONSUMER_SIGNING_CERTS.trustedCertificates, MetadataSyntheticGeneratorEventQuery( SyntheticGenerationSpecs.POPULATION_SPEC, MC_ENCRYPTION_PRIVATE_KEY ), ProtocolConfig.NoiseMechanism.CONTINUOUS_GAUSSIAN ) .also { try { eventGroupsClient.waitForEventGroups( measurementConsumerData.name, measurementConsumerData.apiAuthenticationKey ) } catch (e: StatusException) { throw Exception("Error waiting for EventGroups", e) } } } fun stopPortForwarding() { for (channel in channels) { channel.shutdown() } for (portForwarder in portForwarders) { portForwarder.close() } } private suspend fun loadFullCmms(resourceInfo: ResourceInfo, akidPrincipalMap: File) { val appliedObjects: List<KubernetesObject> = withContext(Dispatchers.IO) { val outputDir = tempDir.newFolder("cmms") extractTar(getRuntimePath(LOCAL_K8S_TESTING_PATH.resolve("cmms.tar")).toFile(), outputDir) val configFilesDir = outputDir.toPath().resolve(CONFIG_FILES_PATH).toFile() logger.info("Copying $akidPrincipalMap to $CONFIG_FILES_PATH") akidPrincipalMap.copyTo(configFilesDir.resolve(akidPrincipalMap.name)) val configTemplate: File = outputDir.resolve("config.yaml") kustomize( outputDir.toPath().resolve(LOCAL_K8S_TESTING_PATH).resolve("cmms").toFile(), configTemplate ) val configContent = configTemplate .readText(StandardCharsets.UTF_8) .replace("{aggregator_cert_name}", resourceInfo.aggregatorCert) .replace("{worker1_cert_name}", resourceInfo.worker1Cert) .replace("{worker2_cert_name}", resourceInfo.worker2Cert) .replace("{mc_name}", resourceInfo.measurementConsumer) .let { var config = it for ((displayName, resource) in resourceInfo.dataProviders) { config = config .replace("{${displayName}_name}", resource.name) .replace("{${displayName}_cert_name}", resource.dataProvider.certificate) } config } kubectlApply(configContent) } appliedObjects.filterIsInstance(V1Deployment::class.java).forEach { k8sClient.waitUntilDeploymentReady(it) } } private suspend fun loadKingdom() { withContext(Dispatchers.IO) { val outputDir = tempDir.newFolder("kingdom-setup") extractTar(getRuntimePath(LOCAL_K8S_PATH.resolve("kingdom_setup.tar")).toFile(), outputDir) val config: File = outputDir.resolve("config.yaml") kustomize( outputDir.toPath().resolve(LOCAL_K8S_PATH).resolve("kingdom_setup").toFile(), config ) kubectlApply(config) } } private suspend fun runResourceSetup( duchyCerts: List<DuchyCert>, edpEntityContents: List<EntityContent>, measurementConsumerContent: EntityContent ): ResourceSetupOutput { val outputDir = withContext(Dispatchers.IO) { tempDir.newFolder("resource-setup") } val kingdomInternalPod = k8sClient .listPodsByMatchLabels( k8sClient.waitUntilDeploymentReady(KINGDOM_INTERNAL_DEPLOYMENT_NAME) ) .items .first() val kingdomPublicPod = k8sClient .listPodsByMatchLabels(k8sClient.waitUntilDeploymentReady(KINGDOM_PUBLIC_DEPLOYMENT_NAME)) .items .first() val resources = PortForwarder(kingdomInternalPod, SERVER_PORT).use { internalForward -> val internalAddress: InetSocketAddress = withContext(Dispatchers.IO) { internalForward.start() } val internalChannel = buildMutualTlsChannel(internalAddress.toTarget(), KINGDOM_SIGNING_CERTS) PortForwarder(kingdomPublicPod, SERVER_PORT) .use { publicForward -> val publicAddress: InetSocketAddress = withContext(Dispatchers.IO) { publicForward.start() } val publicChannel = buildMutualTlsChannel(publicAddress.toTarget(), KINGDOM_SIGNING_CERTS) val resourceSetup = ResourceSetup( AccountsGrpcKt.AccountsCoroutineStub(internalChannel), org.wfanet.measurement.internal.kingdom.DataProvidersGrpcKt .DataProvidersCoroutineStub(internalChannel), org.wfanet.measurement.api.v2alpha.AccountsGrpcKt.AccountsCoroutineStub( publicChannel ), ApiKeysGrpcKt.ApiKeysCoroutineStub(publicChannel), org.wfanet.measurement.internal.kingdom.CertificatesGrpcKt .CertificatesCoroutineStub(internalChannel), MeasurementConsumersGrpcKt.MeasurementConsumersCoroutineStub(publicChannel), runId, outputDir = outputDir, requiredDuchies = listOf("aggregator", "worker1", "worker2") ) withContext(Dispatchers.IO) { resourceSetup .process(edpEntityContents, measurementConsumerContent, duchyCerts) .also { publicChannel.shutdown() } } } .also { internalChannel.shutdown() } } return ResourceSetupOutput( resources, outputDir.resolve(ResourceSetup.AKID_PRINCIPAL_MAP_FILE) ) } private fun extractTar(archive: File, outputDirectory: File) { Processes.runCommand("tar", "-xf", archive.toString(), "-C", outputDirectory.toString()) } @Blocking private fun kustomize(kustomizationDir: File, output: File) { Processes.runCommand( "kubectl", "kustomize", kustomizationDir.toString(), "--output", output.toString() ) } @Blocking private fun kubectlApply(config: File): List<KubernetesObject> { return k8sClient .kubectlApply(config) .onEach { logger.info { "Applied ${it.kind} ${it.metadata.name}" } } .toList() } @Blocking private fun kubectlApply(config: String): List<KubernetesObject> { return k8sClient .kubectlApply(config) .onEach { logger.info { "Applied ${it.kind} ${it.metadata.name}" } } .toList() } data class ResourceSetupOutput( val resources: List<Resources.Resource>, val akidPrincipalMap: File ) } companion object { init { // Remove Conscrypt provider so underlying OkHttp client won't use it and fail on unsupported // certificate algorithms when connecting to cluster (ECFieldF2m). Security.removeProvider(jceProvider.name) } private val logger = Logger.getLogger(this::class.java.name) private const val SERVER_PORT: Int = 8443 private val DEFAULT_RPC_DEADLINE = Duration.ofSeconds(30) private const val KINGDOM_INTERNAL_DEPLOYMENT_NAME = "gcp-kingdom-data-server-deployment" private const val KINGDOM_PUBLIC_DEPLOYMENT_NAME = "v2alpha-public-api-server-deployment" private const val NUM_DATA_PROVIDERS = 6 private val EDP_DISPLAY_NAMES: List<String> = (1..NUM_DATA_PROVIDERS).map { "edp$it" } private val READY_TIMEOUT = Duration.ofMinutes(2L) private val LOCAL_K8S_PATH = Paths.get("src", "main", "k8s", "local") private val LOCAL_K8S_TESTING_PATH = LOCAL_K8S_PATH.resolve("testing") private val CONFIG_FILES_PATH = LOCAL_K8S_TESTING_PATH.resolve("config_files") private val IMAGE_PUSHER_PATH = Paths.get("src", "main", "docker", "push_all_local_images.bash") private val tempDir = TemporaryFolder() private val measurementSystem = LocalMeasurementSystem( lazy { KubernetesClient(ClientBuilder.defaultClient()) }, lazy { tempDir }, lazy { UUID.randomUUID().toString() } ) @ClassRule @JvmField val chainedRule = chainRulesSequentially(tempDir, Images(), measurementSystem) private suspend fun EventGroupsGrpcKt.EventGroupsCoroutineStub.waitForEventGroups( measurementConsumer: String, apiKey: String ) { logger.info { "Waiting for all event groups to be created..." } while (currentCoroutineContext().isActive) { val eventGroups = withAuthenticationKey(apiKey) .listEventGroups( listEventGroupsRequest { parent = measurementConsumer filter = ListEventGroupsRequestKt.filter { measurementConsumers += measurementConsumer } } ) .eventGroupsList // Each EDP simulator creates one event group, so we wait until there are as many event // groups as EDP simulators. if (eventGroups.size == NUM_DATA_PROVIDERS) { logger.info { "All event groups created" } return } delay(Duration.ofSeconds(1)) } } private suspend fun KubernetesClient.waitUntilDeploymentReady(name: String): V1Deployment { logger.info { "Waiting for Deployment $name to be ready..." } return waitUntilDeploymentReady(name, timeout = READY_TIMEOUT).also { logger.info { "Deployment $name ready" } } } private suspend fun KubernetesClient.waitUntilDeploymentReady( deployment: V1Deployment ): V1Deployment { val deploymentName = requireNotNull(deployment.metadata?.name) logger.info { "Waiting for Deployment $deploymentName to be ready..." } return waitUntilDeploymentReady(deployment, timeout = READY_TIMEOUT).also { logger.info { "Deployment $deploymentName ready" } } } } } private fun InetSocketAddress.toTarget(): String { return "$hostName:$port" }
98
null
11
36
b5c84f8051cd189e55f8c43ee2b9cc3f3a75e353
21,168
cross-media-measurement
Apache License 2.0
kswift-gradle-plugin/src/main/kotlin/dev/icerock/moko/kswift/plugin/KmTypeExt.kt
icerockdev
392,317,237
false
null
/* * Copyright 2021 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package dev.icerock.moko.kswift.plugin import io.outfoxx.swiftpoet.ANY_OBJECT import io.outfoxx.swiftpoet.BOOL import io.outfoxx.swiftpoet.DeclaredTypeName import io.outfoxx.swiftpoet.FunctionTypeName import io.outfoxx.swiftpoet.ParameterSpec import io.outfoxx.swiftpoet.STRING import io.outfoxx.swiftpoet.TypeName import io.outfoxx.swiftpoet.TypeVariableName import io.outfoxx.swiftpoet.UINT64 import io.outfoxx.swiftpoet.VOID import io.outfoxx.swiftpoet.parameterizedBy import kotlinx.metadata.ClassName import kotlinx.metadata.KmClassifier import kotlinx.metadata.KmType @Suppress("ReturnCount") fun KmType.toTypeName( moduleName: String, isUsedInGenerics: Boolean = false, typeVariables: Map<Int, TypeVariableName> = emptyMap(), removeTypeVariables: Boolean = false ): TypeName { return when (val classifier = classifier) { is KmClassifier.TypeParameter -> { val typeVariable: TypeVariableName? = typeVariables[classifier.id] if (typeVariable != null) { return if (!removeTypeVariables) typeVariable else typeVariable.bounds.firstOrNull()?.type ?: ANY_OBJECT } else throw IllegalArgumentException("can't read type parameter $this without type variables list") } is KmClassifier.TypeAlias -> { classifier.name.kotlinTypeNameToSwift(moduleName, isUsedInGenerics) ?: throw IllegalArgumentException("can't read type alias $this") } is KmClassifier.Class -> { val name: TypeName? = classifier.name.kotlinTypeNameToSwift(moduleName, isUsedInGenerics) return name ?: kotlinTypeToTypeName( moduleName, classifier.name, typeVariables, removeTypeVariables ) } } } fun String.kotlinTypeNameToSwift(moduleName: String, isUsedInGenerics: Boolean): TypeName? { return when (this) { "kotlin/String" -> if (isUsedInGenerics) { DeclaredTypeName(moduleName = "Foundation", simpleName = "NSString") } else { STRING } "kotlin/Int" -> DeclaredTypeName(moduleName = "Foundation", simpleName = "NSNumber") "kotlin/Boolean" -> if (isUsedInGenerics) { DeclaredTypeName(moduleName = moduleName, simpleName = "KotlinBoolean") } else { BOOL } "kotlin/ULong" -> UINT64 "kotlin/Unit" -> VOID "kotlin/Any" -> ANY_OBJECT else -> { if (this.startsWith("platform/")) { val withoutCompanion: String = this.removeSuffix(".Companion") val moduleAndClass: List<String> = withoutCompanion.split("/").drop(1) val module: String = moduleAndClass[0] val className: String = moduleAndClass[1] DeclaredTypeName.typeName( listOf(module, className).joinToString(".") ).objcNameToSwift() } else if (this.startsWith("kotlin/Function")) { null } else if (this.startsWith("kotlin/") && this.count { it == '/' } == 1) { DeclaredTypeName( moduleName = moduleName, simpleName = "Kotlin" + this.split("/").last() ) } else null } } } fun KmType.kotlinTypeToTypeName( moduleName: String, classifierName: ClassName, typeVariables: Map<Int, TypeVariableName>, removeTypeVariables: Boolean ): TypeName { val typeName = DeclaredTypeName( moduleName = moduleName, simpleName = classifierName.split("/").last() ) if (this.arguments.isEmpty()) return typeName return when (classifierName) { "kotlin/Function1" -> { val inputType: TypeName = arguments[0].type?.toTypeName( moduleName = moduleName, isUsedInGenerics = false, typeVariables = typeVariables, removeTypeVariables = removeTypeVariables )!! val outputType: TypeName = arguments[1].type?.toTypeName( moduleName = moduleName, isUsedInGenerics = false, typeVariables = typeVariables, removeTypeVariables = removeTypeVariables )!! FunctionTypeName.get( parameters = listOf(ParameterSpec.unnamed(inputType)), returnType = outputType ) } else -> { val arguments: List<TypeName> = this.arguments.mapNotNull { typeProj -> typeProj.type?.toTypeName( moduleName = moduleName, isUsedInGenerics = true, typeVariables = typeVariables, removeTypeVariables = removeTypeVariables ) } @Suppress("SpreadOperator") typeName.parameterizedBy(*arguments.toTypedArray()) } } } fun DeclaredTypeName.objcNameToSwift(): DeclaredTypeName { return when (moduleName) { "Foundation" -> peerType(simpleName.removePrefix("NS")) else -> this } }
34
null
19
315
511bb27bccbb96912b9848c8b740a08a5bee94f5
5,314
moko-kswift
Apache License 2.0
app/src/main/java/com/alpriest/energystats/ui/theme/Theme.kt
alpriest
606,081,400
false
null
package com.alpriest.energystats.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color private val DarkColorPalette = darkColors( primary = TintColor, secondary = Teal200, background = DarkBackground, onBackground = Color.White, onPrimary = Color.White, onSecondary = Color.LightGray, surface = DarkHeader ) private val LightColorPalette = lightColors( primary = TintColor, secondary = Teal200, background = PaleWhite, onBackground = Color.DarkGray, onPrimary = Color.White, onSecondary = Color.DarkGray, surface = PaleHeader /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun EnergyStatsTheme(darkTheme: Boolean = isSystemInDarkTheme(), useLargeDisplay: Boolean = false, content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } val typography = if (useLargeDisplay) { LargeTypography } else { Typography } MaterialTheme( colors = colors, typography = typography, shapes = Shapes, content = content ) }
7
Kotlin
3
3
b0094f9774a280bca91c40dfee1da0216c4cd01f
1,538
EnergyStats-Android
MIT License
app/src/main/java/com/alpriest/energystats/ui/theme/Theme.kt
alpriest
606,081,400
false
null
package com.alpriest.energystats.ui.theme import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material.MaterialTheme import androidx.compose.material.darkColors import androidx.compose.material.lightColors import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color private val DarkColorPalette = darkColors( primary = TintColor, secondary = Teal200, background = DarkBackground, onBackground = Color.White, onPrimary = Color.White, onSecondary = Color.LightGray, surface = DarkHeader ) private val LightColorPalette = lightColors( primary = TintColor, secondary = Teal200, background = PaleWhite, onBackground = Color.DarkGray, onPrimary = Color.White, onSecondary = Color.DarkGray, surface = PaleHeader /* Other default colors to override background = Color.White, surface = Color.White, onPrimary = Color.White, onSecondary = Color.Black, onBackground = Color.Black, onSurface = Color.Black, */ ) @Composable fun EnergyStatsTheme(darkTheme: Boolean = isSystemInDarkTheme(), useLargeDisplay: Boolean = false, content: @Composable () -> Unit) { val colors = if (darkTheme) { DarkColorPalette } else { LightColorPalette } val typography = if (useLargeDisplay) { LargeTypography } else { Typography } MaterialTheme( colors = colors, typography = typography, shapes = Shapes, content = content ) }
7
Kotlin
3
3
b0094f9774a280bca91c40dfee1da0216c4cd01f
1,538
EnergyStats-Android
MIT License
app/src/main/java/online/litterae/worldnewsin/view/VideoEntry.kt
YuriShakhov
275,418,170
false
null
package online.litterae.worldnewsin.view class VideoEntry( val text: String, val videoId: String, val date: String )
0
Kotlin
0
0
e8f8820b08c3cd9ebec1b9048f3ec0ce17f774b8
129
world-news-in
Apache License 2.0
FE/Algo/app/src/main/java/com/d204/algo/data/repository/remote/ProblemRemote.kt
OneDayOneAlgorithm
702,771,315
false
{"Kotlin": 214386, "Java": 137214, "Python": 31787, "HTML": 4437, "JavaScript": 3222, "Dockerfile": 537}
package com.d204.algo.data.repository.remote import com.d204.algo.data.api.NetworkResult import com.d204.algo.data.model.Problem interface ProblemRemote { suspend fun getProblems(): NetworkResult<List<Problem>> suspend fun getProblem(problemId: Long): NetworkResult<Problem> suspend fun getStrongProblems(userId: Long): NetworkResult<List<Problem>> suspend fun getWeakProblems(userId: Long): NetworkResult<List<Problem>> suspend fun getSimilarProblems(userId: Long): List<Problem> suspend fun postLikeProblems(problem: Problem): NetworkResult<Unit> suspend fun getLikeProblems(userId: Long): List<Problem> suspend fun isRemote(): Boolean }
0
Kotlin
0
0
273bf6fc4072767e40984d98a47c4a8af0c059b2
674
AlgoArium
MIT License
sweetdependency-gradle-plugin/src/main/java/com/highcapable/sweetdependency/gradle/helper/GradleHelper.kt
HighCapable
643,245,749
false
{"Kotlin": 298044}
/* * SweetDependency - An easy autowire and manage dependencies Gradle plugin. * Copyright (C) 2019-2023 HighCapable * https://github.com/HighCapable/SweetDependency * * Apache License Version 2.0 * * 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. * * This file is created by fankes on 2023/5/19. */ @file:Suppress("MemberVisibilityCanBePrivate") package com.highcapable.sweetdependency.gradle.helper import com.highcapable.sweetdependency.gradle.factory.libraries import com.highcapable.sweetdependency.gradle.factory.plugins import com.highcapable.sweetdependency.gradle.wrapper.LibraryDependencyWrapper import com.highcapable.sweetdependency.gradle.wrapper.PluginDependencyWrapper import com.highcapable.sweetdependency.utils.debug.SError import com.highcapable.sweetdependency.utils.parseFileSeparator import org.gradle.api.Project import org.gradle.api.initialization.Settings import org.gradle.api.invocation.Gradle import java.io.File import java.io.FileReader import java.util.* /** * Gradle 工具类 */ internal object GradleHelper { /** Gradle 配置文件名称 */ private const val GRADLE_PROPERTIES_FILE_NAME = "gradle.properties" /** 当前 [Gradle] 静态实例 */ private var instance: Gradle? = null /** 当前 [Settings] 静态实例 */ private var settings: Settings? = null /** 当前装载的所有项目 */ internal val allProjects = mutableSetOf<Project>() /** 当前装载的项目插件依赖数组 */ internal val projectPlugins = mutableMapOf<Project, MutableList<PluginDependencyWrapper>>() /** 当前装载的项目库依赖数组 */ internal val projectLibraries = mutableMapOf<Project, MutableList<LibraryDependencyWrapper>>() /** * 绑定当前使用的 [Settings] 静态实例 * @param settings 当前设置 */ internal fun attach(settings: Settings) { instance = settings.also { this.settings = it }.gradle } /** * 缓存所有项目列表 * @param rootProject 当前根项目 */ internal fun cachingProjectList(rootProject: Project) { allProjects.clear() allProjects.addAll(rootProject.allprojects) } /** * 缓存所有依赖列表 * @param project 当前项目 * @param isRoot 是否为根项目 */ internal fun cachingDependencyList(project: Project, isRoot: Boolean) { if (isRoot) { projectPlugins.clear() projectLibraries.clear() } project.plugins(isUseCache = false).forEach { if (projectPlugins[project] == null) projectPlugins[project] = mutableListOf() projectPlugins[project]?.add(it) } project.libraries(isUseCache = false).forEach { if (projectLibraries[project] == null) projectLibraries[project] = mutableListOf() projectLibraries[project]?.add(it) } } /** * 获取用户目录的 [Properties] * @return [Properties] or null */ internal val userProperties get() = createProperties(instance?.gradleUserHomeDir) /** * 获取当前项目的 [Properties] * @return [Properties] or null */ internal val projectProperties get() = createProperties(settings?.rootDir) /** * 获取当前 Gradle 项目的根目录 * @return [File] */ internal val rootDir get() = rootProject?.projectDir ?: settings?.rootDir ?: SError.make("Gradle is unavailable") /** * 获取当前 Gradle 项目的根项目 (Root Project) * @return [Project] or null */ internal val rootProject get() = runCatching { instance?.rootProject }.getOrNull() /** * 获取当前 Gradle 版本 * @return [String] */ internal val version get() = instance?.gradle?.gradleVersion ?: "" /** * 获取当前 Gradle 是否处于离线模式 * @return [Boolean] */ internal val isOfflineMode get() = instance?.startParameter?.isOffline == true /** * 获取当前 Gradle 是否处于同步模式 * @return [Boolean] */ internal val isSyncMode get() = runningTaskNames.isNullOrEmpty() /** * 获取当前正在运行的 Task 名称数组 * @return [MutableList]<[String]> or null */ internal val runningTaskNames get() = instance?.startParameter?.taskRequests?.getOrNull(0)?.args /** * 创建新的 [Properties] * @param dir 当前目录 * @return [Properties] or null */ private fun createProperties(dir: File?) = runCatching { Properties().apply { load(FileReader(dir?.resolve(GRADLE_PROPERTIES_FILE_NAME)?.absolutePath?.parseFileSeparator() ?: "")) } }.getOrNull() }
0
Kotlin
0
32
2cbf00e997d1788caa398df7b899d96f571caa87
4,828
SweetDependency
Apache License 2.0
ScalerAndroidPlugin/src/main/kotlin/dev/danperez/gradle/handlers/extensions/ScalerAndroidLibraryExtension.kt
danielPerez97
711,319,077
false
{"Kotlin": 51781}
package dev.danperez.gradle.handlers.extensions import org.gradle.api.provider.Property public abstract class ScalerAndroidLibraryExtension { internal abstract val namespace: Property<String> }
0
Kotlin
0
2
486dcefe637cdf2005896d4de2fbae0e660393bf
199
Scaler
Apache License 2.0
mobile/src/main/java/ch/epfl/sdp/mobile/ui/tournaments/Contest.kt
epfl-SDP
462,385,783
false
null
package ch.epfl.sdp.mobile.ui.tournaments import androidx.compose.foundation.clickable import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.ListItem import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.style.TextOverflow import ch.epfl.sdp.mobile.state.LocalLocalizedStrings import ch.epfl.sdp.mobile.ui.PawniesColors import ch.epfl.sdp.mobile.ui.tournaments.ContestInfo.Status /** * Displays a contest. * * @param contestInfo the given [ContestInfo]. * @param onClick callback function called when the contest item is clicked on. * @param modifier the [Modifier] for this composable. */ @OptIn(ExperimentalMaterialApi::class) @Composable fun Contest( contestInfo: ContestInfo, onClick: () -> Unit, modifier: Modifier = Modifier, ) { val strings = LocalLocalizedStrings.current val title = when (val status = contestInfo.status) { Status.Done -> AnnotatedString(strings.tournamentsDone) is Status.Ongoing -> strings.tournamentsStartingTime( status.since, SpanStyle(color = PawniesColors.Orange200), ) } ListItem( modifier = modifier.clickable { onClick() }, text = { Text( text = contestInfo.name, color = PawniesColors.Green500, style = MaterialTheme.typography.subtitle1, ) }, secondaryText = { Text( text = title, color = PawniesColors.Green200, style = MaterialTheme.typography.subtitle2, maxLines = 1, overflow = TextOverflow.Ellipsis) }, trailing = { val badge = contestInfo.badge if (badge != null) { Badge(type = badge, enabled = false, onClick = {}) } }, ) }
15
Kotlin
3
13
71f6e2a5978087205b35f82e89ed4005902d697e
2,046
android
MIT License
app/src/main/java/cdio/group21/litaire/data/Move.kt
Zahedm45
508,737,533
false
{"Kotlin": 208551}
package cdio.group21.litaire.data import Card data class Move( val isMoveToFoundation: Boolean, val card: Card, val indexOfSourceBlock: Byte, // source, 8 = waste val indexOfDestination: Byte )
0
Kotlin
0
1
543bd8847adfa583a00026bf6dbb0df94be868ee
200
klondike_solitaire_solver
MIT License
app/src/main/kotlin/com/chatter/omeglechat/presentation/ChatScreen/ChatScreen.kt
z0xyz
677,695,548
false
null
package com.chatter.omeglechat import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.chatter.omeglechat.ChatScreen.BottomBar import com.chatter.omeglechat.ChatScreen.ChatViewModel import com.chatter.omeglechat.ChatScreen.MainContent import com.chatter.omeglechat.ChatScreen.TopChattingBar import com.chatter.omeglechat.ui.theme.OmegleChatTheme import android.content.res.Configuration.UI_MODE_NIGHT_NO import android.content.res.Configuration.UI_MODE_NIGHT_YES import androidx.compose.foundation.background import androidx.compose.foundation.layout.Row import com.chatter.omeglechat.presentation.ChatScreen.ChatViewModelMock import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) @Composable fun ChatScreen( chatViewModel: ChatViewModel, arrowBackCallback: () -> Unit, modifier: Modifier = Modifier ) { val scrollState = rememberLazyListState() val coroutineScope = rememberCoroutineScope() val scrollBehavior = TopAppBarDefaults.pinnedScrollBehavior() Scaffold( topBar = { TopChattingBar( scrollBehavior = scrollBehavior, connectionState = chatViewModel.connectionState, commonInterests = chatViewModel.commonInterests, searchButtonCallback = { // TODO: I guess I'll implement another dropdown menu or something, entailing things like block ,save chatlog, etc }, arrowBackCallback = arrowBackCallback ) }, bottomBar = { Row ( modifier = Modifier .fillMaxWidth() .background(MaterialTheme.colorScheme.background) ) { BottomBar( textMessageState = "", // textMessageState = chatViewModel.textMessage.value, onSendClick = { // I guess this button should have some other implementation for the onClick callback // for example if the TextField content is empty, there the Send button is deactivated in some way chatViewModel.sendTextMessage() coroutineScope.launch { // Scroll to the bottom // todo: I guess it needs a bit of refinement. (Still not fully working) // Like what if the user explicitly scrolled up. Should i force him down with each new message, or maybe i should notify him of a new incoming message like whatsapp does? scrollState.layoutInfo.totalItemsCount.let { if (it > 0) { scrollState.animateScrollToItem(it - 1) } } } }, onTerminateClick = { chatViewModel.terminate() }, onValueChange = { chatViewModel.textMessage.value = it }, // TODO: It's a relic of the past (before refactoring business logic code to the chatViewModel). Refine it later on. // enabled = ConnectionStates.values().toMutableList().map { it.displayName }.contains(chatViewModel.connectionState), enabled = true, modifier = Modifier .fillMaxWidth() .padding( horizontal = 5.dp ) ) } }, containerColor = MaterialTheme.colorScheme.background, content = { paddingValue -> MainContent( paddingValue = paddingValue, messages = chatViewModel.messages.toMutableList(), scrollState = scrollState, modifier = Modifier .padding(10.dp) ) }, modifier = Modifier .nestedScroll(scrollBehavior.nestedScrollConnection) ) } @Preview(showBackground = true, uiMode = UI_MODE_NIGHT_NO) @Preview(showBackground = true, uiMode = UI_MODE_NIGHT_YES) @Composable fun PreviewChatScreen() { OmegleChatTheme { ChatScreen( chatViewModel = ChatViewModelMock(), arrowBackCallback = {} ) } }
0
null
0
1
65e892170a65a99895cc5e96cfd63a1456ad3ad7
5,042
omeglechat
MIT License