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
.teamcity/src/main/kotlin/promotion/PublishNightlySnapshotFromQuickFeedback.kt
gradle
302,322
false
null
/* * Copyright 2019 the original author or 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 promotion import common.VersionedSettingsBranch class PublishNightlySnapshotFromQuickFeedback(branch: VersionedSettingsBranch) : PublishGradleDistribution( promotedBranch = branch.branchName, task = branch.promoteNightlyTaskName(), triggerName = "QuickFeedback" ) { init { id("Promotion_SnapshotFromQuickFeedback") name = "Nightly Snapshot (from QuickFeedback)" description = "Promotes the latest successful changes on '${branch.branchName}' from Quick Feedback as a new nightly snapshot" } }
2,095
Groovy
3792
13,076
c1b02a85c1d02816ba0c59fd02b656f6187a4472
1,164
gradle
Apache License 2.0
lib/src/main/kotlin/tsl/nodes/AbstractNode.kt
spbu-coding-2023
771,651,556
false
{"Kotlin": 86881}
package tsl.nodes abstract class AbstractNode<K : Comparable<K>, V, N : AbstractNode<K, V, N>>( var key: K, var value: V ) { internal var leftChild: N? = null internal var rightChild: N? = null }
1
Kotlin
0
4
1293c3b37ba69f8a9edd86f2f3f46641b08c8128
213
trees-2
MIT License
lib/src/main/kotlin/tsl/nodes/AbstractNode.kt
spbu-coding-2023
771,651,556
false
{"Kotlin": 86881}
package tsl.nodes abstract class AbstractNode<K : Comparable<K>, V, N : AbstractNode<K, V, N>>( var key: K, var value: V ) { internal var leftChild: N? = null internal var rightChild: N? = null }
1
Kotlin
0
4
1293c3b37ba69f8a9edd86f2f3f46641b08c8128
213
trees-2
MIT License
src/test/kotlin/skips/SkipLanding.kt
mataframework
770,318,523
false
{"Kotlin": 52775}
package skips import com.github.mataframework.app.App import com.github.mataframework.junit.AppStartUpListener import com.github.mataframework.pages.PageObject import uitests.ui.IntroductionPage import uitests.ui.PlusAdsPage object SkipLanding : AppStartUpListener { override fun onAppStartUp(app: App, pageObject: PageObject) { pageObject .waitForElementAndClick(IntroductionPage.nextButtonLocation) .waitForElementAndClick(IntroductionPage.nextButtonLocation) .waitForElementAndClick(PlusAdsPage.skipButtonLocation) } }
1
Kotlin
0
0
f6f5dbcbfa94f568912db599f6a08f8108423e21
576
mataframework
MIT License
src/main/kotlin/com/swisschain/matching/engine/outgoing/rabbit/impl/services/RabbitMqServiceToLogService.kt
swisschain
255,464,363
false
{"Gradle": 2, "Text": 2, "Ignore List": 1, "Markdown": 1, "Kotlin": 578, "XML": 2, "Shell": 2, "Batchfile": 1, "Java": 3, "Protocol Buffer": 14, "Java Properties": 1, "INI": 2, "YAML": 2}
package com.swisschain.matching.engine.outgoing.rabbit.impl.services import com.google.gson.Gson import com.swisschain.matching.engine.outgoing.messages.v2.events.Event import org.slf4j.LoggerFactory import org.springframework.context.annotation.Profile import org.springframework.stereotype.Service @Service("rabbitMqService") @Profile("local") class RabbitMqServiceToLogService(gson: Gson) : AbstractRabbitMQToLogService<Event>(gson, LOGGER) { companion object { private val LOGGER = LoggerFactory.getLogger(RabbitMqServiceToLogService::class.java) } }
1
null
1
1
5ef23544e9c5b21864ec1de7ad0f3e254044bbaa
572
Exchange.MatchingEngine
Apache License 2.0
app/src/main/java/com/frogobox/basemusic/ui/lyric/SongLyricActivity.kt
amirisback
240,663,454
false
{"Kotlin": 30777}
package com.frogobox.basemusic.ui.lyric import android.os.Bundle import android.view.Menu import android.view.MenuItem import com.frogobox.basemusic.R import com.frogobox.basemusic.core.BaseActivity import com.frogobox.basemusic.databinding.ActivitySongLyricBinding import com.frogobox.basemusic.ui.main.AboutUsActivity class SongLyricActivity : BaseActivity<ActivitySongLyricBinding>() { override fun setupViewBinding(): ActivitySongLyricBinding { return ActivitySongLyricBinding.inflate(layoutInflater) } override fun setupViewModel() { } override fun setupUI(savedInstanceState: Bundle?) { setSupportActionBar(binding.toolbar.toolbarMain) setupShowAdsBanner(binding.ads.adsBanner) setupChildFragment(binding.framelayoutMainContainer.id, SongLyricFragment()) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_toolbar_main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.toolbar_menu_about -> { baseStartActivity<AboutUsActivity>() true } else -> super.onOptionsItemSelected(item) } } }
0
Kotlin
0
5
f2f91a6db1140bc5cf2ae09e8a92a2aa3ecafde7
1,277
music-player
Apache License 2.0
feature-matchingcards/src/main/java/com/rumosoft/feature_memorygame/domain/repo_interfaces/TimerRepository.kt
Rviewer-Challenges
492,594,104
false
{"Kotlin": 72614}
package com.rumosoft.feature_memorygame.domain.repo_interfaces import kotlinx.coroutines.flow.Flow interface TimerRepository { fun countDownFrom(secs: Int): Flow<Long> }
0
Kotlin
0
0
9590cbb8cd589ba11ab703e20f0de1448e1186da
175
kslH9nF4ZJcayHVA49Vf
MIT License
src/tasks/Request3Callbacks.kt
Jason-purse
442,505,771
true
{"Kotlin": 48948}
package tasks import contributors.* import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.util.* import java.util.concurrent.CountDownLatch import java.util.concurrent.atomic.AtomicInteger fun loadContributorsCallbacks(service: GitHubService, req: RequestData, updateResults: (List<User>) -> Unit) { service.getOrgReposCall(req.org).onResponse { responseRepos -> logRepos(req, responseRepos) val repos = responseRepos.bodyList() // 由于处理回调的线程可能不是同一个... // 更好的方式是使用同步版本(这里所说的回调是下面的回调); // 于是. // val allUsers = mutableListOf<User>() // 这里使用同步集合,保证所有的回调对集合的操作都是原子性的.. val allUsers = Collections.synchronizedList(mutableListOf<User>()) val countDownLatch = CountDownLatch(repos.size) // 但是这不是一个最优解.. 使用CountDownLatch,结合synchronizedList 处理.. 然后得到最终结果并 更新. // 所以使用原子数字 // #2 第二种 // val number = AtomicInteger(0) repos.forEachIndexed { index, repo -> service.getRepoContributorsCall(req.org, repo.name).onResponse { responseUsers -> logUsers(repo, responseUsers) val users = responseUsers.bodyList() allUsers += users // 这是第一种.. // 将它放置在最后一个任务中 刷新即可... // 存在一个问题,当 最后一个任务完成的比其他任务快,将会导致任务丢失.. // if(index == repos.size - 1) { // updateResults(allUsers) // } // 这是第二种 .. // 增加 // 原子操作 // if (number.incrementAndGet() == repos.size) { // updateResults(allUsers.aggregate()) // } // 第三种 countDownLatch.countDown() } } // 回调的位置有问题.. // TODO: Why this code doesn't work? How to fix that? /* log.info("callback result user infos: $allUsers") updateResults(allUsers.aggregate())*/ countDownLatch.await() updateResults(allUsers.aggregate()) // 根据这个例子我们发现了 书写一个正确的回调是不简单且容易发生错误的... // 应该使用资源共享/同步的机制去处理它.. // 例如使用RXJava 来正确书写代码... } } // kotlin 不允许 inline 函数在非本地上下文中使用本地return ,所以需要crossinline关键字.. inline fun <T> Call<T>.onResponse(crossinline callback: (Response<T>) -> Unit) { enqueue(object : Callback<T> { override fun onResponse(call: Call<T>, response: Response<T>) { callback(response) } override fun onFailure(call: Call<T>, t: Throwable) { log.error("Call failed", t) } }) }
0
Kotlin
0
0
88fa6bb34f9dfb77e494ae313b9b4454252abb7c
2,568
intro-coroutines
Apache License 2.0
lib-swipetoactionlayout/src/main/java/github/com/st235/swipetoactionlayout/behaviour/BehaviourDelegate.kt
st235
196,595,936
false
null
package github.com.st235.swipetoactionlayout.behaviour import android.view.View import github.com.st235.swipetoactionlayout.QuickActionsStates import github.com.st235.swipetoactionlayout.utils.Size internal interface BehaviourDelegate { fun layoutAction(view: View, l: Int, r: Int, actionSize: Size) fun clampViewPosition(parentView: View, view: View, left: Int, actionSize: Size): Int fun translateAction(mainView: View, actionView: View, actionSize: Size, dx: Int, index: Int) fun isOpened(position: Int, actionSize: Size): Boolean fun getFinalLeftPosition(view: View, velocity: Float, actionSize: Size): Int fun getStateForPosition(view: View, actionSize: Size): QuickActionsStates fun getPositionForState(view: View, actionSize: Size, states: QuickActionsStates): Int }
3
null
6
99
b0f58074648c130cad88a8fdfcb1f5a0dac5135a
811
SwipeToActionLayout
MIT License
connectors/mongo/coroutines/src/main/kotlin/com/coditory/sherlock/mongo/coroutines/MongoDistributedLockConnector.kt
coditory
195,197,396
false
{"Java": 280232, "Groovy": 172037, "Kotlin": 84822}
package com.coditory.sherlock.mongo.coroutines import com.coditory.sherlock.LockRequest import com.coditory.sherlock.SherlockException import com.coditory.sherlock.coroutines.SuspendingDistributedLockConnector import com.coditory.sherlock.mongo.MongoDistributedLock import com.coditory.sherlock.mongo.MongoDistributedLock.fromDocument import com.coditory.sherlock.mongo.MongoDistributedLock.fromLockRequest import com.coditory.sherlock.mongo.MongoDistributedLockQueries.queryAcquired import com.coditory.sherlock.mongo.MongoDistributedLockQueries.queryAcquiredOrReleased import com.coditory.sherlock.mongo.MongoDistributedLockQueries.queryById import com.coditory.sherlock.mongo.MongoDistributedLockQueries.queryReleased import com.mongodb.MongoCommandException import com.mongodb.client.model.FindOneAndReplaceOptions import com.mongodb.client.model.ReturnDocument import com.mongodb.kotlin.client.coroutine.MongoCollection import org.bson.BsonDocument import org.bson.Document import org.bson.conversions.Bson import java.time.Clock import java.time.Instant internal class MongoDistributedLockConnector( collection: MongoCollection<Document>, private val clock: Clock, ) : SuspendingDistributedLockConnector { private val collectionInitializer = MongoCollectionInitializer(collection) override suspend fun initialize() { try { collectionInitializer.getInitializedCollection() } catch (e: Throwable) { throw SherlockException("Could not initialize Mongo collection", e) } } override suspend fun acquire(lockRequest: LockRequest): Boolean { val now = now() return try { upsert( queryReleased(lockRequest.lockId, now), fromLockRequest(lockRequest, now), ) } catch (e: Throwable) { throw SherlockException("Could not acquire lock: $lockRequest", e) } } override suspend fun acquireOrProlong(lockRequest: LockRequest): Boolean { val now = now() return try { upsert( queryAcquiredOrReleased(lockRequest.lockId, lockRequest.ownerId, now), fromLockRequest(lockRequest, now), ) } catch (e: Throwable) { throw SherlockException("Could not acquire or prolong lock: $lockRequest", e) } } override suspend fun forceAcquire(lockRequest: LockRequest): Boolean { return try { upsert( queryById(lockRequest.lockId), fromLockRequest(lockRequest, now()), ) } catch (e: Throwable) { throw SherlockException("Could not acquire or prolong lock: $lockRequest", e) } } override suspend fun release(lockId: String, ownerId: String): Boolean { return try { delete(queryAcquired(lockId, ownerId)) } catch (e: Throwable) { throw SherlockException("Could not release lock: $lockId, owner: $ownerId", e) } } override suspend fun forceRelease(lockId: String): Boolean { return try { delete(queryById(lockId)) } catch (e: Throwable) { throw SherlockException("Could not force release lock: $lockId", e) } } override suspend fun forceReleaseAll(): Boolean { return try { deleteAll() } catch (e: Throwable) { throw SherlockException("Could not force release all locks", e) } } private suspend fun deleteAll(): Boolean { val result = getCollection().deleteMany(BsonDocument()) return result.deletedCount > 0 } private suspend fun delete(query: Bson): Boolean { val deleted = getCollection().findOneAndDelete(query) return deleted != null && fromDocument(deleted).isActive(now()) } private suspend fun upsert(query: Bson, lock: MongoDistributedLock): Boolean { val documentToUpsert = lock.toDocument() return try { val current = getCollection() .findOneAndReplace(query, documentToUpsert, upsertOptions) lock.hasSameOwner(current) } catch (exception: MongoCommandException) { if (exception.errorCode != DUPLICATE_KEY_ERROR_CODE) { throw exception } false } } private fun now(): Instant { return clock.instant() } private suspend fun getCollection(): MongoCollection<Document> { return collectionInitializer.getInitializedCollection() } companion object { private const val DUPLICATE_KEY_ERROR_CODE = 11000 private val upsertOptions = FindOneAndReplaceOptions() .upsert(true) .returnDocument(ReturnDocument.AFTER) } }
4
Java
7
36
18138a8dd64443a54456f7c9a80efa715887de41
4,850
sherlock-distributed-lock
Apache License 2.0
src/jvmMain/kotlin/io/dcctech/mafita/backend/persistence/DocumentPa.kt
timoterik
587,234,059
false
null
/* * Copyright © 2022-2023, DCCTech, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.dcctech.mafita.backend.persistence import io.dcctech.mafita.data.DocumentBo import io.dcctech.mafita.enums.DocumentType import kotlinx.datetime.toJavaInstant import kotlinx.datetime.toKotlinInstant import org.jetbrains.exposed.sql.ResultRow import org.jetbrains.exposed.sql.`java-time`.timestamp import org.jetbrains.exposed.sql.statements.UpdateBuilder import zakadabar.core.persistence.exposed.ExposedPaBase import zakadabar.core.persistence.exposed.ExposedPaTable import zakadabar.core.persistence.exposed.entityId open class DocumentPa( table: DocumentTable = DocumentTableDefault ) : ExposedPaBase<DocumentBo, DocumentTable>( table = table ) { override fun ResultRow.toBo() = DocumentBo( id = this[table.id].entityId(), name = this[table.name], type = this[table.type], createAt = this[table.createAt].toKotlinInstant() ) override fun UpdateBuilder<*>.fromBo(bo: DocumentBo) { this[table.name] = bo.name this[table.type] = bo.type this[table.createAt] = bo.createAt.toJavaInstant() } } object DocumentTableDefault : DocumentTable() open class DocumentTable( tableName: String = "document" ) : ExposedPaTable<DocumentBo>( tableName = tableName ) { val name = varchar("name", length = 60) val type = enumerationByName("type", 15, DocumentType::class) val createAt = timestamp("create_at") }
0
Kotlin
0
0
417bd88d2c1e7faef875df61e082f83445cab3a7
1,543
mafita
Apache License 2.0
src/main/kotlin/org/move/ide/intentions/AddAcquiresIntention.kt
WormholeStudio
386,158,725
true
{"Kotlin": 522703, "Lex": 7602, "HTML": 131}
package org.move.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.move.ide.annotator.ACQUIRES_BUILTIN_FUNCTIONS import org.move.lang.core.psi.MoveCallExpr import org.move.lang.core.psi.MoveFunctionSignature import org.move.lang.core.psi.MovePsiFactory import org.move.lang.core.psi.ext.ancestorOrSelf import org.move.lang.core.psi.ext.typeArguments import org.move.lang.core.psi.ext.typeNames import org.move.lang.core.types.StructType class AddAcquiresIntention : MoveElementBaseIntentionAction<AddAcquiresIntention.Context>() { override fun getText(): String = "Add missing 'acquires' declaration" override fun getFamilyName(): String = text data class Context( val functionSignature: MoveFunctionSignature, val expectedAcquiresType: StructType ) override fun findApplicableContext( project: Project, editor: Editor, element: PsiElement ): Context? { val callExpr = element.ancestorOrSelf<MoveCallExpr>() ?: return null if (callExpr.referenceName == null || callExpr.referenceName !in ACQUIRES_BUILTIN_FUNCTIONS ) return null if (callExpr.typeArguments.isEmpty()) return null val expectedAcquiresType = callExpr.typeArguments .getOrNull(0)?.type ?.resolvedType(emptyMap()) as? StructType ?: return null val outFunction = callExpr.containingFunction ?: return null val outFunctionSignature = outFunction.functionSignature ?: return null val acquiresType = outFunctionSignature.acquiresType val context = Context(outFunctionSignature, expectedAcquiresType) if (acquiresType == null) return context val acquiresTypeNames = acquiresType.typeNames ?: return null if (expectedAcquiresType.name() in acquiresTypeNames) return null return context } override fun invoke(project: Project, editor: Editor, ctx: Context) { val acquiresType = ctx.functionSignature.acquiresType val expectedAcquiresTypeName = ctx.expectedAcquiresType.name() if (acquiresType == null) { val newFunctionSignature = MovePsiFactory(project) .createFunctionSignature("${ctx.functionSignature.text} " + "acquires $expectedAcquiresTypeName") ctx.functionSignature.replace(newFunctionSignature) } else { val acquiresTypeText = acquiresType.text.trimEnd(',') val newAcquiresType = MovePsiFactory(project) .createAcquiresType("$acquiresTypeText, $expectedAcquiresTypeName") acquiresType.replace(newAcquiresType) } } }
0
null
0
0
eaf3fbfaf7183274cab9d88bb4dc25187eb534ad
2,827
intellij-move
MIT License
src/listnode/LeetCode328.kt
Alex-Linrk
180,918,573
false
null
package listnode class LeetCode328 { fun oddEvenList(head: ListNode?): ListNode? { if (head?.next == null) { return head } // head 为奇链表头结点,o 为奇链表尾节点 var o = head // p 为偶链表头结点 var p = head.next // e 为偶链表尾节点 var e = p while (o?.next != null && e?.next != null) { o.next = e.next o = o.next e.next = o?.next e = e.next } o?.next = p return head } } fun main() { println(LeetCode328().oddEvenList(createListNodeByArray(1, 2, 3, 4, 5))) }
0
Kotlin
0
0
59f4ab02819b7782a6af19bc73307b93fdc5bf37
606
LeetCode
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/visitscheduler/dto/sessions/SessionCapacityDto.kt
ministryofjustice
409,259,375
false
{"Kotlin": 1492116, "PLpgSQL": 154405, "FreeMarker": 14114, "Dockerfile": 1541, "Shell": 238}
package uk.gov.justice.digital.hmpps.visitscheduler.dto.sessions import io.swagger.v3.oas.annotations.media.Schema import jakarta.validation.constraints.Min import uk.gov.justice.digital.hmpps.visitscheduler.model.entity.session.SessionTemplate @Schema(description = "Session Capacity") data class SessionCapacityDto( @Schema(description = "closed capacity", example = "10", required = true) @field:Min(0) val closed: Int, @Schema(description = "open capacity", example = "50", required = true) @field:Min(0) val open: Int, ) { constructor(sessionTemplateEntity: SessionTemplate) : this( closed = sessionTemplateEntity.closedCapacity, open = sessionTemplateEntity.openCapacity, ) constructor(sessionTemplates: List<SessionTemplate>) : this( closed = sessionTemplates.sumOf { it.closedCapacity }, open = sessionTemplates.sumOf { it.openCapacity }, ) operator fun plus(sessionCapacityDto: SessionCapacityDto): SessionCapacityDto { return SessionCapacityDto(closed = this.closed + sessionCapacityDto.closed, open = this.open + sessionCapacityDto.open) } }
0
Kotlin
2
6
447ca0111a8f6b3e98b71de471c1f1c129792771
1,100
visit-scheduler
MIT License
src/test/kotlin/com/viartemev/requestmapper/model/RequestedUserPathSpek.kt
kreiger
208,247,682
true
{"Kotlin": 111502}
package com.viartemev.requestmapper.model import org.amshove.kluent.shouldEqual import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object RequestedUserPathSpek : Spek({ describe("RequestedUserPath") { context("toPath on user pattern with one path elements and without host") { it("should return original value") { RequestedUserPath("/api").toPath().toFullPath() shouldEqual "/api" } } context("toPath on user pattern with several path elements and without host") { it("should return original value") { RequestedUserPath("/api/v1").toPath().toFullPath() shouldEqual "/api/v1" } } context("toPath on user pattern with https host") { it("should return path from url") { RequestedUserPath("https://www.somepath.com/api/v1").toPath().toFullPath() shouldEqual "/api/v1" } } context("toPath on user pattern with http host") { it("should return path from url") { RequestedUserPath("http://www.somepath.com/api/v1").toPath().toFullPath() shouldEqual "/api/v1" } } context("toPath on user pattern with site with port") { it("should return path from url") { RequestedUserPath("http://localhost:8080/api/v1").toPath().toFullPath() shouldEqual "/api/v1" } } context("toPath on user pattern with short url form") { it("should return path from url") { RequestedUserPath("http://asd/api/v1").toPath().toFullPath() shouldEqual "/api/v1" } } } })
0
null
0
0
e2787a1f51d114e777b9be40a351f68d12da5f6d
1,720
requestmapper
MIT License
kotlin/src/src/main/java/com/techlabcamp/neuronet/presenterImpl/CourseChapterItemPresenterImpl.kt
dimske-sys
610,048,630
false
null
package com.techlabcamp.neuronet.presenterImpl import com.techlabcamp.neuronet.manager.App import com.techlabcamp.neuronet.manager.Utils import com.techlabcamp.neuronet.manager.net.* import com.techlabcamp.neuronet.model.BaseResponse import com.techlabcamp.neuronet.model.ChapterFileItem import com.techlabcamp.neuronet.model.ChapterItemMark import com.techlabcamp.neuronet.presenter.Presenter import com.techlabcamp.neuronet.ui.frag.CourseChapterItemFrag import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Response import java.io.File class CourseChapterItemPresenterImpl(private val frag: CourseChapterItemFrag) : Presenter.CourseChapterItemPresenter { companion object { val downloadingRequests: HashMap<Int, Call<*>> = HashMap() } override fun changeItemStatus(chapterItemMark: ChapterItemMark) { ApiService.apiClient!!.changeLessonItemStatus(chapterItemMark.courseId, chapterItemMark) .enqueue(object : CustomCallback<BaseResponse> { override fun onStateChanged(): RetryListener? { return RetryListener { changeItemStatus(chapterItemMark) } } override fun onResponse( call: Call<BaseResponse>, response: Response<BaseResponse> ) { if (response.body() != null) { frag.onItemStatusChanged(response.body()!!, chapterItemMark) } } }) } override fun downloadFile( fileItem: ChapterFileItem, progressListener: OnDownloadProgressListener ) { val fileId = fileItem.id val baseUrlAndHost = Utils.getBaseUrlAndHostFromUrl(fileItem.file) ?: return val downloadRequest = ApiService.getDownloadApiClient(baseUrlAndHost[0], progressListener, fileId) .download(baseUrlAndHost[1]) downloadingRequests[fileId] = downloadRequest downloadRequest.enqueue(object : CustomCallback<ResponseBody> { override fun onStateChanged(): RetryListener? { return RetryListener { downloadFile(fileItem, progressListener) } } override fun onResponse( call: Call<ResponseBody>, response: Response<ResponseBody> ) { if (response.body() != null) { frag.context?.let { Thread { val byteStream = response.body()!!.byteStream() val filePath = Utils.saveFile( frag.requireContext(), App.Companion.Directory.DOWNLOADS.value(), "${fileId}.${fileItem.fileType}", byteStream ) if (filePath != null) { Utils.copyFileToDownloads( frag.requireContext(), File(filePath), "${fileItem.title}.${fileItem.fileType}" ) } }.start() } } } }) } override fun cancelDownload(fileId: Int) { if (downloadingRequests.containsKey(fileId)) { downloadingRequests[fileId]!!.cancel() downloadingRequests.remove(fileId) } } }
0
Kotlin
0
0
0f4cc0534a3c77a8edfb0fa043fb2ed7e2707250
3,658
neuronet
Apache License 2.0
kotlin/src/src/main/java/com/techlabcamp/neuronet/presenterImpl/CourseChapterItemPresenterImpl.kt
dimske-sys
610,048,630
false
null
package com.techlabcamp.neuronet.presenterImpl import com.techlabcamp.neuronet.manager.App import com.techlabcamp.neuronet.manager.Utils import com.techlabcamp.neuronet.manager.net.* import com.techlabcamp.neuronet.model.BaseResponse import com.techlabcamp.neuronet.model.ChapterFileItem import com.techlabcamp.neuronet.model.ChapterItemMark import com.techlabcamp.neuronet.presenter.Presenter import com.techlabcamp.neuronet.ui.frag.CourseChapterItemFrag import okhttp3.ResponseBody import retrofit2.Call import retrofit2.Response import java.io.File class CourseChapterItemPresenterImpl(private val frag: CourseChapterItemFrag) : Presenter.CourseChapterItemPresenter { companion object { val downloadingRequests: HashMap<Int, Call<*>> = HashMap() } override fun changeItemStatus(chapterItemMark: ChapterItemMark) { ApiService.apiClient!!.changeLessonItemStatus(chapterItemMark.courseId, chapterItemMark) .enqueue(object : CustomCallback<BaseResponse> { override fun onStateChanged(): RetryListener? { return RetryListener { changeItemStatus(chapterItemMark) } } override fun onResponse( call: Call<BaseResponse>, response: Response<BaseResponse> ) { if (response.body() != null) { frag.onItemStatusChanged(response.body()!!, chapterItemMark) } } }) } override fun downloadFile( fileItem: ChapterFileItem, progressListener: OnDownloadProgressListener ) { val fileId = fileItem.id val baseUrlAndHost = Utils.getBaseUrlAndHostFromUrl(fileItem.file) ?: return val downloadRequest = ApiService.getDownloadApiClient(baseUrlAndHost[0], progressListener, fileId) .download(baseUrlAndHost[1]) downloadingRequests[fileId] = downloadRequest downloadRequest.enqueue(object : CustomCallback<ResponseBody> { override fun onStateChanged(): RetryListener? { return RetryListener { downloadFile(fileItem, progressListener) } } override fun onResponse( call: Call<ResponseBody>, response: Response<ResponseBody> ) { if (response.body() != null) { frag.context?.let { Thread { val byteStream = response.body()!!.byteStream() val filePath = Utils.saveFile( frag.requireContext(), App.Companion.Directory.DOWNLOADS.value(), "${fileId}.${fileItem.fileType}", byteStream ) if (filePath != null) { Utils.copyFileToDownloads( frag.requireContext(), File(filePath), "${fileItem.title}.${fileItem.fileType}" ) } }.start() } } } }) } override fun cancelDownload(fileId: Int) { if (downloadingRequests.containsKey(fileId)) { downloadingRequests[fileId]!!.cancel() downloadingRequests.remove(fileId) } } }
0
Kotlin
0
0
0f4cc0534a3c77a8edfb0fa043fb2ed7e2707250
3,658
neuronet
Apache License 2.0
app/src/main/java/com/example/okcredit/ViewModel/CustomerViewModelFactory.kt
lucifernipun22
345,898,513
false
null
package com.example.okcredit.ViewModel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.okcredit.Repository.OkCreditRepo class CustomerViewModelFactory(val repository: OkCreditRepo) : ViewModelProvider.Factory { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return CustomerViewModel(repository) as T } }
0
Kotlin
0
2
cc27ed6e6668b25637ea92b0fa039a951426b7af
391
okCredit
MIT License
src/main/kotlin/kr/ac/jbnu/ampm/ampmsiteapi/Entity/MemberEntity.kt
ampm-jbnu
599,133,979
false
null
package kr.ac.jbnu.ampm.ampmsiteapi.Entity import jakarta.persistence.Entity import jakarta.persistence.GeneratedValue import jakarta.persistence.GenerationType import jakarta.persistence.Id import kr.ac.jbnu.ampm.ampmsiteapi.DTO.MemberDTO import lombok.Getter import lombok.Setter @Entity @Getter @Setter class MemberEntity( @Id @GeneratedValue(strategy = GenerationType.IDENTITY) var id: Long?, var name: String, var email: String, var studentNum: Long?, var bio: String, var interest: String, var status: Int? ) fun MemberEntity.toDTO() = MemberDTO(id, name, email, studentNum, bio, interest, status)
1
Kotlin
2
2
8d21ee326383f97d8113c7fa84798bd29a8956e6
642
ampm-site-api
MIT License
src/main/kotlin/com/llamalad7/pseudo/utils/ErrorUtils.kt
LlamaLad7
289,768,489
false
{"Markdown": 1, "INI": 1, "Gradle": 1, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Java Properties": 1, "Kotlin": 46, "Java": 1, "ANTLR": 2, "SVG": 1, "Papyrus": 9, "Text": 8}
package com.llamalad7.pseudo.utils import com.llamalad7.pseudo.runtime.abstraction.BaseObject object ErrorUtils { @JvmStatic fun unsupportedOperation(operator: String, instance: BaseObject, other: BaseObject? = null): Nothing { if (other == null) error("Unsupported operation '$operator' on type '${instance::class.simpleName}'") else error("Unsupported operation '$operator' between types '${instance::class.simpleName}' and '${other::class.simpleName}'") } @JvmStatic fun noAccessibleAttribute(name: String, baseObject: BaseObject, accessor: Class<*>?): Nothing = error("Object of type '${baseObject::class.simpleName}' has no attribute '$name' or it is not accessible from type '${accessor?.simpleName}'") @JvmStatic fun noPublicAttribute(name: String, baseObject: BaseObject): Nothing = error("Object of type '${baseObject::class.simpleName}' has no attribute '$name' or it is private") @JvmStatic fun noWriteableAttribute(name: String, baseObject: BaseObject, accessor: Class<*>?): Nothing = error("Object of type '${baseObject::class.simpleName}' has no writeable attribute '$name' or it is not accessible from type '${accessor?.simpleName}'") @JvmStatic fun noAccessibleObject(name: String, accessor: Class<*>?): Nothing = error("Object '$name' doesn't exist in the current scope or it is not accessible from type '${accessor?.simpleName}'") @JvmStatic fun noWriteableObject(name: String, accessor: Class<*>?): Nothing = error("A writeable object '$name' doesn't exist in the current scope or it is not accessible from type '${accessor?.simpleName}'") }
0
Kotlin
1
8
b7abb7cfd99944f4e143a399f10cd7ca2304fd24
1,630
pseudo-kt
Apache License 2.0
arrow-inject-compiler-plugin/src/testData/diagnostics/value-arguments/circular_proof_single_cycle_rule.kt
arrow-kt
471,344,439
false
null
package foo.bar import arrow.inject.annotations.Inject import foo.bar.annotations.Given @Given internal fun n(@Given n: Int): Int = n @Inject fun <A> given(@Given a: A): A = a val result = <!CIRCULAR_CYCLE_ON_GIVEN_PROOF!>given<Int>()<!>
13
Kotlin
2
9
f2d62a93fa18fc7f2944687642c8ad01a0d23bf5
243
arrow-proofs
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/pecs/jpc/cli/BulkPriceImportCommandTest.kt
ministryofjustice
292,861,912
false
null
package uk.gov.justice.digital.hmpps.pecs.jpc.cli import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.verify import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.jupiter.api.Test import uk.gov.justice.digital.hmpps.pecs.jpc.domain.price.EffectiveYear import uk.gov.justice.digital.hmpps.pecs.jpc.domain.price.Supplier import uk.gov.justice.digital.hmpps.pecs.jpc.service.ImportService import java.time.LocalDateTime /** * Provides CLI command to add the latest supplier prices spreadsheet(s) to the price book. * * IMPORTANT: this should be run in a pre-production environment prior to running in production. * * The price spreadsheets are pulled from an Amazon S3 bucket. These are uploaded manually, it is important you are * confident you have the correct spreadsheet(s) in S3 prior to running this command. */ internal class BulkPriceImportCommandTest { private val september2020 = LocalDateTime.of(2020, 9, 1, 0, 0) private val importService: ImportService = mock() private val effectiveYear: EffectiveYear = EffectiveYear { september2020 } private val command: BulkPriceImportCommand = BulkPriceImportCommand(importService, effectiveYear) @Test internal fun `import prices for Serco fails is effective year is two years or more out of date`() { assertThatThrownBy { command.bulkImportPricesFor(Supplier.SERCO, 2018) } .isInstanceOf(RuntimeException::class.java) .hasMessage("Price imports can only take place in the current '2020' or previous effective year '2019'.") } @Test internal fun `import prices for GEOAmey fails is effective year is two years or more out of date`() { assertThatThrownBy { command.bulkImportPricesFor(Supplier.GEOAMEY, 2018) } .isInstanceOf(RuntimeException::class.java) .hasMessage("Price imports can only take place in the current '2020' or previous effective year '2019'.") } @Test internal fun `import prices for Serco for 2019 succeeds`() { command.bulkImportPricesFor(Supplier.SERCO, 2019) verify(importService).importPrices(Supplier.SERCO, 2019) } @Test internal fun `import prices for Geoamey for 2019 succeeds`() { command.bulkImportPricesFor(Supplier.GEOAMEY, 2019) verify(importService).importPrices(Supplier.GEOAMEY, 2019) } @Test internal fun `import prices for Serco for the current effective year (2020) succeeds`() { command.bulkImportPricesFor(Supplier.SERCO, 2020) verify(importService).importPrices(Supplier.SERCO, 2020) } @Test internal fun `import prices for Geoamey for the current effective year (2020) succeeds`() { command.bulkImportPricesFor(Supplier.GEOAMEY, 2020) verify(importService).importPrices(Supplier.GEOAMEY, 2020) } @Test internal fun `import prices for Serco for the effective year in the future fails`() { assertThatThrownBy { command.bulkImportPricesFor(Supplier.SERCO, 2021) }.isInstanceOf(RuntimeException::class.java) } @Test internal fun `import prices for Geoamey for the effective year in the future fails`() { assertThatThrownBy { command.bulkImportPricesFor(Supplier.GEOAMEY, 2021) }.isInstanceOf(RuntimeException::class.java) } @Test internal fun `import prices for Unknown for any valid year fails`() { assertThatThrownBy { command.bulkImportPricesFor(Supplier.UNKNOWN, 2019) }.isInstanceOf(RuntimeException::class.java) } }
1
Kotlin
2
1
f694144f4c2e67eca265ebdebbf8ff0bc48525d2
3,416
calculate-journey-variable-payments
MIT License
async-buffer/src/main/kotlin/org/project/async/buffer/config/datasource/BufferDataSourceConfig.kt
leltonborges
710,551,341
false
{"Kotlin": 91566}
package org.project.async.buffer.config.datasource import jakarta.persistence.EntityManagerFactory import org.springframework.beans.factory.annotation.Qualifier import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.jpa.repository.config.EnableJpaRepositories import org.springframework.orm.jpa.JpaTransactionManager import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter import org.springframework.transaction.PlatformTransactionManager import javax.sql.DataSource @Configuration @EnableJpaRepositories( basePackages = ["org.project.async.buffer.core.repository.buffer"], transactionManagerRef = "bufferTransactionManager", entityManagerFactoryRef = "bufferEntityManager" ) class BufferDataSourceConfig { @Bean("bufferDataSource") fun bufferDataSource( @Qualifier("bufferSourceProperties") dataSourceProperties: DataSourceProperties, ): DataSource { return dataSourceProperties.initializeDataSourceBuilder().build(); } @Bean("bufferEntityManager") fun bufferEntityManager( @Qualifier("bufferDataSource") dataSource: DataSource, ): LocalContainerEntityManagerFactoryBean { val factory = LocalContainerEntityManagerFactoryBean() val vendorAdapter = HibernateJpaVendorAdapter() factory.persistenceUnitName = "bufferUnit" factory.dataSource = dataSource; factory.setPackagesToScan("org.project.async.buffer.core.model.buffer") factory.jpaVendorAdapter = vendorAdapter return factory } @Bean("bufferTransactionManager") fun batchTransactionManager( @Qualifier("bufferEntityManager") entityManager: EntityManagerFactory, ): PlatformTransactionManager { return JpaTransactionManager(entityManager) } }
0
Kotlin
0
0
8f8b9652ebfbee3a1a6161865a350fd602f9a016
2,007
buffer_async_read_writer
MIT License
kotlin-electron/src/jsMain/generated/electron/ResizeOptions.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! package electron typealias ResizeOptions = electron.core.ResizeOptions
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
126
kotlin-wrappers
Apache License 2.0
app/src/test/java/com/garymcgowan/postapocalypse/utils/ReplaceMainThreadSchedulerRule.kt
GaryMcGowan
182,379,305
false
null
package com.garymcgowan.postapocalypse.utils import io.reactivex.Scheduler import io.reactivex.android.plugins.RxAndroidPlugins import io.reactivex.plugins.RxJavaPlugins import io.reactivex.schedulers.Schedulers import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement class ReplaceMainThreadSchedulerRule(val replaceScheduler: Scheduler = Schedulers.trampoline()) : TestRule { override fun apply(base: Statement, description: Description): Statement = object : Statement() { override fun evaluate() { RxAndroidPlugins.setInitMainThreadSchedulerHandler { replaceScheduler } try { base.evaluate() } finally { RxJavaPlugins.reset() } } } }
0
Kotlin
0
0
6214f0d6a3f8397625b81f4ac2d6b50fb76612d9
795
Post-Apocalypse
Apache License 2.0
app/src/main/java/com/cyrus/languagedemo/BaseActivity.kt
QasimCyrus
221,484,540
false
null
package com.cyrus.languagedemo import android.content.Context import androidx.appcompat.app.AppCompatActivity import com.cyrus.language.LanguageHelper /** * 活动基类 * * @author Cyrus */ abstract class BaseActivity : AppCompatActivity() { override fun attachBaseContext(newBase: Context) { super.attachBaseContext(LanguageHelper.onAttach(newBase)) /* * androidx 方法内部调用的代理方法覆盖了我们设置的属性,所以这里再设置一次。 * 注意:这里传的上下文需要是被覆盖过之后的,所以是 this 不是 newBase。 */ LanguageHelper.onAttach(this) } }
0
Kotlin
0
5
8c356e5ab92e1577058c7ce30fb488119e666202
537
MultiLanguage
Apache License 2.0
app/src/main/java/io/hungnguyen/nab/assignment/data/mapper/WeatherMapper.kt
pavel-corsaghin
489,984,562
false
{"Kotlin": 37425}
package io.hungnguyen.nab.assignment.data.mapper import io.hungnguyen.nab.assignment.data.model.response.Weather import io.hungnguyen.nab.assignment.domain.model.WeatherEntity import javax.inject.Inject class WeatherMapper @Inject constructor() { fun mapToEntity(item: Weather): WeatherEntity { return WeatherEntity( date = item.dt ?: 0, temp = item.temp?.day, pressure = item.pressure, humidity = item.humidity, description = item.description.firstOrNull()?.description ) } }
0
Kotlin
0
0
835a090a2a2a7bcc8a6740cee5842cfa6721d557
563
NABAssignment
MIT License
app/src/main/java/com/notmiyouji/newsapp/kotlin/recycleviewholder/rss2json/Rss2JsonMultiFeed.kt
2dgirlismywaifu
576,986,982
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "YAML": 2, "Proguard": 1, "Java": 31, "XML": 111, "Kotlin": 61, "Makefile": 2}
package com.notmiyouji.newsapp.kotlin.recycleviewholder.rss2json import android.annotation.SuppressLint import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.notmiyouji.newsapp.kotlin.model.NewsAppResult import com.notmiyouji.newsapp.kotlin.model.rss2json.Result import com.notmiyouji.newsapp.kotlin.retrofit.NewsAppApi.apiClient import com.notmiyouji.newsapp.kotlin.retrofit.NewsAppInterface import com.notmiyouji.newsapp.kotlin.util.AppUtils.encodeToBase64 import retrofit2.Call import retrofit2.Callback import retrofit2.Response /* * Copyright By @2dgirlismywaifu (2023) . * * 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. * */ class Rss2JsonMultiFeed( var activity: AppCompatActivity, var recyclerView: RecyclerView, var linearLayoutManager: LinearLayoutManager ) { private var newsAppInterface: NewsAppInterface = apiClient!!.create(NewsAppInterface::class.java) var call: Call<NewsAppResult?>? = null var items: MutableList<Result> = ArrayList() var adapterHorizontal: Rss2JsonAdapterHorizontal? = null var adapterVertical: Rss2JsonAdapterVertical? = null fun rss2JsonVertical(userId: String?, type: String?, alertDialog: AlertDialog) { call = newsAppInterface.convertRssUrl2Json(userId, encodeToBase64(type!!), "10") assert(call != null) call!!.enqueue(object : Callback<NewsAppResult?> { @SuppressLint("NotifyDataSetChanged") override fun onResponse( call: Call<NewsAppResult?>, response: Response<NewsAppResult?> ) { if (response.isSuccessful) { assert(response.body() != null) if (response.body()!!.result != null) { if (items.isNotEmpty()) { //Clear the list items.clear() } items = response.body()!!.result as MutableList<Result> adapterVertical = Rss2JsonAdapterVertical(items, activity) recyclerView.removeAllViews() recyclerView.layoutManager = linearLayoutManager recyclerView.adapter = adapterVertical recyclerView.viewTreeObserver.addOnGlobalLayoutListener { if (adapterVertical!!.itemCount > 0) { alertDialog.dismiss() } } adapterVertical!!.notifyDataSetChanged() } } } override fun onFailure(call: Call<NewsAppResult?>, t: Throwable) { println("Failure") } }) } fun rss2JsonVerticalByKeyWord( userId: String?, keyword: String?, type: String?, alertDialog: AlertDialog ) { call = newsAppInterface.searchNewsFromRss(userId, keyword, encodeToBase64(type!!), "5") assert(call != null) call!!.enqueue(object : Callback<NewsAppResult?> { @SuppressLint("NotifyDataSetChanged") override fun onResponse( call: Call<NewsAppResult?>, response: Response<NewsAppResult?> ) { if (response.isSuccessful) { assert(response.body() != null) if (response.body()!!.result != null) { if (items.isNotEmpty()) { items.clear() } items = response.body()!!.result as MutableList<Result> adapterVertical = Rss2JsonAdapterVertical(items, activity) recyclerView.removeAllViews() recyclerView.layoutManager = linearLayoutManager recyclerView.adapter = adapterVertical recyclerView.viewTreeObserver.addOnGlobalLayoutListener { if (adapterVertical!!.itemCount > 0) { alertDialog.dismiss() } } adapterVertical!!.notifyDataSetChanged() } } } override fun onFailure(call: Call<NewsAppResult?>, t: Throwable) { println("Failure") } }) } @SuppressLint("NotifyDataSetChanged") fun clearAdapterVertical() { adapterVertical = Rss2JsonAdapterVertical(items, activity) adapterVertical!!.clear() adapterVertical!!.notifyDataSetChanged() } fun rss2JsonHorizontal(userId: String?, type: String?, alertDialog: AlertDialog) { call = newsAppInterface.convertRssUrl2Json(userId, encodeToBase64(type!!), "5") assert(call != null) call!!.enqueue(object : Callback<NewsAppResult?> { @SuppressLint("NotifyDataSetChanged") override fun onResponse( call: Call<NewsAppResult?>, response: Response<NewsAppResult?> ) { if (response.isSuccessful) { assert(response.body() != null) if (response.body()!!.result != null) { if (items.isNotEmpty()) { items.clear() } items = response.body()!!.result as MutableList<Result> adapterHorizontal = Rss2JsonAdapterHorizontal(items, activity) recyclerView.removeAllViews() recyclerView.layoutManager = linearLayoutManager recyclerView.adapter = adapterHorizontal recyclerView.viewTreeObserver.addOnGlobalLayoutListener { if (adapterHorizontal!!.itemCount > 0) { alertDialog.dismiss() } } adapterHorizontal!!.notifyDataSetChanged() } } } override fun onFailure(call: Call<NewsAppResult?>, t: Throwable) { println("Failure") } }) } @SuppressLint("NotifyDataSetChanged") fun clearAdapterHorizontal() { adapterHorizontal = Rss2JsonAdapterHorizontal(items, activity) adapterHorizontal!!.clear() adapterHorizontal!!.notifyDataSetChanged() } }
5
Java
0
2
c60ad14f219891ed77b61df9f14ffcdebbea7997
7,202
NewsApp-Spring-Api
Apache License 2.0
src/main/kotlin/sqlbuilder/meta/MethodPropertyResolver.kt
laurentvdl
27,872,125
false
null
package sqlbuilder.meta import sqlbuilder.Configuration import sqlbuilder.meta.util.findFieldInHierarchy import java.lang.reflect.Field import java.lang.reflect.Modifier import java.util.HashSet import java.util.LinkedList open class MethodPropertyResolver : PropertyResolver { override fun resolvePropertiesForBean(beanClass: Class<*>, mutators: Boolean, configuration: Configuration): List<PropertyReference> { val prefixes = if (mutators) { setOf("set") } else { setOf("get", "is") } val result = LinkedList<PropertyReference>() val names = HashSet<String>() val methods = beanClass.methods for (method in methods) { val name = method.name!! val methodModifiers = method.modifiers for (prefix in prefixes) { if (name.startsWith(prefix) && !Modifier.isTransient(methodModifiers) && !Modifier.isStatic(methodModifiers)) { val propertyName = name.substring(prefix.length, prefix.length + 1).toLowerCase() + name.substring(prefix.length + 1) var accept = true val privateField = beanClass.findFieldInHierarchy(propertyName) accept = if (privateField == null) { false } else { accept && !isTransient(privateField) } if (accept) { if (mutators) { val parameters = method.parameterTypes if (parameters != null && parameters.size == 1 && (isSqlType(parameters[0], configuration) || Enum::class.java.isAssignableFrom(parameters[0]))) { result.add(JavaGetterSetterPropertyReference(propertyName, method, parameters[0])) names.add(propertyName) } } else { val returnType = method.returnType if (returnType != null && isSqlType(returnType, configuration)) { result.add(JavaGetterSetterPropertyReference(propertyName, method, returnType)) names.add(propertyName) } } } } } } return result } private fun isSqlType(clazz: Class<*>, configuration: Configuration): Boolean { return configuration.objectMapperForType(clazz) != null } protected fun isTransient(privateField: Field): Boolean { val modifiers = privateField.modifiers return Modifier.isTransient(modifiers) || privateField.isAnnotationPresent(Transient::class.java) } }
1
null
2
6
4efe1dd61f6da45192a1b2741d654269616535d0
2,823
sqlbuilder
Apache License 2.0
code/mobile/app/src/main/java/com/iade/streetart/NavRoutes.kt
williansantaana
468,550,359
false
{"Jupyter Notebook": 9659469, "Kotlin": 72757, "JavaScript": 24280, "PLpgSQL": 4073, "Shell": 1033, "HTML": 458, "CSS": 111}
package com.iade.streetart sealed class NavRoutes(val route: String) { object MapView: NavRoutes("map") object HomeView: NavRoutes("home") object LoginView: NavRoutes("login") object SignUpView: NavRoutes("signUp") object CameraView: NavRoutes("camera") object AddImageView: NavRoutes("addImage") object ImagePreviewView: NavRoutes("preview") object AddStreetArtView: NavRoutes("addStreetArt") object SearchView: NavRoutes("search/{authorName}") object SingleStreetArtView: NavRoutes("streetArt/{streetArtId}") }
0
Jupyter Notebook
0
0
7607bccfd92a39c40d632402388d6efd54c50132
534
street-art-app
MIT License
jvm-common/src/main/kotlin/org/digma/intellij/plugin/idea/navigation/JvmNavigationDiscoveryStartupActivity.kt
digma-ai
472,408,329
false
{"Kotlin": 1686412, "Java": 579281, "C#": 117248, "Shell": 13664, "HTML": 11307, "FreeMarker": 10897}
package org.digma.intellij.plugin.idea.navigation import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import org.digma.intellij.plugin.log.Log import org.digma.intellij.plugin.startup.DigmaProjectActivity internal class JvmNavigationDiscoveryStartupActivity : DigmaProjectActivity() { override fun executeProjectStartup(project: Project) { Log.log(logger::info, project, "starting span navigation mapping") val jvmSpanNavigationProvider = JvmSpanNavigationProvider.getInstance(project) jvmSpanNavigationProvider.buildNavigationDiscovery() Log.log(logger::info, project, "starting endpoint navigation mapping") val javaEndpointNavigationProvider = JvmEndpointNavigationProvider.getInstance(project) javaEndpointNavigationProvider.buildNavigationDiscovery() //start the service project.service<NavigationDiscoveryChangeService>() } }
477
Kotlin
7
32
ce460b0cdc604968d267b98e72bf9dd211cf39b3
949
digma-intellij-plugin
MIT License
src/main/kotlin/com/app/norutin/service/api/UserService.kt
Lackier
347,097,828
false
null
package com.app.norutin.service.api import com.app.norutin.model.User interface UserService { fun findByUid(oid: String): User? fun save(user: User): User }
0
Kotlin
0
0
7f350d3c1c0d08a50a6dc9fab6d2b71fe7c2a736
167
norutin-server
MIT License
src/jvmMain/kotlin/acidicoala/koalageddon/steam/ui/SteamScreen.kt
acidicoala
584,899,259
false
null
package acidicoala.koalageddon.steam.ui import acidicoala.koalageddon.core.ui.composable.PlatformScreen import androidx.compose.runtime.Composable @Composable fun SteamScreen() { PlatformScreen( storeTab = { SteamStoreScreen() }, gameTab = { SteamGameScreen() } ) }
1
Kotlin
4
50
9ec09a7ba5cabc7b1be173a9c8e8794c93984a24
291
Koalageddon2
The Unlicense
src/main/kotlin/me/earthme/mysm/utils/ysm/MiscUtils.kt
Era4FunMC
701,306,363
false
{"Kotlin": 119393, "Java": 31228}
package me.earthme.mysm.utils.ysm import java.io.* import java.nio.ByteBuffer import java.util.* object MiscUtils { @Throws(IOException::class) fun <T> objectToByteArray(input: T): ByteArray { ByteArrayOutputStream().use { baseStream -> ObjectOutputStream(baseStream).use { encoder -> encoder.writeObject(input) encoder.flush() return baseStream.toByteArray() } } } fun uuidToByte(paramUUID: UUID): ByteArray { val byteBuffer = ByteBuffer.wrap(ByteArray(16)) byteBuffer.putLong(paramUUID.mostSignificantBits) byteBuffer.putLong(paramUUID.leastSignificantBits) return byteBuffer.array() } }
0
Kotlin
3
7
b46fbafaf0d9bb4a006e893aa7da7062154cf3cc
733
MyYsmNonFull
MIT License
v1_23/src/main/java/de/loosetie/k8s/dsl/manifests/PersistentVolumeClaimCondition.kt
loosetie
283,145,621
false
{"Kotlin": 8925107}
package de.loosetie.k8s.dsl.manifests import de.loosetie.k8s.dsl.K8sTopLevel import de.loosetie.k8s.dsl.K8sDslMarker import de.loosetie.k8s.dsl.K8sManifest import de.loosetie.k8s.dsl.HasMetadata @K8sDslMarker interface PersistentVolumeClaimCondition_core_v1: K8sManifest { /** Last time we probed the condition. */ val lastProbeTime: Time_meta_v1? /** Last time the condition transitioned from one status to another. */ val lastTransitionTime: Time_meta_v1? /** Human-readable message indicating details about last transition. */ @K8sDslMarker var message: String? /** Unique, this should be a short, machine understandable string that gives the reason for condition's last transition. If it reports "ResizeStarted" that means the underlying persistent volume is being resized. */ @K8sDslMarker var reason: String? /** */ @K8sDslMarker var status: String? /** Possible enum values: - `"FileSystemResizePending"` - controller resize is finished and a file system resize is pending on node - `"Resizing"` - a user trigger resize of pvc has been started */ @K8sDslMarker var type: String? }
0
Kotlin
0
2
57d56ab780bc3134c43377e647e7f0336a5f17de
1,115
k8s-dsl
Apache License 2.0
service-xmpp/src/main/java/io/github/zohrevand/dialogue/service/xmpp/collector/ContactsCollector.kt
zohrevand
510,113,579
false
{"Kotlin": 271495}
package io.github.zohrevand.dialogue.service.xmpp.collector import io.github.zohrevand.core.model.data.Contact interface ContactsCollector { /** * Collects the changes to contacts stream which should be added * to roster entries, originated from database * */ suspend fun collectShouldAddToRosterContacts( addToRoster: suspend (List<Contact>) -> Unit ) }
1
Kotlin
2
11
9607aed6f182d3eb051e5da4cee6ddf82c659690
392
dialogue
Apache License 2.0
core/src/main/java/io/snabble/sdk/codes/ScannedCode.kt
snabble
124,525,499
false
null
package io.snabble.sdk.codes import io.snabble.sdk.Project import io.snabble.sdk.Unit import java.io.Serializable import java.math.BigDecimal import java.util.ArrayList // TODO: Kotlinify this class more, get rid of the "hasXX" methods and use optionals /** * Class representing a scanned code, including its potentially embedded data */ class ScannedCode private constructor() : Serializable { private var _embeddedData: Int? = null private var _embeddedDecimalData: BigDecimal? = null private var _price: Int? = null /** * The code that you use to lookup the product in the product database */ var lookupCode: String? = null private set /** * The code that was actually scanned */ var code: String? = null private set /** * The template that this code matches to */ var templateName: String? = null private set /** * The template that this code may be transformed to when embedding in encoded codes */ var transformationTemplateName: String? = null private set /** * The code used when embedding in encoded codes */ var transformationCode: String? = null private set var embeddedData: Int /** * Get the data embedded in the code, or 0 */ get() = _embeddedData?.let { it } ?: 0 /** * Set the data embedded in the code, or 0 */ set(value) { _embeddedData = value } /** * Returns true if the code holds embedded data */ fun hasEmbeddedData(): Boolean { return _embeddedData != null } var embeddedDecimalData: BigDecimal /** * Get the data embedded in the code, as a big decimal */ get() = _embeddedDecimalData?.let { it } ?: BigDecimal.ZERO /** * Set the data embedded in the code, as a big decimal */ set(value) { _embeddedDecimalData = value } /** * Returns true if the code holds embedded decimal data */ fun hasEmbeddedDecimalData(): Boolean { return _embeddedDecimalData != null } /** * Gets the unit of the embedded data */ var embeddedUnit: Unit? = null /** * Gets the embedded price */ val price: Int get() = _price?.let { it } ?: 0 /** * Returns true if the code holds a embedded price */ fun hasPrice(): Boolean { return _price != null } /** * Creates a new builder, based on this code. */ fun newBuilder(): Builder { return Builder(this) } class Builder { var scannedCode: ScannedCode constructor(templateName: String?) { scannedCode = ScannedCode().apply { this.templateName = templateName } } constructor(source: ScannedCode) { scannedCode = ScannedCode().apply { _embeddedData = source._embeddedData _embeddedDecimalData = source._embeddedDecimalData _price = source._price lookupCode = source.lookupCode code = source.code templateName = source.templateName embeddedUnit = source.embeddedUnit transformationTemplateName = source.transformationTemplateName transformationCode = source.transformationCode } } fun setScannedCode(scannedCode: String?) = apply { this.scannedCode.code = scannedCode } fun setLookupCode(lookupCode: String?) = apply { this.scannedCode.lookupCode = lookupCode } fun setEmbeddedData(embeddedData: Int) = apply { this.scannedCode._embeddedData = embeddedData } fun setEmbeddedDecimalData(embeddedDecimalData: BigDecimal?) = apply { this.scannedCode._embeddedDecimalData = embeddedDecimalData } fun setEmbeddedUnit(unit: Unit?) = apply { this.scannedCode.embeddedUnit = unit } fun setTransformationCode(transformationCode: String?) = apply { this.scannedCode.transformationCode = transformationCode } fun setTransformationTemplateName(name: String?) = apply { this.scannedCode.transformationTemplateName = name } fun setPrice(price: Int) = apply { this.scannedCode._price = price } fun create(): ScannedCode { return scannedCode } } companion object { @JvmStatic fun parseDefault(project: Project, code: String?): ScannedCode? { project.codeTemplates.forEach { codeTemplate -> val scannedCode = codeTemplate.match(code).buildCode() if (scannedCode != null && scannedCode.templateName == "default") { return scannedCode } } return null } @JvmStatic fun parse(project: Project, code: String): List<ScannedCode> { val matches: MutableList<ScannedCode> = ArrayList() val defaultTemplate = project.defaultCodeTemplate project.codeTemplates.forEach { codeTemplate -> val scannedCode = codeTemplate.match(code).buildCode() if (scannedCode != null) { matches.add(scannedCode) } } project.priceOverrideTemplates.forEach { priceOverrideTemplate -> val codeTemplate = priceOverrideTemplate.codeTemplate val scannedCode = codeTemplate.match(code).buildCode() scannedCode?.let { val lookupCode = scannedCode.lookupCode if (lookupCode != code) { val defaultCode = defaultTemplate?.match(lookupCode)?.buildCode() defaultCode?.let { defaultCode._embeddedData = scannedCode._embeddedData defaultCode.embeddedUnit = Unit.PRICE defaultCode.code = scannedCode.code val transformTemplate = priceOverrideTemplate.transmissionCodeTemplate if (transformTemplate != null) { defaultCode.transformationTemplateName = transformTemplate.name defaultCode.transformationCode = priceOverrideTemplate.transmissionCode } matches.add(defaultCode) } } } } return matches } } }
1
null
1
6
8fc301be7512714e127eb12566a905b59e2eed9d
6,777
Android-SDK
MIT License
core/src/main/java/io/snabble/sdk/codes/ScannedCode.kt
snabble
124,525,499
false
null
package io.snabble.sdk.codes import io.snabble.sdk.Project import io.snabble.sdk.Unit import java.io.Serializable import java.math.BigDecimal import java.util.ArrayList // TODO: Kotlinify this class more, get rid of the "hasXX" methods and use optionals /** * Class representing a scanned code, including its potentially embedded data */ class ScannedCode private constructor() : Serializable { private var _embeddedData: Int? = null private var _embeddedDecimalData: BigDecimal? = null private var _price: Int? = null /** * The code that you use to lookup the product in the product database */ var lookupCode: String? = null private set /** * The code that was actually scanned */ var code: String? = null private set /** * The template that this code matches to */ var templateName: String? = null private set /** * The template that this code may be transformed to when embedding in encoded codes */ var transformationTemplateName: String? = null private set /** * The code used when embedding in encoded codes */ var transformationCode: String? = null private set var embeddedData: Int /** * Get the data embedded in the code, or 0 */ get() = _embeddedData?.let { it } ?: 0 /** * Set the data embedded in the code, or 0 */ set(value) { _embeddedData = value } /** * Returns true if the code holds embedded data */ fun hasEmbeddedData(): Boolean { return _embeddedData != null } var embeddedDecimalData: BigDecimal /** * Get the data embedded in the code, as a big decimal */ get() = _embeddedDecimalData?.let { it } ?: BigDecimal.ZERO /** * Set the data embedded in the code, as a big decimal */ set(value) { _embeddedDecimalData = value } /** * Returns true if the code holds embedded decimal data */ fun hasEmbeddedDecimalData(): Boolean { return _embeddedDecimalData != null } /** * Gets the unit of the embedded data */ var embeddedUnit: Unit? = null /** * Gets the embedded price */ val price: Int get() = _price?.let { it } ?: 0 /** * Returns true if the code holds a embedded price */ fun hasPrice(): Boolean { return _price != null } /** * Creates a new builder, based on this code. */ fun newBuilder(): Builder { return Builder(this) } class Builder { var scannedCode: ScannedCode constructor(templateName: String?) { scannedCode = ScannedCode().apply { this.templateName = templateName } } constructor(source: ScannedCode) { scannedCode = ScannedCode().apply { _embeddedData = source._embeddedData _embeddedDecimalData = source._embeddedDecimalData _price = source._price lookupCode = source.lookupCode code = source.code templateName = source.templateName embeddedUnit = source.embeddedUnit transformationTemplateName = source.transformationTemplateName transformationCode = source.transformationCode } } fun setScannedCode(scannedCode: String?) = apply { this.scannedCode.code = scannedCode } fun setLookupCode(lookupCode: String?) = apply { this.scannedCode.lookupCode = lookupCode } fun setEmbeddedData(embeddedData: Int) = apply { this.scannedCode._embeddedData = embeddedData } fun setEmbeddedDecimalData(embeddedDecimalData: BigDecimal?) = apply { this.scannedCode._embeddedDecimalData = embeddedDecimalData } fun setEmbeddedUnit(unit: Unit?) = apply { this.scannedCode.embeddedUnit = unit } fun setTransformationCode(transformationCode: String?) = apply { this.scannedCode.transformationCode = transformationCode } fun setTransformationTemplateName(name: String?) = apply { this.scannedCode.transformationTemplateName = name } fun setPrice(price: Int) = apply { this.scannedCode._price = price } fun create(): ScannedCode { return scannedCode } } companion object { @JvmStatic fun parseDefault(project: Project, code: String?): ScannedCode? { project.codeTemplates.forEach { codeTemplate -> val scannedCode = codeTemplate.match(code).buildCode() if (scannedCode != null && scannedCode.templateName == "default") { return scannedCode } } return null } @JvmStatic fun parse(project: Project, code: String): List<ScannedCode> { val matches: MutableList<ScannedCode> = ArrayList() val defaultTemplate = project.defaultCodeTemplate project.codeTemplates.forEach { codeTemplate -> val scannedCode = codeTemplate.match(code).buildCode() if (scannedCode != null) { matches.add(scannedCode) } } project.priceOverrideTemplates.forEach { priceOverrideTemplate -> val codeTemplate = priceOverrideTemplate.codeTemplate val scannedCode = codeTemplate.match(code).buildCode() scannedCode?.let { val lookupCode = scannedCode.lookupCode if (lookupCode != code) { val defaultCode = defaultTemplate?.match(lookupCode)?.buildCode() defaultCode?.let { defaultCode._embeddedData = scannedCode._embeddedData defaultCode.embeddedUnit = Unit.PRICE defaultCode.code = scannedCode.code val transformTemplate = priceOverrideTemplate.transmissionCodeTemplate if (transformTemplate != null) { defaultCode.transformationTemplateName = transformTemplate.name defaultCode.transformationCode = priceOverrideTemplate.transmissionCode } matches.add(defaultCode) } } } } return matches } } }
1
null
1
6
8fc301be7512714e127eb12566a905b59e2eed9d
6,777
Android-SDK
MIT License
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/ArrayComponents.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: ArrayComponents * * Full name: System`ArrayComponents * * ArrayComponents[array] gives an array in which all identical elements of array are replaced by an integer index representing the component in which the element lies. * ArrayComponents[array, level] finds the identical elements at the specified level in array * Usage: ArrayComponents[array, level, rules] uses a rule or a list of rules for specifying the labels. * * Options: None * * Protected * Attributes: ReadProtected * * local: paclet:ref/ArrayComponents * Documentation: web: http://reference.wolfram.com/language/ref/ArrayComponents.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun arrayComponents(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("ArrayComponents", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,341
mathemagika
Apache License 2.0
src/main/kotlin/pcf/crskdev/koonsplash/auth/AuthCodeServer.kt
criske
297,303,213
false
null
/* * Copyright (c) 2020. <NAME> * 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 pcf.crskdev.koonsplash.auth import okhttp3.HttpUrl import java.net.URI /** * Authorization code server. * * @author <NAME> * @since 0.1 */ interface AuthCodeServer { companion object { /** * Default port. */ const val DEFAULT_PORT = 3000u /** * Default host */ const val DEFAULT_HOST = "localhost" /** * Callback builder * * @param host Host. * @param port Port. * @return URI */ @ExperimentalUnsignedTypes fun createCallback(host: String, port: UInt): URI = HttpUrl.Builder().scheme("http").host(host).port(port.toInt()).build().toUri() } /** * Callback uri */ val callbackUri: URI /** * Start serving within the given timeout. * * @param timeoutSec Timeout in seconds. * @return True is server started. */ fun startServing(timeoutSec: Int = 30): Boolean /** * Stop serving * */ fun stopServing() /** * Called when authorization code is available. * * @param block * @receiver Contains the result with the code. */ fun onAuthorizeCode(block: (AuthorizationCode) -> Unit) }
13
Kotlin
0
0
463d9cf9cda3a092a1abf1a3301cdc184eee5c97
2,396
koonsplash
MIT License
sketch/src/androidTest/java/com/github/panpf/sketch/test/decode/DrawableDecodeResultTest.kt
fltwlulu
188,455,050
false
{"Gradle Kotlin DSL": 14, "Markdown": 35, "Java Properties": 2, "Shell": 1, "TOML": 1, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Proguard": 12, "XML": 124, "Kotlin": 587, "Java": 10, "SVG": 2, "INI": 11}
package com.github.panpf.sketch.test.decode import android.graphics.Color import android.graphics.drawable.ColorDrawable import androidx.test.ext.junit.runners.AndroidJUnit4 import com.github.panpf.sketch.datasource.DataFrom.LOCAL import com.github.panpf.sketch.decode.DrawableDecodeResult import com.github.panpf.sketch.decode.ImageInfo import com.github.panpf.sketch.decode.internal.createInSampledTransformed import com.github.panpf.sketch.transform.createRotateTransformed import org.junit.Assert import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class DrawableDecodeResultTest { @Test fun testConstructor() { val newDrawable = ColorDrawable(Color.RED) val imageInfo = ImageInfo(3000, 500, "image/png", 0) val transformedList = listOf(createInSampledTransformed(4), createRotateTransformed(45)) DrawableDecodeResult(newDrawable, imageInfo, LOCAL, transformedList).apply { Assert.assertTrue(newDrawable === drawable) Assert.assertEquals( "ImageInfo(width=3000, height=500, mimeType='image/png', exifOrientation=UNDEFINED)", imageInfo.toString() ) Assert.assertEquals(LOCAL, dataFrom) Assert.assertEquals( "InSampledTransformed(4), RotateTransformed(45)", this.transformedList?.joinToString() ) } } }
1
null
1
1
c9ff98d80c36d7c4ba5c28bbf358dc8ee53278b1
1,428
sketch
MIT License
dm-service/src/main/kotlin/service/WorkoutService.kt
otuskotlin
382,547,521
false
null
package service import DataNotAllowedException import Mapper.setQuery import Mapper.toCreateResponse import Mapper.toDeleteResponse import Mapper.toReadResponse import Mapper.toSearchResponse import Mapper.toUpdateResponse import ModelForRequest.cruds.* import StubData import WorkoutCrud import context.MpContext class WorkoutService( var crud: WorkoutCrud ) { suspend fun createWorkout(context: MpContext, request: CreateWorkoutRequest): CreateWorkoutResponse { context.setQuery(request) crud.create(context) return context.toCreateResponse() } suspend fun readWorkout(context: MpContext, request: ReadWorkoutRequest): ReadWorkoutResponse { context.responseWorkout = StubData.getModel() crud.read(context.setQuery(request)) return context.toReadResponse() } suspend fun updateWorkout(context: MpContext, request: UpdateWorkoutRequest): UpdateWorkoutResponse { context.responseWorkout = StubData.getModel() crud.update(context.setQuery(request)) return context.toUpdateResponse() } suspend fun deleteWorkout(context: MpContext, request: DeleteWorkoutRequest): DeleteWorkoutResponse { context.responseWorkout = StubData.getModel() crud.delete(context.setQuery(request)) return context.toDeleteResponse() } suspend fun searchWorkout(context: MpContext, request: SearchWorkoutRequest): SearchWorkoutResponse { context.responseWorkouts = StubData.getModels().toMutableList() crud.search(context.setQuery(request)) return context.toSearchResponse() } suspend fun errorAd(context: MpContext, e: Throwable): BaseMessage { context.addError(e) return context.toReadResponse() } suspend fun handleWorkout(context: MpContext, request: BaseMessage): BaseMessage = try { when (request) { is CreateWorkoutRequest -> createWorkout(context, request) is ReadWorkoutRequest -> readWorkout(context, request) is UpdateWorkoutRequest -> updateWorkout(context, request) is DeleteWorkoutRequest -> deleteWorkout(context, request) is SearchWorkoutRequest -> searchWorkout(context, request) else -> throw DataNotAllowedException("Request is not Allowed", request) } } catch (e: Throwable) { errorAd(context, e) } }
1
Kotlin
1
0
ab962d306cab6512c5cffe61b87e810ddc28f193
2,175
ok-202105-workout-dm
MIT License
src/main/kotlin/no/nav/aap/api/oppslag/arkiv/ArkivOppslagClientBeanConfig.kt
navikt
402,698,973
false
null
package no.nav.aap.api.oppslag.arkiv import com.fasterxml.jackson.databind.ObjectMapper import graphql.kickstart.spring.webclient.boot.GraphQLWebClient import no.nav.aap.api.oppslag.arkiv.ArkivOppslagConfig.Companion.SAF import no.nav.aap.api.oppslag.arkiv.ArkivOppslagConfig.Companion.SAFQL import no.nav.aap.health.AbstractPingableHealthIndicator import no.nav.aap.rest.tokenx.TokenXFilterFunction import no.nav.aap.util.LoggerUtil.getLogger import org.springframework.beans.factory.annotation.Qualifier import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClient.Builder @Configuration class ArkivOppslagClientBeanConfig { val log = getLogger(javaClass) @Qualifier(SAF) @Bean fun arkivOppslagWebClient(b: Builder, cfg: ArkivOppslagConfig, tokenX: TokenXFilterFunction) = b.baseUrl("${cfg.baseUri}") .filter(tokenX) .build() @Qualifier(SAFQL) @Bean fun arkivOppslagQLWebClient(b: Builder, cfg: ArkivOppslagConfig, tokenX: TokenXFilterFunction) = b.baseUrl("${cfg.baseUri}/graphql") .filter(tokenX) .build() @Bean @ConditionalOnProperty("$SAF.enabled", havingValue = "true") fun arkivOppslagHealthIndicator(a: ArkivOppslagWebClientAdapter) = object : AbstractPingableHealthIndicator(a) {} @Qualifier(SAF) @Bean fun arkivOppslagGraphQLWebClient(@Qualifier(SAFQL) client: WebClient, mapper: ObjectMapper) = GraphQLWebClient.newInstance(client, mapper) }
2
Kotlin
1
3
d4456fdd7934f79503123f0d9ce9318c081b45ba
1,736
aap-soknad-api
MIT License
app/src/main/java/com/weathermap/features/main/MainActivity.kt
xuanqh
507,506,257
false
null
package com.weathermap.features.main import android.app.Activity import android.content.Intent import android.os.Bundle import android.text.Editable import android.text.TextUtils import android.view.Menu import android.view.MenuItem import android.view.View import android.view.inputmethod.EditorInfo import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.core.content.ContextCompat import androidx.core.widget.doAfterTextChanged import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.DividerItemDecoration import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener import com.weathermap.R import com.weathermap.base.BaseActivity import com.weathermap.data.models.CityWeatherModel import com.weathermap.databinding.ActivityMainBinding import com.weathermap.features.setting.SettingActivity import org.koin.androidx.viewmodel.ext.android.getViewModel class MainActivity : BaseActivity<MainViewModel>() { lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = DataBindingUtil.setContentView(this, R.layout.activity_main) initView() setDataListener() setEventListener() } private fun initView() { val itemDecorator = DividerItemDecoration(this, DividerItemDecoration.VERTICAL) val drawable = ContextCompat.getDrawable(this, R.drawable.row_divider) drawable?.let { itemDecorator.setDrawable(drawable) } binding.weatherList.addItemDecoration(itemDecorator) } private fun setDataListener() { viewModel.cityWeather.observe(this) { hideLoadingProgress() updateCityWeatherView(it) } } private fun updateCityWeatherView(cityWeatherModel: CityWeatherModel?) { if (cityWeatherModel?.list?.isNotEmpty() == true) { binding.tvEmpty.visibility = View.GONE binding.weatherList.visibility = View.VISIBLE val adapter = WeatherDayAdapter(cityWeatherModel.list) binding.weatherList.adapter = adapter } else { binding.tvEmpty.visibility = View.VISIBLE binding.weatherList.visibility = View.GONE } } private fun setEventListener() { binding.btnGetWeather.setOnClickListener { doSearchTerm() } binding.txtSearch.setOnEditorActionListener { _, actionId, _ -> if (actionId == EditorInfo.IME_ACTION_SEARCH) { doSearchTerm() true } else false } binding.txtSearch.doAfterTextChanged { text -> setClearButtonVisibility(text) } binding.btnClear.setOnClickListener { binding.txtSearch.setText("") } binding.swipeContainer.setOnRefreshListener(OnRefreshListener { // Your code to refresh the list here. // Make sure you call swipeContainer.setRefreshing(false) // once the network request has completed successfully. doSearchTerm() }) } private fun setClearButtonVisibility(text: Editable?) { if (TextUtils.isEmpty(text)) { binding.btnClear.visibility = View.INVISIBLE } else { binding.btnClear.visibility = View.VISIBLE } } private fun doSearchTerm() { if (binding.txtSearch.text.toString().length >= 3) { showLoadingProgress() viewModel.getCityWeather(binding.txtSearch.text.toString().trim()) hideSoftKeyboard() } else { Toast.makeText(this, getString(R.string.term_search_required), Toast.LENGTH_SHORT) .show() } binding.swipeContainer.isRefreshing = false } override fun onCreateOptionsMenu(menu: Menu): Boolean { val inflater = menuInflater inflater.inflate(R.menu.menu, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.menuSetting -> { openSetting() return true } } return super.onOptionsItemSelected(item) } private fun openSetting() { val intent = Intent(this, SettingActivity::class.java) getResult.launch(intent) } private val getResult = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { if (it.resultCode == Activity.RESULT_OK) { val intent = intent finish() startActivity(intent) } } override val viewModel: MainViewModel get() = getViewModel() }
0
Kotlin
0
0
7e37b70d423694d9355b21843d4d4889d8ced8e7
4,826
weathermap
MIT License
app/src/main/kotlin/me/sweetll/tucao/model/raw/ShowtimeSection.kt
xiaole0310
91,590,492
false
null
package me.sweetll.tucao.model.raw import com.chad.library.adapter.base.entity.SectionEntity import me.sweetll.tucao.model.json.Result class ShowtimeSection: SectionEntity<Result> { constructor(header: String, isHeader: Boolean = true): super(isHeader, header) constructor(result: Result): super(result) }
0
null
0
2
f83d75ac9747f2df2ede4b8f3a8c12d701327fb5
317
Tucao
MIT License
kt/godot-library/src/main/kotlin/godot/gen/godot/GLTFPhysicsBody.kt
utopia-rise
289,462,532
false
{"Kotlin": 1549917, "GDScript": 535642, "C++": 403741, "C": 13152, "C#": 10278, "Shell": 7406, "Java": 2165, "CMake": 939, "Python": 75}
// THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! @file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier", "UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST", "RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT", "RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate") package godot import godot.`annotation`.CoreTypeHelper import godot.`annotation`.CoreTypeLocalCopy import godot.`annotation`.GodotBaseType import godot.core.Basis import godot.core.Dictionary import godot.core.Quaternion import godot.core.TypeManager import godot.core.VariantType.BASIS import godot.core.VariantType.DICTIONARY import godot.core.VariantType.DOUBLE import godot.core.VariantType.NIL import godot.core.VariantType.OBJECT import godot.core.VariantType.QUATERNION import godot.core.VariantType.STRING import godot.core.VariantType.VECTOR3 import godot.core.Vector3 import godot.core.memory.TransferContext import godot.util.VoidPtr import kotlin.Any import kotlin.Double import kotlin.Float import kotlin.Int import kotlin.String import kotlin.Suppress import kotlin.Unit /** * Represents a physics body as an intermediary between the `OMI_physics_body` GLTF data and Godot's * nodes, and it's abstracted in a way that allows adding support for different GLTF physics extensions * in the future. */ @GodotBaseType public open class GLTFPhysicsBody : Resource() { /** * The type of the body. When importing, this controls what type of [CollisionObject3D] node Godot * should generate. Valid values are "static", "animatable", "character", "rigid", "vehicle", and * "trigger". When exporting, this will be squashed down to one of "static", "kinematic", or * "dynamic" motion types, or the "trigger" property. */ public var bodyType: String get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getBodyTypePtr, STRING) return (TransferContext.readReturnValue(STRING, false) as String) } set(`value`) { TransferContext.writeArguments(STRING to value) TransferContext.callMethod(rawPtr, MethodBindings.setBodyTypePtr, NIL) } /** * The mass of the physics body, in kilograms. This is only used when the body type is "rigid" or * "vehicle". */ public var mass: Float get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getMassPtr, DOUBLE) return (TransferContext.readReturnValue(DOUBLE, false) as Double).toFloat() } set(`value`) { TransferContext.writeArguments(DOUBLE to value.toDouble()) TransferContext.callMethod(rawPtr, MethodBindings.setMassPtr, NIL) } /** * The linear velocity of the physics body, in meters per second. This is only used when the body * type is "rigid" or "vehicle". */ @CoreTypeLocalCopy public var linearVelocity: Vector3 get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getLinearVelocityPtr, VECTOR3) return (TransferContext.readReturnValue(VECTOR3, false) as Vector3) } set(`value`) { TransferContext.writeArguments(VECTOR3 to value) TransferContext.callMethod(rawPtr, MethodBindings.setLinearVelocityPtr, NIL) } /** * The angular velocity of the physics body, in radians per second. This is only used when the * body type is "rigid" or "vehicle". */ @CoreTypeLocalCopy public var angularVelocity: Vector3 get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getAngularVelocityPtr, VECTOR3) return (TransferContext.readReturnValue(VECTOR3, false) as Vector3) } set(`value`) { TransferContext.writeArguments(VECTOR3 to value) TransferContext.callMethod(rawPtr, MethodBindings.setAngularVelocityPtr, NIL) } /** * The center of mass of the body, in meters. This is in local space relative to the body. By * default, the center of the mass is the body's origin. */ @CoreTypeLocalCopy public var centerOfMass: Vector3 get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getCenterOfMassPtr, VECTOR3) return (TransferContext.readReturnValue(VECTOR3, false) as Vector3) } set(`value`) { TransferContext.writeArguments(VECTOR3 to value) TransferContext.callMethod(rawPtr, MethodBindings.setCenterOfMassPtr, NIL) } /** * The inertia strength of the physics body, in kilogram meter squared (kg⋅m²). This represents * the inertia around the principle axes, the diagonal of the inertia tensor matrix. This is only * used when the body type is "rigid" or "vehicle". * When converted to a Godot [RigidBody3D] node, if this value is zero, then the inertia will be * calculated automatically. */ @CoreTypeLocalCopy public var inertiaDiagonal: Vector3 get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getInertiaDiagonalPtr, VECTOR3) return (TransferContext.readReturnValue(VECTOR3, false) as Vector3) } set(`value`) { TransferContext.writeArguments(VECTOR3 to value) TransferContext.callMethod(rawPtr, MethodBindings.setInertiaDiagonalPtr, NIL) } /** * The inertia orientation of the physics body. This defines the rotation of the inertia's * principle axes relative to the object's local axes. This is only used when the body type is * "rigid" or "vehicle" and [inertiaDiagonal] is set to a non-zero value. */ @CoreTypeLocalCopy public var inertiaOrientation: Quaternion get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getInertiaOrientationPtr, QUATERNION) return (TransferContext.readReturnValue(QUATERNION, false) as Quaternion) } set(`value`) { TransferContext.writeArguments(QUATERNION to value) TransferContext.callMethod(rawPtr, MethodBindings.setInertiaOrientationPtr, NIL) } /** * The inertia tensor of the physics body, in kilogram meter squared (kg⋅m²). This is only used * when the body type is "rigid" or "vehicle". * When converted to a Godot [RigidBody3D] node, if this value is zero, then the inertia will be * calculated automatically. */ @CoreTypeLocalCopy public var inertiaTensor: Basis get() { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.getInertiaTensorPtr, BASIS) return (TransferContext.readReturnValue(BASIS, false) as Basis) } set(`value`) { TransferContext.writeArguments(BASIS to value) TransferContext.callMethod(rawPtr, MethodBindings.setInertiaTensorPtr, NIL) } public override fun new(scriptIndex: Int): Unit { callConstructor(ENGINECLASS_GLTFPHYSICSBODY, scriptIndex) } /** * The linear velocity of the physics body, in meters per second. This is only used when the body * type is "rigid" or "vehicle". * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = gltfphysicsbody.linearVelocity * //Your changes * gltfphysicsbody.linearVelocity = myCoreType * `````` */ @CoreTypeHelper public open fun linearVelocityMutate(block: Vector3.() -> Unit): Vector3 = linearVelocity.apply{ block(this) linearVelocity = this } /** * The angular velocity of the physics body, in radians per second. This is only used when the * body type is "rigid" or "vehicle". * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = gltfphysicsbody.angularVelocity * //Your changes * gltfphysicsbody.angularVelocity = myCoreType * `````` */ @CoreTypeHelper public open fun angularVelocityMutate(block: Vector3.() -> Unit): Vector3 = angularVelocity.apply{ block(this) angularVelocity = this } /** * The center of mass of the body, in meters. This is in local space relative to the body. By * default, the center of the mass is the body's origin. * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = gltfphysicsbody.centerOfMass * //Your changes * gltfphysicsbody.centerOfMass = myCoreType * `````` */ @CoreTypeHelper public open fun centerOfMassMutate(block: Vector3.() -> Unit): Vector3 = centerOfMass.apply{ block(this) centerOfMass = this } /** * The inertia strength of the physics body, in kilogram meter squared (kg⋅m²). This represents * the inertia around the principle axes, the diagonal of the inertia tensor matrix. This is only * used when the body type is "rigid" or "vehicle". * When converted to a Godot [RigidBody3D] node, if this value is zero, then the inertia will be * calculated automatically. * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = gltfphysicsbody.inertiaDiagonal * //Your changes * gltfphysicsbody.inertiaDiagonal = myCoreType * `````` */ @CoreTypeHelper public open fun inertiaDiagonalMutate(block: Vector3.() -> Unit): Vector3 = inertiaDiagonal.apply{ block(this) inertiaDiagonal = this } /** * The inertia orientation of the physics body. This defines the rotation of the inertia's * principle axes relative to the object's local axes. This is only used when the body type is * "rigid" or "vehicle" and [inertiaDiagonal] is set to a non-zero value. * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = gltfphysicsbody.inertiaOrientation * //Your changes * gltfphysicsbody.inertiaOrientation = myCoreType * `````` */ @CoreTypeHelper public open fun inertiaOrientationMutate(block: Quaternion.() -> Unit): Quaternion = inertiaOrientation.apply{ block(this) inertiaOrientation = this } /** * The inertia tensor of the physics body, in kilogram meter squared (kg⋅m²). This is only used * when the body type is "rigid" or "vehicle". * When converted to a Godot [RigidBody3D] node, if this value is zero, then the inertia will be * calculated automatically. * * This is a helper function to make dealing with local copies easier. * * For more information, see our * [documentation](https://godot-kotl.in/en/stable/user-guide/api-differences/#core-types). * * Allow to directly modify the local copy of the property and assign it back to the Object. * * Prefer that over writing: * `````` * val myCoreType = gltfphysicsbody.inertiaTensor * //Your changes * gltfphysicsbody.inertiaTensor = myCoreType * `````` */ @CoreTypeHelper public open fun inertiaTensorMutate(block: Basis.() -> Unit): Basis = inertiaTensor.apply{ block(this) inertiaTensor = this } /** * Converts this GLTFPhysicsBody instance into a Godot [CollisionObject3D] node. */ public fun toNode(): CollisionObject3D? { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.toNodePtr, OBJECT) return (TransferContext.readReturnValue(OBJECT, true) as CollisionObject3D?) } /** * Serializes this GLTFPhysicsBody instance into a [Dictionary]. It will be in the format expected * by the `OMI_physics_body` GLTF extension. */ public fun toDictionary(): Dictionary<Any?, Any?> { TransferContext.writeArguments() TransferContext.callMethod(rawPtr, MethodBindings.toDictionaryPtr, DICTIONARY) return (TransferContext.readReturnValue(DICTIONARY, false) as Dictionary<Any?, Any?>) } public companion object { /** * Creates a new GLTFPhysicsBody instance from the given Godot [CollisionObject3D] node. */ public fun fromNode(bodyNode: CollisionObject3D): GLTFPhysicsBody? { TransferContext.writeArguments(OBJECT to bodyNode) TransferContext.callMethod(0, MethodBindings.fromNodePtr, OBJECT) return (TransferContext.readReturnValue(OBJECT, true) as GLTFPhysicsBody?) } /** * Creates a new GLTFPhysicsBody instance by parsing the given [Dictionary] in the * `OMI_physics_body` GLTF extension format. */ public fun fromDictionary(dictionary: Dictionary<Any?, Any?>): GLTFPhysicsBody? { TransferContext.writeArguments(DICTIONARY to dictionary) TransferContext.callMethod(0, MethodBindings.fromDictionaryPtr, OBJECT) return (TransferContext.readReturnValue(OBJECT, true) as GLTFPhysicsBody?) } } internal object MethodBindings { public val fromNodePtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "from_node") public val toNodePtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "to_node") public val fromDictionaryPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "from_dictionary") public val toDictionaryPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "to_dictionary") public val getBodyTypePtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "get_body_type") public val setBodyTypePtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "set_body_type") public val getMassPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "get_mass") public val setMassPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "set_mass") public val getLinearVelocityPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "get_linear_velocity") public val setLinearVelocityPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "set_linear_velocity") public val getAngularVelocityPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "get_angular_velocity") public val setAngularVelocityPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "set_angular_velocity") public val getCenterOfMassPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "get_center_of_mass") public val setCenterOfMassPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "set_center_of_mass") public val getInertiaDiagonalPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "get_inertia_diagonal") public val setInertiaDiagonalPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "set_inertia_diagonal") public val getInertiaOrientationPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "get_inertia_orientation") public val setInertiaOrientationPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "set_inertia_orientation") public val getInertiaTensorPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "get_inertia_tensor") public val setInertiaTensorPtr: VoidPtr = TypeManager.getMethodBindPtr("GLTFPhysicsBody", "set_inertia_tensor") } }
50
Kotlin
38
580
fd1af79075e7b918200aba3302496b70c76a2028
16,502
godot-kotlin-jvm
MIT License
composeApp/src/commonMain/kotlin/repository/DatabaseRepository.kt
jeffreyliu8
722,357,386
false
{"Kotlin": 21142, "Swift": 594}
package repository import com.example.database.HockeyPlayer import kotlinx.coroutines.flow.Flow interface DatabaseRepository { fun getPlayers(): Flow<List<HockeyPlayer>> suspend fun removeAll() suspend fun addPlayer(player: HockeyPlayer) }
0
Kotlin
0
0
81a0cd8b44a29e0c9d49ba94e70d092e1be091ed
254
kmmcompose
MIT License
src/main/kotlin/com/imoonday/skill/ItemAttractionSkill.kt
iMoonDay
759,188,611
false
{"Kotlin": 472390, "Java": 57363}
package com.imoonday.skill import com.imoonday.trigger.GlowingTrigger import com.imoonday.trigger.UsingRenderTrigger import com.imoonday.util.SkillType import com.imoonday.util.UseResult import net.minecraft.client.network.ClientPlayerEntity import net.minecraft.entity.Entity import net.minecraft.entity.ItemEntity import net.minecraft.entity.player.PlayerEntity import net.minecraft.particle.ParticleTypes import net.minecraft.server.network.ServerPlayerEntity class ItemAttractionSkill : LongPressSkill( id = "item_attraction", types = listOf(SkillType.FUNCTION), cooldown = 15, rarity = Rarity.SUPERB, ), UsingRenderTrigger, GlowingTrigger { override fun getMaxPressTime(): Int = 20 * 10 override fun onRelease(player: ServerPlayerEntity, pressedTime: Int): UseResult { player.stopUsing() return UseResult.success() } override fun tick(player: PlayerEntity, usedTime: Int) { if (player.isUsing()) player.world.getOtherEntities( player, player.boundingBox.expand(15.0) ) { it is ItemEntity && !it.cannotPickup() } .forEach { if (player.world.isClient) { it.world.addParticle( ParticleTypes.ENCHANT, it.x, it.boundingBox.maxY, it.z, 0.0, 0.25, 0.0 ) } else { it.velocityDirty = true it.velocity = player.eyePos.subtract(it.pos).normalize().multiply(0.25) if (it.horizontalCollision) it.addVelocity(0.0, 0.25, 0.0) } } super.tick(player, usedTime) } override fun isGlowing(player: ClientPlayerEntity, entity: Entity): Boolean = player.isUsing() && entity is ItemEntity && !entity.cannotPickup() && player.boundingBox.expand(15.0).contains(entity.pos) }
0
Kotlin
0
0
bdccadd1cdfaeaf551ce38cb82b5ec536eff30f9
2,115
AdvancedSkills
Creative Commons Zero v1.0 Universal
app/src/main/java/com/five/android/widgetstutorial/di/Modules.kt
lukamijic
372,011,706
false
null
package com.five.android.widgetstutorial.di import com.five.android.widgetstutorial.BuildConfig import com.five.android.widgetstutorial.data.mapper.ApiMapper import com.five.android.widgetstutorial.data.mapper.ApiMapperImpl import com.five.android.widgetstutorial.data.repository.MovieRepository import com.five.android.widgetstutorial.data.repository.MovieRepositoryImpl import com.five.android.widgetstutorial.data.retrofit.RetrofitFactory import com.five.android.widgetstutorial.data.retrofit.RetrofitFactoryImpl import com.five.android.widgetstutorial.data.service.MovieService import com.five.android.widgetstutorial.domain.usecases.GetTopRatedMoviesUseCase import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import org.koin.dsl.module val appModule = module(moduleDeclaration = { single { GetTopRatedMoviesUseCase(movieRepository = get()) } single<RetrofitFactory> { RetrofitFactoryImpl(okHttpClient = get()) } single { get<RetrofitFactory>().getMovieApiInstance() } single { OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor().apply { level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE }) .build() } single { MovieService(movieApi = get()) } single<ApiMapper> { ApiMapperImpl() } single<MovieRepository> { MovieRepositoryImpl( apiMapper = get(), movieService = get() ) } })
0
Kotlin
0
0
70d9884f38c0fd13821fcf1beaddb953b5a1888b
1,553
android-widgets
MIT License
app/src/main/java/ru/tech/papricoin/domain/use_case/favorite_coins/get_favorite_coins/GetFavoriteCoinsUseCase.kt
T8RIN
476,364,479
false
{"Kotlin": 94271}
package ru.tech.papricoin.domain.use_case.favorite_coins.get_favorite_coins import kotlinx.coroutines.flow.Flow import ru.tech.papricoin.domain.model.Coin import ru.tech.papricoin.domain.repository.PapriCoinRepository import ru.tech.papricoin.presentation.ui.utils.Action import javax.inject.Inject class GetFavoriteCoinsUseCase @Inject constructor( private val repository: PapriCoinRepository ) { operator fun invoke(): Flow<Action<List<Coin>>> { return repository.getFavoriteCoins() } }
0
Kotlin
1
47
fd513fb72a7bf56e31d0e96d5dae8f39d4dd84a2
512
PapriCoin
Apache License 2.0
app/src/main/java/me/tatocaster/letinterview/features/movieslist/presentation/MoviesList.kt
tatocaster
126,601,486
false
null
package me.tatocaster.letinterview.features.movieslist.presentation import android.app.DatePickerDialog import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.view.animation.OvershootInterpolator import jp.wasabeef.recyclerview.animators.SlideInUpAnimator import kotlinx.android.synthetic.main.activity_movies_list.* import kotlinx.android.synthetic.main.content_movies_list.* import me.tatocaster.letinterview.App import me.tatocaster.letinterview.AppComponent import me.tatocaster.letinterview.R import me.tatocaster.letinterview.entity.Pallete import me.tatocaster.letinterview.features.moviesdetail.presentation.MoviesDetail import me.tatocaster.letinterview.features.movieslist.model.TvShow import me.tatocaster.letinterview.utils.GridSpacingItemDecoration import me.tatocaster.letinterview.utils.dpToPx import me.tatocaster.letinterview.utils.showErrorAlert import java.util.* import javax.inject.Inject class MoviesList : AppCompatActivity(), MoviesListContract.View { @Inject lateinit var mainPresenter: MoviesListContract.Presenter private lateinit var scopeGraph: MoviesListComponent private lateinit var adapter: MoviesListAdapter private var newPageRequestAvailable = true private val listOnScrollListener = object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView?, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) if (dy > 0) { // only when scrolling up val visibleThreshold = 4 val layoutManager = moviesList.layoutManager as GridLayoutManager val lastItem = layoutManager.findLastCompletelyVisibleItemPosition() val currentTotalCount = layoutManager.itemCount if (currentTotalCount <= lastItem + visibleThreshold && newPageRequestAvailable) { newPageRequestAvailable = false swipeRefreshLayout.isRefreshing = true mainPresenter.newPageRequested() } } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_movies_list) setupScopeGraph(App.getAppContext(this).appComponent) setUpRecyclerView() fab.setOnClickListener { showDatePicker() } } private fun setUpRecyclerView() { adapter = MoviesListAdapter(this, { item, backdropColor -> navigateToDetailsScreen(item.id, backdropColor) }, false) moviesList.adapter = adapter val layoutManager = GridLayoutManager(this, 2) moviesList.layoutManager = layoutManager moviesList.addItemDecoration(GridSpacingItemDecoration(2, dpToPx(4), false)) moviesList.addOnScrollListener(listOnScrollListener) val animator = SlideInUpAnimator(OvershootInterpolator(1f)) moviesList.itemAnimator = animator swipeRefreshLayout.setOnRefreshListener({ swipeRefreshLayout.isRefreshing = true mainPresenter.refreshData() }) swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, android.R.color.holo_green_dark, android.R.color.holo_orange_dark, android.R.color.holo_blue_dark) } override fun showError(message: String) { showErrorAlert(this, "", message) } override fun dataLoaded(shows: MutableList<TvShow>) { swipeRefreshLayout.isRefreshing = false newPageRequestAvailable = true adapter.submitList(shows) } override fun dataFiltered(shows: MutableList<TvShow>) { adapter.displayFilteredData(shows) } override fun navigateToDetailsScreen(id: Int, backDropColor: Pallete) { MoviesDetail.startActivity(this, id, backDropColor) } override fun onResume() { super.onResume() swipeRefreshLayout.post({ swipeRefreshLayout.isRefreshing = true mainPresenter.attach() }) } override fun showDatePicker() { val calendar = Calendar.getInstance() DatePickerDialog(this, DatePickerDialog.OnDateSetListener { datePicker, year, month, day -> mainPresenter.filterByDate(year) }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show() } override fun onPause() { super.onPause() mainPresenter.detach() } private fun setupScopeGraph(appComponent: AppComponent) { scopeGraph = DaggerMoviesListComponent.builder() .appComponent(appComponent) .moviesListModule(MoviesListModule(this)) .build() scopeGraph.inject(this) } companion object { val TAG = "MoviesList" } }
0
Kotlin
0
0
3d048923870ae54216894bed31bee4ccea11f3da
4,995
TVShowsExplorer
MIT License
mahua/src/main/java/com/movies/mahua/entities/BodyParams.kt
chenshige
152,017,908
false
null
package com.movies.mahua.entities /** * @author donnieSky * @created_at 2018/9/12. * @description * @version */ data class BodyParams( val appInfo: AppInfo? = AppInfo(), val cip: String? = "127.0.0.1", val ctime: Long? = System.currentTimeMillis() / 1000, val uid: Long? = 14357495, val token: String? = "mb_token:<PASSWORD><PASSWORD>", val fetchAll: Boolean? = false, val searchContent: String? = null, val currentPage: Int? = null, val pageSize: Int? = null, val entry: Int? = null, val data: DataParam? = null, val columnId: Int? = null ) data class AppInfo( val modelName: Int? = 4, val packageId: String? = "7", val terminal: Int? = 2, val uuid: String? = "3e1eebf750b322df", val version: String? = "1.5.2" ) data class DataParam( val videoId: Int? = -1, val videoInfoId: Long? = null )
0
Kotlin
1
0
d4d4d898b334aa29a1943728673e5549ddc58766
951
Digging
MIT License
module_web/src/main/java/com/sunhy/demo/web/TemplateWebViewPool.kt
RDSunhy
536,120,160
false
{"Kotlin": 122335, "JavaScript": 10808, "HTML": 8546, "AIDL": 772, "CSS": 763}
package com.sunhy.demo.web import android.content.Context import android.content.MutableContextWrapper import android.util.Log import com.sunhy.demo.web.core.BaseWebChromeClient import com.sunhy.demo.web.core.BaseWebViewClient import java.util.* class TemplateWebViewPool private constructor() { companion object { private const val TAG = "TemplateWebViewPool" @Volatile private var instance: TemplateWebViewPool? = null fun getInstance(): TemplateWebViewPool { return instance ?: synchronized(this) { instance ?: TemplateWebViewPool().also { instance = it } } } } private val sPool = Stack<TemplateWebView>() private val lock = byteArrayOf() private var maxSize = 1 /** * 设置 webview 池容量 */ fun setMaxPoolSize(size: Int) { synchronized(lock) { maxSize = size } } /** * 初始化webview 放在list中 */ fun init(context: Context, initSize: Int = maxSize) { for (i in 0 until initSize) { val view = TemplateWebView(MutableContextWrapper(context)) // 初始化时就加载模板 view.loadUrl("file:///android_asset/template_news.html") sPool.push(view) } } /** * 获取webview */ fun getWebView(context: Context): TemplateWebView { synchronized(lock) { val webView: TemplateWebView if (sPool.size > 0) { webView = sPool.pop() Log.d(TAG, "getWebView from pool") } else { webView = TemplateWebView(MutableContextWrapper(context)) // 初始化时就加载模板 webView.loadUrl("file:///android_asset/template_news.html") Log.d(TAG, "getWebView from create") } val contextWrapper = webView.context as MutableContextWrapper contextWrapper.baseContext = context // 默认设置 webView.webChromeClient = BaseWebChromeClient() webView.webViewClient = BaseWebViewClient() return webView } } /** * 回收 WebView */ fun recycle(webView: TemplateWebView) { // 释放资源 webView.release() // 根据池容量判断是否销毁 【也可以增加其他条件 如手机低内存等等】 val contextWrapper = webView.context as MutableContextWrapper contextWrapper.baseContext = webView.context.applicationContext synchronized(lock) { if (sPool.size < maxSize) { sPool.push(webView) } else { webView.destroy() } } } }
0
Kotlin
20
84
334b89a85eb2ee0e94833a4c50cc086bc85c7335
2,603
WebViewSimpleDemo
Apache License 2.0
app/src/main/java/com/patmore/android/core/imageloader/ImageLoader.kt
jawnpaul
514,394,689
false
{"Kotlin": 189149}
package com.patmore.android.core.imageloader import android.content.Context import android.widget.ImageView import androidx.core.graphics.drawable.toBitmap import androidx.palette.graphics.Palette import coil.imageLoader import coil.load import coil.request.ImageRequest import coil.transform.CircleCropTransformation import com.bumptech.glide.Glide import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject import javax.inject.Singleton @Singleton class ImageLoader @Inject constructor(@ApplicationContext val context: Context) : IImageLoader { override fun loadImage(url: String, imageView: ImageView) { Glide.with(context).load(url).into(imageView) } override fun loadCircleImage(url: String, imageView: ImageView) { imageView.load(url) { transformations(CircleCropTransformation()) } } override fun getPalette(url: String, palette: (Palette?) -> Unit) { val imageLoader = context.imageLoader val request = ImageRequest.Builder(context) .allowHardware(false) .data(url) .target { drawable -> Palette.Builder(drawable.toBitmap()).generate { palette(it) } } .build() imageLoader.enqueue(request) } }
3
Kotlin
1
11
9a36efdd72ea4b7ee51e09de28c863be52cf53fa
1,327
patmore-android
MIT License
base/sdk-common/src/test/java/com/android/ide/common/blame/parser/Aapt2OutputParserTest.kt
qiangxu1996
255,410,085
false
null
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.ide.common.blame.parser import com.android.ide.common.blame.Message import com.android.ide.common.blame.SourcePosition import com.android.ide.common.blame.parser.aapt.Aapt2OutputParser import com.android.ide.common.blame.parser.util.OutputLineReader import com.android.utils.ILogger import com.android.utils.StdLogger import com.google.common.truth.Truth.assertThat import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.mockito.Mock import org.mockito.MockitoAnnotations class Aapt2OutputParserTest { @get:Rule val temporaryFolder = TemporaryFolder() lateinit var parser: ToolOutputParser @Mock lateinit var reader: OutputLineReader @Mock lateinit var logger: ILogger @Before fun setUp() { MockitoAnnotations.initMocks(this) parser = ToolOutputParser( Aapt2OutputParser(), Message.Kind.SIMPLE, StdLogger(StdLogger.Level.INFO) ) } @Test fun parseErrorWithLineAndColumn() { val file = createTempFile("colors", ".xml", temporaryFolder.newFolder()) val line = "${file.absolutePath}:5:5-49: invalid color." val messages = parser.parseToolOutput(line) assertThat(messages).hasSize(1) val message = messages[0] assertThat(message.kind).isEqualTo(Message.Kind.ERROR) assertThat(message.text).isEqualTo("invalid color.") assertThat(message.toolName).isEqualTo("AAPT") assertThat(message.sourceFilePositions).hasSize(1) assertThat(message.sourceFilePositions[0].file.sourceFile!!.absolutePath).isEqualTo(file.absolutePath) // error is in line 5, columns from 5 to 49 assertThat(message.sourceFilePositions[0].position).isEqualTo(SourcePosition(4, 4, -1, 4, 48, -1)) } @Test fun parseErrorWithPathOnly() { val file = createTempFile("foo", ".9.png", temporaryFolder.newFolder()) val line = "${file.absolutePath}: error: failed to read PNG signature: file does not start with PNG signature.\n" val messages = parser.parseToolOutput(line, true) assertThat(messages).hasSize(1) val message = messages[0] assertThat(message.kind).isEqualTo(Message.Kind.ERROR) assertThat(message.text).isEqualTo("error: failed to read PNG signature: file does not start with PNG signature.") assertThat(message.toolName).isEqualTo("AAPT") assertThat(message.sourceFilePositions).hasSize(1) assertThat(message.sourceFilePositions[0].file.sourceFile!!.absolutePath).isEqualTo(file.absolutePath) assertThat(message.sourceFilePositions[0].position).isEqualTo(SourcePosition.UNKNOWN) } @Test fun testMultipleErrorsParsing() { val file1 = createTempFile("ic_launcher", ".xml", temporaryFolder.newFolder()) val file2 = createTempFile("colors", ".xml", temporaryFolder.newFolder()) val text = """2 exception was raised by workers: com.android.builder.internal.aapt.v2.Aapt2Exception: Android resource linking failed ${file1.absolutePath}:3: error: attribute android:drawadxble not found. ${file2.absolutePath}:4:5-62: error: resource string/apgfp_name (aka com.example.myapplication:string/apgfp_name) not found. """.trimIndent() val messages = parser.parseToolOutput(text, true) assertThat(messages).hasSize(2) var message = messages[0] assertThat(message.kind).isEqualTo(Message.Kind.ERROR) assertThat(message.text).isEqualTo("error: attribute android:drawadxble not found.") assertThat(message.toolName).isEqualTo("AAPT") assertThat(message.sourceFilePositions).hasSize(1) assertThat(message.sourceFilePositions[0].file.sourceFile!!.absolutePath).isEqualTo(file1.absolutePath) // error is in line 3 assertThat(message.sourceFilePositions[0].position).isEqualTo(SourcePosition(2, -1, -1, 2, -1, -1)) message = messages[1] assertThat(message.kind).isEqualTo(Message.Kind.ERROR) assertThat(message.text).isEqualTo("error: resource string/apgfp_name (aka com.example.myapplication:string/apgfp_name) not found.") assertThat(message.toolName).isEqualTo("AAPT") assertThat(message.sourceFilePositions).hasSize(1) assertThat(message.sourceFilePositions[0].file.sourceFile!!.absolutePath).isEqualTo(file2.absolutePath) // error is in line 4, columns from 5 to 62 assertThat(message.sourceFilePositions[0].position).isEqualTo(SourcePosition(3, 4, -1, 3, 61, -1)) } }
0
null
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
5,303
vmtrace
Apache License 2.0
features/cards/src/test/java/pokemontcg/features/cards/ui/MainViewModelTest.kt
jsmontteiro
248,234,185
false
null
package pokemontcg.features.cards.ui import androidx.arch.core.executor.testing.InstantTaskExecutorRule import io.mockk.coEvery import io.mockk.mockk import io.mockk.spyk import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Rule import org.junit.Test import pokemontcg.features.cards.mockCard import pokemontcg.features.cards.ui.main.MainViewModel import pokemontcg.features.cards.usecase.ListCardsUseCase import pokemontcg.libraries.network.exceptions.ServerErrorException import pokemontcg.libraries.testutils.CoroutineTestRule class MainViewModelTest { @Rule @JvmField val coroutineTestRule = CoroutineTestRule() @Rule @JvmField val instantTaskExecutorRule = InstantTaskExecutorRule() private val useCase: ListCardsUseCase = spyk(ListCardsUseCase(mockk())) private lateinit var viewModel: MainViewModel @Before fun setup() { viewModel = MainViewModel(useCase) } @Test fun `init with success, set initialized true and fill cards correctly`() { //arrange val cards = listOf(mockCard()) coEvery { useCase.execute(null) } returns cards //act viewModel.init() //assert assert(viewModel.isInitialized) assertEquals(cards, viewModel.cards.value) } @Test fun `init with error from usecase, let initialized as false and NOT fill cards`() { //arrange coEvery { useCase.execute(null) } throws ServerErrorException() //act viewModel.init() //assert assertEquals(false, viewModel.isInitialized) assert(viewModel.cards.value.isNullOrEmpty()) } }
0
Kotlin
1
1
15df26675e92fce4db45bc8f9fda4f6935c7a1fb
1,668
kotlin-pokemon-tcg
MIT License
v8binding/src/main/java/com/github/boybeak/v8x/binding/Key.kt
boybeak
616,090,715
false
null
package com.github.boybeak.v8x.binding import com.eclipsesource.v8.V8 import com.eclipsesource.v8.V8Object data class Key(val name: String, val typeName: String) { companion object { fun from(v8obj: V8Object): Key { return Key(v8obj.getString("name"), v8obj.getString("typeName")) } } fun toV8Object(v8: V8): V8Object { return V8Object(v8).apply { add("name", name) add("typeName", typeName) } } }
0
Kotlin
0
1
51b79c523ab50ba10112f0ec10d77b89a1ed9c35
484
v8x
MIT License
rd-kt/rd-framework/src/test/kotlin/com/jetbrains/rd/framework/test/cases/RdAsyncTaskTest2.kt
JetBrains
107,686,809
false
{"C#": 1845849, "Kotlin": 1606295, "C++": 1087156, "CMake": 45400, "Batchfile": 8969, "C": 688, "Shell": 672, "Dockerfile": 152}
package com.jetbrains.rd.framework.test.cases import com.jetbrains.rd.framework.FrameworkMarshallers import com.jetbrains.rd.framework.ISerializer import com.jetbrains.rd.framework.base.static import com.jetbrains.rd.framework.impl.RdCall import com.jetbrains.rd.framework.impl.RdList import com.jetbrains.rd.framework.impl.RdSignal import com.jetbrains.rd.framework.test.util.RdFrameworkTestBase import com.jetbrains.rd.framework.util.asCoroutineDispatcher import com.jetbrains.rd.framework.util.setSuspend import com.jetbrains.rd.framework.util.withContext import com.jetbrains.rd.util.lifetime.Lifetime import com.jetbrains.rd.util.reactive.IScheduler import com.jetbrains.rd.util.threading.TestSingleThreadScheduler import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withTimeout import kotlinx.coroutines.yield import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import kotlin.test.assertEquals import kotlin.time.Duration.Companion.milliseconds class RdAsyncTaskTest2 : RdFrameworkTestBase() { override val clientScheduler: IScheduler = TestSingleThreadScheduler("Client Protocol Scheduler") override val serverScheduler: IScheduler = TestSingleThreadScheduler("Server Protocol Scheduler") @Test fun defaultResponseScheduler() { val entity_id = 1 val callsite = RdCall<Int, String>().static(entity_id).apply { async = true } val endpoint = RdCall<Int, String>(null) { x -> throw Exception() }.static(entity_id) runBlocking(clientScheduler.asCoroutineDispatcher) { clientProtocol.bindStatic(callsite, "client") } runBlocking(serverScheduler.asCoroutineDispatcher) { serverProtocol.bindStatic(endpoint, "server") } endpoint.setSuspend { lifetime, arg -> serverScheduler.assertThread() yield() serverScheduler.assertThread() arg.toString() } runBlocking(clientScheduler.asCoroutineDispatcher) { runBlocking { withTimeout(5000L) { val result = callsite.startSuspending(5) Assertions.assertEquals("5", result) } } } } @Test fun defaultResponseSchedulerWithBindableResult() { val entity_id = 1 val callsite = RdCall(FrameworkMarshallers.Void, RdSignal.Companion as ISerializer<RdSignal<Int>>).static(entity_id).apply { async = true } val endpoint = RdCall(FrameworkMarshallers.Void, RdSignal.Companion as ISerializer<RdSignal<Int>>).static(entity_id) runBlocking(clientScheduler.asCoroutineDispatcher) { clientProtocol.bindStatic(callsite, "client") } runBlocking(serverScheduler.asCoroutineDispatcher) { serverProtocol.bindStatic(endpoint, "server") } val signal = RdSignal<Int>() val list = mutableListOf<Int>() Lifetime.using { adviseLifetime -> signal.advise(adviseLifetime) { value -> serverScheduler.assertThread() list.add(value) } endpoint.setSuspend { lifetime, arg -> serverScheduler.assertThread() yield() serverScheduler.assertThread() signal } runBlocking(clientScheduler.asCoroutineDispatcher) { val def = clientLifetime.createNested() val lifetime = def.lifetime val result = runBlocking { withTimeout(5000L) { callsite.startSuspending(lifetime, Unit) } } result.fire(1) withContext(serverScheduler) { assertEquals(1, list.single()) } result.fire(2) withContext(serverScheduler) { assertEquals(1, list[0]) assertEquals(2, list[1]) assertEquals(2, list.size) } def.terminate() result.fire(3) withContext(serverScheduler) { assertEquals(1, list[0]) assertEquals(2, list[1]) assertEquals(2, list.size) } } } } @Test fun bindableRdCallListTest() { clientLifetime.usingNested { lifetime -> val entity_id = 1 val callsite = RdCall(FrameworkMarshallers.Void, RdList.Companion as ISerializer<RdList<Int>>).static(entity_id) val endpoint = RdCall(FrameworkMarshallers.Void, RdList.Companion as ISerializer<RdList<Int>>).static(entity_id) val n = 100 runBlocking(serverScheduler.asCoroutineDispatcher) { serverProtocol.bindStatic(endpoint, "top") endpoint.set { i -> RdList<Int>().apply { for (i in 0 until n) { add(i) } } } } runBlocking(clientScheduler.asCoroutineDispatcher) { clientProtocol.bindStatic(callsite, "top") val list = callsite.startSuspending(Unit) var count = 0 list.view(lifetime) { lt, index, value -> assertEquals(count++, value) assertEquals(index, value) } withTimeout(1000.milliseconds) { while (count != n) { yield() } } } } } }
36
C#
53
384
e25603699e1751abfe1beeeec77c89db9d3fda80
5,725
rd
Apache License 2.0
domain/src/main/java/com/chun/domain/model/Genre.kt
nchungdev
398,720,732
false
null
package com.chun.domain.model data class Genre( var id: Int, var name: String, var type: String, var url: String )
0
Kotlin
0
0
92a75c4304243f379f168ad4eb786de1028cc727
131
AnimeDi
MIT License
kot_pool/lib/src/main/kotlin/concurrency/Crawler.kt
bhatti
309,012,602
false
{"Go": 38096, "Elixir": 32574, "Erlang": 30277, "Kotlin": 10664, "Rust": 6862, "Swift": 6604, "TypeScript": 5404, "JavaScript": 2103, "Shell": 282}
package concurrency import concurrency.domain.Response interface Crawler { fun crawl(urls: List<String>): Response }
0
Go
0
0
e235a71d042cf1093544cc7b878a68f27e653747
122
concurency-katas
MIT License
app/src/main/java/com/github/hailouwang/demosforapi/kotlin/CompanionTest.kt
lichang2464
293,675,010
true
{"Gradle": 37, "Java Properties": 4, "Shell": 2, "Text": 6, "Ignore List": 28, "Batchfile": 2, "Markdown": 27, "Checksums": 6, "XML": 848, "HTML": 11, "Java": 1032, "AIDL": 3, "INI": 17, "Proguard": 17, "Groovy": 2, "YAML": 3, "Dart": 40, "Kotlin": 51, "CMake": 1, "C": 1, "JSON": 4, "Ruby": 2, "OpenStep Property List": 4, "Objective-C": 3, "Swift": 2}
package com.github.hailouwang.demosforapi.kotlin class CompanionTest { companion object{ val a = "6666" } } // 相当于 //public class CompanionTest { // private static String a = "666"; // // public static String getA(){ // return a; // } //} /** public final class com/github/hailouwang/demosforapi/kotlin/CompanionTest { // access flags 0x1 public <init>()V L0 LINENUMBER 3 L0 ALOAD 0 INVOKESPECIAL java/lang/Object.<init> ()V RETURN L1 LOCALVARIABLE this Lcom/github/hailouwang/demosforapi/kotlin/CompanionTest; L0 L1 0 MAXSTACK = 1 MAXLOCALS = 1 // access flags 0x1A private final static Ljava/lang/String; a = "6666" @Lorg/jetbrains/annotations/NotNull;() // invisible // access flags 0x8 static <clinit>()V NEW com/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion DUP ACONST_NULL INVOKESPECIAL com/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion.<init> (Lkotlin/jvm/internal/DefaultConstructorMarker;)V PUTSTATIC com/github/hailouwang/demosforapi/kotlin/CompanionTest.Companion : Lcom/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion; L0 LINENUMBER 5 L0 LDC "6666" PUTSTATIC com/github/hailouwang/demosforapi/kotlin/CompanionTest.a : Ljava/lang/String; RETURN MAXSTACK = 3 MAXLOCALS = 0 // access flags 0x19 public final static Lcom/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion; Companion // access flags 0x1019 public final static synthetic access$getA$cp()Ljava/lang/String; L0 LINENUMBER 3 L0 GETSTATIC com/github/hailouwang/demosforapi/kotlin/CompanionTest.a : Ljava/lang/String; ARETURN L1 MAXSTACK = 1 MAXLOCALS = 0 @Lkotlin/Metadata;(mv={1, 1, 16}, bv={1, 0, 3}, k=1, d1={"\u0000\u000c\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\u0008\u0003\u0018\u0000 \u00032\u00020\u0001:\u0001\u0003B\u0005\u00a2\u0006\u0002\u0010\u0002\u00a8\u0006\u0004"}, d2={"Lcom/github/hailouwang/demosforapi/kotlin/CompanionTest;", "", "()V", "Companion", "app_debug"}) // access flags 0x19 public final static INNERCLASS com/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion com/github/hailouwang/demosforapi/kotlin/CompanionTest Companion // compiled from: CompanionTest.kt } // ================com/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion.class ================= // class version 50.0 (50) // access flags 0x31 public final class com/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion { // access flags 0x11 public final getA()Ljava/lang/String; @Lorg/jetbrains/annotations/NotNull;() // invisible L0 LINENUMBER 5 L0 INVOKESTATIC com/github/hailouwang/demosforapi/kotlin/CompanionTest.access$getA$cp ()Ljava/lang/String; ARETURN L1 LOCALVARIABLE this Lcom/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion; L0 L1 0 MAXSTACK = 1 MAXLOCALS = 1 // access flags 0x2 private <init>()V L0 LINENUMBER 4 L0 ALOAD 0 INVOKESPECIAL java/lang/Object.<init> ()V RETURN L1 LOCALVARIABLE this Lcom/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion; L0 L1 0 MAXSTACK = 1 MAXLOCALS = 1 // access flags 0x1001 public synthetic <init>(Lkotlin/jvm/internal/DefaultConstructorMarker;)V L0 LINENUMBER 4 L0 ALOAD 0 INVOKESPECIAL com/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion.<init> ()V RETURN L1 LOCALVARIABLE this Lcom/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion; L0 L1 0 LOCALVARIABLE $constructor_marker Lkotlin/jvm/internal/DefaultConstructorMarker; L0 L1 1 MAXSTACK = 1 MAXLOCALS = 2 @Lkotlin/Metadata;(mv={1, 1, 16}, bv={1, 0, 3}, k=1, d1={"\u0000\u0014\n\u0002\u0018\u0002\n\u0002\u0010\u0000\n\u0002\u0008\u0002\n\u0002\u0010\u000e\n\u0002\u0008\u0003\u0008\u0086\u0003\u0018\u00002\u00020\u0001B\u0007\u0008\u0002\u00a2\u0006\u0002\u0010\u0002R\u0014\u0010\u0003\u001a\u00020\u0004X\u0086D\u00a2\u0006\u0008\n\u0000\u001a\u0004\u0008\u0005\u0010\u0006\u00a8\u0006\u0007"}, d2={"Lcom/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion;", "", "()V", "a", "", "getA", "()Ljava/lang/String;", "app_debug"}) // access flags 0x19 public final static INNERCLASS com/github/hailouwang/demosforapi/kotlin/CompanionTest$Companion com/github/hailouwang/demosforapi/kotlin/CompanionTest Companion // compiled from: CompanionTest.kt } */
0
null
0
1
cdd5583c6aa34414ae59528357b9b20545b36d4b
4,215
AndroidGo
Apache License 2.0
zoomimage-compose/src/main/java/com/github/panpf/zoom/Utils.kt
panpf
647,222,866
false
null
package com.github.panpf.zoom import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.geometry.Offset import androidx.compose.ui.geometry.Rect import androidx.compose.ui.geometry.Size import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.unit.Dp import java.math.RoundingMode import java.text.DecimalFormat fun Size.toShortString(): String = "(${width}x$height)" fun Offset.toShortString(): String = "(${x.format(1)}x${y.format(1)})" fun Rect.toShortString(): String = "(${left.format(1)},${top.format(1)},${right.format(1)},${bottom.format(1)})" fun Centroid.toShortString(): String = "(${x.format(1)}x${y.format(1)})" val ContentScale.name: String get() = when (this) { ContentScale.FillWidth -> "FillWidth" ContentScale.FillHeight -> "FillHeight" ContentScale.FillBounds -> "FillBounds" ContentScale.Fit -> "Fit" ContentScale.Crop -> "Crop" ContentScale.Inside -> "Inside" ContentScale.None -> "None" else -> "Unknown" } val Alignment.name: String get() = when (this) { Alignment.TopStart -> "TopStart" Alignment.TopCenter -> "TopCenter" Alignment.TopEnd -> "TopEnd" Alignment.CenterStart -> "CenterStart" Alignment.Center -> "Center" Alignment.CenterEnd -> "CenterEnd" Alignment.BottomStart -> "BottomStart" Alignment.BottomCenter -> "BottomCenter" Alignment.BottomEnd -> "BottomEnd" else -> "Unknown" } val Alignment.isStart: Boolean get() = this == Alignment.TopStart || this == Alignment.CenterStart || this == Alignment.BottomStart val Alignment.isHorizontalCenter: Boolean get() = this == Alignment.TopCenter || this == Alignment.Center || this == Alignment.BottomCenter val Alignment.isCenter: Boolean get() = this == Alignment.Center val Alignment.isEnd: Boolean get() = this == Alignment.TopEnd || this == Alignment.CenterEnd || this == Alignment.BottomEnd val Alignment.isTop: Boolean get() = this == Alignment.TopStart || this == Alignment.TopCenter || this == Alignment.TopEnd val Alignment.isVerticalCenter: Boolean get() = this == Alignment.CenterStart || this == Alignment.Center || this == Alignment.CenterEnd val Alignment.isBottom: Boolean get() = this == Alignment.BottomStart || this == Alignment.BottomCenter || this == Alignment.BottomEnd /* ******************************************* Double and Float *******************************************/ fun Float.format( decimalPlacesLength: Int = 2, decimalPlacesFillZero: Boolean = false, suffix: String? = null, ): String { val value = this val buffString = StringBuilder() buffString.append("#") if (decimalPlacesLength > 0) { buffString.append(".") for (w in 0 until decimalPlacesLength) { buffString.append(if (decimalPlacesFillZero) "0" else "#") } } val format = DecimalFormat(buffString.toString()) format.roundingMode = RoundingMode.HALF_UP return if (suffix == null) { format.format(value) } else { format.format(value) + suffix } } @Composable fun Dp.toPx(): Float { return with(LocalDensity.current) { this@toPx.toPx() } } @Composable fun Float.toDp(): Dp { return with(LocalDensity.current) { this@toDp.toDp() } }
0
Kotlin
0
2
eed5f12533e86d8f563ec8438df15ed29f80c24a
3,433
zoomimage
Apache License 2.0
api/src/main/kotlin/de/jnkconsulting/e3dc/easyrscp/api/crypt/AESCipherFactory.kt
jnk-cons
691,762,451
false
{"Kotlin": 918056}
package de.jnkconsulting.e3dc.easyrscp.api.crypt /** * Factory to create [AESCipher] instances * * @since 2.0 */ interface AESCipherFactory { /** * Creates a new instance. * * According to the E3DC requirements, an array of zeros is (unfortunately) used as IV here. * * @return New [AESCipher] instance */ fun buildCipher(): AESCipher }
5
Kotlin
0
1
8627cdddb76e29624ec4d186f063dd05ff9489da
381
easy-rscp
MIT License
compose/material3/material3/src/skikoMain/kotlin/androidx/compose/material3/l10n/Mk.kt
VexorMC
838,305,267
false
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
/* * Copyright 2024 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 androidx.compose.material3.l10n import androidx.compose.material3.internal.Strings import androidx.compose.material3.internal.Translations @Suppress("UnusedReceiverParameter", "DuplicatedCode") internal fun Translations.mk() = mapOf( Strings.NavigationMenu to "Мени за навигација", Strings.ExposedDropdownMenu to "Паѓачко мени", Strings.CloseDrawer to "Затворете го менито за навигација", Strings.CloseSheet to "Затворете го листот", Strings.DefaultErrorMessage to "Неважечки запис", Strings.SliderRangeStart to "Почеток на опсегот", Strings.SliderRangeEnd to "Крај на опсегот", Strings.Dialog to "Дијалог", Strings.MenuExpanded to "Проширено", Strings.MenuCollapsed to "Собрано", Strings.ToggleDropdownMenu to "Вклучување/исклучување паѓачко мени", Strings.SnackbarDismiss to "Отфрли", Strings.SearchBarSearch to "Пребарување", Strings.SuggestionsAvailable to "Предлозите се наведени подолу", Strings.DatePickerTitle to "Изберете датум", Strings.DatePickerHeadline to "Избран датум", Strings.DatePickerSwitchToYearSelection to "Префрли на избирање година", Strings.DatePickerSwitchToDaySelection to "Повлечете за да изберете година или допрете за да се вратите на избирање ден", Strings.DatePickerSwitchToNextMonth to "Промени на следниот месец", Strings.DatePickerSwitchToPreviousMonth to "Промени на претходниот месец", Strings.DatePickerNavigateToYearDescription to "Одете на %1\$s година", Strings.DatePickerHeadlineDescription to "Тековен избор: %1\$s", Strings.DatePickerNoSelectionDescription to "Нема", Strings.DatePickerTodayDescription to "Денес", Strings.DatePickerYearPickerPaneTitle to "Избирачот на година е видлив", Strings.DateInputTitle to "Изберете датум", Strings.DateInputHeadline to "Внесен датум", Strings.DateInputLabel to "Датум", Strings.DateInputHeadlineDescription to "Внесен датум: %1\$s", Strings.DateInputNoInputDescription to "Нема", Strings.DateInputInvalidNotAllowed to "Датумот не е дозволен: %1\$s", Strings.DateInputInvalidForPattern to "Не се совпаѓа со очекуваната шема: %1\$s", Strings.DateInputInvalidYearRange to "Датумот не е во очекуваниот опсег на години %1\$s - %2\$s", Strings.DatePickerSwitchToCalendarMode to "Префрли на режим за внесување во календарот", Strings.DatePickerSwitchToInputMode to "Префрли на режим за внесување текст", Strings.DatePickerScrollToShowLaterYears to "Лизгајте за да ги прикажете подоцнежните години", Strings.DatePickerScrollToShowEarlierYears to "Лизгајте за да ги прикажете претходните години", Strings.DateRangePickerTitle to "Изберете датуми", Strings.DateRangePickerStartHeadline to "Датум на започнување", Strings.DateRangePickerEndHeadline to "Датум на завршување", Strings.DateRangePickerScrollToShowNextMonth to "Лизгајте за да се прикаже следниот месец", Strings.DateRangePickerScrollToShowPreviousMonth to "Лизгајте за да се прикаже претходниот месец", Strings.DateRangePickerDayInRange to "Во опсег", Strings.DateRangeInputTitle to "Внесете датуми", Strings.DateRangeInputInvalidRangeInput to "Внесовте неважечки временски период", Strings.BottomSheetPaneTitle to "Долен лист", Strings.BottomSheetDragHandleDescription to "Рачка за влечење", Strings.BottomSheetPartialExpandDescription to "Собери го долниот лист", Strings.BottomSheetDismissDescription to "Отфрли го долниот лист", Strings.BottomSheetExpandDescription to "Прошири го долниот лист", Strings.TooltipPaneDescription to "Совет за алатка", Strings.TooltipLongPressLabel to "Прикажи совет за алатка", Strings.TimePickerPM to "попл.", Strings.TimePickerAM to "прет.", Strings.TimePickerPeriodToggle to "Изберете претпладне или попладне", Strings.TimePickerHourSelection to "Изберете час", Strings.TimePickerMinuteSelection to "Изберете минути", Strings.TimePickerHourSuffix to "%1\$d часот", Strings.TimePicker24HourSuffix to "%1\$d часа", Strings.TimePickerMinuteSuffix to "%1\$d минути", Strings.TimePickerMinute to "Минута", Strings.TimePickerHour to "Час", Strings.TimePickerMinuteTextField to "за минути", Strings.TimePickerHourTextField to "за час", )
0
Kotlin
0
2
9730aa39ce1cafe408f28962a59b95b82c68587f
4,890
compose
Apache License 2.0
compose/material3/material3/src/skikoMain/kotlin/androidx/compose/material3/l10n/Mk.kt
VexorMC
838,305,267
false
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
/* * Copyright 2024 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 androidx.compose.material3.l10n import androidx.compose.material3.internal.Strings import androidx.compose.material3.internal.Translations @Suppress("UnusedReceiverParameter", "DuplicatedCode") internal fun Translations.mk() = mapOf( Strings.NavigationMenu to "Мени за навигација", Strings.ExposedDropdownMenu to "Паѓачко мени", Strings.CloseDrawer to "Затворете го менито за навигација", Strings.CloseSheet to "Затворете го листот", Strings.DefaultErrorMessage to "Неважечки запис", Strings.SliderRangeStart to "Почеток на опсегот", Strings.SliderRangeEnd to "Крај на опсегот", Strings.Dialog to "Дијалог", Strings.MenuExpanded to "Проширено", Strings.MenuCollapsed to "Собрано", Strings.ToggleDropdownMenu to "Вклучување/исклучување паѓачко мени", Strings.SnackbarDismiss to "Отфрли", Strings.SearchBarSearch to "Пребарување", Strings.SuggestionsAvailable to "Предлозите се наведени подолу", Strings.DatePickerTitle to "Изберете датум", Strings.DatePickerHeadline to "Избран датум", Strings.DatePickerSwitchToYearSelection to "Префрли на избирање година", Strings.DatePickerSwitchToDaySelection to "Повлечете за да изберете година или допрете за да се вратите на избирање ден", Strings.DatePickerSwitchToNextMonth to "Промени на следниот месец", Strings.DatePickerSwitchToPreviousMonth to "Промени на претходниот месец", Strings.DatePickerNavigateToYearDescription to "Одете на %1\$s година", Strings.DatePickerHeadlineDescription to "Тековен избор: %1\$s", Strings.DatePickerNoSelectionDescription to "Нема", Strings.DatePickerTodayDescription to "Денес", Strings.DatePickerYearPickerPaneTitle to "Избирачот на година е видлив", Strings.DateInputTitle to "Изберете датум", Strings.DateInputHeadline to "Внесен датум", Strings.DateInputLabel to "Датум", Strings.DateInputHeadlineDescription to "Внесен датум: %1\$s", Strings.DateInputNoInputDescription to "Нема", Strings.DateInputInvalidNotAllowed to "Датумот не е дозволен: %1\$s", Strings.DateInputInvalidForPattern to "Не се совпаѓа со очекуваната шема: %1\$s", Strings.DateInputInvalidYearRange to "Датумот не е во очекуваниот опсег на години %1\$s - %2\$s", Strings.DatePickerSwitchToCalendarMode to "Префрли на режим за внесување во календарот", Strings.DatePickerSwitchToInputMode to "Префрли на режим за внесување текст", Strings.DatePickerScrollToShowLaterYears to "Лизгајте за да ги прикажете подоцнежните години", Strings.DatePickerScrollToShowEarlierYears to "Лизгајте за да ги прикажете претходните години", Strings.DateRangePickerTitle to "Изберете датуми", Strings.DateRangePickerStartHeadline to "Датум на започнување", Strings.DateRangePickerEndHeadline to "Датум на завршување", Strings.DateRangePickerScrollToShowNextMonth to "Лизгајте за да се прикаже следниот месец", Strings.DateRangePickerScrollToShowPreviousMonth to "Лизгајте за да се прикаже претходниот месец", Strings.DateRangePickerDayInRange to "Во опсег", Strings.DateRangeInputTitle to "Внесете датуми", Strings.DateRangeInputInvalidRangeInput to "Внесовте неважечки временски период", Strings.BottomSheetPaneTitle to "Долен лист", Strings.BottomSheetDragHandleDescription to "Рачка за влечење", Strings.BottomSheetPartialExpandDescription to "Собери го долниот лист", Strings.BottomSheetDismissDescription to "Отфрли го долниот лист", Strings.BottomSheetExpandDescription to "Прошири го долниот лист", Strings.TooltipPaneDescription to "Совет за алатка", Strings.TooltipLongPressLabel to "Прикажи совет за алатка", Strings.TimePickerPM to "попл.", Strings.TimePickerAM to "прет.", Strings.TimePickerPeriodToggle to "Изберете претпладне или попладне", Strings.TimePickerHourSelection to "Изберете час", Strings.TimePickerMinuteSelection to "Изберете минути", Strings.TimePickerHourSuffix to "%1\$d часот", Strings.TimePicker24HourSuffix to "%1\$d часа", Strings.TimePickerMinuteSuffix to "%1\$d минути", Strings.TimePickerMinute to "Минута", Strings.TimePickerHour to "Час", Strings.TimePickerMinuteTextField to "за минути", Strings.TimePickerHourTextField to "за час", )
0
Kotlin
0
2
9730aa39ce1cafe408f28962a59b95b82c68587f
4,890
compose
Apache License 2.0
app/src/main/java/com/storyteller_f/fei/service/FeiServer.kt
storytellerF
612,287,528
false
null
package com.storyteller_f.fei.service import android.net.Uri import android.util.Log import android.widget.Toast import androidx.core.net.toFile import com.storyteller_f.fei.Message import com.storyteller_f.fei.cacheInvalid import com.storyteller_f.fei.removeUri import com.storyteller_f.fei.respondUri import com.storyteller_f.fei.shares import com.storyteller_f.fei.webSocketsService import io.ktor.client.HttpClient import io.ktor.client.engine.cio.CIO import io.ktor.client.plugins.websocket.DefaultClientWebSocketSession import io.ktor.client.plugins.websocket.WebSockets import io.ktor.client.plugins.websocket.receiveDeserialized import io.ktor.client.plugins.websocket.webSocket import io.ktor.http.ContentDisposition import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.http.HttpStatusCode import io.ktor.serialization.kotlinx.KotlinxWebsocketSerializationConverter import io.ktor.server.application.Application import io.ktor.server.application.ApplicationCall import io.ktor.server.application.call import io.ktor.server.application.install import io.ktor.server.engine.ApplicationEngine import io.ktor.server.engine.embeddedServer import io.ktor.server.netty.Netty import io.ktor.server.plugins.autohead.AutoHeadResponse import io.ktor.server.plugins.callloging.CallLogging import io.ktor.server.plugins.partialcontent.PartialContent import io.ktor.server.plugins.statuspages.StatusPages import io.ktor.server.response.header import io.ktor.server.response.respond import io.ktor.server.response.respondFile import io.ktor.server.response.respondText import io.ktor.server.routing.get import io.ktor.server.routing.routing import io.ktor.server.thymeleaf.Thymeleaf import io.ktor.server.thymeleaf.ThymeleafContent import io.ktor.server.websocket.pingPeriod import io.ktor.server.websocket.timeout import io.ktor.websocket.close import io.ktor.websocket.send import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import kotlinx.coroutines.channels.BroadcastChannel import kotlinx.coroutines.channels.broadcast import kotlinx.coroutines.channels.produce import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver import java.io.File import java.io.FileInputStream import java.nio.ByteBuffer import java.time.Duration import java.util.UUID @OptIn(ObsoleteCoroutinesApi::class) class FeiServer(private val feiService: FeiService) { private var server: ApplicationEngine? = null var channel: BroadcastChannel<SseEvent>? = null private var selfClient: HttpClient? = null private var selfSession: DefaultClientWebSocketSession? = null var port = FeiService.defaultPort val messagesCache = MutableStateFlow(listOf<Message>()) @OptIn(ExperimentalCoroutinesApi::class) private suspend fun startInternal() { Log.d(TAG, "startInternal() called") try { server = embeddedServer(Netty, port = port, host = FeiService.listenerAddress) { plugPlugins() channel = produce { var n = 0 while (true) { send(SseEvent("$n", "ping")) delay(1000) n++ } }.broadcast() routing { get("/sse") { val events = channel!!.openSubscription() try { call.respondSse(events) } finally { events.cancel() } } } configureRouting(feiService) webSocketsService() }.start(wait = false) Log.i(TAG, "startInternal: $server") val httpClient = HttpClient(CIO) { install(WebSockets) { pingInterval = 20_000 contentConverter = KotlinxWebsocketSerializationConverter(Json) } } selfClient = httpClient feiService.scope.launch { httpClient.webSocket(method = HttpMethod.Get, host = "127.0.0.1", port = port, path = "/chat") { selfSession = this try { while (true) { val receiveDeserialized = receiveDeserialized<Message>() messagesCache.value = messagesCache.value.plus(receiveDeserialized) } } catch (e: Exception) { Log.e(TAG, "startInternal: self webSocket", e) } selfSession = null } Log.i(TAG, "startInternal: self webSocket end") } feiService.postNotify("running on $port") } catch (th: Throwable) { Log.e(TAG, "startInternal: ${th.localizedMessage}", th) } } fun stop() { feiService.scope.launch { stopInternal() } } private suspend fun stopInternal() { Log.d(TAG, "stopInternal() called") feiService.postNotify("stopped") selfSession?.close() selfSession = null selfClient?.close() selfClient = null server?.stop() server = null channel?.cancel() channel = null } fun restart() { feiService.scope.launch { stopInternal() startInternal() } Toast.makeText(feiService, "restarted", Toast.LENGTH_SHORT).show() } suspend fun restartAsync() { stopInternal() startInternal() } fun stopAsync() { runBlocking { stopInternal() } } private fun Application.plugPlugins() { install(StatusPages) { exception<Throwable> { call: ApplicationCall, cause -> call.respondText( cause.localizedMessage ?: cause.javaClass.canonicalName, status = HttpStatusCode.InternalServerError ) Log.e(TAG, "plugPlugins: ", cause) } } install(CallLogging) install(Thymeleaf) { setTemplateResolver(ClassLoaderTemplateResolver().apply { prefix = "templates/" suffix = ".html" characterEncoding = "utf-8" }) } install(PartialContent) install(AutoHeadResponse) install(io.ktor.server.websocket.WebSockets) { pingPeriod = Duration.ofSeconds(15) timeout = Duration.ofSeconds(15) maxFrameSize = Long.MAX_VALUE masking = false contentConverter = KotlinxWebsocketSerializationConverter(Json) } } fun saveToLocal(uri: Uri?, info: SharedFileInfo) { uri ?: return feiService.scope.launch { saveFile(File(info.name).extension, uri) feiService.removeUri(info) feiService.cacheInvalid()//when save to local channel?.send(SseEvent("refresh")) } } private suspend fun saveFile(extension: String?, uri: Uri) { try { withContext(Dispatchers.IO) { val file = File(feiService.filesDir, "saved/file-${UUID.randomUUID()}.$extension") val parentFile = file.parentFile!! if (!parentFile.exists()) { parentFile.mkdirs() } if (file.createNewFile()) { uri.writeToFile(file) } else { Log.e(TAG, "create file failed ${file.absolutePath}") } } } catch (e: Exception) { Log.e(TAG, "saveFile: ", e) } } private fun Uri.writeToFile(file: File) { file.outputStream().channel.use { oChannel -> feiService.contentResolver.openFileDescriptor(this, "r")?.use { parcelFileDescriptor -> FileInputStream(parcelFileDescriptor.fileDescriptor).channel.use { iChannel -> val byteBuffer = ByteBuffer.allocateDirect(1024) while (iChannel.read(byteBuffer) != -1) { byteBuffer.flip() oChannel.write(byteBuffer) byteBuffer.clear() } } } } } fun sendMessage(content: String) { feiService.scope.launch { selfSession?.send(content) } } companion object { private const val TAG = "FeiServer" } } private fun Application.configureRouting(feiService: FeiService) { routing { get("/") { call.respond( ThymeleafContent( "index", mapOf("shares" to List(shares.value.size) { index -> index.toString() }) ) ) } get("/messages") { call.respond(ThymeleafContent("chat", mapOf())) } get("/shares") { val encodeToString = Json.encodeToString(shares.value) call.respond(encodeToString) } get("/shares/{count}") { val index = call.parameters["count"]?.toInt() ?: return@get val info = shares.value.getOrNull(index) if (info == null) { call.respond(HttpStatusCode.NotFound) } else { call.response.header( HttpHeaders.ContentDisposition, ContentDisposition.Attachment.withParameter( ContentDisposition.Parameters.FileName, info.name ) .toString() ) val file = Uri.parse(info.uri) if (file.scheme == "file") { call.respondFile(file.toFile()) } else call.respondUri(feiService, file) } } } }
1
Kotlin
0
3
f7fd9ef05b5dcd179783bedaa0bcf92588f8234a
10,433
Fei
MIT License
Base/src/main/java/xy/xy/base/assembly/qr/QrCreateAssemblyView.kt
xiuone
291,512,847
false
null
package xy.xy.base.assembly.qr import android.graphics.Bitmap import android.view.View import android.widget.ImageView import xy.xy.base.assembly.base.BaseAssemblyViewWithContext interface QrCreateAssemblyView :BaseAssemblyViewWithContext { fun createSaveView():View? fun createQrImageViewList():MutableList<ImageView?> fun createSaveQrButton():View? fun createChangeQrButton():View? fun createLogoBitmap():Bitmap? fun createNewContent():String? fun createBitmapSize():Int = 600 fun createSaveHistoryKey():String? }
0
Kotlin
1
2
51bc46fde7d03484241b04cddc77236dbecf4469
549
ajinlib
Apache License 2.0
core/src/main/kotlin/kairi/core/entities/UserEntity.kt
AugustArchive
405,771,313
false
{"Kotlin": 57852}
/** * Copyright (c) 2021 Noel * * 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 kairi.core.entities import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class UserEntity( @SerialName("_id") val id: String, val username: String, val badges: Int, val avatar: AvatarEntity, val bot: BotEntity, val relationship: String, val online: Boolean )
1
Kotlin
0
3
aaba6f40ba5865e9727f1050e507132916acce9e
1,460
Kairi
MIT License
src/main/kotlin/su/gachi/commands/items/ArmorsCommand.kt
Oxygen-Studio-VAX
577,374,170
false
{"Kotlin": 57867, "Shell": 188}
package su.gachi.commands.items import net.dv8tion.jda.api.EmbedBuilder import net.dv8tion.jda.api.interactions.DiscordLocale import net.dv8tion.jda.api.interactions.commands.OptionType import net.dv8tion.jda.api.interactions.commands.build.OptionData import org.json.JSONObject import su.gachi.Config import su.gachi.core.commands.Command import su.gachi.core.commands.CommandContext import su.gachi.items.ArmoryItems import su.gachi.items.NpcsData import kotlin.text.StringBuilder class ArmorsCommand : Command() { init { name = "armors" description = "Information about armors" options = listOf( OptionData(OptionType.STRING, "id", "Armor ID (short name)", true, true) .setDescriptionLocalization(DiscordLocale.RUSSIAN, "ID бронезащиты (короткое имя)") ) isGuildOnly = false } override fun handle(ctx: CommandContext) { ctx.deferReply() if (ctx.getOption("id")!!.asString == "list") { val builder = StringBuilder() ArmoryItems.raw.forEach { val item = it as JSONObject builder.append("`${item.getString("id")}` = **") builder.append( if (item.getJSONObject("name_localized").has(ctx.locale)) item.getJSONObject("name_localized").getString(ctx.locale) else item.getString("name") ) builder.append("**\n") } ctx.editOriginalEmbeds( EmbedBuilder().setColor(Config.embedColor) .setTitle(ctx.translate("commands.armors.title")) .setDescription(builder.toString()) .setFooter(ctx.translate("commands.armors.footer")) .build() ) } else { val item = ArmoryItems.findByID(ctx.getOption("id")!!.asString) ?: return ctx.editOriginalWithError(ctx.translate("commands.armors.error")) val itemName = if (item.getJSONObject("name_localized").has(ctx.locale)) item.getJSONObject("name_localized").getString(ctx.locale) else item.getString("name") val itemDescription = if (item.getJSONObject("description_localized").has(ctx.locale)) item.getJSONObject("description_localized").getString(ctx.locale) else item.getString("description") val pricingKeys = item.getJSONObject("pricing").keySet() .filter { key -> !item.getJSONObject("pricing").isNull(key) } val pricing = mutableMapOf<String, Any>() pricingKeys.forEach { key -> pricing[key] = item.getJSONObject("pricing").get(key) } val parametersKeys = item.getJSONObject("parameters").keySet() .filter { key -> !item.getJSONObject("parameters").isNull(key) } val parameters = mutableMapOf<String, Any>() parametersKeys.forEach { key -> parameters[key] = item.getJSONObject("parameters").get(key) } if (!item.isNull("npc")) { val npc = NpcsData.npcs[item.getString("npc")] if (npc != null) { pricing["npc"] = "${if (npc.getJSONObject("name_localized").has(ctx.locale)) npc.getJSONObject("name_localized").getString(ctx.locale) else npc.getString("name")} ${npc.getString("emoji")}" } } ctx.editOriginalEmbeds( EmbedBuilder().setColor(if (item.isNull("color")) Config.embedColor else item.getInt("color")) .setTitle(ctx.translate("commands.armors.info.title", mapOf("name" to itemName))) .setDescription(itemDescription) .setThumbnail(item.getString("image")) .addField(ctx.translate("commands.armors.info.pricing.name"), ctx.translate("commands.armors.info.pricing.value", pricing), true) .addField(ctx.translate("commands.armors.info.parameters.name"), ctx.translate("commands.armors.info.parameters.value", parameters), true) .addField(ctx.translate("commands.armors.info.found.name"), ctx.translate("commands.armors.undefined"), true) .build() ) } } }
0
Kotlin
0
0
08bf5ece5c02acaf2c99265488d0280d21ee25a4
4,426
oxybot-jda
Apache License 2.0
diktat-rules/src/main/kotlin/org/cqfn/diktat/ruleset/utils/SequenceUtils.kt
cqfn
275,879,956
false
null
/** * Utility methods to work with sequences */ package org.cqfn.diktat.ruleset.utils /** * @param pred a predicate * @return filtered sequence */ fun <T> Sequence<T>.takeWhileInclusive(pred: (T) -> Boolean): Sequence<T> { var shouldContinue = true return takeWhile { val result = shouldContinue shouldContinue = pred(it) result } }
93
null
23
361
d8c4cea250a651244fb6bad0ecf9bad505ece89b
376
diKTat
MIT License
app/src/main/java/reach52/marketplace/community/fragments/follow_up/FollowUpsFragment.kt
reach52
422,514,975
false
{"Kotlin": 1436380, "Java": 18303}
package reach52.marketplace.community.fragments.follow_up import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import androidx.paging.LivePagedListBuilder import androidx.recyclerview.widget.LinearLayoutManager import com.jakewharton.rxbinding3.view.clicks import reach52.marketplace.community.R import reach52.marketplace.community.adapters.follow_up.FollowUpAdapter import reach52.marketplace.community.persistence.DispergoDatabase import reach52.marketplace.community.persistence.EntityDataSource import reach52.marketplace.community.persistence.EntityDataSourceFactory import reach52.marketplace.community.persistence.followup_mapper.FollowUpMapper import reach52.marketplace.community.viewmodels.FollowUpViewModel import reach52.marketplace.community.viewmodels.ResidentLogisticViewModel import io.reactivex.disposables.CompositeDisposable import kotlinx.android.synthetic.main.fragment_follow_ups.view.* class FollowUpsFragment : Fragment() { private val disposables = CompositeDisposable() private val residentLogisticViewModel by lazy { activity?.run { ViewModelProvider(this)[ResidentLogisticViewModel::class.java] }?: throw Exception("Invalid Activity") } private val followUpViewModel by lazy { activity?.run { ViewModelProvider(this)[FollowUpViewModel::class.java] }?: throw Exception("Invalid Activity") } private val followUpAdapter = FollowUpAdapter {id -> followUpViewModel.selectedFollowId.value = id parentFragmentManager .beginTransaction() .replace(R.id.fragment_container, FollowUpDetailsFragment()) .addToBackStack(null) .commit() } private val followUpQuery by lazy { DispergoDatabase.toFollowUpsView(context!!).createQuery() } private val followUpLiveQuery by lazy { followUpQuery.toLiveQuery() } private val factory by lazy { EntityDataSourceFactory(followUpQuery::run, FollowUpMapper()) } private val followUp by lazy { LivePagedListBuilder(factory, EntityDataSource.PAGED_LIST_CONFIG).build() } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) if(residentLogisticViewModel.isLogisticResident.value == true){ followUpQuery.apply { startKey = followUpViewModel.selectedLogisticResident.value?.residentId endKey = followUpViewModel.selectedLogisticResident.value?.residentId } } else { followUpQuery.apply { startKey = followUpViewModel.selectedResident.value?.id endKey = followUpViewModel.selectedResident.value?.id } } followUpLiveQuery.apply { addChangeListener { event -> if(event.source == this) { factory.fnEnumerator = {event.rows} followUp.value?.dataSource?.invalidate() } } start() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { followUp.observe(viewLifecycleOwner, Observer { it -> followUpAdapter.submitList(it?.sortedBy { it?.record?.dateFollowUp }) }) return inflater.inflate(R.layout.fragment_follow_ups, container, false).apply { // Auth.currentSession(context).map { session -> // // this will check the role of the login user first before emitting the document // if(session.user.roles.contains(AppUser.ROLE_SELF_SIGNPUP)) { // followUpNotAvailableTxt.visibility = View.VISIBLE // floatingActionButton.visibility = View.GONE // } // } followUpRecyclerView.apply { layoutManager = LinearLayoutManager(activity) adapter = followUpAdapter } disposables.add(floatingActionButton.clicks().subscribe{ parentFragmentManager .beginTransaction() .replace(R.id.fragment_container, AddFollowUpFragment()) .addToBackStack(null) .commit() }) } } }
0
Kotlin
0
0
629c52368d06f978f19238d0bd865f4ef84c23d8
4,601
Marketplace-Community-Edition
MIT License
vpn/src/main/java/com/duckduckgo/mobile/android/vpn/processor/tcp/TcpConnectionInitializer.kt
cmonfortep
252,403,423
true
{"Kotlin": 6042652, "HTML": 42259, "Java": 35279, "JavaScript": 8281, "Ruby": 7654, "C++": 1820, "CMake": 1298, "Shell": 784}
/* * Copyright (c) 2020 DuckDuckGo * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.duckduckgo.mobile.android.vpn.processor.tcp import com.duckduckgo.di.scopes.VpnScope import com.duckduckgo.mobile.android.vpn.network.channels.NetworkChannelCreator import com.duckduckgo.mobile.android.vpn.processor.tcp.ConnectionInitializer.TcpConnectionParams import com.duckduckgo.mobile.android.vpn.service.VpnQueues import com.squareup.anvil.annotations.ContributesBinding import timber.log.Timber import xyz.hexene.localvpn.ByteBufferPool import xyz.hexene.localvpn.Packet import xyz.hexene.localvpn.Packet.TCPHeader import xyz.hexene.localvpn.TCB import java.net.InetSocketAddress import java.nio.ByteBuffer import java.nio.channels.SocketChannel import javax.inject.Inject import javax.inject.Provider import kotlin.random.Random interface ConnectionInitializer { fun initializeConnection(params: TcpConnectionParams): Pair<TCB, SocketChannel>? data class TcpConnectionParams( val destinationAddress: String, val destinationPort: Int, val sourcePort: Int, val packet: Packet, val responseBuffer: ByteBuffer ) { fun key(): String { return "$destinationAddress:$destinationPort:$sourcePort" } fun close() { ByteBufferPool.release(responseBuffer) ByteBufferPool.release(packet.backingBuffer) } fun tcb(): TCB? { return TCB.getTCB(key()) } fun tcbOrClose(): TCB? { val tcb = tcb() if (tcb == null) { Timber.w("null TCB") close() } return tcb } } } @ContributesBinding(VpnScope::class) class TcpConnectionInitializer @Inject constructor( private val queues: VpnQueues, networkChannelCreatorProvider: Provider<NetworkChannelCreator> ) : ConnectionInitializer { private val networkChannelCreator by lazy { networkChannelCreatorProvider.get() } override fun initializeConnection(params: TcpConnectionParams): Pair<TCB, SocketChannel>? { val key = params.key() val header = params.packet.tcpHeader params.packet.swapSourceAndDestination() Timber.d("Initializing connection $key") val pair = if (header.isSYN) { val channel = networkChannelCreator.createSocketChannelAndConnect(InetSocketAddress(params.destinationAddress, params.destinationPort)) val sequenceNumberToClient = Random.nextLong(Short.MAX_VALUE.toLong() + 1) val sequenceToServer = header.sequenceNumber val ackNumberToClient = header.sequenceNumber + 1 val ackNumberToServer = header.acknowledgementNumber val tcb = TCB(key, sequenceNumberToClient, sequenceToServer, ackNumberToClient, ackNumberToServer, channel, params.packet) TCB.putTCB(params.key(), tcb) Pair(tcb, channel) } else { Timber.i("Trying to initialize a connection but is not a SYN packet; sending RST") params.packet.updateTcpBuffer( params.responseBuffer, TCPHeader.RST.toByte(), 0, params.packet.tcpHeader.sequenceNumber + 1, params.packet.tcpPayloadSize(true) ) queues.networkToDevice.offer(params.responseBuffer) null } return pair } }
5
Kotlin
0
3
228a1217aad96d19f90750d94664b7a4a5744c9a
3,963
Android
Apache License 2.0
src/nam/tran/factory/_method/ChicagoStyleClamPizza.kt
NamTranDev
229,420,809
false
null
package nam.tran.factory._method class ChicagoStyleClamPizza : Pizza()
1
null
1
3
1222d4fadb460012819bd61841f59423eb6e8346
71
DesignPattern
Apache License 2.0
app/src/main/java/io/sefu/nuntium/presentation/authentication/SignUpScreen.kt
SefuZeph
601,832,754
false
null
package io.sefu.nuntium.presentation.authentication import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import io.sefu.nuntium.R import io.sefu.nuntium.composable.HeaderDescriptionTopBar import io.sefu.nuntium.composable.NuntiumButton import io.sefu.nuntium.composable.NuntiumEditText import io.sefu.nuntium.composable.NuntiumText import io.sefu.nuntium.designsystem.NuntiumTheme import io.sefu.nuntium.navigation.Screens @Composable fun SignUpScreen(navController: NavController) { HeaderDescriptionTopBar( header = "Welcome to Nuntium \uD83D\uDC4B", description = "Hello, I guess you are new around here. You can start using the application after sign up." ) { LazyColumn(content = { item { Spacer(modifier = Modifier.height(32.dp)) NuntiumEditText( modifier = Modifier.fillMaxWidth(), "Username", imagePlaceHolder = R.drawable.usericon, iconHeight = 20.dp, iconWidth = 20.dp ) Spacer(modifier = Modifier.height(16.dp)) NuntiumEditText( modifier = Modifier.fillMaxWidth(), "Email Address", imagePlaceHolder = R.drawable.email_inac, iconHeight = 20.dp, iconWidth = 16.dp ) Spacer(modifier = Modifier.height(16.dp)) NuntiumEditText( modifier = Modifier.fillMaxWidth(), "Password", imagePlaceHolder = R.drawable.password_inac, iconHeight = 20.dp, iconWidth = 16.dp ) Spacer(modifier = Modifier.height(16.dp)) NuntiumEditText( modifier = Modifier.fillMaxWidth(), "Repeat Password", imagePlaceHolder = R.drawable.password_inac, iconHeight = 20.dp, iconWidth = 16.dp ) Spacer(modifier = Modifier.height(16.dp)) NuntiumButton(modifier = Modifier.fillMaxWidth(), textValue = "Confirm") { navController.navigate(Screens.TopicScreen.routes) } } }) Row(modifier = Modifier .clickable { navController.navigate(Screens.LoginScreen.routes) } .fillMaxWidth() .align(alignment = Alignment.BottomCenter), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.Center) { NuntiumText( text = "Already have an account?", modifier = Modifier, style = TextStyle( color = NuntiumTheme.colors.greyPrimary, fontWeight = FontWeight.SemiBold, fontSize = 16.sp ) ) Spacer(modifier = Modifier.width(4.dp)) NuntiumText( text = "Send again", modifier = Modifier, style = TextStyle( color = NuntiumTheme.colors.blackPrimary, fontWeight = FontWeight.SemiBold, fontSize = 16.sp ) ) } } }
0
Kotlin
0
0
0f4db6422dafdff184e53fd8c1d5da06173efd7a
3,772
Nuntium
Apache License 2.0
app/src/main/java/com/my_1st/fincalc/ui/dep/DepositViewModel.kt
Tigran-Khachikyan
234,118,867
false
null
package com.my_1st.fincalc.ui.dep import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.my_1st.fincalc.data.Repository import com.my_1st.fincalc.data.db.dep.Deposit import kotlinx.coroutines.launch class DepositViewModel(application: Application): AndroidViewModel(application) { private val repo = Repository.getInstance(application) fun addDep(dep:Deposit) = viewModelScope.launch { repo?.insertDep(dep) } }
0
Kotlin
0
0
68480517fc7465d3b4052664e98fba0192a832c5
505
FinCalc
Apache License 2.0
app/src/main/java/com/example/note_app/MainActivity.kt
enesulkerr
651,983,924
false
null
package com.example.note_app import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.* lateinit var titleText: EditText lateinit var detailText: EditText lateinit var btngotodetail: Button lateinit var titlelistview : ListView lateinit var db: DB lateinit var adapter: ArrayAdapter<String> class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) db = DB(this) titleText = findViewById(R.id.titleText) detailText = findViewById(R.id.detailText) btngotodetail = findViewById(R.id.btngotodetail) titlelistview = findViewById(R.id.titlelistview) val ls = db.allNote() var titleList = mutableListOf<String>() for (note in ls) { val title = note.title titleList.add(title) } adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, titleList) titlelistview.adapter = adapter btngotodetail.setOnClickListener { var title = titleText.text var detail = detailText.text db.addNote(title.toString(), detail.toString()) val ls = db.allNote() var titleList = mutableListOf<String>() for (note in ls) { val title = note.title titleList.add(title) } adapter.clear() adapter.addAll(titleList) adapter.notifyDataSetChanged() } titlelistview.onItemClickListener = AdapterView.OnItemClickListener { parent, view, position, id -> val ls = db.allNote() var detailList = mutableListOf<String>() var nidList = mutableListOf<Int>() for (note in ls) { val detail = note.detail val nid = note.nid nidList.add(nid) detailList.add(detail) } val clickedItemDetail = detailList[position] val clickedItem = titleList[position] val clikedItemNid = nidList[position] var intent= Intent(this, detailwindow::class.java) intent.putExtra("clikedItem", clickedItem) intent.putExtra("clickedItemDetail",clickedItemDetail) intent.putExtra("position",clikedItemNid) startActivity(intent) } } override fun onResume() { super.onResume() // Adapter güncellenir val ls = db.allNote() val titleList = mutableListOf<String>() for (note in ls) { val title = note.title titleList.add(title) } adapter.clear() adapter.addAll(titleList) adapter.notifyDataSetChanged() } }
0
Kotlin
0
0
fdea31fd19f17a4ba76ad5f8b946ad601bbddc7e
2,933
Note-App
MIT License
domain/src/main/java/ru/rznnike/eyehealthmanager/domain/model/enums/AcuitySymbolLetterEn.kt
RznNike
207,148,781
false
null
package ru.rznnike.eyehealthmanager.domain.model.enums import androidx.annotation.DrawableRes import ru.rznnike.eyehealthmanager.domain.R import ru.rznnike.eyehealthmanager.domain.model.IAcuitySymbol enum class AcuitySymbolLetterEn( @DrawableRes val iconResId: Int ) : IAcuitySymbol { E(R.drawable.ic_letters_en_e), F(R.drawable.ic_letters_en_f), P(R.drawable.ic_letters_en_p), T(R.drawable.ic_letters_en_t), O(R.drawable.ic_letters_en_o), Z(R.drawable.ic_letters_en_z), L(R.drawable.ic_letters_en_l), D(R.drawable.ic_letters_en_d), C(R.drawable.ic_letters_en_c); override fun getDrawableRes() = iconResId override fun getTag() = toString() }
0
null
0
4
70c802c797d8d893e9d19952a4ea4269ed33e544
694
EyeHealthManager
MIT License
fileboxlib/src/main/java/com/lyrebirdstudio/fileboxlib/downloader/DownloadRequest.kt
lyrebirdstudio
238,207,373
false
null
package com.lyrebirdstudio.fileboxlib.downloader import com.lyrebirdstudio.fileboxlib.core.Record internal data class DownloadRequest(val record: Record)
3
Kotlin
24
312
0cfaa0d0b05ed5d25d87eed88de224f630ba91e6
155
filebox
Apache License 2.0
backstackexample/src/main/java/com/gregorymarkthomas/backstackexample/presenter/ActivityPresenterInterface.kt
gregorymarkthomas
751,530,531
false
{"Kotlin": 37484}
package com.gregorymarkthomas.backstackexample.presenter interface ActivityPresenterInterface { fun onGoToButtonPress(position: Int) fun onResumeToButtonPress(position: Int) fun onClearToButtonPress(position: Int) fun onGoBackButtonPress() }
0
Kotlin
0
0
d4207e396820eb20310015c951cd26940fb24337
258
kotlin-backstack
MIT License
data/communication/src/main/java/io/github/mmolosay/datalayercommunication/data/communication/convertion/encode/CompressingDecorator.kt
mmolosay
594,482,339
false
null
package io.github.mmolosay.datalayercommunication.data.communication.convertion.encode import io.github.mmolosay.datalayercommunication.domain.communication.convertion.Encoder import io.github.mmolosay.datalayercommunication.domain.communication.model.Data import io.github.mmolosay.datalayercommunication.domain.communication.model.asString import java.io.ByteArrayOutputStream import java.nio.charset.StandardCharsets import java.util.zip.GZIPOutputStream /** * [Encoder] with data compressing functionality. */ class CompressingDecorator<T>( encoder: Encoder<T> ) : EncoderDecorator<T>(encoder) { override fun encode(value: T): Data { val encoded = encoder.encode(value) val string = encoded.asString() val bos = ByteArrayOutputStream() GZIPOutputStream(bos) .bufferedWriter(StandardCharsets.UTF_8) .use { it.write(string) } val bytes = bos.toByteArray() return Data(bytes) } }
0
Kotlin
0
0
91656536b5597b91263266c10999759c85a72ff8
969
DataLayerCommunication
Apache License 2.0
src/test/kotlin/no/nav/syfo/api/CORSTest.kt
navikt
208,218,158
false
null
package no.nav.syfo.api import io.ktor.application.install import io.ktor.features.CORS import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.http.HttpStatusCode import io.ktor.routing.routing import io.ktor.server.testing.TestApplicationEngine import io.ktor.server.testing.handleRequest import no.nav.syfo.application.ApplicationState import no.nav.syfo.application.api.registerNaisApi import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object CORSTest : Spek({ describe("CORS-test, anyhost med allow credentials = true") { with(TestApplicationEngine()) { start() application.install(CORS) { host("syfosmmanuell.nais.preprod.local", schemes = listOf("https")) allowCredentials = true } val applicationState = ApplicationState() applicationState.ready = true applicationState.alive = true application.routing { registerNaisApi(applicationState) } it("No origin header") { with(handleRequest(HttpMethod.Get, "/is_alive")) { response.status() shouldBeEqualTo HttpStatusCode.OK response.headers[HttpHeaders.AccessControlAllowOrigin] shouldBeEqualTo null response.content shouldBeEqualTo "I'm alive! :)" } } it("Wrong origin header") { with( handleRequest(HttpMethod.Get, "/is_ready") { addHeader(HttpHeaders.Origin, "invalid-host") } ) { response.status() shouldBeEqualTo HttpStatusCode.OK response.headers[HttpHeaders.AccessControlAllowOrigin] shouldBeEqualTo null response.content shouldBeEqualTo "I'm ready! :)" } } it("Wrong origin header is empty") { with( handleRequest(HttpMethod.Get, "/is_ready") { addHeader(HttpHeaders.Origin, "") } ) { response.status() shouldBeEqualTo HttpStatusCode.OK response.headers[HttpHeaders.AccessControlAllowOrigin] shouldBeEqualTo null response.content shouldBeEqualTo "I'm ready! :)" } } it("Simple credentials") { with( handleRequest(HttpMethod.Options, "/is_ready") { addHeader(HttpHeaders.Origin, "https://syfosmmanuell.nais.preprod.local") addHeader(HttpHeaders.AccessControlRequestMethod, "GET") } ) { response.status() shouldBeEqualTo HttpStatusCode.OK response.headers[HttpHeaders.AccessControlAllowOrigin] shouldBeEqualTo "https://syfosmmanuell.nais.preprod.local" response.headers[HttpHeaders.Vary] shouldBeEqualTo HttpHeaders.Origin response.headers[HttpHeaders.AccessControlAllowCredentials] shouldBeEqualTo "true" } } } } describe("CORS-test, <NAME>") { it("Simple Request") { with(TestApplicationEngine()) { start() application.install(CORS) { host("syfosmmanuell.nais.preprod.local", schemes = listOf("http", "https")) } val applicationState = ApplicationState() applicationState.ready = true applicationState.alive = true application.routing { registerNaisApi(applicationState) } with( handleRequest(HttpMethod.Get, "/is_ready") { addHeader(HttpHeaders.Origin, "https://syfosmmanuell.nais.preprod.local") } ) { response.status() shouldBeEqualTo HttpStatusCode.OK response.headers[HttpHeaders.AccessControlAllowOrigin] shouldBeEqualTo "https://syfosmmanuell.nais.preprod.local" response.content shouldBeEqualTo "I'm ready! :)" } } } it("Simple Null") { with(TestApplicationEngine()) { start() application.install(CORS) { anyHost() } val applicationState = ApplicationState() applicationState.ready = true applicationState.alive = true application.routing { registerNaisApi(applicationState) } with( handleRequest(HttpMethod.Get, "/is_ready") { addHeader(HttpHeaders.Origin, "null") } ) { response.status() shouldBeEqualTo HttpStatusCode.OK response.headers[HttpHeaders.AccessControlAllowOrigin] shouldBeEqualTo "*" response.content shouldBeEqualTo "I'm ready! :)" } } } it("Pre flight custom host") { with(TestApplicationEngine()) { start() application.install(CORS) { host("syfosmmanuell.nais.preprod.local", schemes = listOf("http", "https")) allowNonSimpleContentTypes = true } val applicationState = ApplicationState() applicationState.ready = true applicationState.alive = true application.routing { registerNaisApi(applicationState) } with( handleRequest(HttpMethod.Options, "/is_ready") { addHeader(HttpHeaders.Origin, "https://syfosmmanuell.nais.preprod.local") addHeader(HttpHeaders.AccessControlRequestMethod, "GET") } ) { response.status() shouldBeEqualTo HttpStatusCode.OK response.headers[HttpHeaders.AccessControlAllowOrigin] shouldBeEqualTo "https://syfosmmanuell.nais.preprod.local" response.headers[HttpHeaders.AccessControlAllowHeaders] shouldBeEqualTo "Content-Type" response.headers[HttpHeaders.Vary] shouldBeEqualTo HttpHeaders.Origin } } } } })
0
Kotlin
0
0
d307b5a6a030cabc547441826bcdc8b2cb3dbd71
6,530
syfosmmanuell-backend
MIT License
app/src/main/java/be/digitalia/fosdem/db/RoomDatabaseExt.kt
cbeyls
15,915,146
false
{"Kotlin": 338620}
package be.digitalia.fosdem.db import androidx.room.RoomDatabase import androidx.room.invalidationTrackerFlow import be.digitalia.fosdem.utils.BackgroundWorkScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.stateIn fun RoomDatabase.createVersionFlow(vararg tables: String): Flow<Int> { return flow { var version = 0 invalidationTrackerFlow(*tables).collect { emit(version++) } }.stateIn( scope = BackgroundWorkScope, started = SharingStarted.Eagerly, initialValue = null ).filterNotNull() }
14
Kotlin
93
136
db1f6b05c59c818a58e673ec9b4b40dc6f694d50
714
fosdem-companion-android
Apache License 2.0
dmn-test-cases/standard/tck/1.1/cl3/0021-singleton-list/translator/expected/kotlin/dmn/Decision4.kt
goldmansachs
118,478,361
false
{"Java": 10136959, "Kotlin": 1021119, "Python": 419543, "FreeMarker": 229313, "ANTLR": 102014, "Batchfile": 1400, "Shell": 980}
import java.util.* import java.util.stream.Collectors @javax.annotation.Generated(value = ["decision.ftl", "decision4"]) @com.gs.dmn.runtime.annotation.DRGElement( namespace = "", name = "decision4", label = "", elementKind = com.gs.dmn.runtime.annotation.DRGElementKind.DECISION, expressionKind = com.gs.dmn.runtime.annotation.ExpressionKind.LITERAL_EXPRESSION, hitPolicy = com.gs.dmn.runtime.annotation.HitPolicy.UNKNOWN, rulesCount = -1 ) class Decision4() : com.gs.dmn.runtime.DefaultDMNBaseDecision() { override fun applyMap(input_: MutableMap<String, String>, context_: com.gs.dmn.runtime.ExecutionContext): String? { try { return apply(input_.get("Employees")?.let({ com.gs.dmn.serialization.JsonSerializer.OBJECT_MAPPER.readValue(it, object : com.fasterxml.jackson.core.type.TypeReference<List<String?>?>() {}) }), context_) } catch (e: Exception) { logError("Cannot apply decision 'Decision4'", e) return null } } fun apply(employees: List<String?>?, context_: com.gs.dmn.runtime.ExecutionContext): String? { try { // Start decision 'decision4' var annotationSet_: com.gs.dmn.runtime.annotation.AnnotationSet = context_.getAnnotations() var eventListener_: com.gs.dmn.runtime.listener.EventListener = context_.getEventListener() var externalExecutor_: com.gs.dmn.runtime.external.ExternalFunctionExecutor = context_.getExternalFunctionExecutor() var cache_: com.gs.dmn.runtime.cache.Cache = context_.getCache() val decision4StartTime_ = System.currentTimeMillis() val decision4Arguments_ = com.gs.dmn.runtime.listener.Arguments() decision4Arguments_.put("Employees", employees) eventListener_.startDRGElement(DRG_ELEMENT_METADATA, decision4Arguments_) // Evaluate decision 'decision4' val output_: String? = evaluate(employees, context_) // End decision 'decision4' eventListener_.endDRGElement(DRG_ELEMENT_METADATA, decision4Arguments_, output_, (System.currentTimeMillis() - decision4StartTime_)) return output_ } catch (e: Exception) { logError("Exception caught in 'decision4' evaluation", e) return null } } private inline fun evaluate(employees: List<String?>?, context_: com.gs.dmn.runtime.ExecutionContext): String? { var annotationSet_: com.gs.dmn.runtime.annotation.AnnotationSet = context_.getAnnotations() var eventListener_: com.gs.dmn.runtime.listener.EventListener = context_.getEventListener() var externalExecutor_: com.gs.dmn.runtime.external.ExternalFunctionExecutor = context_.getExternalFunctionExecutor() var cache_: com.gs.dmn.runtime.cache.Cache = context_.getCache() return asElement(employees?.filter({ item -> stringEqual(item, "Bob") })) as String? } companion object { val DRG_ELEMENT_METADATA : com.gs.dmn.runtime.listener.DRGElement = com.gs.dmn.runtime.listener.DRGElement( "", "decision4", "", com.gs.dmn.runtime.annotation.DRGElementKind.DECISION, com.gs.dmn.runtime.annotation.ExpressionKind.LITERAL_EXPRESSION, com.gs.dmn.runtime.annotation.HitPolicy.UNKNOWN, -1 ) } }
10
Java
41
136
2f3da498778c8b6ab648cc53353f52991e88ae2c
3,398
jdmn
Apache License 2.0
src/test/kotlin/com/atlassian/pedagogical/ao/SystemPropertyJdbcConfiguration.kt
atl-mk
529,135,749
false
{"Kotlin": 26021, "Java": 4142, "Closure Templates": 351}
package com.atlassian.pedagogical.ao import net.java.ao.test.jdbc.AbstractJdbcConfiguration import net.java.ao.test.jdbc.H2Memory import net.java.ao.test.jdbc.JdbcConfiguration import org.slf4j.LoggerFactory class SystemPropertyJdbcConfiguration : JdbcConfiguration { private val log = LoggerFactory.getLogger(SystemPropertyJdbcConfiguration::class.java) private val jdbcConfiguration: JdbcConfiguration companion object { const val PROTOCOL_JTDS = "jdbc:jtds:sqlserver" const val PROTOCOL_SQLSERVER = "jdbc:sqlserver" private const val PROP_JDBC_PREFIX = "jdbc." private const val PROP_JDBC_TYPE = PROP_JDBC_PREFIX + "type" private const val PROP_JDBC_USER = PROP_JDBC_PREFIX + "user" private const val PROP_JDBC_PASSWORD = PROP_JDBC_PREFIX + "password" private const val PROP_JDBC_SCHEMA = PROP_JDBC_PREFIX + "schema" const val PROP_JDBC_URL = PROP_JDBC_PREFIX + "url" } init { var url = System.getProperty(PROP_JDBC_URL) val user = System.getProperty(PROP_JDBC_USER) val password = System.getProperty(PROP_JDBC_PASSWORD) var schema = System.getProperty(PROP_JDBC_SCHEMA) val jdbcType = System.getProperty(PROP_JDBC_TYPE) log.info( "System properties: {}={}, {}={}, {}={}, {}={}, {}={}", PROP_JDBC_URL, url, PROP_JDBC_USER, user, PROP_JDBC_PASSWORD, password, PROP_JDBC_SCHEMA, schema, PROP_JDBC_TYPE, jdbcType ) if (url != null && user != null && password != null) { if (url.startsWith(PROTOCOL_JTDS)) { val temp = PROTOCOL_SQLSERVER + url.substring(PROTOCOL_JTDS.length) log.warn("Rewrote jTDS JDBC URL to Microsoft equivalent. {} -> {}", url, temp) url = temp } // Hack for SQLServer 2012. Currently ActiveObjects test module uses the default implementation of // net.java.ao.SchemaConfiguration.shouldManageTable() which always returns true, which in the case // of SQLServer 2012 picks up system tables. This does not happen at runtime as the ActiveObjects table // uses com.atlassian.activeobjects.ao.PrefixedSchemaConfiguration which is what the unit tests should use // as well if (schema == null && url.startsWith(PROTOCOL_SQLSERVER)) { schema = "dbo" } jdbcConfiguration = SimpleJdbcConfiguration(url, user, password, schema) log.info( "Using custom database configurations for AO test. url={}, user={}, password={}, schema={}", url, user, password, schema ) } else if ("H2".equals(jdbcType, ignoreCase = true)) { //H2Memory doesn't configure DB_CLOSE_DELAY, so after the first connection is closed the schema is //destroyed and the tests all fail val h2 = H2Memory() jdbcConfiguration = SimpleJdbcConfiguration( h2.url + ";DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=TRUE", h2.username, h2.password, h2.schema ) log.info("Using in-memory H2 database for AO test") } else { throw RuntimeException( String.format( "No JDBC arguments specified! You can use append 'h2' or other db profiles. If you are running this in " + "IDE then make sure to set system environment variable %s=h2", PROP_JDBC_TYPE ) ) } } override fun getPassword(): String { return jdbcConfiguration.password } override fun getSchema(): String { return jdbcConfiguration.schema } override fun getUrl(): String { return jdbcConfiguration.url } override fun getUsername(): String { return jdbcConfiguration.username } override fun init() { jdbcConfiguration.init() } private class SimpleJdbcConfiguration constructor( url: String?, user: String, password: String, schema: String? ) : AbstractJdbcConfiguration(url, user, password, schema) { override fun getDefaultSchema(): String { return "" } override fun getDefaultUrl(): String { return "" } } }
0
Kotlin
2
2
7ff3600d7f3b9b2cdc5a1a088b354624add9fe96
4,413
kotlin-p2
MIT License
batch/src/main/kotlin/com/isystk/sample/batch/jobs/solrRegist/SolrRegistDto.kt
isystk
328,037,305
false
{"Kotlin": 462354, "TypeScript": 88591, "HTML": 77276, "SCSS": 24557, "FreeMarker": 21801, "JavaScript": 5293, "Shell": 3607, "Dockerfile": 1581, "CSS": 942}
package com.isystk.sample.batch.jobs.solrRegist import com.isystk.sample.batch.item.ItemPosition class SolrRegistDto : ItemPosition { // 取り込み元ファイル override var sourceName: String? = null override var position = 0 }
0
Kotlin
0
2
2e4e0c62af22c05403e5d3452ba08eb09c05a7f1
229
kotlin-springboot-boilerplate
MIT License
newm-server/src/main/kotlin/io/newm/server/database/migration/V11__SongsUpdates.kt
projectNEWM
447,979,150
false
null
package io.newm.server.database.migration import org.flywaydb.core.api.migration.BaseJavaMigration import org.flywaydb.core.api.migration.Context import org.jetbrains.exposed.sql.transactions.transaction @Suppress("unused") class V11__SongsUpdates : BaseJavaMigration() { override fun migrate(context: Context?) { transaction { exec( "ALTER TABLE songs ADD COLUMN IF NOT EXISTS payment_key_id uuid CONSTRAINT fk_songs_payment_key_id__id REFERENCES keys (id) ON DELETE NO ACTION ON UPDATE RESTRICT" ) } } }
1
null
4
9
b25c5a6d016c232707b6aefad18abec35fc4c167
572
newm-server
Apache License 2.0
learning-kotlin-2020/src/ArraysSetsLists.kt
kevin2-cyber
437,880,493
false
{"Kotlin": 765037, "CSS": 301626, "SCSS": 287609, "HTML": 208821, "JavaScript": 16612, "Java": 2758, "TypeScript": 366}
/* * Copyright (c) 2020 UG Short course (Mobile Apps) * Facilitator: <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 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. */ // Arrays // Sets // Lists fun main() { // An array => a collection of items of the same type println("Arrays") val items = arrayOf<Any>(1, "<NAME>", true, 89.99, 89.99f) // items.forEach { println(it) } println() println("ArrayList") val arrayList = arrayListOf<Any>(1, "<NAME>", true, 89.99, 89.99f) arrayList.add(0, "New item") // arrayList.removeAll(arrayListOf(1, true)) arrayList.remove(1) // arrayList.forEach { println(it) } println() println("Sets") val set = setOf<Any>(1, 2, 3, 4, 5) val mutableSet = mutableSetOf<Any>(1, 2, 3, 4, 5) println("Lists") val list = listOf<Any>(1, 2, 3) list.plus(5) // list.forEach{ println(it)} val mutableList = mutableListOf<Any>(1, 2, 3) mutableList.add(5) mutableList.forEach { println(it) } }
0
Kotlin
0
1
260d0d3bbae9bfaa24df4fb933188e37c82cc8a6
1,373
ug-short-course
MIT License
app/src/main/java/dev/abhaycloud/fdtracker/presentation/ui/components/FixedDepositItem.kt
Abhay-cloud
816,359,684
false
{"Kotlin": 164703}
package dev.abhaycloud.fdtracker.presentation.ui.components import android.util.Log import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.LinearProgressIndicator import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap 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 dev.abhaycloud.fdtracker.R import dev.abhaycloud.fdtracker.domain.model.FixedDeposit import dev.abhaycloud.fdtracker.utils.DateUtils.getDifferenceBetweenDays import dev.abhaycloud.fdtracker.utils.DateUtils.toDateString import dev.abhaycloud.fdtracker.utils.Utils.getFraction import dev.abhaycloud.fdtracker.utils.Utils.toIndianFormat @Composable fun FixedDepositItem( modifier: Modifier, fixedDeposit: FixedDeposit, onClick: (FixedDeposit) -> Unit ) { var completedDays by rememberSaveable { mutableIntStateOf(0) } var remainingDays by rememberSaveable { mutableIntStateOf(0) } LaunchedEffect(key1 = fixedDeposit) { completedDays = System.currentTimeMillis().getDifferenceBetweenDays(fixedDeposit.startDate.time) remainingDays = fixedDeposit.maturityDate.time.getDifferenceBetweenDays(System.currentTimeMillis()) Log.d( "myapp", "maturity: ${fixedDeposit.maturityDate.time} current: ${System.currentTimeMillis()}" ) } val progress by rememberSaveable(fixedDeposit.tenure, completedDays) { mutableFloatStateOf(fixedDeposit.tenure.toDouble().getFraction(completedDays.toDouble())) } val progressAnim by animateFloatAsState( targetValue = progress, animationSpec = tween(1000), label = "progressAnimation" ) // val progress = fixedDeposit.tenure.toDouble().getFraction(completedDays.toDouble()) Box( modifier = modifier .fillMaxWidth() .clip(RoundedCornerShape(10.dp)) .clickable { onClick.invoke(fixedDeposit) } .background( brush = Brush.horizontalGradient( listOf( Color(0xff001F3F), Color(0xe5001F3F) ), ) ) ) { ImageWrapper( resource = R.drawable.icon_fd_card, modifier = Modifier .height(84.dp) .align(Alignment.TopEnd) .offset(y = (-24).dp) ) Column( modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Text( text = fixedDeposit.bankName, fontSize = 20.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) Spacer(modifier = Modifier.height(8.dp)) Row(modifier = Modifier.fillMaxWidth()) { Column { AmountItem( title = "Principle Amount", value = "₹${fixedDeposit.principalAmount.toIndianFormat(includeDecimal = true)}" ) Spacer(modifier = Modifier.height(16.dp)) AmountItem( title = "Annual Interest Rate", value = "${fixedDeposit.interestRate}%" ) } Spacer(modifier = Modifier.width(32.dp)) Column { AmountItem( title = "Maturity Amount", value = "₹${fixedDeposit.maturityAmount.toIndianFormat(includeDecimal = true)}" ) Spacer(modifier = Modifier.height(16.dp)) AmountItem( title = "Maturity Date", value = fixedDeposit.maturityDate.time.toDateString() ) } } Spacer(modifier = Modifier.height(24.dp)) LinearProgressIndicator( modifier = Modifier .fillMaxWidth() .height(7.dp), progress = progressAnim, // progress = fixedDeposit.tenure.toDouble().getFraction(completedDays.toDouble()), color = Color(0xff596420), trackColor = Color.White, strokeCap = StrokeCap.Round ) Spacer(modifier = Modifier.height(4.dp)) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween ) { Text( text = "Completed: $completedDays Days", fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) Text( text = "Remaining: $remainingDays Days", fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) } } } } @Composable fun AmountItem(title: String, value: String) { Text( text = title, fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = Color(0xff787878) ) Spacer(modifier = Modifier.height(4.dp)) Text( text = value, fontSize = 16.sp, fontWeight = FontWeight.SemiBold, color = Color.White ) } //@Preview //@Composable //fun FixedDepositItemPreview() { // FixedDepositItem() //}
2
Kotlin
4
32
a8ab2db4b600c29ecfffe45c263305bf939a5142
6,975
Fixed-Deposit-Tracker
MIT License
app/src/test/java/com/example/gourmetsearchercompose/viewmodel/InputKeyWordViewModelTest.kt
0v0d
826,241,127
false
{"Kotlin": 188477, "Shell": 236}
package com.example.gourmetsearchercompose.viewmodel import com.example.gourmetsearchercompose.usecase.keywordhistory.ClearKeyWordHistoryUseCase import com.example.gourmetsearchercompose.usecase.keywordhistory.GetKeyWordHistoryUseCase import com.example.gourmetsearchercompose.usecase.keywordhistory.SaveKeyWordHistoryUseCase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Assert.assertEquals import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.anyString import org.mockito.Mockito.verify import org.mockito.Mockito.`when` import org.mockito.junit.MockitoJUnitRunner /** InputKeyWordViewModelのユニットテストクラス */ @ExperimentalCoroutinesApi @RunWith(MockitoJUnitRunner::class) class InputKeyWordViewModelTest { @Mock private lateinit var getHistoryListUseCase: GetKeyWordHistoryUseCase @Mock private lateinit var saveHistoryItemUseCase: SaveKeyWordHistoryUseCase @Mock private lateinit var clearHistoryUseCase: ClearKeyWordHistoryUseCase private lateinit var viewModel: InputKeyWordViewModel /** 各テスト前の準備 */ @Before fun setup() { Dispatchers.setMain(UnconfinedTestDispatcher()) } /** 各テスト後のCleanup */ @After fun tearDown() { Dispatchers.resetMain() } /** テキストの更新が正しく行われることを確認するテスト */ @Test fun testUpdateWithNewValue() = runTest { val newText = "Hello, World!" viewModel = InputKeyWordViewModel( getHistoryListUseCase, saveHistoryItemUseCase, clearHistoryUseCase, ) viewModel.updateInputText(newText) assertEquals(newText, viewModel.inputText.value) } /** 空文字列での更新が正しく行われることを確認するテスト */ @Test fun testUpdateWithEmptyString() = runTest { val emptyText = "" viewModel = InputKeyWordViewModel( getHistoryListUseCase, saveHistoryItemUseCase, clearHistoryUseCase, ) viewModel.updateInputText(emptyText) assertEquals(emptyText, viewModel.inputText.value) } /** 複数回の更新が正しく行われることを確認するテスト */ @Test fun testMultipleUpdates() = runTest { val firstText = "First" val secondText = "Second" viewModel = InputKeyWordViewModel( getHistoryListUseCase, saveHistoryItemUseCase, clearHistoryUseCase, ) viewModel.updateInputText(firstText) assertEquals(firstText, viewModel.inputText.value) viewModel.updateInputText(secondText) assertEquals(secondText, viewModel.inputText.value) } /** 初期値が正しく設定されていることを確認するテスト */ @Test fun testInitialValue() { viewModel = InputKeyWordViewModel( getHistoryListUseCase, saveHistoryItemUseCase, clearHistoryUseCase, ) assertEquals("", viewModel.inputText.value) } /** 初期化時に履歴リストが正しく読み込まれることを確認するテスト */ @Test fun testLoadHistoryOnInit() = runTest { val testHistory = listOf("test1", "test2") `when`(getHistoryListUseCase()).thenReturn(flowOf(testHistory)) viewModel = InputKeyWordViewModel( getHistoryListUseCase, saveHistoryItemUseCase, clearHistoryUseCase, ) assertEquals(testHistory.reversed(), viewModel.historyListData.value) } /** 新しい項目を保存した後、履歴リストが更新されることを確認するテスト */ @Test fun testSaveHistoryItemUpdatesHistoryList() = runTest { val updatedHistory = listOf("test1", "test2", "test3") `when`(getHistoryListUseCase()).thenReturn( flowOf(updatedHistory), ) `when`(saveHistoryItemUseCase(anyString())).thenReturn(Unit) viewModel = InputKeyWordViewModel( getHistoryListUseCase, saveHistoryItemUseCase, clearHistoryUseCase, ) viewModel.saveHistoryItem("test3") verify(saveHistoryItemUseCase).invoke("test3") assertEquals(updatedHistory.reversed(), viewModel.historyListData.value) } /** 履歴リストの保存と取得を確認するテスト */ @Test fun testSaveAndGetHistoryItem() = runTest { val testHistory = listOf("test1", "test2") `when`(getHistoryListUseCase()).thenReturn(flowOf(testHistory)) `when`(saveHistoryItemUseCase(anyString())).thenReturn(Unit) viewModel = InputKeyWordViewModel( getHistoryListUseCase, saveHistoryItemUseCase, clearHistoryUseCase, ) viewModel.saveHistoryItem("test3") verify(saveHistoryItemUseCase).invoke("test3") assertEquals(testHistory.reversed(), viewModel.historyListData.value) } /** 履歴リストのクリアを確認するテスト */ @Test fun testClearHistory() = runTest { `when`(clearHistoryUseCase()).thenReturn(Unit) `when`(getHistoryListUseCase.invoke()).thenReturn(flowOf(emptyList())) viewModel = InputKeyWordViewModel( getHistoryListUseCase, saveHistoryItemUseCase, clearHistoryUseCase, ) viewModel.clearHistory() verify(clearHistoryUseCase).invoke() assertEquals(emptyList<String>(), viewModel.historyListData.value) } }
2
Kotlin
0
1
9a03b536f8f5334a96659877c9d8bff3436acc79
5,980
GourmetSearcher-Compose
MIT License
Full Stack App Development/Book App/app/src/main/java/com/example/recyclerview/MainActivity.kt
bread-board-coding
403,271,695
false
null
package com.example.recyclerview import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.GridLayoutManager 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 recyclerView = findViewById<RecyclerView>(R.id.recyclerView) recyclerView.layoutManager = GridLayoutManager(this,2) val book = ArrayList<Book>() book.add( Book( "Code Name God", "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAoHCBUUFBcVFBQYFxcZGhkZGhoZGRcXGh4aGRoaGRkZGR0aICwjGh0pIBcZJDYkKS0vMzMzGSI4PjgyPSwyMy8BCwsLDw4PHhISHTIpIik0MjIyMjIvMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMv/AABEIARYAtQMBIgACEQEDEQH/xAAbAAAABwEAAAAAAAAAAAAAAAAAAQIEBQYHA//EAE4QAAIBAgMCCQULCgUEAgMAAAECAwARBBIhBTEGBxMiQVFhcXMygZGxshYjNFJykqGzw9LTFBUkMzVUgpPC8EJiwdHhJUNTg6LxF2OU/8QAGQEAAwEBAQAAAAAAAAAAAAAAAAECAwQF/8QAJxEAAgICAgIDAAICAwAAAAAAAAECEQMhEjEyUQQiQRNhIzMUgaH/2gAMAwEAAhEDEQA/AKNtXaM/LzAYiYASygASSAAB2AAAbTdTdNoYg3tiZdAW1mkFwOgXbU9lJ2r8In8aX6xqamtEjllJ29jn85z/ALzP/Nk+9SjtKc2tiJ79Pv0lvNzqaKtz/vpRk6do/vWnRPOXscjac/TiJ/50m/51F+cp/wB4n/myfeprSmPbRQc5exyNqYj94m/myfeohtOf95m/myfepsKAFFBzfsc/nKf94n/myfeo/wA5T/vE/wDNk+9TYjoogKKFzl7HX5yn/eZ/5sn3qL85z/vE382T71NhRUqQc5exyNp4j94n/myfeoztLEfvE/8ANk+9TbTT6b7v/qjuR6PoNFIfOXscfnOf95m/myfeoztPEfvE382T71NQeijB1G7++unQc37HB2niP3if+bJ96lJtLEan8plFhfWWTXosOdqdfopr2efspN6VBzfsdfnLEfvE/wDNk+9Rnak/RiJ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WbSlKqZClKUApSlAKUpQClKUBC+ezzPifkvGjr80V+l+ezzPifkvGjr80UJR2sNiMKUjEq9JVAJVcuuaa5Yr5Wm4+bvuxc+EGQxKb51LZwTZAoVhYsVNyC3D31uquLSosSSBpsCSxy2Y5rX<KEY>t<KEY>bygVY9zCsheOORI3zAFN66NKTlF1BVMoCn37nW+nO2byxELxe6I5JpcNLKyPnCkxzR5WjYEE2DnONdLkddWREjWw+zIYsXh8DLEHkaeJZ2fOls7KDFEAw6ADf9T3xN16IBa3eY2JUw2LRRZVxsyqNdFCRADX1Cqd2ZyqQbj3RE0z4V42hlVwkgjjcMIZLgh49Oj1pwBK6Vb/MRiRJhMVIoID4yVwDxAaOFrEjja9WKFi0pSgFKUoBSlKAUpSgFKUoDg8ueT7Y7BS4VZBGZMnSKlgMsivwBHo2qvdkcyc0LFhjIyGFiNy1jr8Pvq4KUBW3+VsnA4hCOzdn+6vMfNbKp0xKZT1GNj8xzVZVKrlRbMyt35rZT/wDIT6tv7qx/5UzXv7pT6pv7qsylMqGZlZjmpl/3CfVt/dX1uaqQgj3Sn1bf3VZdKmyGZlLHmEm/3kf1Lf31n2bzGyxSrIcXGct9Nyw6iPT9dXFSpIuVr/lVL/uU+rb+6vq81kgN/dCX+Lb+6rJpUWROZlbJzWygfvKdf/bbrN/SrUxHNHO7hvdahQDoImvc6XBLdmnDrPeLUpSyGZlVtzPy2smJjX5Jjr2np6n11yZuYSVmJ92pqf8ARY/bnq6qUsRcpP8AyAl/3qfUt/fVhc2vJBtmYZ4GlEpeVpMyqUADIi2sSfQ+2pXSpIFKUoBSlKAUpSgP/9k=" ) ) val mAdapter = BookAdapter(this,book) recyclerView.adapter = mAdapter } }
1
C++
116
20
04aa1e707efb31def25593047768c08ae1660839
20,131
Hacktober_Fest_2021
MIT License
app/src/main/java/vinova/henry/com/hotfilm/server/ITheMovieDBService.kt
henryduong26
120,248,676
false
{"Kotlin": 175185, "Java": 1151}
package vinova.henry.com.hotfilm.server import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query import vinova.henry.com.hotfilm.models.MovieResponse import vinova.henry.com.hotfilm.models.detail.MovieDetail import vinova.henry.com.hotfilm.models.trailer.TrailerResponse interface ITheMovieDBService { @GET("/3/movie/{movieId}") fun getMovieDetail(@Path("movieId") movieId: Int, @Query("api_key") api_key: String, @Query("language") language: String): Call<MovieDetail> @GET("/3/discover/movie") fun getDiscoverMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int): Call<MovieResponse> @GET("/3/movie/{movie_id}/videos") fun getMovieTrailer(@Path("movie_id") movieId: Int, @Query("api_key") api_key: String, @Query("language") language: String): Call<TrailerResponse> @GET("/3/search/movie") fun getSearchResult(@Query("api_key") api_key: String, @Query("language") language: String, @Query("page") page: Int, @Query("include_adult") include_adult: String, @Query("query") query: String): Call<MovieResponse> @GET("/3/genre/{genre_id}/movies") fun getMovieByGenre(@Path("genre_id") genre_id: String?, @Query("api_key") api_key: String, @Query("language") language: String?, @Query("sort_by") sort_by: String?, @Query("page") page: Int?): Call<MovieResponse> @GET("/3/movie/{movie_id}/similar") fun getRelateMovie(@Path("movie_id") movieId: Int?, @Query("api_key") api_key: String, @Query("language") language: String?, @Query("page") page: Int?) : Call<MovieResponse> } /* @GET("/3/genre/movie/list") fun getGenre(@Query("api_key") api_key: String, @Query("language") language: String): Call<Genre> */ /*@GET("/3/genre/28/movies") fun getActionMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/12/movies") fun getAdventureMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/16/movies") fun getAnimationMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/99/movies") fun getDocumentaryMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/10751/movies") fun getFamilyMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/80/movies") fun getCrimeMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/18/movies") fun getDramaMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/14/movies") fun getFantasyMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/36/movies") fun getHistoryMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/27/movies") fun getHorrorMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/10402/movies") fun getMusicMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/9648/movies") fun getMysteryMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/10749/movies") fun getRomanceMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/878/movies") fun getScienceMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/10770/movies") fun getTVMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/53/movies") fun getThrillerMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/10752/movies") fun getWarMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse> @GET("/3/genre/37/movies") fun getWesternMovie(@Query("api_key") api_key: String, @Query("language") language: String, @Query("sort_by") sort_by: String, @Query("page") page: Int) : Call<MovieResponse>*/
0
Kotlin
0
0
97db98daa63c275b69cbb4b8e9887af6f9d16ada
6,964
HotFilm
Apache License 2.0
app/src/main/java/br/com/movieapp/feature/moviepopular/presentation/components/MovieItem.kt
flaviosfdev
789,509,918
false
{"Kotlin": 41319}
package br.com.movieapp.feature.moviepopular.presentation.components import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import br.com.movieapp.R import br.com.movieapp.framework.domain.model.Movie import br.com.movieapp.ui.theme.black import coil.compose.AsyncImage import coil.request.ImageRequest @Composable fun MovieItem( movie: Movie, modifier: Modifier = Modifier, onClick: (id: Int) -> Unit, ) { Box( modifier = modifier ) { MovieRate( rate = movie.voteAverage, modifier = Modifier .align(Alignment.BottomStart) .zIndex(2f) .padding(8.dp) .background( color = black, shape = RoundedCornerShape(75.dp) ) ) Card( modifier = Modifier .fillMaxSize() .height(200.dp) .padding(4.dp) .clickable { onClick(movie.id) }, shape = RoundedCornerShape(8.dp), elevation = 4.dp ) { Box { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(movie.imageUrl) .crossfade(true) .error(R.drawable.ic_error_image) .placeholder(R.drawable.ic_placeholder) .build(), contentDescription = "Movie Post", contentScale = ContentScale.FillHeight, modifier = Modifier .fillMaxSize() .align(Alignment.Center) ) } } } } @Preview @Composable private fun MovieItemPreview() { MovieItem( movie = Movie( id = 1, title = "Title", voteAverage = 8.1, imageUrl = "" ), onClick = {} ) }
0
Kotlin
0
0
09dcd2d3d7320b5c834772a4b98092cf7ece691b
2,639
movie-app
MIT License
core/src/test/java/com/standup/core/activityMonitor/CheckIsUserSittingTest.kt
kevalpatel2106
109,775,416
false
null
/* * Copyright 2018 <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.standup.core.activityMonitor import com.google.android.gms.location.DetectedActivity import org.junit.Assert import org.junit.Test import org.junit.experimental.runners.Enclosed import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.junit.runners.Parameterized import java.io.IOException /** * Created by Kevalpatel2106 on 22-Dec-17. * * @author <a href="https://github.com/kevalpatel2106">kevalpatel2106</a> */ @RunWith(Enclosed::class) class CheckIsUserSittingTest { @RunWith(Parameterized::class) class CheckIsUserSittingParameterizeTest(private val activities: ArrayList<DetectedActivity>, private val expected: Boolean) { companion object { @JvmStatic @Parameterized.Parameters fun data(): ArrayList<Array<out Any?>> { return arrayListOf( arrayOf(arrayListOf( DetectedActivity(DetectedActivity.IN_VEHICLE, 100), /*Highest*/ DetectedActivity(DetectedActivity.STILL, 20), DetectedActivity(DetectedActivity.ON_FOOT, 45), DetectedActivity(DetectedActivity.ON_BICYCLE, 70), DetectedActivity(DetectedActivity.RUNNING, 10), DetectedActivity(DetectedActivity.WALKING, 50) ), true), arrayOf(arrayListOf( DetectedActivity(DetectedActivity.IN_VEHICLE, 60), DetectedActivity(DetectedActivity.STILL, 96), /*Highest*/ DetectedActivity(DetectedActivity.ON_FOOT, 85), DetectedActivity(DetectedActivity.ON_BICYCLE, 70), DetectedActivity(DetectedActivity.RUNNING, 10), DetectedActivity(DetectedActivity.WALKING, 50) ), true), arrayOf(arrayListOf( DetectedActivity(DetectedActivity.STILL, 20), DetectedActivity(DetectedActivity.RUNNING, 60), DetectedActivity(DetectedActivity.IN_VEHICLE, 70), /*Highest*/ DetectedActivity(DetectedActivity.ON_FOOT, 33), DetectedActivity(DetectedActivity.ON_BICYCLE, 70), /*Highest*/ DetectedActivity(DetectedActivity.WALKING, 50) ), true), arrayOf(arrayListOf( DetectedActivity(DetectedActivity.RUNNING, 60), DetectedActivity(DetectedActivity.ON_BICYCLE, 70), /*Highest*/ DetectedActivity(DetectedActivity.ON_FOOT, 33), DetectedActivity(DetectedActivity.STILL, 20), DetectedActivity(DetectedActivity.IN_VEHICLE, 70), /*Highest*/ DetectedActivity(DetectedActivity.WALKING, 50) ), true), arrayOf(arrayListOf( DetectedActivity(DetectedActivity.IN_VEHICLE, 60), DetectedActivity(DetectedActivity.STILL, 20), DetectedActivity(DetectedActivity.ON_FOOT, 100), /*Highest*/ DetectedActivity(DetectedActivity.ON_BICYCLE, 70), DetectedActivity(DetectedActivity.RUNNING, 10), DetectedActivity(DetectedActivity.WALKING, 50) ), false), arrayOf(arrayListOf( DetectedActivity(DetectedActivity.IN_VEHICLE, 60), DetectedActivity(DetectedActivity.STILL, 12), DetectedActivity(DetectedActivity.ON_FOOT, 55), DetectedActivity(DetectedActivity.ON_BICYCLE, 70), /*Highest*/ DetectedActivity(DetectedActivity.RUNNING, 88), DetectedActivity(DetectedActivity.WALKING, 50) ), false), arrayOf(arrayListOf( DetectedActivity(DetectedActivity.IN_VEHICLE, 60), DetectedActivity(DetectedActivity.STILL, 12), DetectedActivity(DetectedActivity.ON_FOOT, 85), DetectedActivity(DetectedActivity.ON_BICYCLE, 70), DetectedActivity(DetectedActivity.RUNNING, 88), /*Highest*/ DetectedActivity(DetectedActivity.WALKING, 50) ), false), arrayOf(arrayListOf( DetectedActivity(DetectedActivity.IN_VEHICLE, 60), DetectedActivity(DetectedActivity.STILL, 12), DetectedActivity(DetectedActivity.ON_FOOT, 85), DetectedActivity(DetectedActivity.ON_BICYCLE, 70), DetectedActivity(DetectedActivity.RUNNING, 88), DetectedActivity(DetectedActivity.WALKING, 90) /*Highest*/ ), false) ) } } @Test @Throws(IOException::class) fun checkIsUserSitting() { Assert.assertEquals(expected, ActivityMonitorHelper.isUserSitting(activities)) } } @RunWith(JUnit4::class) class CheckIsUserSittingNotParameterizeTest { @Test @Throws(IOException::class) fun checkForEmptyArray() { try { ActivityMonitorHelper.isUserSitting(ArrayList()) Assert.fail() } catch (e: IllegalStateException) { //Test passed } } @Test @Throws(IOException::class) fun checkForTiltingActivity() { try { ActivityMonitorHelper.isUserSitting(arrayListOf( DetectedActivity(DetectedActivity.IN_VEHICLE, 60), DetectedActivity(DetectedActivity.STILL, 12), DetectedActivity(DetectedActivity.ON_FOOT, 85), DetectedActivity(DetectedActivity.ON_BICYCLE, 70), DetectedActivity(DetectedActivity.RUNNING, 88), DetectedActivity(DetectedActivity.TILTING, 90) /*Highest*/ )) Assert.fail() } catch (e: IllegalStateException) { //Test passed } } @Test @Throws(IOException::class) fun checkForUnknownActivity() { try { Assert.assertFalse(ActivityMonitorHelper.isUserSitting(arrayListOf( DetectedActivity(DetectedActivity.IN_VEHICLE, 60), DetectedActivity(DetectedActivity.STILL, 12), DetectedActivity(DetectedActivity.ON_FOOT, 85), DetectedActivity(DetectedActivity.ON_BICYCLE, 70), DetectedActivity(DetectedActivity.RUNNING, 88), DetectedActivity(DetectedActivity.UNKNOWN, 90) /*Highest*/ ))) } catch (e: IllegalStateException) { Assert.fail() } } } }
18
Kotlin
1
3
d4d0313062118521621da5dac90e836f512ddd54
8,318
Stand-Up
Apache License 2.0
tulip/libtulip-persistence-api/src/commonMain/kotlin/com/tajmoti/libtulip/repository/UserPlayingProgressRepository.kt
Tajmoti
391,138,914
false
null
package com.tajmoti.libtulip.repository import com.tajmoti.libtulip.model.LastPlayedPosition import com.tajmoti.libtulip.model.key.EpisodeKey import com.tajmoti.libtulip.model.key.ItemKey import com.tajmoti.libtulip.model.key.MovieKey import com.tajmoti.libtulip.model.key.StreamableKey import kotlinx.coroutines.flow.Flow interface UserPlayingProgressRepository { /** * Retrieves the last played position of the TV show or movie specified by [key]. * The returned flow may never complete, and it may emit an updated value at any time! */ fun getLastPlayedPosition(key: ItemKey) = when (key) { is ItemKey.Tmdb -> getLastPlayedPositionForTmdbItem(key) is ItemKey.Hosted -> getLastPlayedPositionForHostedItem(key) } /** * Retrieves the last played position of the TV show or movie specified by [key]. * The returned flow may never complete, and it may emit an updated value at any time! */ fun getLastPlayedPositionForTmdbItem(key: ItemKey.Tmdb): Flow<LastPlayedPosition.Tmdb?> /** * Retrieves the last played position of the TV show or movie specified by [key]. * The returned flow may never complete, and it may emit an updated value at any time! */ fun getLastPlayedPositionForHostedItem(key: ItemKey.Hosted): Flow<LastPlayedPosition.Hosted?> /** * Retrieves the last played position of the TV show episode or movie specified by [key]. * The returned flow may never complete, and it may emit an updated value at any time! */ fun getLastPlayedPosition(key: StreamableKey) = when (key) { is EpisodeKey.Tmdb -> getLastPlayedPositionTmdb(key) is EpisodeKey.Hosted -> getLastPlayedPositionHosted(key) is MovieKey.Tmdb -> getLastPlayedPositionTmdb(key as StreamableKey.Tmdb) is MovieKey.Hosted -> getLastPlayedPositionHosted(key as StreamableKey.Hosted) } /** * Retrieves the last played position of the TV show episode or movie specified by [key]. * The returned flow may never complete, and it may emit an updated value at any time! */ fun getLastPlayedPositionTmdb(key: StreamableKey.Tmdb): Flow<LastPlayedPosition.Tmdb?> /** * Retrieves the last played position of the TV show episode or movie specified by [key]. * The returned flow may never complete, and it may emit an updated value at any time! */ fun getLastPlayedPositionHosted(key: StreamableKey.Hosted): Flow<LastPlayedPosition.Hosted?> /** * Sets the playing [progress] of the TV show episode or movie specified by [key]. * The [progress] is a real number in the range 0.0 to 1.0. */ suspend fun setLastPlayedPosition(key: StreamableKey, progress: Float) /** * Removes the last playing progress for [key]. */ suspend fun removeLastPlayedPosition(key: StreamableKey) }
6
Kotlin
0
0
5f1a6a4a5432981535313710f0037726c80118b8
2,873
Tulip
MIT License
services/csm.cloud.project.project/src/main/kotlin/com/bosch/pt/iot/smartsite/project/external/boundary/ExternalIdService.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright: <NAME> Power Tools GmbH, 2018 - 2023 * * ************************************************************************ */ package com.bosch.pt.iot.smartsite.project.external.boundary import com.bosch.pt.csm.cloud.projectmanagement.external.messages.ExternalIdEventEnumAvro.CREATED import com.bosch.pt.iot.smartsite.application.security.NoPreAuthorize import com.bosch.pt.iot.smartsite.project.external.model.ExternalId import com.bosch.pt.iot.smartsite.project.external.repository.ExternalIdRepository import datadog.trace.api.Trace import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional @Service open class ExternalIdService(private val externalIdRepository: ExternalIdRepository) { @Trace @Transactional @NoPreAuthorize open fun saveAll(ids: List<ExternalId>) { ids.map { externalIdRepository.save(it, CREATED).identifier } } }
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
1,004
bosch-pt-refinemysite-backend
Apache License 2.0
common/src/main/java/io/novafoundation/nova/common/utils/formatting/duration/WrapDurationFormatter.kt
novasamatech
415,834,480
false
{"Kotlin": 7667438, "Java": 14723, "JavaScript": 425}
package io.novafoundation.nova.common.utils.formatting.duration import android.content.Context import androidx.annotation.StringRes import kotlin.time.Duration class WrapDurationFormatter( private val context: Context, @StringRes private val resId: Int, private val nestedFormatter: BoundedDurationFormatter ) : BoundedDurationFormatter { override val threshold: Duration = nestedFormatter.threshold override fun format(duration: Duration): String { val nestedFormatterString = nestedFormatter.format(duration) return context.getString(resId, nestedFormatterString) } } fun BoundedDurationFormatter.wrapInto(context: Context, @StringRes prefixRes: Int): WrapDurationFormatter { return WrapDurationFormatter(context, prefixRes, this) }
13
Kotlin
6
9
dea9f1144c1cbba1d876a9bb753f8541da38ebe0
784
nova-wallet-android
Apache License 2.0
app/src/main/java/com/leichui/shortviedeo/activity/QueRenActivity.kt
kknet
378,407,063
false
{"Java": 1891463, "Kotlin": 227641}
package com.leichui.shortviedeo.activity import android.content.Intent import android.view.LayoutInflater import android.view.View import android.widget.TextView import com.facebook.drawee.view.SimpleDraweeView import com.leichui.conghua.utils.T import com.leichui.shortviedeo.Base.BaseBean import com.leichui.shortviedeo.base.BaseActivity import com.leichui.shortviedeo.bean.GoodInfoBean import com.leichui.shortviedeo.bean.OrderInfoBean import com.leichui.shortviedeo.http.OkGoStringCallBack import com.leichui.shortviedeo.mapper.ApiMapper import com.tencent.qcloud.ugckit.module.upload.TCUserMgr import com.tencent.qcloud.xiaoshipin.R import kotlinx.android.synthetic.main.activity_que_ren.* class QueRenActivity : BaseActivity() { var address_id = "" var score_or_price = "" var video_id = "" lateinit var layout: LayoutInflater lateinit var gouWuCheYiXuanBean: GoodInfoBean override fun setLayoutId(): Int { return R.layout.activity_que_ren } override fun startAction() { showLeftBackButton() setTitleCenter("确认订单") layout = LayoutInflater.from(this) getDef() setClick() } private fun setClick() { dizhi_lin.setOnClickListener { val inn = Intent(this, XuanDizhiActivity::class.java) startActivityForResult(inn, 222) } nodizhi_lin.setOnClickListener { val inn = Intent(this, XuanDizhiActivity::class.java) startActivityForResult(inn, 222) } gouWuCheYiXuanBean = intent.getSerializableExtra("bean") as GoodInfoBean price_tv2.text = gouWuCheYiXuanBean.data.good_price price_tv3.text = gouWuCheYiXuanBean.data.good_price addView(gouWuCheYiXuanBean) jiesuan_btn.setOnClickListener { if (address_id.isNullOrEmpty()) { T(this, "地址不可为空") return@setOnClickListener } ApiMapper.addOrder(TCUserMgr.getInstance().userToken, address_id,gouWuCheYiXuanBean.data.good_id,"1",gouWuCheYiXuanBean.data.good_specs[0],video_id, object : OkGoStringCallBack<OrderInfoBean>(this, OrderInfoBean::class.java, false) { override fun onSuccess2Bean(bean: OrderInfoBean) { T(this@QueRenActivity,"订单提交成功") val inn = Intent(this@QueRenActivity, ShouYinTaiActivity::class.java) inn.putExtra("out_trade_no",bean.data.order_number) inn.putExtra("order_price",bean.data.order_price) startActivity(inn) } }) } } private fun getDef() { // // FragmentMapper.getMyDefaultInfo(BaseApplication.getUser(this)!!.user_token, object : OkGoStringCallBack<DefaultAddressBean>(this, DefaultAddressBean::class.java, false) { // override fun onSuccess2Bean(bean: DefaultAddressBean) { // // if (bean.data.is_have.equals("1")) { // nodizhi_lin.visibility = View.GONE // dizhi_lin.visibility = View.VISIBLE // dizhi_name.text = bean.data.name + " " + bean.data.tel // dizhi_tv.text = bean.data.address_info // address_id = bean.data.address_id // } else { // nodizhi_lin.visibility = View.VISIBLE // dizhi_lin.visibility = View.GONE // } // } // }) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == 2) { nodizhi_lin.visibility = View.GONE dizhi_lin.visibility = View.VISIBLE dizhi_name.text = data!!.getStringExtra("name") dizhi_tv.text = data!!.getStringExtra("address") address_id = data!!.getStringExtra("id") } } fun addView(bean: GoodInfoBean) { val view = layout.inflate(R.layout.activity_querendingdan_item, null) val img = view.findViewById<SimpleDraweeView>(R.id.img) val tv1 = view.findViewById<TextView>(R.id.tv1) val tv2 = view.findViewById<TextView>(R.id.tv2) img.setImageURI(bean.data.good_one_pic) tv1.text = bean.data.good_name tv2.text = "${bean.data.good_price}" lin.addView(view) } }
0
Java
1
0
8f8f69b200886d4b6671bcc0b2eb11a5343fd7fd
4,397
VideoChat
Apache License 2.0
platform/platform-impl/src/com/intellij/ui/dsl/builder/components/TabbedPaneHeader.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.ui.dsl.builder.components import com.intellij.ide.ui.laf.darcula.ui.DarculaTabbedPaneUI import com.intellij.ui.components.JBTabbedPane import org.jetbrains.annotations.ApiStatus import java.awt.Dimension @ApiStatus.Internal internal class TabbedPaneHeader : JBTabbedPane() { private var preferredSizeCalculation = false init { setUI(HeaderTabbedPaneUI()) } override fun getSize(): Dimension { return if (preferredSizeCalculation) Dimension(2000, 100) else super.getSize() } override fun getPreferredSize(): Dimension { // Allow aligning tabs in large area preferredSizeCalculation = true try { val lastTabBounds = getBoundsAt(tabCount - 1) return Dimension(lastTabBounds.x + lastTabBounds.width, (ui as HeaderTabbedPaneUI).getTabHeight(tabPlacement)) } finally { preferredSizeCalculation = false } } } private class HeaderTabbedPaneUI : DarculaTabbedPaneUI() { fun getTabHeight(tabPlacement: Int): Int { return calculateMaxTabHeight(tabPlacement) } override fun getOffset(): Int { return 0 } }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
1,225
intellij-community
Apache License 2.0
app/src/main/java/com/fifteen11/checkappversion/screens/details/DetailScreen.kt
pansuriyasumit
837,884,509
false
{"Kotlin": 84957}
package com.fifteen11.checkappversion.screens.details import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import com.fifteen11.checkappversion.data.model.ProblemsItem import com.fifteen11.checkappversion.navigation.Route import com.fifteen11.checkappversion.screens.component.AppBar import com.fifteen11.checkappversion.screens.component.MedicineCard @Composable fun DetailScreen( problemItem: ProblemsItem?, onClick: (problemId: Int) -> Unit = {} ) { Scaffold( topBar = { AppBar("${Route.DetailsScreen.title.toString()} - ${problemItem?.type}") } ) { innerPadding -> Column( modifier = Modifier .fillMaxSize() .padding(innerPadding) ) { MedicineCard(medicine = problemItem, onClick) } } }
0
Kotlin
0
0
3b447671a617822068641f0eb8a5cc7a956ea643
1,043
MedicineTestCode
Apache License 2.0
subprojects/test-runner/device-provider/model/src/main/kotlin/com/avito/runner/service/worker/device/DeviceCoordinate.kt
avito-tech
230,265,582
false
{"Kotlin": 3747948, "Java": 67252, "Shell": 27892, "Dockerfile": 12799, "Makefile": 8086}
package com.avito.runner.service.worker.device public sealed class DeviceCoordinate { public abstract val serial: Serial public data class Kubernetes( override val serial: Serial.Remote, val podName: String ) : DeviceCoordinate() public data class Local(override val serial: Serial.Local) : DeviceCoordinate() { public companion object } }
10
Kotlin
50
414
bc94abf5cbac32ac249a653457644a83b4b715bb
389
avito-android
MIT License