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
eip1559_signer/src/main/kotlin/org/kethereum/eip1559/signer/EIP1559.kt
komputing
92,780,266
false
{"Kotlin": 776856}
package org.kethereum.eip1559.signer import org.kethereum.crypto.signMessage import org.kethereum.extensions.transactions.encodeAsEIP1559Tx import org.kethereum.model.ECKeyPair import org.kethereum.model.Transaction /** * Signs a transaction via EIP1559 * * @return SignatureData - the signature of the transaction signed with the key * */ fun Transaction.signViaEIP1559(key: ECKeyPair) = key.signMessage(encodeAsEIP1559Tx())
43
Kotlin
82
333
1f42cede2d31cb5d3c488bd74eeb8480ec47c919
434
KEthereum
MIT License
j2k/new/tests/testData/newJ2k/boxedType/object.kt
JetBrains
278,369,660
false
null
val i: Any = 10
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
15
intellij-kotlin
Apache License 2.0
game/plugin/entity/spawn/src/spawn.kt
stevesoltys
140,373,082
false
{"Java": 873190, "Ruby": 227078, "Kotlin": 222820, "Groovy": 2503}
package org.apollo.game.plugin.entity.spawn import org.apollo.game.model.Animation import org.apollo.game.model.Direction import org.apollo.game.model.Graphic import org.apollo.game.model.Position data class Spawn(val id: Int?, val name: String, val position: Position, val facing: Direction, val spawnAnimation: Animation? = null, val spawnGraphic: Graphic? = null) object Spawns { val list = mutableListOf<Spawn>() } fun npc_spawn(name: String, x: Int, y: Int, z: Int = 0, id: Int? = null, facing: Direction = Direction.NORTH) { Spawns.list.add(Spawn(id, name, Position(x, y, z), facing)) }
18
null
1
1
3818a83fd2b437c3bd878d147fd6aff2374ee3fb
622
apollo-osrs
ISC License
tibiakt-core/src/main/kotlin/com/galarzaa/tibiakt/core/models/leaderboards/LeaderboardEntry.kt
Galarzaa90
285,669,589
false
{"Kotlin": 530502, "Dockerfile": 1445}
/* * Copyright © 2024 Allan Galarza * * 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.galarzaa.tibiakt.core.models.leaderboards import com.galarzaa.tibiakt.core.models.character.BaseCharacter import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * Base class for Leaderboards entries. * * @property rank The rank of the character. * @property dromeLevel The drome level of the character. */ @Serializable public sealed class BaseLeaderboardEntry { public abstract val rank: Int public abstract val dromeLevel: Int } /** * An entry in the [LeaderboardEntry]. */ @Serializable @SerialName("leaderboardsEntry") public data class LeaderboardEntry( override val rank: Int, override val name: String, override val dromeLevel: Int, ) : BaseLeaderboardEntry(), BaseCharacter /** A leaderboard entry belonging to a deleted character. */ @Serializable @SerialName("deletedLeaderboardsEntry") public data class DeletedLeaderboardEntry( override val rank: Int, override val dromeLevel: Int, ) : BaseLeaderboardEntry()
0
Kotlin
1
1
7274af579c1d4fa7865c05436c0e3ee5b293301a
1,604
TibiaKt
Apache License 2.0
finger-paint/server/src/main/kotlin/ru/cscenter/fingerpaint/db/entities/Image.kt
cscenter
214,458,041
false
null
package ru.cscenter.fingerpaint.db.entities import javax.persistence.* @Entity @Table(name = "Images") class Image( @Column(name = "path", unique = true) var path: String ) { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") var id: Long = 0 override fun equals(other: Any?) = other is Image && path == other.path override fun hashCode() = path.hashCode() }
0
Kotlin
0
0
1d86529c2ad31092eceae5f80844dd090ac58aef
417
Y02_Project_finger-paint
MIT License
plugins/markdown/src/org/intellij/plugins/markdown/lang/formatter/blocks/MarkdownFormattingBlock.kt
ingokegel
284,920,751
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.formatter.blocks import com.intellij.formatting.* import com.intellij.lang.ASTNode import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.formatter.common.AbstractBlock import com.intellij.psi.formatter.common.SettingsAwareBlock import com.intellij.psi.tree.TokenSet import org.intellij.plugins.markdown.injection.MarkdownCodeFenceUtils import org.intellij.plugins.markdown.lang.MarkdownElementTypes import org.intellij.plugins.markdown.lang.MarkdownTokenTypeSets import org.intellij.plugins.markdown.util.MarkdownPsiUtil import org.intellij.plugins.markdown.util.children import org.intellij.plugins.markdown.util.parents /** * Formatting block used by markdown plugin * * It defines alignment equal for all block on the same line, and new for inner lists */ internal open class MarkdownFormattingBlock( node: ASTNode, private val settings: CodeStyleSettings, protected val spacing: SpacingBuilder, alignment: Alignment? = null, wrap: Wrap? = null ) : AbstractBlock(node, wrap, alignment), SettingsAwareBlock { companion object { private val NON_ALIGNABLE_LIST_ELEMENTS = TokenSet.orSet(MarkdownTokenTypeSets.LIST_MARKERS, MarkdownTokenTypeSets.LISTS) } override fun getSettings(): CodeStyleSettings = settings override fun isLeaf(): Boolean = subBlocks.isEmpty() override fun getSpacing(child1: Block?, child2: Block): Spacing? = spacing.getSpacing(this, child1, child2) override fun getIndent(): Indent? { if (node.elementType in MarkdownTokenTypeSets.LISTS && node.parents().any { it.elementType == MarkdownElementTypes.LIST_ITEM }) { return Indent.getNormalIndent() } return Indent.getNoneIndent() } /** * Get indent for new formatting block, that will be created when user will start typing after enter * In general `getChildAttributes` defines where to move caret after enter. * Other changes (for example, adding of `>` for blockquote) are handled by MarkdownEnterHandler */ override fun getChildAttributes(newChildIndex: Int): ChildAttributes { return MarkdownEditingAligner.calculateChildAttributes(subBlocks.getOrNull(newChildIndex - 1)) } override fun getSubBlocks(): List<Block?> { //Non top-level codefences cannot be formatted correctly even with correct inject, so -- just ignore it if (MarkdownCodeFenceUtils.isCodeFence(node) && !MarkdownPsiUtil.isTopLevel(node)) return EMPTY return super.getSubBlocks() } override fun buildChildren(): List<Block> { val newAlignment = Alignment.createAlignment() return when (node.elementType) { //Code fence alignment is not supported for now because of manipulator problems // and the fact that when end of code fence is in blockquote -- parser // would treat blockquote as a part of code fence end token MarkdownElementTypes.CODE_FENCE -> emptyList() MarkdownElementTypes.LIST_ITEM -> { MarkdownBlocks.create(node.children(), settings, spacing) { if (it.elementType in NON_ALIGNABLE_LIST_ELEMENTS) alignment else newAlignment }.toList() } MarkdownElementTypes.PARAGRAPH, MarkdownElementTypes.CODE_BLOCK, MarkdownElementTypes.BLOCK_QUOTE -> { MarkdownBlocks.create(node.children(), settings, spacing) { alignment ?: newAlignment }.toList() } else -> { MarkdownBlocks.create(node.children(), settings, spacing) { alignment }.toList() } } } }
284
null
5162
2
dc846ecb926c9d9589c1ed8a40fdb20e47874db9
3,617
intellij-community
Apache License 2.0
app/src/main/java/com/jhteck/icebox/activity/LoginOldActivity.kt
weid2014
687,383,758
false
{"Kotlin": 476004, "Java": 414775, "C": 4589, "Makefile": 821, "Shell": 90}
package com.jhteck.icebox.activity import android.Manifest import android.annotation.SuppressLint import android.content.* import android.content.pm.PackageManager import android.net.Uri import android.os.IBinder import android.util.Log import android.view.View import android.widget.Toast import androidx.activity.viewModels import androidx.camera.core.* import androidx.camera.lifecycle.ProcessCameraProvider import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.GridLayoutManager.SpanSizeLookup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.gson.Gson import com.hele.mrd.app.lib.base.BaseActivity import com.jhteck.cameratest.FileUtils import com.jhteck.icebox.adapter.LoginPageShowItemAdapter import com.jhteck.icebox.api.* import com.jhteck.icebox.bean.InventoryDao import com.jhteck.icebox.databinding.AppActivityLoginBinding import com.jhteck.icebox.service.MyService import com.jhteck.icebox.utils.SharedPreferencesUtils import com.jhteck.icebox.utils.ToastUtils import com.jhteck.icebox.viewmodel.LoginViewModel import java.io.File import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.ExecutorService import java.util.concurrent.Executors import java.util.stream.Collectors import kotlin.system.exitProcess /** *@Description:(登录界面) *@author wade *@date 2023/6/28 17:21 */ class LoginActivity : BaseActivity<LoginViewModel, AppActivityLoginBinding>() { private var service: MyService? = null private var isBind = false private val TAG = "LoginActivity" private var imageCamera: ImageCapture? = null private lateinit var cameraExecutor: ExecutorService var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA//当前相机 var preview: Preview? = null//预览对象 var cameraProvider: ProcessCameraProvider? = null//相机信息 var camera: Camera? = null//相机对象 private var conn = object : ServiceConnection { override fun onServiceConnected(p0: ComponentName?, p1: IBinder?) { isBind = true val myBinder = p1 as MyService.MyBinder service = myBinder.service } override fun onServiceDisconnected(p0: ComponentName?) { isBind = false } } override fun createViewBinding(): AppActivityLoginBinding { //隐藏底部的虚拟键并全屏显示 window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN window.decorView.setOnSystemUiVisibilityChangeListener( View.OnSystemUiVisibilityChangeListener() { fun onSystemUiVisibilityChange(visibility: Int) { window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or View.SYSTEM_UI_FLAG_FULLSCREEN } }) return AppActivityLoginBinding.inflate(layoutInflater) } override fun createViewModel(): LoginViewModel { return viewModels<LoginViewModel>().value } override fun initView() { //开启service,初始化TCP服务 // CrashReport.testJavaCrash(); // startService() binding.btnLogin.setOnClickListener { //登录按键点击事件 viewModel.login(binding.edUserName.text.toString(), binding.edPassword.text.toString()) } viewModel.initHFCradList() //点击切换到账号登录 binding.llLoginByAccount.setOnClickListener { changLoginType(false) } binding.llLoginByCard.setOnClickListener { changLoginType(true) } changLoginType(true) initRecyclerView() if (DEBUG) { viewModel.mockDataToLocal() } viewModel.loadRfidsFromLocal(); //测试入口 binding.imTestLogin.setOnClickListener { if (DEBUG) { // takePhoto() viewModel.login("admin", "Jinghe233") // service?.sendRfid() // viewModel.activeEngine() // startActivity(Intent(this, FaceManageActivity::class.java)) // startActivity(Intent(this, RegisterAndRecognizeActivity::class.java)) } } initPermission() // doRegisterReceiver(); } override fun tryLoadData() { } private fun initPermission() { if (allPermissionsGranted()) { // ImageCapture startCamera() } else { ActivityCompat.requestPermissions( this, REQUIRED_PERMISSIONS, REQUEST_CODE_PERMISSIONS ) } } fun initRecyclerView() { //区分暂存区域展示 clearList() rvNormalArray = arrayOf( binding.rvNormalContent11, binding.rvNormalContent12, binding.rvNormalContent13, binding.rvNormalContent21, binding.rvNormalContent22, binding.rvNormalContent23, binding.rvNormalContent31, binding.rvNormalContent32, binding.rvNormalContent33, binding.rvNormalContent41, binding.rvNormalContent42, binding.rvNormalContent43, binding.rvNormalContent51, binding.rvNormalContent52, binding.rvNormalContent53, ) inventoryDaoArray = arrayOf( arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), arrayListOf(), ) for (rvItem in rvNormalArray) { rvItem?.layoutManager = LinearLayoutManager(this, RecyclerView.HORIZONTAL, false) } for (i in 0 until 15) { rvNormalArray[i]?.layoutManager = GridLayoutManager(this, 3) rvNormalArray[i]?.adapter = inventoryDaoArray[i]?.let { LoginPageShowItemAdapter(it) } } binding.rvPauseContent?.layoutManager = GridLayoutManager(this, 4) binding.rvPauseContent?.adapter = LoginPageShowItemAdapter(tempList10) binding.rvPauseContent1?.layoutManager = GridLayoutManager(this, 4) binding.rvPauseContent1?.adapter = LoginPageShowItemAdapter(tempList30) } override fun initObservables() { super.initObservables() viewModel.loginUserInfo.observe(this) { SharedPreferencesUtils.setPrefInt(this, ROLE_ID, it.role_id.toInt()) toMainPage() // takePhoto() } viewModel.loginStatus.observe(this) { //如果账户验证成功,跳转到主界面 if (it) toMainPage() // takePhoto() } loadRridsData() } var rvNormalArray = arrayOfNulls<RecyclerView>(15) var inventoryDaoArray = arrayOfNulls<ArrayList<InventoryDao>>(15) var tempList10 = mutableListOf<InventoryDao>()//未编辑位置 var tempList30 = mutableListOf<InventoryDao>()//未编辑位置 var tempList = mutableListOf<InventoryDao>() var tempListNormal = mutableListOf<AvailRfid>() private fun clearList() { tempList.clear() tempListNormal.clear() tempList10.clear() tempList30.clear() for (item in inventoryDaoArray) { item?.clear() } } private fun loadRridsData() { viewModel.rfidDatas.observe(this) { clearList() var map = it.avail_rfids.stream() .collect(Collectors.groupingBy { t -> t.material.eas_material_name + t.material.eas_unit_id + t.cell_number })//根据批号分组 for (i in map.values) { tempList.add( InventoryDao( "${i[0].material_batch.eas_lot}", "${i[0].material?.eas_material_name}", i.size, i[0].cell_number ) ) } for (item in it.avail_rfids) { if (item.cell_number > 1) tempListNormal.add(item) } for (item in tempList) { when (item.cellNumber) { 2 -> inventoryDaoArray[0]?.add(item) 3 -> inventoryDaoArray[1]?.add(item) 4 -> inventoryDaoArray[2]?.add(item) 5 -> inventoryDaoArray[3]?.add(item) 6 -> inventoryDaoArray[4]?.add(item) 7 -> inventoryDaoArray[5]?.add(item) 8 -> inventoryDaoArray[6]?.add(item) 9 -> inventoryDaoArray[7]?.add(item) 10 -> inventoryDaoArray[8]?.add(item) 11 -> inventoryDaoArray[9]?.add(item) 12 -> inventoryDaoArray[10]?.add(item) 13 -> inventoryDaoArray[11]?.add(item) 14 -> inventoryDaoArray[12]?.add(item) 15 -> inventoryDaoArray[13]?.add(item) 16 -> inventoryDaoArray[14]?.add(item) else -> tempList10.add(item) } } for (rvItem in rvNormalArray) { rvItem?.adapter?.notifyDataSetChanged() } binding.tvNormalNum.text = "共${tempListNormal.size}个" binding.rvPauseContent?.adapter?.notifyDataSetChanged() binding.tvPauseNum?.text = "共${it.avail_rfids.size - tempListNormal.size}个" //显示暂存区域 for (i in it.avail_rfids) { if (i.remain < 100) { tempList30.add( InventoryDao( "${i.material_batch.eas_lot}", "${i.material?.eas_material_name}", 1, i.cell_number ) ) } } binding.rvPauseContent1?.adapter?.notifyDataSetChanged() binding.tvPauseNum1?.text = "共${tempList30.size}个" } } //拍照 private fun takePhoto() { //拍照前删除30天前的相片 FileUtils.deleteImageByDate(-30) val imageCapture = imageCamera ?: return val mDateFormat = SimpleDateFormat("yyyyMMddHHmmss", Locale.US) val file = File(FileUtils.getImageFileName(), mDateFormat.format(Date()).toString() + ".png") val outputOptions = ImageCapture.OutputFileOptions.Builder(file).build() imageCapture.takePicture(outputOptions, ContextCompat.getMainExecutor(this), object : ImageCapture.OnImageSavedCallback { override fun onError(exc: ImageCaptureException) { Log.e(TAG, "Photo capture failed: ${exc.message}", exc) ToastUtils.shortToast(" 拍照失败 ${exc.message}") // Toasty.info(this@LoginActivity, " 拍照失败 ${exc.message}", Toast.LENGTH_SHORT, true).show() // toMainPage() } override fun onImageSaved(output: ImageCapture.OutputFileResults) { val savedUri = Uri.fromFile(file) val msg = "Photo capture succeeded: $savedUri" ToastUtils.shortToast(" 拍照成功 $savedUri") // Toasty.info(this@LoginActivity, " 拍照成功 $savedUri", Toast.LENGTH_SHORT, true).show() Log.d(TAG, msg) // toMainPage() } }) } private fun toMainPage() { //跳转到主页面 binding.edPassword.setText("") val intent = Intent(this, MainActivity::class.java) intent.putExtra("loginUserInfo", Gson().toJson(viewModel.loginUserInfo.value)) intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION); startActivity(intent) finish() } override fun onStart() { super.onStart() doRegisterReceiver() } override fun onDestroy() { super.onDestroy() stopService() // cameraExecutor.shutdown() } override fun onRestart() { super.onRestart() viewModel.loadRfidsFromLocal(); //从主页面返回 } private fun startService() { val intent = Intent(this, MyService::class.java) intent.putExtra("from", "LoginActivity") bindService(intent, conn, Context.BIND_AUTO_CREATE) } private fun stopService() { // unbindService(conn); if (mReceiver != null) { unregisterReceiver(mReceiver); } } private fun changLoginType(isLoginByCard: Boolean) { if (isLoginByCard) { binding.llHFCard.visibility = View.VISIBLE binding.llAccount?.visibility = View.GONE } else { binding.llHFCard.visibility = View.GONE binding.llAccount?.visibility = View.VISIBLE } } /** * 注册广播接收者 */ private var mReceiver: ContentReceiver? = null private fun doRegisterReceiver() { mReceiver = ContentReceiver() val filter = IntentFilter( BROADCAST_INTENT_FILTER ) registerReceiver(mReceiver, filter) } inner class ContentReceiver : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent) { val key = intent.getStringExtra(TCP_MSG_KEY) val value = intent.getStringExtra(TCP_MSG_VALUE) Log.d("BroadcastReceiver", "Login key--->${key},value--${value}") when (key) { EXIT_APP_MSG -> { exitProcess(0) } HFCard -> { value?.let { viewModel.loginByCark(it) } } } } } /** * 开始拍照 */ @SuppressLint("RestrictedApi") private fun startCamera() { cameraExecutor = Executors.newSingleThreadExecutor() val cameraProviderFuture = ProcessCameraProvider.getInstance(this) cameraProviderFuture.addListener(Runnable { cameraProvider = cameraProviderFuture.get()//获取相机信息 //预览配置 preview = Preview.Builder() .build() .also { it.setSurfaceProvider(binding.viewFinder?.surfaceProvider) } imageCamera = ImageCapture.Builder() .setCaptureMode(ImageCapture.CAPTURE_MODE_MINIMIZE_LATENCY) .setFlashMode(ImageCapture.FLASH_MODE_AUTO) // .setCaptureMode(ImageCapture.CAPTURE_MODE_MAXIMIZE_QUALITY) .build() // previewView is a PreviewView instance try { cameraProvider?.unbindAll()//先解绑所有用例 camera = cameraProvider?.bindToLifecycle( this, cameraSelector, preview, imageCamera )//绑定用例 Log.e(TAG, "绑定用例") } catch (exc: Exception) { Log.e(TAG, "Use case binding failed", exc) } }, ContextCompat.getMainExecutor(this)) } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { if (requestCode == REQUEST_CODE_PERMISSIONS) { if (allPermissionsGranted()) { startCamera() } else { Toast.makeText( this, "Permissions not granted by the user.", Toast.LENGTH_SHORT ).show() finish() } } } private fun allPermissionsGranted() = REQUIRED_PERMISSIONS.all { ContextCompat.checkSelfPermission(baseContext, it) == PackageManager.PERMISSION_GRANTED } companion object { private const val TAG = "CameraXBasic" private const val FILENAME_FORMAT = "yyyy-MM-dd-HH-mm-ss-SSS" private const val REQUEST_CODE_PERMISSIONS = 10 private val REQUIRED_PERMISSIONS = arrayOf( Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO ) } }
0
Kotlin
0
0
ea0f75d52d29ce71001f740d7bd4e4e795b3562f
16,367
FridgeSystem30
Apache License 2.0
src/main/kotlin/no/nav/syfo/behandler/kafka/KafkaConfig.kt
navikt
378,118,189
false
null
package no.nav.syfo.behandler.kafka import no.nav.syfo.application.kafka.ApplicationEnvironmentKafka import no.nav.syfo.application.kafka.kafkaConsumerConfig import org.apache.kafka.clients.consumer.ConsumerConfig import java.util.* fun kafkaSykmeldingConsumerConfig( applicationEnvironmentKafka: ApplicationEnvironmentKafka, ): Properties { return kafkaConsumerConfig(applicationEnvironmentKafka).apply { this[ConsumerConfig.MAX_POLL_RECORDS_CONFIG] = "500" this[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = JacksonKafkaDeserializerSykmelding::class.java.canonicalName } } fun kafkaDialogmeldingFromBehandlerConsumerConfig( applicationEnvironmentKafka: ApplicationEnvironmentKafka, ): Properties { return kafkaConsumerConfig(applicationEnvironmentKafka).apply { this[ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG] = JacksonKafkaDeserializerDialogmeldingFromBehandler::class.java.canonicalName } }
1
Kotlin
2
0
b901fd968b75de2c33de786479eab3d7c6cfece2
979
isdialogmelding
MIT License
app/src/main/java/com/android/skip/dataclass/PackageInfoV2.kt
GuoXiCheng
506,451,823
false
{"Kotlin": 130289, "TypeScript": 12715, "JavaScript": 289}
package com.android.skip.dataclass data class PackageInfoV2( val packageName: String, val skipIds: List<SkipId>? = null, val skipTexts: List<SkipText>? = null, val skipBounds: List<SkipBound>? = null ) data class SkipId( val id: String ) data class SkipText( val text: String, val length: Int? = null ) data class SkipBound( val bound: String, val resolution: String )
23
Kotlin
73
2,212
7d0f5c0155431e4cfe4a5de99de0efd9c0b14a44
408
SKIP
MIT License
app/src/main/java/com/android/skip/dataclass/PackageInfoV2.kt
GuoXiCheng
506,451,823
false
{"Kotlin": 130289, "TypeScript": 12715, "JavaScript": 289}
package com.android.skip.dataclass data class PackageInfoV2( val packageName: String, val skipIds: List<SkipId>? = null, val skipTexts: List<SkipText>? = null, val skipBounds: List<SkipBound>? = null ) data class SkipId( val id: String ) data class SkipText( val text: String, val length: Int? = null ) data class SkipBound( val bound: String, val resolution: String )
23
Kotlin
73
2,212
7d0f5c0155431e4cfe4a5de99de0efd9c0b14a44
408
SKIP
MIT License
src/main/kotlin/com/baulsupp/oksocial/services/spotify/SpotifyAuthFlow.kt
umerkiani
116,174,513
true
{"Kotlin": 345221, "Shell": 8250, "JavaScript": 1691}
package com.baulsupp.oksocial.services.spotify import com.baulsupp.oksocial.authenticator.AuthUtil import com.baulsupp.oksocial.authenticator.SimpleWebServer import com.baulsupp.oksocial.authenticator.oauth2.Oauth2Token import com.baulsupp.oksocial.output.OutputHandler import okhttp3.Credentials import okhttp3.FormBody import okhttp3.OkHttpClient import okhttp3.Request import java.io.IOException import java.net.URLEncoder object SpotifyAuthFlow { @Throws(IOException::class) fun login(client: OkHttpClient, outputHandler: OutputHandler<*>, clientId: String, clientSecret: String, scopes: Iterable<String>): Oauth2Token { SimpleWebServer.forCode().use { s -> val scopesString = URLEncoder.encode(scopes.joinToString(" "), "UTF-8") val loginUrl = "https://accounts.spotify.com/authorize?client_id=$clientId&response_type=code&state=x&redirect_uri=${s.redirectUri}&scope=$scopesString" outputHandler.openLink(loginUrl) val code = s.waitForCode() val tokenUrl = "https://accounts.spotify.com/api/token" val body = FormBody.Builder().add("client_id", clientId) .add("redirect_uri", s.redirectUri) .add("code", code) .add("grant_type", "authorization_code") .build() val request = Request.Builder().header("Authorization", Credentials.basic(clientId, clientSecret)) .url(tokenUrl) .method("POST", body) .build() val responseMap = AuthUtil.makeJsonMapRequest(client, request) return Oauth2Token(responseMap["access_token"] as String, responseMap["refresh_token"] as String, clientId, clientSecret) } } }
0
Kotlin
0
0
f7e496f47500a1c3bb0b86d0ac239f4fb46e15f3
1,840
oksocial
Apache License 2.0
TachiServer/src/main/java/xyz/nulldev/ts/api/v2/java/impl/extensions/ExtensionsControllerImpl.kt
TachiWeb
63,995,519
false
null
package xyz.nulldev.ts.api.v2.java.impl.extensions import com.github.salomonbrys.kodein.Kodein import com.github.salomonbrys.kodein.conf.global import com.github.salomonbrys.kodein.instance import com.github.salomonbrys.kodein.lazy import eu.kanade.tachiyomi.extension.ExtensionManager import eu.kanade.tachiyomi.extension.model.Extension import xyz.nulldev.androidcompat.pm.PackageController import xyz.nulldev.ts.api.v2.java.model.extensions.ExtensionsController import xyz.nulldev.ts.ext.kInstance import xyz.nulldev.ts.ext.kInstanceLazy import java.io.File class ExtensionsControllerImpl : ExtensionsController { private val controller by kInstanceLazy<PackageController>() override fun get(vararg packageNames: String) = ExtensionCollectionImpl(packageNames.toList()) // TODO Check these extensions exist override fun getAll() = ExtensionCollectionImpl(getAllExtensions().map { it.pkgName }) override fun trust(hash: String) { manager.trustSignature(hash) } override fun reloadAvailable() { manager.findAvailableExtensions() manager.getAvailableExtensionsObservable().take(2).toBlocking().subscribe() } override fun reloadLocal() { manager.init(kInstance()) } override fun installExternal(apk: File) { controller.installPackage(apk, true) reloadLocal() } companion object { private val manager by Kodein.global.lazy.instance<ExtensionManager>() internal fun getAllExtensions(): List<Extension> { var localExtensions = manager.installedExtensions + manager.untrustedExtensions // Get available extensions excluding ones that have already been installed localExtensions += manager.availableExtensions.filter { avail -> localExtensions.none { it.pkgName == avail.pkgName } } return localExtensions } init { // Forcibly fill this initially to allow the reloadAvailable endpoint to function manager.findAvailableExtensions() } } }
45
Java
44
376
756aed147f9d3ad64b0620ab69c3eb4575264177
2,123
TachiWeb-Server
Apache License 2.0
src/main/kotlin/com/jalgoarena/data/UsersRepository.kt
kostekman
114,119,849
true
{"Kotlin": 51334, "Shell": 103}
package com.jalgoarena.data import com.jalgoarena.domain.User interface UsersRepository { fun findAll(): List<User> fun findByUsername(username: String): User fun destroy() fun add(user: User): User fun update(user: User): User }
0
Kotlin
0
0
cf80a1f616f8b1660967e8887d71bdd5910cb1fa
252
JAlgoArena-Auth
Apache License 2.0
compiler/testData/diagnostics/tests/evaluate/parentesized.kt
JakeWharton
99,388,807
false
null
val p1: Byte = <!TYPE_MISMATCH!>(1 + 2) * 2<!> val p2: Short = <!TYPE_MISMATCH!>(1 + 2) * 2<!> val p3: Int = (1 + 2) * 2 val p4: Long = (1 + 2) * 2 val b1: Byte = <!TYPE_MISMATCH!>(1.toByte() + 2) * 2<!> val b2: Short = <!TYPE_MISMATCH!>(1.toShort() + 2) * 2<!> val b3: Int = (1.toInt() + 2) * 2 val b4: Long = (1.toLong() + 2) * 2 val i1: Int = (1.toByte() + 2) * 2 val i2: Int = (1.toShort() + 2) * 2
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
405
kotlin
Apache License 2.0
Android/app/src/main/java/bd/ctracker/com/ctracker/TrackingUpdateBroadcastReceiver.kt
hissain
249,047,323
false
null
package bd.ctracker.com.ctracker import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.widget.Toast import bd.ctracker.com.ctracker.model.CTEventInfo import bd.ctracker.com.ctracker.model.CTLocation import bd.ctracker.com.ctracker.repository.RestApiService import bd.ctracker.com.ctracker.utility.PreferenceKeys import com.google.android.gms.location.LocationResult import kotlinx.coroutines.* import timber.log.Timber class TrackingUpdateBroadcastReceiver: BroadcastReceiver() { private val scope = CoroutineScope(Job() + Dispatchers.IO) override fun onReceive(context: Context?, intent: Intent?) { Timber.d( "onReceive() context:$context, intent:$intent") if (intent != null) { if(intent.action == ACTION_PROCESS_UPDATES) { LocationResult.extractResult(intent)?.let { locationResult -> val locations = locationResult.locations.map { location -> CTLocation( latitude = location.latitude, longitude = location.longitude, altitude = location.altitude ) } if (locations.isNotEmpty()) { var loc: String = "" for(location in locations) { loc += "Lat: ${location.latitude} -- lon: ${location.longitude} -- alt: ${location.altitude} \n" Timber.i( "Location ${location.latitude}, ${location.longitude} & ${location.altitude}") scope.launch { // Save close contact data/Send to data to server withContext(Dispatchers.Main) { Toast.makeText( context, "Getting contact details and stored into DB...", Toast.LENGTH_SHORT ) } Timber.d("Getting contact details and stored into DB") val id = BaseApplication.preference().getInt(PreferenceKeys.userID, -1) if (id != -1) { // registered valid user val eventInfo = CTEventInfo( null, userId = id, latitude = location.latitude, longitude = location.longitude, altitude = location.altitude ) RestApiService().addEvent(eventInfo, onResult = { if (it != null) { Timber.d( "Event added for user %s, event id: %s", id, it.eventId ) } else { Timber.e("Event could not be added. Need to check at Server side") } }) } } } Timber.d("Location updates :-\n $loc"); } } } } } companion object { const val ACTION_PROCESS_UPDATES = "bd.ctracker.com.ctracker.action." + "PROCESS_UPDATES" } }
0
Kotlin
13
13
572fbe510afb74d3798ef25511d8846492031ed3
3,882
CoronaTracker
MIT License
android/app/src/main/kotlin/io/aquawallet/extension/MethodChannelExt.kt
AquaWallet
743,008,963
false
{"Dart": 2176004, "C": 48908, "Swift": 5743, "Kotlin": 3612, "Nix": 3243, "Makefile": 3093, "Ruby": 2630, "Shell": 916, "Objective-C": 650, "CMake": 464}
package io.aquawallet.extension import io.flutter.plugin.common.MethodCall import io.flutter.plugin.common.MethodChannel import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.android.MainThreadDisposable fun MethodChannel.callHandlerFlowable(): Flowable<Pair<MethodCall, MethodChannel.Result>> = Flowable .create({ emitter -> val callHandler = MethodChannel.MethodCallHandler { call, result -> emitter.onNext(Pair(call, result)) } emitter.setDisposable(object : MainThreadDisposable() { override fun onDispose() { setMethodCallHandler(null) } }) setMethodCallHandler(callHandler) }, BackpressureStrategy.LATEST)
29
Dart
8
78
a5b196b1dd3d51554aebbe3077a5b755b4511ed9
793
aqua-wallet
MIT License
app/core/src/main/java/com/fsck/k9/mailstore/FolderRepository.kt
poldi171254
355,379,114
true
{"INI": 2, "Gradle": 27, "Shell": 5, "EditorConfig": 1, "Markdown": 9, "Git Attributes": 1, "Batchfile": 1, "Text": 4, "Ignore List": 3, "Git Config": 1, "XML": 380, "YAML": 4, "AIDL": 2, "Java": 505, "SVG": 67, "PostScript": 1, "Kotlin": 519, "Proguard": 2, "E-mail": 11, "JSON": 20}
package com.fsck.k9.mailstore import androidx.core.content.contentValuesOf import com.fsck.k9.Account import com.fsck.k9.Account.FolderMode import com.fsck.k9.mail.FolderClass import com.fsck.k9.mail.FolderType as RemoteFolderType class FolderRepository( private val localStoreProvider: LocalStoreProvider, private val messageStoreManager: MessageStoreManager, private val account: Account ) { private val sortForDisplay = compareByDescending<DisplayFolder> { it.folder.type == FolderType.INBOX } .thenByDescending { it.folder.type == FolderType.OUTBOX } .thenByDescending { it.folder.type != FolderType.REGULAR } .thenByDescending { it.isInTopGroup } .thenBy(String.CASE_INSENSITIVE_ORDER) { it.folder.name } fun getDisplayFolders(displayMode: FolderMode?): List<DisplayFolder> { val messageStore = messageStoreManager.getMessageStore(account) return messageStore.getDisplayFolders( displayMode = displayMode ?: account.folderDisplayMode, outboxFolderId = account.outboxFolderId ) { folder -> DisplayFolder( folder = Folder( id = folder.id, name = folder.name, type = folderTypeOf(folder.id), isLocalOnly = folder.isLocalOnly ), isInTopGroup = folder.isInTopGroup, unreadCount = folder.messageCount ) }.sortedWith(sortForDisplay) } fun getFolder(folderId: Long): Folder? { val messageStore = messageStoreManager.getMessageStore(account) return messageStore.getFolder(folderId) { folder -> Folder( id = folder.id, name = folder.name, type = folderTypeOf(folder.id), isLocalOnly = folder.isLocalOnly ) } } fun getFolderDetails(folderId: Long): FolderDetails? { val messageStore = messageStoreManager.getMessageStore(account) return messageStore.getFolder(folderId) { folder -> FolderDetails( folder = Folder( id = folder.id, name = folder.name, type = folderTypeOf(folder.id), isLocalOnly = folder.isLocalOnly ), isInTopGroup = folder.isInTopGroup, isIntegrate = folder.isIntegrate, syncClass = folder.syncClass, displayClass = folder.displayClass, notifyClass = folder.notifyClass, pushClass = folder.pushClass ) } } fun getRemoteFolders(): List<RemoteFolder> { val messageStore = messageStoreManager.getMessageStore(account) return messageStore.getFolders(excludeLocalOnly = true) { folder -> RemoteFolder( id = folder.id, serverId = folder.serverId, name = folder.name, type = folder.type.toFolderType() ) } } fun getRemoteFolderDetails(): List<RemoteFolderDetails> { val messageStore = messageStoreManager.getMessageStore(account) return messageStore.getFolders(excludeLocalOnly = true) { folder -> RemoteFolderDetails( folder = RemoteFolder( id = folder.id, serverId = folder.serverId, name = folder.name, type = folder.type.toFolderType() ), isInTopGroup = folder.isInTopGroup, isIntegrate = folder.isIntegrate, syncClass = folder.syncClass, displayClass = folder.displayClass, notifyClass = folder.notifyClass, pushClass = folder.pushClass ) } } fun getFolderServerId(folderId: Long): String? { val messageStore = messageStoreManager.getMessageStore(account) return messageStore.getFolder(folderId) { folder -> folder.serverId } } fun getFolderId(folderServerId: String): Long? { val messageStore = messageStoreManager.getMessageStore(account) return messageStore.getFolderId(folderServerId) } fun isFolderPresent(folderId: Long): Boolean { val messageStore = messageStoreManager.getMessageStore(account) return messageStore.getFolder(folderId) { true } ?: false } fun updateFolderDetails(folderDetails: FolderDetails) { val database = localStoreProvider.getInstance(account).database database.execute(false) { db -> val contentValues = contentValuesOf( "top_group" to folderDetails.isInTopGroup, "integrate" to folderDetails.isIntegrate, "poll_class" to folderDetails.syncClass.name, "display_class" to folderDetails.displayClass.name, "notify_class" to folderDetails.notifyClass.name, "push_class" to folderDetails.pushClass.name ) db.update("folders", contentValues, "id = ?", arrayOf(folderDetails.folder.id.toString())) } } private fun folderTypeOf(folderId: Long) = when (folderId) { account.inboxFolderId -> FolderType.INBOX account.outboxFolderId -> FolderType.OUTBOX account.sentFolderId -> FolderType.SENT account.trashFolderId -> FolderType.TRASH account.draftsFolderId -> FolderType.DRAFTS account.archiveFolderId -> FolderType.ARCHIVE account.spamFolderId -> FolderType.SPAM else -> FolderType.REGULAR } private fun RemoteFolderType.toFolderType(): FolderType = when (this) { RemoteFolderType.REGULAR -> FolderType.REGULAR RemoteFolderType.INBOX -> FolderType.INBOX RemoteFolderType.OUTBOX -> FolderType.REGULAR // We currently don't support remote Outbox folders RemoteFolderType.DRAFTS -> FolderType.DRAFTS RemoteFolderType.SENT -> FolderType.SENT RemoteFolderType.TRASH -> FolderType.TRASH RemoteFolderType.SPAM -> FolderType.SPAM RemoteFolderType.ARCHIVE -> FolderType.ARCHIVE } fun setIncludeInUnifiedInbox(folderId: Long, includeInUnifiedInbox: Boolean) { val localStore = localStoreProvider.getInstance(account) val folder = localStore.getFolder(folderId) folder.isIntegrate = includeInUnifiedInbox } fun setDisplayClass(folderId: Long, folderClass: FolderClass) { val localStore = localStoreProvider.getInstance(account) val folder = localStore.getFolder(folderId) folder.displayClass = folderClass } fun setSyncClass(folderId: Long, folderClass: FolderClass) { val localStore = localStoreProvider.getInstance(account) val folder = localStore.getFolder(folderId) folder.syncClass = folderClass } fun setNotificationClass(folderId: Long, folderClass: FolderClass) { val localStore = localStoreProvider.getInstance(account) val folder = localStore.getFolder(folderId) folder.notifyClass = folderClass } } data class Folder(val id: Long, val name: String, val type: FolderType, val isLocalOnly: Boolean) data class RemoteFolder(val id: Long, val serverId: String, val name: String, val type: FolderType) data class FolderDetails( val folder: Folder, val isInTopGroup: Boolean, val isIntegrate: Boolean, val syncClass: FolderClass, val displayClass: FolderClass, val notifyClass: FolderClass, val pushClass: FolderClass ) data class RemoteFolderDetails( val folder: RemoteFolder, val isInTopGroup: Boolean, val isIntegrate: Boolean, val syncClass: FolderClass, val displayClass: FolderClass, val notifyClass: FolderClass, val pushClass: FolderClass ) data class DisplayFolder( val folder: Folder, val isInTopGroup: Boolean, val unreadCount: Int ) enum class FolderType { REGULAR, INBOX, OUTBOX, SENT, TRASH, DRAFTS, ARCHIVE, SPAM }
1
null
0
0
62bf9c36f75275673b37a33fdbf254ac429937d1
8,178
k-9
Apache License 2.0
2019-10-02/SystemServices/app/src/main/java/br/ufpe/cin/android/systemservices/notification/NotificationSubActivity.kt
if710
99,732,816
false
null
package br.ufpe.cin.android.systemservices.notification import android.app.Activity import android.os.Bundle import br.ufpe.cin.android.systemservices.R class NotificationSubActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_notification_sub) } }
1
null
29
12
ce4131eb6aca5e33fa5ed503d613ba6ed40dec4d
368
if710.github.io
MIT License
kotlin-html-wasm/src/commonMain/kotlin/dev/scottpierce/html/writer/style/PaddingStyles.kt
kowasm
586,987,800
false
{"Kotlin": 620989, "JavaScript": 545, "Shell": 263}
// This file was generated using the `kotlin-html-generator` module. Instead of modifying it, modify the // `html-builder-generator` and run it again. @file:Suppress("unused") package dev.scottpierce.html.writer.style import dev.scottpierce.html.writer.BaseStyleContext import dev.scottpierce.html.writer.InlineStyleContext import dev.scottpierce.html.writer.StyleContext import kotlin.Boolean import kotlin.Suppress fun BaseStyleContext.padding(value: Dimension, important: Boolean = false) { writeStyleProperty("padding", value, important) } fun BaseStyleContext.padding( y: Dimension, x: Dimension, important: Boolean = false ) { writeStyleProperty("padding", """$y $x""", important) } fun BaseStyleContext.padding( top: Dimension, x: Dimension, bottom: Dimension, important: Boolean = false ) { writeStyleProperty("padding", """$top $x $bottom""", important) } fun BaseStyleContext.padding( top: Dimension, right: Dimension, bottom: Dimension, left: Dimension, important: Boolean = false ) { writeStyleProperty("padding", """$top $right $bottom $left""", important) } fun BaseStyleContext.padding(value: CssValue, important: Boolean = false) { writeStyleProperty("padding", value, important) } fun StyleContext.padding(value: Dimension, important: Boolean = false) { writeStyleProperty("padding", value, important) } fun StyleContext.padding( y: Dimension, x: Dimension, important: Boolean = false ) { writeStyleProperty("padding", """$y $x""", important) } fun StyleContext.padding( top: Dimension, x: Dimension, bottom: Dimension, important: Boolean = false ) { writeStyleProperty("padding", """$top $x $bottom""", important) } fun StyleContext.padding( top: Dimension, right: Dimension, bottom: Dimension, left: Dimension, important: Boolean = false ) { writeStyleProperty("padding", """$top $right $bottom $left""", important) } fun StyleContext.padding(value: CssValue, important: Boolean = false) { writeStyleProperty("padding", value, important) } fun InlineStyleContext.padding(value: Dimension, important: Boolean = false) { writeStyleProperty("padding", value, important) } fun InlineStyleContext.padding( y: Dimension, x: Dimension, important: Boolean = false ) { writeStyleProperty("padding", """$y $x""", important) } fun InlineStyleContext.padding( top: Dimension, x: Dimension, bottom: Dimension, important: Boolean = false ) { writeStyleProperty("padding", """$top $x $bottom""", important) } fun InlineStyleContext.padding( top: Dimension, right: Dimension, bottom: Dimension, left: Dimension, important: Boolean = false ) { writeStyleProperty("padding", """$top $right $bottom $left""", important) } fun InlineStyleContext.padding(value: CssValue, important: Boolean = false) { writeStyleProperty("padding", value, important) }
10
Kotlin
5
315
a45430d559057f5a3e10ee88d26eba07103bf69d
2,971
kowasm
Apache License 2.0
data/src/main/java/com/nawrot/mateusz/sportapp/data/base/AndroidSchedulersProvider.kt
mateusz-nawrot
111,897,181
false
null
package com.nawrot.mateusz.oversearch.data.base import android.util.Log import com.nawrot.mateusz.oversearch.domain.base.SchedulersProvider import io.reactivex.* import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import javax.inject.Inject import javax.inject.Singleton @Singleton class AndroidSchedulersProvider @Inject constructor() : SchedulersProvider { override fun completableTransformer(): CompletableTransformer { Log.d("AndroidSchedulersProv", "CREATING COMPLETABLE TRANSFORMER"); return CompletableTransformer { it -> it.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } } override fun <T> singleTransformer(): SingleTransformer<T, T> { Log.d("AndroidSchedulersProv", "CREATING SINGLE TRANSFORMER"); return SingleTransformer { it -> it.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } } override fun <T> observableTransformer(): ObservableTransformer<T, T> { Log.d("AndroidSchedulersProv", "CREATING OBSERVABLE TRANSFORMER"); return ObservableTransformer { it -> it.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } } }
0
Kotlin
0
0
dc5966d4648b6967213ca14a531526e1c7abda25
1,286
sportapp
Apache License 2.0
app/src/test/kotlin/com/ivanovsky/passnotes/domain/NoteDifferTest.kt
aivanovski
95,774,290
false
null
package com.ivanovsky.passnotes.domain import com.google.common.truth.Truth.assertThat import com.ivanovsky.passnotes.data.entity.Attachment import com.ivanovsky.passnotes.data.entity.Hash import com.ivanovsky.passnotes.data.entity.HashType import com.ivanovsky.passnotes.data.entity.Note import com.ivanovsky.passnotes.util.asDate import java.util.UUID import org.junit.Test class NoteDifferTest { @Test fun `getAttachmentsDiff should return empty list`() { // arrange val oldNote = newNote( listOf(Attachments.FIRST.copy(), Attachments.SECOND.copy()) ) val newNote = newNote( listOf(Attachments.SECOND.copy(), Attachments.FIRST.copy()) ) // act val diff = NoteDiffer().getAttachmentsDiff(oldNote, newNote) // assert assertThat(diff).isEmpty() } @Test fun `getAttachmentsDiff should return items to insert`() { // arrange val oldNote = newNote(emptyList()) val newNote = newNote( listOf(Attachments.FIRST.copy(), Attachments.SECOND.copy()) ) // act val diff = NoteDiffer().getAttachmentsDiff(oldNote, newNote) // assert assertThat(diff).isEqualTo( listOf( Pair(NoteDiffer.DiffAction.INSERT, Attachments.FIRST), Pair(NoteDiffer.DiffAction.INSERT, Attachments.SECOND) ) ) } @Test fun `getAttachmentsDiff should return items to remove`() { // arrange val oldNote = newNote( listOf(Attachments.FIRST.copy(), Attachments.SECOND.copy()) ) val newNote = newNote( emptyList() ) // act val diff = NoteDiffer().getAttachmentsDiff(oldNote, newNote) // assert assertThat(diff).isEqualTo( listOf( Pair(NoteDiffer.DiffAction.REMOVE, Attachments.FIRST), Pair(NoteDiffer.DiffAction.REMOVE, Attachments.SECOND) ) ) } @Test fun `getAttachmentsDiff should return items to remove and to insert`() { // arrange val oldNote = newNote( listOf(Attachments.FIRST.copy(), Attachments.SECOND.copy()) ) val newNote = newNote( listOf(Attachments.FIRST.copy(), Attachments.THIRD.copy()) ) // act val diff = NoteDiffer().getAttachmentsDiff(oldNote, newNote) // assert assertThat(diff).isEqualTo( listOf( Pair(NoteDiffer.DiffAction.REMOVE, Attachments.SECOND), Pair(NoteDiffer.DiffAction.INSERT, Attachments.THIRD) ) ) } private fun newNote(attachments: List<Attachment>): Note = Note( uid = UUID(1, 1), groupUid = UUID(2, 2), created = "2020-01-10".asDate(), modified = "2020-01-11".asDate(), title = "note", properties = emptyList(), attachments = attachments ) private object Attachments { val FIRST = Attachment( uid = "file1-uid", name = "file1.txt", hash = Hash("hash1".toByteArray(), HashType.SHA_256), data = "file1-content".toByteArray() ) val SECOND = Attachment( uid = "file2-uid", name = "file2.txt", hash = Hash("hash2".toByteArray(), HashType.SHA_256), data = "file2-content".toByteArray() ) val THIRD = Attachment( uid = "file3-uid", name = "file3.txt", hash = Hash("hash3".toByteArray(), HashType.SHA_256), data = "file3-content".toByteArray() ) val FOURTH = Attachment( uid = "file4-uid", name = "file4.txt", hash = Hash("hash4".toByteArray(), HashType.SHA_256), data = "file4-content".toByteArray() ) } companion object { } }
7
null
4
53
83605c13c7f13e1f484aa00f6b3e9af622880888
4,012
keepassvault
Apache License 2.0
app/src/main/java/fi/kroon/vadret/domain/feedsourcepreference/DeleteAllFeedSourcePreferenceTask.kt
marvinmosa
241,497,201
true
{"Kotlin": 871560}
package fi.kroon.vadret.domain.feedsourcepreference import fi.kroon.vadret.data.failure.Failure import fi.kroon.vadret.data.feedsourcepreference.FeedSourcePreferenceRepository import io.github.sphrak.either.Either import io.reactivex.Single import javax.inject.Inject class DeleteAllFeedSourcePreferenceTask @Inject constructor( private val repo: FeedSourcePreferenceRepository ) { operator fun invoke(usedBy: String): Single<Either<Failure, Unit>> = repo.deleteAllEnabledUsedBy(usedBy = usedBy) }
0
null
0
0
f8149920c34bb3bc5e3148785ce217e37e596fbe
515
android
Apache License 2.0
http4k-core/src/test/kotlin/org/http4k/filter/TrafficFiltersTest.kt
http4k
86,003,479
false
null
package org.http4k.filter import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.http4k.client.JavaHttpClient import org.http4k.core.Method.GET import org.http4k.core.Method.POST import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.ACCEPTED import org.http4k.core.Status.Companion.BAD_REQUEST import org.http4k.core.Status.Companion.NOT_FOUND import org.http4k.core.Status.Companion.OK import org.http4k.core.Uri import org.http4k.core.then import org.http4k.filter.ClientFilters.SetBaseUriFrom import org.http4k.filter.TrafficFilters.RecordTo import org.http4k.hamkrest.hasBody import org.http4k.server.SunHttp import org.http4k.server.asServer import org.http4k.traffic.ReadWriteCache import org.http4k.traffic.ReadWriteStream import org.junit.jupiter.api.Test import org.junit.jupiter.api.fail class TrafficFiltersTest { private val request = Request(GET, "/bob") private val response = Response(OK) @Test fun `RecordTo stores traffic in underlying storage`() { val stream = ReadWriteStream.Memory() val handler = RecordTo(stream).then { response } assertThat(handler(request), equalTo(response)) assertThat(stream.requests().toList(), equalTo(listOf(request))) assertThat(stream.responses().toList(), equalTo(listOf(response))) } @Test fun `RecordTo stores traffic in underlying storage on server`() { val stream = ReadWriteStream.Memory() val request1 = Request(POST, "").body("helloworld") val request2 = Request(POST, "").body("goodbyeworld") RecordTo(stream) .then { responseFor(it) } .asServer(SunHttp(0)) .start().use { val client = SetBaseUriFrom(Uri.of("http://localhost:${it.port()}")) .then(JavaHttpClient()) assertThat(client(request1), hasBody("helloworld".reversed())) assertThat(client(request2), hasBody("goodbyeworld".reversed())) } assertThat(stream.requests().toList()[0], hasBody(request1.bodyString())) assertThat(stream.requests().toList()[1], hasBody(request2.bodyString())) assertThat(stream.responses().toList()[0], hasBody(responseFor(request1).bodyString())) assertThat(stream.responses().toList()[1], hasBody(responseFor(request2).bodyString())) } private fun responseFor(req: Request) = Response(OK).body(req.body.stream.reader().readText().reversed().byteInputStream()) @Test fun `ServeCachedFrom serves stored requests later or falls back`() { val cache = ReadWriteCache.Memory() cache[request] = response val notFound = Response(NOT_FOUND) val handler = TrafficFilters.ServeCachedFrom(cache).then { notFound } assertThat(handler(request), equalTo(response)) assertThat(handler(Request(GET, "/bob2")), equalTo(notFound)) } @Test fun `ReplayFrom serves stored requests later or returns 400`() { val cache = ReadWriteStream.Memory() cache[Request(GET, "/bob1")] = Response(OK) cache[Request(GET, "/bob2")] = Response(ACCEPTED) cache[Request(GET, "/bob3")] = Response(NOT_FOUND) val handler = TrafficFilters.ReplayFrom(cache).then { fail("") } assertThat(handler(Request(GET, "/bob1")), equalTo(Response(OK))) assertThat(handler(Request(GET, "/bob2")), equalTo(Response(ACCEPTED))) assertThat(handler(Request(GET, "/bob3")), equalTo(Response(NOT_FOUND))) assertThat(handler(Request(GET, "/bob2")), equalTo(Response(BAD_REQUEST))) } }
34
null
249
2,615
7ad276aa9c48552a115a59178839477f34d486b1
3,681
http4k
Apache License 2.0
src/main/kotlin/restApi/GroupChatPic.kt
ertprs
330,072,795
true
{"Kotlin": 548594, "Dockerfile": 1135}
package com.neelkamath.omniChat.restApi import com.neelkamath.omniChat.db.tables.Chats import com.neelkamath.omniChat.db.tables.GroupChatUsers import com.neelkamath.omniChat.db.tables.GroupChats import com.neelkamath.omniChat.userId import io.ktor.application.* import io.ktor.auth.* import io.ktor.http.* import io.ktor.response.* import io.ktor.routing.* fun routeGroupChatPic(routing: Routing): Unit = with(routing) { route("group-chat-pic") { getGroupChatPic(this) authenticate { patchGroupChatPic(this) } } } private fun getGroupChatPic(route: Route): Unit = with(route) { get { val chatId = call.parameters["chat-id"]!!.toInt() if (!Chats.exists(chatId)) call.respond(HttpStatusCode.BadRequest) else { val pic = GroupChats.readPic(chatId) if (pic == null) call.respond(HttpStatusCode.NoContent) else call.respondBytes(pic.bytes) } } } private fun patchGroupChatPic(route: Route): Unit = with(route) { patch { val chatId = call.parameters["chat-id"]!!.toInt() val pic = readMultipartPic() when { pic == null -> call.respond(HttpStatusCode.BadRequest) !GroupChatUsers.isAdmin(call.userId!!, chatId) -> call.respond(HttpStatusCode.Unauthorized) else -> { GroupChats.updatePic(chatId, pic) call.respond(HttpStatusCode.NoContent) } } } }
0
null
0
0
ce27f094c2d33967367be0c8d8e36c021272f77c
1,451
omni-chat
MIT License
src/jvmMain/kotlin/chat/sphinx/features/repository/mappers/feed/podcast/FeedDestinationDboPodcastDestinationPresenterMapper.kt
stakwork
456,999,775
false
null
package chat.sphinx.features.repository.mappers.feed.podcast import chat.sphinx.concepts.coroutines.CoroutineDispatchers import chat.sphinx.database.core.FeedDestinationDbo import chat.sphinx.features.repository.mappers.ClassMapper import chat.sphinx.wrapper.podcast.PodcastDestination internal class FeedDestinationDboPodcastDestinationPresenterMapper( dispatchers: CoroutineDispatchers, ): ClassMapper<FeedDestinationDbo, PodcastDestination>(dispatchers) { override suspend fun mapFrom(value: FeedDestinationDbo): PodcastDestination { return PodcastDestination( split = value.split, address = value.address, type = value.type, podcastId = value.feed_id ) } override suspend fun mapTo(value: PodcastDestination): FeedDestinationDbo { return FeedDestinationDbo( address = value.address, split = value.split, type = value.type, feed_id = value.podcastId ) } }
10
Kotlin
1
0
4d626ce7f3db4eaab8d3cca7396b2925552910cc
1,009
sphinx-kotlin-core
MIT License
ui-test-example/src/test/kotlin/org/intellij/examples/simple/plugin/pages/ActionMenuFixture.kt
JetBrains
301,411,608
false
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.move.ui.fixtures import com.intellij.remoterobot.RemoteRobot import com.intellij.remoterobot.data.RemoteComponent import com.intellij.remoterobot.fixtures.ComponentFixture import com.intellij.remoterobot.fixtures.FixtureName import com.intellij.remoterobot.search.locators.byXpath import com.intellij.remoterobot.utils.waitFor fun RemoteRobot.actionMenu(text: String): ActionMenuFixture { val xpath = byXpath("text '$text'", "//div[@class='ActionMenu' and @text='$text']") waitFor { findAll<ActionMenuFixture>(xpath).isNotEmpty() } return findAll<ActionMenuFixture>(xpath).first() } fun RemoteRobot.actionMenuItem(text: String): ActionMenuItemFixture { val xpath = byXpath("text '$text'", "//div[@class='ActionMenuItem' and @text='$text']") waitFor { findAll<ActionMenuItemFixture>(xpath).isNotEmpty() } return findAll<ActionMenuItemFixture>(xpath).first() } @FixtureName("ActionMenu") class ActionMenuFixture(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) : ComponentFixture(remoteRobot, remoteComponent) @FixtureName("ActionMenuItem") class ActionMenuItemFixture(remoteRobot: RemoteRobot, remoteComponent: RemoteComponent) : ComponentFixture(remoteRobot, remoteComponent)
5
null
55
98
392d71ddf93a4817d2094a64026075b595d6b01d
1,393
intellij-ui-test-robot
Apache License 2.0
ai/sample/wear-prompt-app/src/main/java/com/google/android/horologist/ai/sample/wear/prompt/settings/SettingsScreen.kt
google
451,563,714
false
null
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.horologist.ai.sample.wear.prompt.settings import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.key import androidx.compose.ui.Modifier import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.wear.compose.foundation.lazy.items import androidx.wear.compose.material.Text import androidx.wear.compose.ui.tooling.preview.WearPreviewLargeRound import com.google.android.horologist.ai.ui.model.ModelInstanceUiModel import com.google.android.horologist.composables.PlaceholderChip import com.google.android.horologist.compose.layout.ScalingLazyColumn import com.google.android.horologist.compose.layout.ScalingLazyColumnDefaults.ItemType import com.google.android.horologist.compose.layout.ScalingLazyColumnDefaults.listTextPadding import com.google.android.horologist.compose.layout.ScalingLazyColumnDefaults.padding import com.google.android.horologist.compose.layout.ScreenScaffold import com.google.android.horologist.compose.layout.rememberResponsiveColumnState import com.google.android.horologist.compose.material.ResponsiveListHeader import com.google.android.horologist.compose.material.ToggleChip import com.google.android.horologist.compose.material.ToggleChipToggleControl @Composable fun SettingsScreen( modifier: Modifier = Modifier, viewModel: SettingsViewModel = hiltViewModel(), ) { val uiState by viewModel.uiState.collectAsStateWithLifecycle() SettingsScreen( uiState = uiState, modifier = modifier, selectModel = viewModel::selectModel, ) } @Composable private fun SettingsScreen( uiState: SettingsUiState, modifier: Modifier = Modifier, selectModel: (ModelInstanceUiModel) -> Unit, ) { val columnState = rememberResponsiveColumnState( contentPadding = padding( first = ItemType.Text, last = ItemType.Chip, ), ) ScreenScaffold(scrollState = columnState, modifier = modifier) { ScalingLazyColumn(columnState = columnState) { if (uiState.models == null) { items(3) { PlaceholderChip() } } else { item { ResponsiveListHeader(modifier = Modifier.listTextPadding()) { Text("Browse") } } items(uiState.models) { model -> key(model.id) { ToggleChip( checked = model == uiState.current, onCheckedChanged = { selectModel(model) }, label = model.name, toggleControl = ToggleChipToggleControl.Radio, ) } } } } } } @WearPreviewLargeRound @Composable fun SettingsScreenPreview() { val current = ModelInstanceUiModel("dummy", "Dummy Model") val other1 = ModelInstanceUiModel("1", "Dummy Model 1") val other2 = ModelInstanceUiModel("2", "Dummy Model 2") val uiState = SettingsUiState(current, listOf(current, other1, other2)) SettingsScreen( uiState = uiState, selectModel = {}, ) }
45
null
93
565
bde87db14f63338904550fc1827d0141ebe24d9a
3,957
horologist
Apache License 2.0
fotoapparat/src/main/java/io/fotoapparat/view/CameraView.kt
dxn920128
116,450,773
true
{"Kotlin": 211232, "Java": 10076}
package io.fotoapparat.view import android.content.Context import android.graphics.SurfaceTexture import android.util.AttributeSet import android.view.TextureView import android.view.ViewGroup import android.widget.FrameLayout import io.fotoapparat.exception.camera.UnavailableSurfaceException import io.fotoapparat.parameter.Resolution import io.fotoapparat.parameter.ScaleType import java.util.concurrent.CountDownLatch /** * Uses [android.view.TextureView] as an output for camera. */ class CameraView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr), CameraRenderer { private val textureLatch = CountDownLatch(1) private val textureView = TextureView(context) private lateinit var previewResolution: Resolution private lateinit var scaleType: ScaleType private var surfaceTexture: SurfaceTexture? = textureView.tryInitialize() init { addView(textureView) } override fun onDetachedFromWindow() { super.onDetachedFromWindow() textureLatch.countDown() } override fun setScaleType(scaleType: ScaleType) { this.scaleType = scaleType } override fun setPreviewResolution(resolution: Resolution) { post { previewResolution = resolution requestLayout() } } override fun getPreview(): Preview { return surfaceTexture?.toPreview() ?: getPreviewAfterLatch() } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { if (isInEditMode || !::previewResolution.isInitialized || !::scaleType.isInitialized) { super.onLayout(changed, left, top, right, bottom) } else { layoutTextureView(previewResolution, scaleType) } } private fun getPreviewAfterLatch(): Preview.Texture { textureLatch.await() return surfaceTexture?.toPreview() ?: throw UnavailableSurfaceException() } private fun TextureView.tryInitialize() = surfaceTexture ?: null.also { surfaceTextureListener = TextureAvailabilityListener { [email protected] = this textureLatch.countDown() } } } private fun ViewGroup.layoutTextureView( previewResolution: Resolution?, scaleType: ScaleType? ) = when (scaleType) { ScaleType.CenterInside -> previewResolution?.centerInside(this) ScaleType.CenterCrop -> previewResolution?.centerCrop(this) else -> null } private fun Resolution.centerInside(view: ViewGroup) { val scale = Math.min( view.measuredWidth / width.toFloat(), view.measuredHeight / height.toFloat() ) val width = (width * scale).toInt() val height = (height * scale).toInt() val extraX = Math.max(0, view.measuredWidth - width) val extraY = Math.max(0, view.measuredHeight - height) view.getChildAt(0).layout( extraX / 2, extraY / 2, width + extraX / 2, height + extraY / 2 ) } private fun Resolution.centerCrop(view: ViewGroup) { val scale = Math.max( view.measuredWidth / width.toFloat(), view.measuredHeight / height.toFloat() ) val width = (width * scale).toInt() val height = (height * scale).toInt() val extraX = Math.max(0, width - view.measuredWidth) val extraY = Math.max(0, height - view.measuredHeight) view.getChildAt(0).layout( -extraX / 2, -extraY / 2, width - extraX / 2, height - extraY / 2 ) }
0
Kotlin
0
0
cd6cebdb6c92a899a722b701b55d3851da117df9
3,656
Fotoapparat
Apache License 2.0
app/src/main/java/com/example/androiddevchallenge/ui/widget/Controller.kt
wavever
344,865,614
false
null
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.androiddevchallenge.ui.widget import android.util.Log import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.Button import androidx.compose.material.ButtonDefaults import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import com.example.androiddevchallenge.R import com.example.androiddevchallenge.ui.timer.TimerViewModel @Composable fun Controller(viewModel: TimerViewModel) { val isStart by viewModel.isStart.collectAsState() val isPlaying by viewModel.isPlaying.collectAsState() Log.i("wavever_tag", "Controller(), isPlaying=$isPlaying") Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceEvenly) { // Replay Button( onClick = { viewModel.replay() }, shape = CircleShape, enabled = !isPlaying, colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.onPrimary) ) { Icon(painter = painterResource(id = R.drawable.ic_replay_24), contentDescription = null) } // Play & Pause Button( onClick = { viewModel.play() }, shape = CircleShape, colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.onPrimary) ) { Icon( painter = painterResource(if (isPlaying) R.drawable.ic_pause_24 else R.drawable.ic_play_24), contentDescription = null ) } // End Button( onClick = { viewModel.end() }, shape = CircleShape, enabled = isStart, colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.onPrimary) ) { Icon(painter = painterResource(id = R.drawable.ic_stop_24), contentDescription = null) } } }
0
Kotlin
0
1
33c471a37ef08cbc5250fb0a0b3d3dc77228427f
2,917
WaveTimer
Apache License 2.0
app/src/main/java/br/com/raveline/todo2021/presentation/ui/fragment/TodoListFragment.kt
ravelinejunior
408,579,990
false
{"Kotlin": 40747}
package br.com.raveline.todo2021.presentation.ui.fragment import android.app.AlertDialog import android.os.Bundle import android.util.Log import android.view.* import android.view.animation.OvershootInterpolator import androidx.activity.OnBackPressedCallback import androidx.appcompat.widget.SearchView import androidx.core.content.ContextCompat import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.ItemTouchHelper import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.StaggeredGridLayoutManager import br.com.raveline.todo2021.R import br.com.raveline.todo2021.databinding.FragmentTodoListBinding import br.com.raveline.todo2021.presentation.helpers.SwipeToDelete import br.com.raveline.todo2021.presentation.ui.adapter.ToDoItemsAdapter import br.com.raveline.todo2021.presentation.viewmodel.ToDoViewModel import br.com.raveline.todo2021.presentation.viewmodel.viewmodel_factory.ToDoViewModelFactory import br.com.raveline.todo2021.utils.observeOnce import com.google.android.material.snackbar.Snackbar import dagger.hilt.android.AndroidEntryPoint import jp.wasabeef.recyclerview.animators.LandingAnimator import kotlinx.coroutines.launch import javax.inject.Inject @AndroidEntryPoint class TodoListFragment : Fragment(), SearchView.OnQueryTextListener { private lateinit var mBinding: FragmentTodoListBinding @Inject lateinit var mFactory: ToDoViewModelFactory private lateinit var mViewModel: ToDoViewModel @Inject lateinit var mAdapter: ToDoItemsAdapter private var searchView: SearchView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mViewModel = ViewModelProvider(this, mFactory)[ToDoViewModel::class.java] } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment mBinding = FragmentTodoListBinding.inflate(inflater, container, false) mBinding.lifecycleOwner = this mBinding.mToDoViewModel = mViewModel //Set menu setHasOptionsMenu(true) return mBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupRecyclerView() getItemsFromDb() mBinding.floatingActionButton.setOnClickListener { findNavController().navigate(R.id.action_todoListFragment_to_addFragment) } backPressedSearchView() } private fun getItemsFromDb() { lifecycleScope.launchWhenStarted { mViewModel.toDoReadLiveData.observe(viewLifecycleOwner, { toDoItems -> try { mAdapter.setToDoItemData(toDoItems) } catch (e: Exception) { Log.i("TAGFRAGMENT", e.message.toString()) } }) } } private fun swipeToDelete(recyclerView: RecyclerView) { val swipeToDeleteCallback = object : SwipeToDelete() { override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) { lifecycleScope.launch { val itemToDelete = mAdapter.toDoItemsList[viewHolder.absoluteAdapterPosition] mViewModel.deleteData(itemToDelete) view?.let { Snackbar.make(it, "Tarefa deletada com sucesso!", Snackbar.LENGTH_LONG) .setAction("Desfazer") { lifecycleScope.launch { mViewModel.insertData(itemToDelete) } } .show() } } } } val itemTouchHelper = ItemTouchHelper(swipeToDeleteCallback) itemTouchHelper.attachToRecyclerView(recyclerView) } private fun setupRecyclerView() { mBinding.recyclerViewFragmentTodo.apply { layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL) setHasFixedSize(true) setItemViewCacheSize(25) itemAnimator = LandingAnimator(OvershootInterpolator(1f)).apply { addDuration = 300 moveDuration = 500 } adapter = mAdapter } swipeToDelete(mBinding.recyclerViewFragmentTodo) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.itemDeleteAllMenuTodoId -> displayDialogDeleteItems() R.id.menuItemPriorityHighMenuTodoId -> mViewModel.sortByHighPriorityLiveData.observe( viewLifecycleOwner, { items -> mAdapter.setToDoItemData(items) mBinding.recyclerViewFragmentTodo.scheduleLayoutAnimation() }) R.id.menuItemPriorityLowMenuTodoId -> mViewModel.sortByLowPriorityLiveData.observe( viewLifecycleOwner, { items -> mAdapter.setToDoItemData(items) mBinding.recyclerViewFragmentTodo.scheduleLayoutAnimation() }) } return super.onOptionsItemSelected(item) } private fun displayDialogDeleteItems() { val dialog = AlertDialog.Builder(requireContext()) dialog.setCancelable(false) .setTitle("Deletar Tarefas") .setMessage("Deseja deletar todas as tarefas cadastradas?") .setIcon( ContextCompat.getDrawable( requireContext(), R.drawable.ic_baseline_coronavirus_24 ) ) .setNegativeButton( "Não" ) { dialogInterface, _ -> dialogInterface.dismiss() } .setPositiveButton("Sim") { _, _ -> lifecycleScope.launch { mViewModel.deleteAllData() view?.let { Snackbar.make(it, "Tarefas deletadas com sucesso!", Snackbar.LENGTH_SHORT) .show() } } } val alertDialog = dialog.create() alertDialog.show() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.menu_todo_list, menu) val searchMenu = menu.findItem(R.id.itemSearchMenuTodoId) searchView = searchMenu.actionView as? SearchView searchView?.isSubmitButtonEnabled = true searchView?.queryHint = "Digite ao menos 3 caracteres" searchView?.onActionViewCollapsed() searchView?.isIconified = true searchView?.setOnQueryTextListener(this) } private fun backPressedSearchView() { if (searchView != null) { requireActivity().onBackPressedDispatcher.addCallback(requireActivity(), object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { searchView?.onActionViewCollapsed() searchView?.isIconified = true } }) } } override fun onQueryTextSubmit(query: String?): Boolean { if (query != null) { searchToDoItem(query) return true } else return false } override fun onQueryTextChange(newText: String?): Boolean { if (newText != null) { searchToDoItem(newText) } return true } private fun searchToDoItem(query: String) { val searchQuery = "%$query%" mViewModel.searchToDoItem(searchQuery).observeOnce(viewLifecycleOwner, { items -> items?.let { mAdapter.setToDoItemData(items) mBinding.recyclerViewFragmentTodo.scheduleLayoutAnimation() } }) } }
0
Kotlin
0
0
b80aa90af82507dcb75f632fb393d4b19acdd1bd
8,262
Todo2021
MIT License
library/core/src/main/java/com/michaelflisar/composechangelog/classes/ChangelogData.kt
MFlisar
709,648,030
false
{"Kotlin": 31130}
package com.michaelflisar.composechangelog.classes class ChangelogData( val releases: List<DataItemRelease> ) { fun isEmpty() = releases.sumOf { it.items.size } == 0 }
0
Kotlin
0
3
848855c03f0699cf093be16d9ad88449b63d1a06
176
ComposeChangelog
Apache License 2.0
src/test/kotlin/g2801_2900/s2851_string_transformation/SolutionTest.kt
javadev
190,711,550
false
{"Kotlin": 4909193, "TypeScript": 50446, "Python": 3646, "Shell": 994}
package g2801_2900.s2851_string_transformation import org.hamcrest.CoreMatchers.equalTo import org.hamcrest.MatcherAssert.assertThat import org.junit.jupiter.api.Test internal class SolutionTest { @Test fun numberOfWays() { assertThat(Solution().numberOfWays("abcd", "cdab", 2), equalTo(2)) } @Test fun numberOfWays2() { assertThat(Solution().numberOfWays("ababab", "ababab", 1), equalTo(2)) } }
0
Kotlin
20
43
62708bc4d70ca2bfb6942e4bbfb4c64641e598e8
439
LeetCode-in-Kotlin
MIT License
markdown/src/main/java/com/bohregard/markdown/model/MarkdownConfiguration.kt
bohregard
284,123,182
false
{"Kotlin": 177825}
package com.bohregard.markdown.model import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue class MarkdownConfiguration( /** * onClickEvent - Called when the ClickableText is tapped, but the annotation has no available * action to consume */ val onClickEvent: () -> Unit = {}, )
0
Kotlin
0
0
de7011b118bbd97ec9d5a7acd9bb66e0c02519cc
394
Compose-Companion
MIT License
core/src/test/kotlin/TestCache.kt
cs124-illinois
584,151,809
false
null
package edu.illinois.cs.cs125.jeed.core import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.ints.shouldBeGreaterThan import io.kotest.matchers.longs.shouldBeLessThan import io.kotest.matchers.should import io.kotest.matchers.shouldBe import io.kotest.matchers.shouldNot import io.kotest.matchers.shouldNotBe import io.kotest.matchers.types.shouldBeTypeOf import java.util.PropertyPermission class TestCache : StringSpec({ "should cache compiled simple snippets" { val first = Source.fromSnippet( "int weirdName = 8;", ).compile(CompilationArguments(useCache = true, waitForCache = true)) val second = Source.fromSnippet( "int weirdName = 8;", ).compile(CompilationArguments(useCache = true, waitForCache = true)) first.cached shouldBe false second.cached shouldBe true second.interval.length shouldBeLessThan first.interval.length first.compiled shouldBe second.compiled } "should calculate size for file managers" { val snippet = Source.fromSnippet( "int weirdName = 8;", ).compile(CompilationArguments(useCache = true, waitForCache = true)) snippet.fileManager.size shouldBeGreaterThan 0 } "cache should return different classloaders and file managers for identical code" { val first = Source.fromSnippet( "int weirdName = 9;", ).compile(CompilationArguments(useCache = true, waitForCache = true)) val second = Source.fromSnippet( "int weirdName = 9;", ).compile(CompilationArguments(useCache = true, waitForCache = true)) first.cached shouldBe false second.cached shouldBe true first.classLoader shouldNotBe second.classLoader } "should cache compiled sources" { val first = Source( mapOf( "Weird.java" to "public class Weird {}", "Name.java" to "public class Name {}", ), ).compile(CompilationArguments(useCache = true, waitForCache = true)) val second = Source( mapOf( "Name.java" to "public class Name {}", "Weird.java" to "public class Weird {}", ), ).compile(CompilationArguments(useCache = true, waitForCache = true)) first.cached shouldBe false second.cached shouldBe true second.interval.length shouldBeLessThan first.interval.length first.compiled shouldBe second.compiled } "should not cache compiled sources when told not to" { val first = Source( mapOf( "Testee.java" to "public class Testee {}", "Meee.java" to "public class Meee {}", ), ).compile(CompilationArguments(useCache = true, waitForCache = true)) val second = Source( mapOf( "Meee.java" to "public class Meee {}", "Testee.java" to "public class Testee {}", ), ).compile(CompilationArguments(useCache = false)) first.cached shouldBe false second.cached shouldBe false first.compiled shouldNotBe second.compiled } "!static initializers should still work while cached" { val source = Source( mapOf( "Main.java" to """ public class Main { private static int times = 0; static { times = 1; } public static void main() { times++; System.out.println(times); } }""".trim(), ), ) val first = source.compile(CompilationArguments(useCache = true, waitForCache = true)) val second = source.compile(CompilationArguments(useCache = true, waitForCache = true)) first.cached shouldBe false second.cached shouldBe true second.interval.length shouldBeLessThan first.interval.length first.compiled shouldBe second.compiled val firstResult = first.execute() firstResult should haveCompleted() firstResult should haveOutput("2") val secondResult = second.execute() secondResult should haveOutput("2") } "should cache compiled simple kotlin snippets" { val first = Source.fromSnippet( "val weirdKame = 8", SnippetArguments(fileType = Source.FileType.KOTLIN), ).kompile(KompilationArguments(useCache = true, waitForCache = true)) val second = Source.fromSnippet( "val weirdKame = 8", SnippetArguments(fileType = Source.FileType.KOTLIN), ).kompile(KompilationArguments(useCache = true, waitForCache = true)) first.cached shouldBe false second.cached shouldBe true second.interval.length shouldBeLessThan first.interval.length first.compiled shouldBe second.compiled } "should cache compiled kotlin sources" { val first = Source( mapOf( "Weird.kt" to "class Weird {}", "Name.kt" to "data class Name(val name: String)", ), ).kompile(KompilationArguments(useCache = true, waitForCache = true)) val second = Source( mapOf( "Name.kt" to "data class Name(val name: String)", "Weird.kt" to "class Weird {}", ), ).kompile(KompilationArguments(useCache = true, waitForCache = true)) first.cached shouldBe false second.cached shouldBe true second.interval.length shouldBeLessThan first.interval.length first.compiled shouldBe second.compiled } "should not cache compiled kotlin sources when told not to" { val first = Source( mapOf( "Testee.kt" to "class Testee {}", "Meee.kt" to "data class Meee(val whee: Int)", ), ).kompile(KompilationArguments(useCache = true, waitForCache = true)) val second = Source( mapOf( "Meee.kt" to "data class Meee(val whee: Int)", "Testee.kt" to "class Testee {}", ), ).kompile(KompilationArguments(useCache = false)) first.cached shouldBe false second.cached shouldBe false first.compiled shouldNotBe second.compiled } "permission requests should work in the presence of caching" { val source = Source.fromSnippet( """ System.out.println(System.getProperty("file.separator")); """.trim(), ) val compiled1 = source.compile() val compiled2 = source.compile() compiled1.execute( SourceExecutionArguments( permissions = setOf(PropertyPermission("*", "read")), ), ) val executionResult2 = compiled2.execute( SourceExecutionArguments( permissions = setOf(PropertyPermission("*", "read")), ), ) executionResult2.threw?.printStackTrace() executionResult2 should haveCompleted() executionResult2.permissionDenied shouldBe false } "bytecode rewriting should work in the presence of caching" { val source = Source.fromSnippet( """ try { System.out.println("Try"); Object o = null; o.toString(); } catch (NullPointerException e) { System.out.println("Catch"); } finally { System.out.println("Finally"); } """.trim(), ) source.compile() // .execute(SourceExecutionArguments(dryRun = true)) val executionResult = source.compile( CompilationArguments(useCache = true, waitForCache = true), ).execute( SourceExecutionArguments( classLoaderConfiguration = Sandbox.ClassLoaderConfiguration( unsafeExceptions = setOf( "java.lang.NullPointerException", ), ), ), ) executionResult shouldNot haveCompleted() executionResult shouldNot haveTimedOut() executionResult should haveOutput("Try") executionResult.threw.shouldBeTypeOf<NullPointerException>() } })
4
null
9
2
9e6089b726acafc33db3368f71693c3cd5b1b2bf
8,865
jeed
MIT License
jps/jps-builders/testSrc/org/jetbrains/jps/builders/rebuild/JpsRebuildTestCase.kt
brettwooldridge
47,746,540
true
{"Java": 153599793, "Python": 23161125, "Groovy": 2366582, "HTML": 1755624, "Kotlin": 1298262, "C": 214994, "C++": 190765, "Lex": 166321, "CSS": 164277, "JavaScript": 141020, "XSLT": 113040, "Jupyter Notebook": 92629, "NSIS": 88100, "Shell": 64460, "Batchfile": 63554, "TeX": 62325, "Groff": 35232, "Objective-C": 28878, "AMPL": 20665, "Gherkin": 14382, "Scala": 11698, "Protocol Buffer": 6570, "TypeScript": 6152, "J": 5050, "Makefile": 2352, "CoffeeScript": 1759, "C#": 1538, "Ruby": 1213, "AspectJ": 182, "Smalltalk": 64, "FLUX": 57, "Perl 6": 26, "Erlang": 10}
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.jps.builders.rebuild; import com.intellij.openapi.application.ex.PathManagerEx import com.intellij.openapi.util.io.FileUtil import com.intellij.util.io.TestFileSystemBuilder import com.intellij.util.io.TestFileSystemItem import org.jetbrains.jps.builders.CompileScopeTestBuilder import org.jetbrains.jps.builders.JpsBuildTestCase import org.jetbrains.jps.model.java.JpsJavaExtensionService import org.jetbrains.jps.util.JpsPathUtil import java.io.File import java.util.* /** * @author nik */ abstract class JpsRebuildTestCase: JpsBuildTestCase() { protected val myOutputDirectory: File by lazy { FileUtil.createTempDirectory("jps-build-output", "") } override fun setUp() { super.setUp() addJdk("1.6"); } fun doTest(projectPath: String, expectedOutput: TestFileSystemItem) { doTest(projectPath, LinkedHashMap<String, String>(), expectedOutput); } fun doTest(projectPath: String, pathVariables: Map<String, String>, expectedOutput: TestFileSystemItem) { loadAndRebuild(projectPath, pathVariables); assertOutput(myOutputDirectory.absolutePath, expectedOutput); } fun assertOutput(targetFolder: String, expectedOutput: TestFileSystemItem) { expectedOutput.assertDirectoryEqual(File(FileUtil.toSystemDependentName(targetFolder))); } fun loadAndRebuild(projectPath: String, pathVariables: Map<String, String>) { loadProject(projectPath, pathVariables); rebuild(); } fun rebuild() { JpsJavaExtensionService.getInstance()!!.getOrCreateProjectExtension(myProject).outputUrl = JpsPathUtil.pathToUrl(FileUtil.toSystemIndependentName(myOutputDirectory.absolutePath)); doBuild(CompileScopeTestBuilder.rebuild().allModules().allArtifacts()).assertSuccessful() } override fun getAdditionalPathVariables(): MutableMap<String, String> = hashMapOf("ARTIFACTS_OUT" to FileUtil.toSystemIndependentName(myOutputDirectory.absolutePath) + "/artifacts") override fun getTestDataRootPath(): String { return PathManagerEx.findFileUnderCommunityHome("jps/jps-builders/testData/output")!!.absolutePath; } } fun fs(init: TestFileSystemBuilderBuilder.() -> Unit): TestFileSystemItem { val builder = TestFileSystemBuilder.fs() TestFileSystemBuilderBuilder(builder).init() return builder.build() } class TestFileSystemBuilderBuilder(val current: TestFileSystemBuilder) { fun file(name: String) { current.file(name) } fun file(name: String, content: String) { current.file(name, content) } inline fun dir(name: String, init: TestFileSystemBuilderBuilder.() -> Unit) { val dir = current.dir(name) TestFileSystemBuilderBuilder(dir).init() dir.end() } inline fun archive(name: String, init: TestFileSystemBuilderBuilder.() -> Unit) { val dir = current.archive(name) TestFileSystemBuilderBuilder(dir).init() dir.end() } }
0
Java
1
3
b77e5c869d975f857e32349de5897186aafba6d1
3,465
intellij-community
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsbookavideolinkapi/service/emails/court/CourtEmailFactory.kt
ministryofjustice
789,053,149
false
{"Kotlin": 960555, "Dockerfile": 1492, "Shell": 1007}
package uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.emails import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.client.locationsinsideprison.model.Location import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.common.toHourMinuteStyle import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.config.Email import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.entity.BookingContact import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.entity.ContactType import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.entity.Prison import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.entity.PrisonAppointment import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.entity.VideoBooking import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.model.Prisoner import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.AmendedCourtBookingPrisonCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.AmendedCourtBookingPrisonNoCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.AmendedCourtBookingUserEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.BookingAction import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.CancelledCourtBookingPrisonCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.CancelledCourtBookingPrisonNoCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.CancelledCourtBookingUserEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.NewCourtBookingCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.NewCourtBookingPrisonCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.NewCourtBookingPrisonNoCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.NewCourtBookingUserEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.ReleasedCourtBookingCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.ReleasedCourtBookingPrisonCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.ReleasedCourtBookingPrisonNoCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.TransferredCourtBookingCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.TransferredCourtBookingPrisonCourtEmail import uk.gov.justice.digital.hmpps.hmppsbookavideolinkapi.service.TransferredCourtBookingPrisonNoCourtEmail object CourtEmailFactory { fun user( contact: BookingContact, prisoner: Prisoner, booking: VideoBooking, prison: Prison, main: PrisonAppointment, pre: PrisonAppointment?, post: PrisonAppointment?, locations: Map<String, Location>, action: BookingAction, ): Email? { booking.requireIsCourtBooking() require(contact.contactType == ContactType.USER) { "Incorrect contact type ${contact.contactType} for user email" } return when (action) { BookingAction.CREATE -> NewCourtBookingUserEmail( address = contact.email!!, userName = contact.name ?: "Book Video", prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, prisonerNumber = prisoner.prisonerNumber, court = booking.court!!.description, prison = prison.name, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) BookingAction.AMEND -> AmendedCourtBookingUserEmail( address = contact.email!!, userName = contact.name ?: "Book Video", prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, prisonerNumber = prisoner.prisonerNumber, court = booking.court!!.description, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) BookingAction.CANCEL -> CancelledCourtBookingUserEmail( address = contact.email!!, userName = contact.name ?: "Book Video", prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, prisonerNumber = prisoner.prisonerNumber, court = booking.court!!.description, prison = prison.name, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) else -> null } } fun court( contact: BookingContact, prisoner: Prisoner, booking: VideoBooking, prison: Prison, main: PrisonAppointment, pre: PrisonAppointment?, post: PrisonAppointment?, locations: Map<String, Location>, action: BookingAction, ): Email? { booking.requireIsCourtBooking() require(contact.contactType == ContactType.COURT) { "Incorrect contact type ${contact.contactType} for court email" } return when (action) { BookingAction.CREATE -> NewCourtBookingCourtEmail( address = contact.email!!, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, prisonerNumber = prisoner.prisonerNumber, court = booking.court!!.description, prison = prison.name, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) BookingAction.AMEND -> null // TODO: Inform court when the prison amends a booking BookingAction.CANCEL -> null // TODO: Inform court when the prison cancels a booking BookingAction.RELEASED -> ReleasedCourtBookingCourtEmail( address = contact.email!!, court = booking.court!!.description, prison = prison.name, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, dateOfBirth = prisoner.dateOfBirth, prisonerNumber = prisoner.prisonerNumber, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) BookingAction.TRANSFERRED -> TransferredCourtBookingCourtEmail( address = contact.email!!, court = booking.court!!.description, prison = prison.name, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, dateOfBirth = prisoner.dateOfBirth, prisonerNumber = prisoner.prisonerNumber, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } } fun prison( contact: BookingContact, prisoner: Prisoner, booking: VideoBooking, prison: Prison, contacts: Collection<BookingContact>, main: PrisonAppointment, pre: PrisonAppointment?, post: PrisonAppointment?, locations: Map<String, Location>, action: BookingAction, ): Email { booking.requireIsCourtBooking() require(contact.contactType == ContactType.PRISON) { "Incorrect contact type ${contact.contactType} for prison email" } val primaryCourtContact = contacts.primaryCourtContact() return when (action) { BookingAction.CREATE -> { if (primaryCourtContact != null) { NewCourtBookingPrisonCourtEmail( address = contact.email!!, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, prisonerNumber = prisoner.prisonerNumber, court = booking.court!!.description, courtEmailAddress = primaryCourtContact.email!!, prison = prison.name, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } else { NewCourtBookingPrisonNoCourtEmail( address = contact.email!!, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, prisonerNumber = prisoner.prisonerNumber, court = booking.court!!.description, prison = prison.name, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } } BookingAction.AMEND -> { if (primaryCourtContact != null) { AmendedCourtBookingPrisonCourtEmail( address = contact.email!!, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, prisonerNumber = prisoner.prisonerNumber, court = booking.court!!.description, courtEmailAddress = primaryCourtContact.email!!, prison = prison.name, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } else { AmendedCourtBookingPrisonNoCourtEmail( address = contact.email!!, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, prisonerNumber = prisoner.prisonerNumber, court = booking.court!!.description, prison = prison.name, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } } BookingAction.CANCEL -> { if (primaryCourtContact != null) { CancelledCourtBookingPrisonCourtEmail( address = contact.email!!, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, prisonerNumber = prisoner.prisonerNumber, court = booking.court!!.description, courtEmailAddress = primaryCourtContact.email!!, prison = prison.name, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } else { CancelledCourtBookingPrisonNoCourtEmail( address = contact.email!!, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, prisonerNumber = prisoner.prisonerNumber, court = booking.court!!.description, prison = prison.name, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } } BookingAction.RELEASED -> if (primaryCourtContact != null) { // Note: primary contact is only used to determine which template to use, it is not used in the template. ReleasedCourtBookingPrisonCourtEmail( address = contact.email!!, court = booking.court!!.description, prison = prison.name, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, dateOfBirth = prisoner.dateOfBirth, prisonerNumber = prisoner.prisonerNumber, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } else { ReleasedCourtBookingPrisonNoCourtEmail( address = contact.email!!, court = booking.court!!.description, prison = prison.name, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, dateOfBirth = prisoner.dateOfBirth, prisonerNumber = prisoner.prisonerNumber, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } BookingAction.TRANSFERRED -> // Note: primary contact is only used to determine which template to use, it is not used in the template. if (primaryCourtContact != null) { TransferredCourtBookingPrisonCourtEmail( address = contact.email!!, court = booking.court!!.description, prison = prison.name, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, dateOfBirth = prisoner.dateOfBirth, prisonerNumber = prisoner.prisonerNumber, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } else { TransferredCourtBookingPrisonNoCourtEmail( address = contact.email!!, court = booking.court!!.description, prison = prison.name, prisonerFirstName = prisoner.firstName, prisonerLastName = prisoner.lastName, dateOfBirth = prisoner.dateOfBirth, prisonerNumber = prisoner.prisonerNumber, date = main.appointmentDate, preAppointmentInfo = pre?.appointmentInformation(locations), mainAppointmentInfo = main.appointmentInformation(locations), postAppointmentInfo = post?.appointmentInformation(locations), comments = booking.comments, ) } } } private fun PrisonAppointment.appointmentInformation(locations: Map<String, Location>) = "${locations.room(prisonLocKey)} - ${startTime.toHourMinuteStyle()} to ${endTime.toHourMinuteStyle()}" private fun Map<String, Location>.room(key: String) = this[key]?.localName ?: "" private fun Collection<BookingContact>.primaryCourtContact() = singleOrNull { it.contactType == ContactType.COURT && it.primaryContact } private fun VideoBooking.requireIsCourtBooking() { require(isCourtBooking()) { "Booking ID $videoBookingId is not a court booking" } } }
1
Kotlin
0
0
f4fcbdf9874b4bdf48c0ac80f18a673b15c11e30
16,297
hmpps-book-a-video-link-api
MIT License
spring-social-samples/src/main/kotlin/io/t28/springframework/social/ApiExceptionHandler.kt
t28hub
280,412,223
false
null
/* * Copyright 2020 Tatsuya Maki * * 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 io.t28.springframework.social import io.t28.springframework.social.entity.ErrorResponse import io.t28.springframework.social.slideshare.api.InvalidParameterException import org.springframework.http.HttpStatus import org.springframework.http.HttpStatus.BAD_REQUEST import org.springframework.http.HttpStatus.FORBIDDEN import org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR import org.springframework.http.HttpStatus.NOT_FOUND import org.springframework.http.HttpStatus.TOO_MANY_REQUESTS import org.springframework.http.HttpStatus.UNAUTHORIZED import org.springframework.http.MediaType.APPLICATION_JSON import org.springframework.http.ResponseEntity import org.springframework.social.ApiException import org.springframework.social.InvalidAuthorizationException import org.springframework.social.OperationNotPermittedException import org.springframework.social.RateLimitExceededException import org.springframework.social.ResourceNotFoundException import org.springframework.web.bind.annotation.ControllerAdvice import org.springframework.web.bind.annotation.ExceptionHandler @ControllerAdvice object ApiExceptionHandler { @ExceptionHandler(InvalidParameterException::class) fun handle(exception: InvalidParameterException): ResponseEntity<ErrorResponse> { return handle(BAD_REQUEST, exception) } @ExceptionHandler(InvalidAuthorizationException::class) fun handle(exception: InvalidAuthorizationException): ResponseEntity<ErrorResponse> { return handle(UNAUTHORIZED, exception) } @ExceptionHandler(OperationNotPermittedException::class) fun handle(exception: OperationNotPermittedException): ResponseEntity<ErrorResponse> { return handle(FORBIDDEN, exception) } @ExceptionHandler(ResourceNotFoundException::class) fun handle(exception: ResourceNotFoundException): ResponseEntity<ErrorResponse> { return handle(NOT_FOUND, exception) } @ExceptionHandler(RateLimitExceededException::class) fun handle(exception: RateLimitExceededException): ResponseEntity<ErrorResponse> { return handle(TOO_MANY_REQUESTS, exception) } @ExceptionHandler(ApiException::class) fun handle(exception: ApiException): ResponseEntity<ErrorResponse> { return handle(BAD_REQUEST, exception) } @ExceptionHandler(RuntimeException::class) fun handle(exception: RuntimeException): ResponseEntity<ErrorResponse> { return handle(INTERNAL_SERVER_ERROR, exception) } private fun handle(status: HttpStatus, exception: Exception): ResponseEntity<ErrorResponse> { return ResponseEntity.status(status) .contentType(APPLICATION_JSON) .body(ErrorResponse("${exception.message}")) } }
1
Kotlin
0
0
a87b4991dbe121f84253825a5c5dc147603be998
3,341
spring-social-slideshare
Apache License 2.0
src/ii_collections/_17_MaxMin.kt
saraiva132
45,123,477
false
null
package ii_collections fun example4() { val max = listOf(1, 42, 4).max() val longestString = listOf("a", "b").maxBy { it.length } } fun Shop.getCustomerWithMaximumNumberOfOrders(): Customer? =this.customers.maxBy { it.orders.size} fun Customer.getMostExpensiveOrderedProduct(): Product? =this.orders.flatMap { it.products }.maxBy { it.price }
0
null
0
1
b4f9412001a648c6a795dad45e073cf0ac20c452
354
workshop-jb
MIT License
app/src/main/java/com/sumitt/findhome/api/ServiceInterface.kt
developer-sumit-thakur
176,067,069
false
null
package com.sumitt.findhome.api import com.sumitt.findhome.model.Homes import io.reactivex.Observable import retrofit2.http.GET import retrofit2.http.QueryMap interface ServiceInterface { @GET("/listings") fun getListing(@QueryMap param: Map<String, Int>): Observable<List<Homes>> }
0
Kotlin
0
0
d892289e138457502b3af5a1a9daa1fcbe3b1360
292
FindHome
MIT License
kdoctor/src/commonMain/kotlin/org/jetbrains/kotlin/doctor/printer/TextPainter.kt
Kotlin
448,964,171
false
{"Kotlin": 147695, "Batchfile": 2673}
package org.jetbrains.kotlin.doctor.printer object TextPainter { const val RESET = "\u001B[0m" const val RED = "\u001B[31m" const val GREEN = "\u001B[32m" const val YELLOW = "\u001B[33m" const val BOLD = "\u001B[1m" }
7
Kotlin
21
543
e07d16ac6b5a411e3212a7c7681fd64877095b36
239
kdoctor
Apache License 2.0
tmp/arrays/youTrackTests/6511.kt
DaniilStepanov
228,623,440
false
null
// Original bug: KT-22529 class LongBuilder { fun longLongLong(): LongBuilder = this fun longLongLong(a: Any): LongBuilder = this fun longLongLong(a: Any, b: Any): LongBuilder = this } private val longBuilder: LongBuilder get() = LongBuilder().longLongLong().longLongLong("Some other long string", "Long string").longLongLong(12).longLongLong(111111, "Some long string").longLongLong(1122323)
1
null
12
1
602285ec60b01eee473dcb0b08ce497b1c254983
411
bbfgradle
Apache License 2.0
app/src/main/java/com/jorgeav/laspeliculas/MainActivity.kt
jorgeavilae
270,651,213
false
null
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.jorgeav.laspeliculas import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.Menu import android.view.MenuItem import androidx.lifecycle.Observer import androidx.work.WorkManager import com.jorgeav.laspeliculas.background.RefreshListCoroutineWorker import com.jorgeav.laspeliculas.database.room.api.MovieDatabase import com.jorgeav.laspeliculas.ui.main.MainFragment import com.wajahatkarim3.roomexplorer.RoomExplorer import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) WorkManager.getInstance(applicationContext).getWorkInfosForUniqueWorkLiveData("RefreshListCoroutineWorker") .observe(this, Observer { workInfos -> if (workInfos.size > 0) { val workerResult = RefreshListCoroutineWorker.getOutputData(workInfos[0].outputData) Log.d("MainActivity", "onCreate: $workInfos") Log.d("MainActivity", "onCreate:Result.Data $workerResult") } }) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { if (BuildConfig.DEBUG) menu?.add(Menu.NONE, R.id.ddbb_content, Menu.NONE, R.string.ddbb_content) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.ddbb_content -> { RoomExplorer.show( this, MovieDatabase::class.java, MovieDatabase.databaseName) true } else -> super.onOptionsItemSelected(item) } } }
0
Kotlin
0
0
421e28c72aab6901cc1c81a1b9a4c1b06f14bf4b
2,470
LasPeliculas
Apache License 2.0
core/src/test/kotlin/UserTest.kt
HoshinoTented
152,888,590
false
null
import kotlinx.coroutines.runBlocking import org.hoshino9.luogu.test.BaseTest import org.hoshino9.luogu.test.printAllMember import org.hoshino9.luogu.user.currentUser import org.hoshino9.luogu.user.doFollow import org.junit.Test class UserTest : BaseTest() { @Test fun user() { runBlocking { client.currentUser?.run { printAllMember() followers().printAllMember() followings().printAllMember() } } } }
12
Kotlin
0
34
28523e9057462aca5ac2eb0af375fb220069dbe8
427
LuoGuAPI
MIT License
tasks/common/src/commonMain/kotlin/models/DraftInfoPack.kt
InsanusMokrassar
606,391,766
false
{"Kotlin": 386449, "Shell": 1463, "HTML": 692, "Dockerfile": 224}
package center.sciprog.tasks_bot.tasks.common.models import center.sciprog.tasks_bot.common.utils.getChatLanguage import center.sciprog.tasks_bot.tasks.common.models.tasks.TaskDraft import center.sciprog.tasks_bot.teachers.common.models.RegisteredTeacher import center.sciprog.tasks_bot.teachers.common.models.TeacherId import center.sciprog.tasks_bot.teachers.common.repos.ReadTeachersRepo import center.sciprog.tasks_bot.users.common.models.RegisteredUser import center.sciprog.tasks_bot.users.common.repos.ReadUsersRepo import dev.inmo.micro_utils.language_codes.IetfLang import dev.inmo.micro_utils.repos.KeyValueRepo import dev.inmo.tgbotapi.types.IdChatIdentifier import dev.inmo.tgbotapi.types.UserId data class DraftInfoPack( val ietfLanguageCode: IetfLang, val user: RegisteredUser, val teacher: RegisteredTeacher, val draft: TaskDraft? ) suspend fun DraftInfoPack( userId: UserId, languagesRepo: KeyValueRepo<IdChatIdentifier, IetfLang>, usersRepo: ReadUsersRepo, teachersRepo: ReadTeachersRepo, draftsRepo: KeyValueRepo<TeacherId, TaskDraft> ): DraftInfoPack? { val user = usersRepo.getById(userId) ?: return null val teacher = teachersRepo.getById(user.id) ?: return null return DraftInfoPack( languagesRepo.getChatLanguage(userId), user, teacher, draftsRepo.get(teacher.id) ) }
1
Kotlin
2
2
2b570e7ab96bec4c2f015e6529e44cb6ea91f9bf
1,379
SchoolTasksBot
MIT License
defitrack-rest/defitrack-protocol-services/defitrack-adamant/src/main/java/io/defitrack/AdamantApplication.kt
decentri-fi
426,174,152
false
null
package io.defitrack import io.defitrack.protocol.Company import io.defitrack.protocol.Protocol import org.springframework.boot.runApplication class AdamantApplication : ProtocolApplication() { override fun getCompany(): Company { return Company.ADAMANT } } fun main(args: Array<String>) { runApplication<AdamantApplication>(*args) }
17
Kotlin
6
9
f7c65aa58bec3268101d90fc538c3f8bd0c29093
357
defi-hub
MIT License
krossbow-websocket-core/src/jvmMain/kotlin/org/hildan/krossbow/websocket/DefaultJvmClient.kt
jatsqi
359,865,761
true
{"Kotlin": 294019}
package org.hildan.krossbow.websocket import org.hildan.krossbow.websocket.jdk.Jdk11WebSocketClient actual fun defaultWebSocketClient(): WebSocketClient = Jdk11WebSocketClient()
0
null
0
0
538ab99a87573b2981070c4e1374b16393cb1502
180
krossbow
MIT License
sample/shared/src/commonMain/kotlin/com/test/kostra/appsample/SampleScreen.kt
jbruchanov
670,094,402
false
null
package com.test.kostra.appsample import androidx.compose.animation.animateContentSize import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.horizontalScroll 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.padding import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.Button import androidx.compose.material.Checkbox import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.material.minimumInteractiveComponentSize import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState 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.unit.dp import com.jibru.kostra.Dpi import com.jibru.kostra.Locale import com.jibru.kostra.Qualifiers import com.jibru.kostra.compose.LocalQualifiers import com.sample.app.K import com.sample.app.assetPath import com.sample.app.painterResource import com.sample.app.pluralStringResource import com.sample.app.stringResource private object SampleScreenDefaults { val spacing = 8.dp } @Composable fun SampleScreen() = with(SampleScreenDefaults) { Box( modifier = Modifier .padding(spacing) .verticalScroll(rememberScrollState()) .horizontalScroll(rememberScrollState()) ) { Column( verticalArrangement = Arrangement.spacedBy(spacing), modifier = Modifier .padding(spacing) .animateContentSize() .wrapContentSize() ) { val locales = remember { listOf(java.util.Locale.getDefault(), java.util.Locale.ENGLISH, java.util.Locale("cs")) } var localeIndex by remember { mutableStateOf(0) } val locale by derivedStateOf { Locale(locales[localeIndex].toLanguageTag()) } val defaultQualifiers = LocalQualifiers.current val dpis = remember { listOf(null, Dpi.Undefined, Dpi.XXXHDPI) } var dpiIndex by remember { mutableStateOf(0) } val dpi by derivedStateOf { dpis[dpiIndex] ?: defaultQualifiers.dpi } val qualifiers by derivedStateOf { Qualifiers(locale, dpi) } CompositionLocalProvider(LocalQualifiers provides qualifiers) { Text("Locale") Row( horizontalArrangement = Arrangement.spacedBy(spacing), verticalAlignment = Alignment.CenterVertically ) { locales.forEachIndexed { index, locale -> TextCheckBox( onCheckedChange = { if (it) localeIndex = index else Unit }, checked = index == localeIndex, text = locale.toLanguageTag() ) } } Text("DPI") Row( horizontalArrangement = Arrangement.spacedBy(spacing), verticalAlignment = Alignment.CenterVertically ) { dpis.forEachIndexed { index, dpi -> TextCheckBox( onCheckedChange = { if (it) dpiIndex = index else Unit }, checked = index == dpiIndex, text = (dpi ?: defaultQualifiers.dpi).name ) } } Row(horizontalArrangement = Arrangement.spacedBy(spacing)) { Button(onClick = {}) { Text(stringResource(K.string.action_add)) } Button(onClick = {}) { Text(stringResource(K.string.action_remove)) } Button(onClick = {}) { Text(stringResource(K.string.color)) } } Text(assetPath(K.drawable.capital_city)) Image(painterResource(K.drawable.capital_city), contentDescription = null) var quantity by remember { mutableStateOf("1") } TextField( value = quantity, label = { Text(stringResource(K.string.plurals)) }, placeholder = { Text(stringResource(K.string.type_quantity)) }, onValueChange = { quantity = it.takeIf { it.isEmpty() || it.toFloatOrNull() != null } ?: quantity } ) quantity.toFloatOrNull()?.let { Text(pluralStringResource(K.plural.bug_x, it, quantity)) } } } } } @Composable private fun TextCheckBox(onCheckedChange: (Boolean) -> Unit, checked: Boolean, text: String, modifier: Modifier = Modifier) = with(SampleScreenDefaults) { @Suppress("NAME_SHADOWING") val checked by rememberUpdatedState(checked) Row( horizontalArrangement = Arrangement.spacedBy(spacing), verticalAlignment = Alignment.CenterVertically, modifier = modifier .minimumInteractiveComponentSize() .clip(RoundedCornerShape(spacing)) .clickable { onCheckedChange(!checked) } .padding(end = spacing) ) { Checkbox(checked = checked, onCheckedChange = onCheckedChange) Text(text) } }
0
Kotlin
0
0
0ffa01cce91857d2eafbf6cdcf86366d2d7cb220
5,972
kostra
Apache License 2.0
app/src/main/java/io/aman/newseveryday/data/ArticleDatabase.kt
amntoppo
519,863,961
false
{"Kotlin": 21905}
package io.aman.newseveryday.data import androidx.room.Database import androidx.room.RoomDatabase import io.aman.newseveryday.model.Article @Database(entities = [Article::class], version = 1) abstract class ArticleDatabase: RoomDatabase() { abstract fun articleDao(): ArticleDao }
0
Kotlin
0
1
78c787f9d6586e0ef977b41dd7c0085ddc524abc
287
News-Everyday
Apache License 2.0
packages/test-base/src/nativeDarwinTest/kotlin/io/realm/kotlin/test/darwin/CoroutineTests.kt
realm
235,075,339
false
{"Kotlin": 4564631, "C++": 126122, "SWIG": 26070, "Shell": 23822, "C": 5126, "CMake": 2858, "Ruby": 1586, "Java": 1470}
/* * Copyright 2021 Realm Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.realm.kotlin.test import io.realm.kotlin.internal.platform.singleThreadDispatcher import io.realm.kotlin.test.platform.NsQueueDispatcher import io.realm.kotlin.test.platform.PlatformUtils import io.realm.kotlin.test.util.Utils.printlntid import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.newSingleThreadContext import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runTest import platform.CoreFoundation.CFRunLoopRun import platform.Foundation.NSNumber import platform.darwin.DISPATCH_QUEUE_PRIORITY_BACKGROUND import platform.darwin.dispatch_get_global_queue import kotlin.test.Ignore import kotlin.test.Test import kotlin.test.assertEquals /** * Various coroutine tests to track if basic dispatching, etc. works. * * FIXME Remove when we have an overview of the constraints. */ class CoroutineTests { @Test fun dispatchBetweenThreads() = runTest { val dispatcher1 = newSingleThreadContext("test-dispatcher-1") val dispatcher2 = newSingleThreadContext("test-disptacher-2") val tid2 = runBlocking(dispatcher2) { PlatformUtils.threadId() } runBlocking(dispatcher1) { val currentTid = PlatformUtils.threadId() CoroutineScope(Dispatchers.Unconfined).async { assertEquals(currentTid, PlatformUtils.threadId()) }.await() runBlocking(dispatcher2) { assertEquals(tid2, PlatformUtils.threadId()) } } } // Both with and without native-mt: // - NSQueueDispatcher tries to access non-shared block and scheduled lambda // - Freezing block and lambda yields InvalidMutabilityException as block is tranformed into // continuation that is supposed to be modified on both threads @Test @Ignore fun dispatchQueueScheduler() { val queue = dispatch_get_global_queue(NSNumber(DISPATCH_QUEUE_PRIORITY_BACKGROUND).integerValue, 0) val dispatcher = NsQueueDispatcher(queue) CoroutineScope(dispatcher).async { printlntid("async") } CFRunLoopRun() } @OptIn(ExperimentalStdlibApi::class) @Test fun currentDispatcher() { val dispatcher = singleThreadDispatcher("background") val tid = runBlocking(dispatcher) { PlatformUtils.threadId() } val currentDispatcher = runBlocking(dispatcher) { coroutineContext[CoroutineDispatcher.Key] } runBlocking(currentDispatcher!!) { assertEquals(tid, PlatformUtils.threadId()) } } }
243
Kotlin
57
942
50797be5a0dfde9b4eb5c00a528c04b49d5706d6
3,289
realm-kotlin
Apache License 2.0
compiler/testData/diagnostics/tests/testWithModifiedMockJdk/notConsideredMethod.kt
JetBrains
3,432,266
false
null
// !JDK_KIND: MODIFIED_MOCK_JDK // !CHECK_TYPE interface A : MutableCollection<String> { // Override of deprecated function could be marked as deprecated too override fun <!OVERRIDE_DEPRECATION!>nonExistingMethod<!>(x: String) = "" } fun foo(x: MutableCollection<Int>, y: Collection<String>, z: A) { x.<!DEPRECATION!>nonExistingMethod<!>(1).checkType { _<String>() } y.<!DEPRECATION!>nonExistingMethod<!>("") z.nonExistingMethod("") }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
457
kotlin
Apache License 2.0
projects/approved-premises-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/service/StaffService.kt
ministryofjustice
500,855,647
false
{"Kotlin": 4329094, "HTML": 70066, "D2": 44286, "Ruby": 25921, "Shell": 19356, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2447, "JavaScript": 1372, "Python": 268}
package uk.gov.justice.digital.hmpps.service import org.springframework.data.domain.Pageable import org.springframework.data.web.PagedModel import org.springframework.ldap.core.LdapTemplate import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import uk.gov.justice.digital.hmpps.exception.NotFoundException import uk.gov.justice.digital.hmpps.integrations.delius.approvedpremises.ApprovedPremisesRepository import uk.gov.justice.digital.hmpps.integrations.delius.staff.LdapUser import uk.gov.justice.digital.hmpps.integrations.delius.staff.Staff import uk.gov.justice.digital.hmpps.integrations.delius.staff.StaffRepository import uk.gov.justice.digital.hmpps.ldap.findByUsername import uk.gov.justice.digital.hmpps.model.* @Service class StaffService( private val approvedPremisesRepository: ApprovedPremisesRepository, private val staffRepository: StaffRepository, private val ldapTemplate: LdapTemplate ) { @Transactional fun getStaffInApprovedPremises( approvedPremisesCode: String, keyWorkersOnly: Boolean, pageable: Pageable ): PagedModel<StaffResponse> { if (!approvedPremisesRepository.existsByCodeCode(approvedPremisesCode)) { throw NotFoundException("Approved Premises", "code", approvedPremisesCode) } return if (keyWorkersOnly) { staffRepository.findKeyWorkersLinkedToApprovedPremises(approvedPremisesCode, pageable).map { it.toResponse(approvedPremisesCode) } } else { staffRepository.findAllStaffLinkedToApprovedPremisesTeam(approvedPremisesCode, pageable).map { it.toResponse(approvedPremisesCode) } }.let { PagedModel(it) } } fun getStaffByUsername(username: String) = staffRepository.findByUsername(username)?.toStaffDetail(ldapTemplate.findByUsername<LdapUser>(username)) ?: throw NotFoundException( "Staff", "username", username ) fun Staff.toResponse(approvedPremisesCode: String) = StaffResponse( code = code, name = PersonName(forename, surname, middleName), grade = grade?.let { grade -> StaffGrade(grade.code, grade.description) }, keyWorker = approvedPremises.map { ap -> ap.code.code }.contains(approvedPremisesCode) ) fun Staff.toStaffDetail(ldapUser: LdapUser?) = StaffDetail( telephoneNumber = ldapUser?.telephoneNumber, email = ldapUser?.email, teams = teams.map { Team( code = it.code, name = it.description, borough = Borough(code = it.district.borough.code, description = it.district.borough.description), ldu = Ldu(code = it.district.code, name = it.district.description), startDate = it.startDate, endDate = it.endDate ) }, username = user!!.username, name = PersonName(forename, surname, middleName), code = code, probationArea = ProbationArea( code = probationArea.code, description = probationArea.description ), active = isActive(), staffIdentifier = id ) }
7
Kotlin
0
2
190088e2e7f6956c243ad859daad5eb4895fd51e
3,308
hmpps-probation-integration-services
MIT License
src/main/kotlin/MyRegex.kt
aestepanova
451,883,055
false
{"Kotlin": 42196}
class MyRegex (str: String){ var tree = SyntaxTree() var automataDFA = mutableListOf<DFA>() var automataNFA = NFA() var string = str constructor(dfa: MutableList<DFA>) : this("") { automataDFA = dfa } fun makeTree(){ tree = SyntaxTree(string) tree.printTree(tree.rootNode, 4) } fun makeNFA(): NFA{ tree.createNFA() automataNFA = tree.rootNode.startNode return automataNFA } fun printNFA(){ tree.printNFA(node = tree.nodes[0], tab = 0) } fun makeDFA(){ automataDFA = DFA().createDFA(tree.nodes[0], tree.language, 0) } fun printDFA() = DFA().printDFA(automataDFA) fun makeMDFA(){ val mdfa = DFA().minimize(automataDFA, tree.language) DFA().printDFA(mdfa) } }
0
Kotlin
0
0
bdd16c8cec8cfd7ad0e1d3739da8c5edb29eafa2
809
RegexLib
MIT License
async/src/main/kotlin/com/mcxiaoke/koi/async/Async.kt
mcxiaoke
50,421,113
false
null
package com.mcxiaoke.koi.async import android.content.Context import java.lang.ref.WeakReference import java.util.concurrent.ExecutorService import java.util.concurrent.Future import android.support.v4.app.Fragment as SupportFragment /** * Author: mcxiaoke * Date: 2016/1/29 8:23 */ //*******************************************************************// // Extension Async Functions With Context Check //*******************************************************************// inline fun <T, R> T.asyncSafe( crossinline action: WeakContext<T>.() -> R): Future<Unit> { return asyncSafe(CoreExecutor.executor, action) } inline fun <T, R> T.asyncSafe( executor: ExecutorService, crossinline action: WeakContext<T>.() -> R): Future<Unit> { val weakCtx = WeakContext(WeakReference(this)) return executor.submit<Unit> { weakCtx.safe { action() } } } fun <T, R> T.asyncSafe( action: WeakContext<T>.() -> R, callback: (result: R?, error: Throwable?) -> Unit): Future<Unit> { return asyncSafe(CoreExecutor.executor, action, callback) } fun <T, R> T.asyncSafe( executor: ExecutorService, action: WeakContext<T>.() -> R, callback: (result: R?, error: Throwable?) -> Unit): Future<Unit> { val weakCtx = WeakContext(WeakReference(this)) return executor.submit<Unit> { weakCtx.safe { try { val ret = action() mainThreadSafe { callback(ret, null) } } catch(ex: Exception) { mainThreadSafe { callback(null, ex) } } } } } inline fun <T, R> T.asyncSafe( crossinline action: WeakContext<T>.() -> R, crossinline success: (result: R) -> Unit, crossinline failure: (error: Throwable) -> Unit): Future<Unit> { return asyncSafe(CoreExecutor.executor, action, success, failure) } inline fun <T, R> T.asyncSafe( executor: ExecutorService, crossinline action: WeakContext<T>.() -> R, crossinline success: (result: R) -> Unit, crossinline failure: (error: Throwable) -> Unit): Future<Unit> { val weakCtx = WeakContext(WeakReference(this)) return executor.submit<Unit> { weakCtx.safe { try { val ret = action() mainThreadSafe { success(ret) } } catch(ex: Exception) { mainThreadSafe { failure(ex) } } } } } //*******************************************************************// // Async Functions Nullable With Context Check //*******************************************************************// inline fun <T, R> T.asyncSafe2( crossinline action: WeakContext<T>.() -> R?, noinline success: ((result: R?) -> Unit)?, noinline failure: ((error: Throwable?) -> Unit)?): Future<Unit> { return asyncSafe2(CoreExecutor.executor, action, success, failure) } inline fun <T, R> T.asyncSafe2( executor: ExecutorService, crossinline action: WeakContext<T>.() -> R?, noinline success: ((result: R?) -> Unit)?, noinline failure: ((error: Throwable?) -> Unit)?): Future<Unit> { val weakCtx = WeakContext(WeakReference(this)) return executor.submit<Unit> { weakCtx.safe { try { val ret = action() mainThreadSafe { success?.invoke(ret) } } catch(e: Exception) { mainThreadSafe { failure?.invoke(e) } } } } } //*******************************************************************// // Extension Async Functions With Delay //*******************************************************************// fun <T, R> T.asyncDelay( delayInMillis: Long, action: WeakContext<T>.() -> R): Unit { asyncDelay(CoreExecutor.executor, delayInMillis, action) } fun <T, R> T.asyncDelay( executor: ExecutorService, delayInMillis: Long, action: WeakContext<T>.() -> R): Unit { val weakCtx = WeakContext(WeakReference(this)) CoreExecutor.mainHandler.postDelayed({ executor.submit<Unit> { weakCtx.safe { action() } } }, delayInMillis) } inline fun <T, R> T.asyncDelay( delayInMillis: Long, crossinline action: WeakContext<T>.() -> R?, crossinline callback: (result: R?) -> Unit): Unit { return asyncDelay(CoreExecutor.executor, delayInMillis, action, callback) } inline fun <T, R> T.asyncDelay( executor: ExecutorService, delayInMillis: Long, crossinline action: WeakContext<T>.() -> R?, crossinline callback: (result: R?) -> Unit): Unit { val weakCtx = WeakContext(WeakReference(this)) CoreExecutor.mainHandler.postDelayed({ executor.submit<Unit> { weakCtx.safe { val ret = action() mainThreadSafe { callback(ret) } } } }, delayInMillis) } inline fun <T, R> T.asyncDelay( delayInMillis: Long, crossinline action: WeakContext<T>.() -> R?, crossinline success: (result: R?) -> Unit, crossinline failure: (error: Throwable) -> Unit): Unit { return asyncDelay(CoreExecutor.executor, delayInMillis, action, success, failure) } inline fun <T, R> T.asyncDelay( executor: ExecutorService, delayInMillis: Long, crossinline action: WeakContext<T>.() -> R?, crossinline success: (result: R?) -> Unit, crossinline failure: (error: Throwable) -> Unit): Unit { val weakCtx = WeakContext(WeakReference(this)) CoreExecutor.mainHandler.postDelayed({ executor.submit<Unit> { weakCtx.safe { try { val ret = action() mainThreadSafe { success(ret) } } catch(e: Exception) { mainThreadSafe { failure(e) } } } } }, delayInMillis) } //*******************************************************************// // Extension Async Functions Without Context Check //*******************************************************************// fun <T, R> T.asyncUnsafe( action: () -> R?): Future<R> { return asyncUnsafe(CoreExecutor.executor, action) } fun <T, R> T.asyncUnsafe( executor: ExecutorService, action: () -> R?): Future<R> { return executor.submit<R>(action) } inline fun <T, R> T.asyncUnsafe( crossinline action: () -> R?, crossinline callback: (result: R?, error: Throwable?) -> Unit): Future<Unit> { return asyncUnsafe(CoreExecutor.executor, action, callback) } inline fun <T, R> T.asyncUnsafe( executor: ExecutorService, crossinline action: () -> R?, crossinline callback: (result: R?, error: Throwable?) -> Unit): Future<Unit> { return executor.submit<Unit> { try { val ret = action() mainThread { callback(ret, null) } } catch(ex: Exception) { mainThread { callback(null, ex) } } } } inline fun <T, R> T.asyncUnsafe( crossinline action: () -> R?, crossinline success: (result: R?) -> Unit, crossinline failure: (error: Throwable) -> Unit): Future<Unit> { return asyncUnsafe(CoreExecutor.executor, action, success, failure) } inline fun <T, R> T.asyncUnsafe( executor: ExecutorService, crossinline action: () -> R?, crossinline success: (result: R?) -> Unit, crossinline failure: (error: Throwable) -> Unit): Future<Unit> { return executor.submit<Unit> { try { val ret = action() mainThread { success(ret) } } catch(e: Exception) { mainThread { failure(e) } } } }
4
Kotlin
54
519
58e548a531e1f66ce4bd8535058cf8d4173c5709
7,791
kotlin-koi
Apache License 2.0
app/src/main/java/com/spiderbiggen/manga/MainActivity.kt
spiderbiggen
624,650,535
false
{"Kotlin": 129647}
package com.spiderbiggen.manga import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.core.view.WindowCompat import coil3.SingletonImageLoader import coil3.disk.DiskCache import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.ktx.Firebase import com.spiderbiggen.manga.presentation.ui.main.MainContent import dagger.hilt.android.AndroidEntryPoint import java.io.File import okio.Path.Companion.toOkioPath @AndroidEntryPoint class MainActivity : ComponentActivity() { private lateinit var analytics: FirebaseAnalytics private val coverDiskCache: DiskCache get() = DiskCache.Builder().directory(File(cacheDir, "covers").toOkioPath()).build() private val chapterDiskCache: DiskCache get() = DiskCache.Builder().directory(File(cacheDir, "chapters").toOkioPath()).build() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Obtain the FirebaseAnalytics instance. analytics = Firebase.analytics WindowCompat.setDecorFitsSystemWindows(window, false) val coverImageLoader = SingletonImageLoader.get(this).newBuilder() .diskCache(coverDiskCache).build() val chapterImageLoader = SingletonImageLoader.get(this).newBuilder() .diskCache(chapterDiskCache).build() enableEdgeToEdge() setContent { MainContent( coverImageLoader = coverImageLoader, chapterImageLoader = chapterImageLoader, ) } } }
1
Kotlin
0
0
9b4eb12861a672f55264d72919da293d39ad5d03
1,709
manhwa-reader
MIT License
ok-propertysale-be-repository-in-memory/src/main/kotlin/ru/otus/otuskotlin/propertysale/backend/repository/inmemory/flat/FlatRepoInMemory.kt
otuskotlin
330,109,804
false
null
package ru.otus.otuskotlin.propertysale.backend.repository.inmemory.flat import org.cache2k.Cache import org.cache2k.Cache2kBuilder import ru.otus.otuskotlin.propertysale.be.common.context.BePsContext import ru.otus.otuskotlin.propertysale.be.common.exceptions.PsRepoIndexException import ru.otus.otuskotlin.propertysale.be.common.exceptions.PsRepoNotFoundException import ru.otus.otuskotlin.propertysale.be.common.exceptions.PsRepoWrongIdException import ru.otus.otuskotlin.propertysale.be.common.models.flat.BePsFlatIdModel import ru.otus.otuskotlin.propertysale.be.common.models.flat.BePsFlatModel import ru.otus.otuskotlin.propertysale.be.common.repositories.IFlatRepository import java.util.* import java.util.concurrent.TimeUnit import kotlin.time.Duration import kotlin.time.DurationUnit import kotlin.time.ExperimentalTime import kotlin.time.toDuration class FlatRepoInMemory @OptIn(ExperimentalTime::class) constructor( ttl: Duration = 30.toDuration(DurationUnit.SECONDS), initObjects: Collection<BePsFlatModel> = emptyList() ) : IFlatRepository { @OptIn(ExperimentalTime::class) private var cache: Cache<String, FlatInMemoryDto> = object : Cache2kBuilder<String, FlatInMemoryDto>() {} .expireAfterWrite(ttl.toLongMilliseconds(), TimeUnit.MILLISECONDS) // expire/refresh after 5 minutes .suppressExceptions(false) .build() .also { cache -> initObjects.forEach { cache.put(it.id.id, FlatInMemoryDto.of(it)) } } override suspend fun read(context: BePsContext): BePsFlatModel { val id = context.requestFlatId if (id == BePsFlatIdModel.NONE) throw PsRepoWrongIdException(id.id) val model = cache.get(id.id)?.toModel() ?: throw PsRepoNotFoundException(id.id) context.responseFlat = model return model } override suspend fun create(context: BePsContext): BePsFlatModel { val dto = FlatInMemoryDto.of(context.requestFlat, UUID.randomUUID().toString()) val model = save(dto).toModel() context.responseFlat = model return model } override suspend fun update(context: BePsContext): BePsFlatModel { if (context.requestFlat.id == BePsFlatIdModel.NONE) throw PsRepoWrongIdException(context.requestFlat.id.id) val model = save(FlatInMemoryDto.of(context.requestFlat)).toModel() context.responseFlat = model return model } override suspend fun delete(context: BePsContext): BePsFlatModel { val id = context.requestFlatId if (id == BePsFlatIdModel.NONE) throw PsRepoWrongIdException(id.id) val model = cache.peekAndRemove(id.id)?.toModel() ?: throw PsRepoNotFoundException(id.id) context.responseFlat = model return model } override suspend fun list(context: BePsContext): Collection<BePsFlatModel> { val textFilter = context.flatFilter.text if (textFilter.length < 3) throw PsRepoIndexException(textFilter) val records = cache.asMap().filterValues { it.name?.contains(textFilter, true) ?: false || if (context.flatFilter.includeDescription) { it.description?.contains(textFilter, true) ?: false } else false }.values if (records.count() <= context.flatFilter.offset) throw PsRepoIndexException(textFilter) val list = records.toList() .subList( context.flatFilter.offset, if (records.count() >= context.flatFilter.offset + context.flatFilter.count) context.flatFilter.offset + context.flatFilter.count else records.count() ).map { it.toModel() } context.responseFlats = list.toMutableList() context.pageCount = list.count().takeIf { it != 0 } ?.let { (records.count().toDouble() / it + 0.5).toInt() } ?: Int.MIN_VALUE return list } private suspend fun save(dto: FlatInMemoryDto): FlatInMemoryDto { cache.put(dto.id, dto) return cache.get(dto.id) } }
0
Kotlin
0
1
ed9a38627e64ed36131280ca7449547ba1d06829
4,095
otuskotlin-202012-propertysale-ks
MIT License
appactions/interaction/interaction-capabilities-core/src/main/java/androidx/appactions/interaction/capabilities/serializers/properties/StartTimeTypeSpec.kt
androidx
256,589,781
false
{"Kotlin": 102962181, "Java": 64545272, "C++": 9133578, "AIDL": 614395, "Python": 310931, "Shell": 188067, "TypeScript": 40586, "HTML": 35176, "Groovy": 27482, "ANTLR": 26700, "Svelte": 20307, "CMake": 18011, "C": 16982, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2023 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.appactions.interaction.capabilities.serializers.properties import androidx.appactions.builtintypes.properties.EndDate import androidx.appactions.interaction.capabilities.core.impl.converters.TypeSpec import androidx.appactions.interaction.capabilities.core.impl.converters.UnionTypeSpec val END_DATE_TYPE_SPEC = UnionTypeSpec.Builder<EndDate>().bindMemberType( memberGetter = EndDate::asDate, ctor = { EndDate(it) }, typeSpec = TypeSpec.LOCAL_DATE_TYPE_SPEC ).build()
24
Kotlin
930
5,073
559b440b4b57a373b305bfc0fe0f284a9f68a1c1
1,110
androidx
Apache License 2.0
tokenx-validation/src/main/kotlin/no/nav/tms/token/support/tokenx/validation/install/TokenXInstaller.kt
navikt
339,078,199
false
{"Kotlin": 158627}
package no.nav.tms.token.support.tokenx.validation.install import io.ktor.server.auth.* import no.nav.tms.token.support.tokenx.validation.LevelOfAssurance import no.nav.tms.token.support.tokenx.validation.TokenXAuthenticatorConfig internal object TokenXInstaller { fun AuthenticationConfig.performTokenXAuthenticatorInstallation( config: TokenXAuthenticatorConfig ) { val tokenVerifier = initializeTokenVerifier( minLevelOfAssurance = getMinLoa(config.levelOfAssurance) ) registerTokenXValidatorProvider( authenticatorName = getAuthenticatorName(config), tokenVerifier = tokenVerifier ) } private fun getAuthenticatorName(config: TokenXAuthenticatorConfig): String? { return if (config.setAsDefault) { null } else { config.authenticatorName } } private fun getMinLoa(loa: LevelOfAssurance): IdPortenLevelOfAssurance { return when (loa) { LevelOfAssurance.SUBSTANTIAL -> IdPortenLevelOfAssurance.Substantial LevelOfAssurance.HIGH -> IdPortenLevelOfAssurance.High } } }
1
Kotlin
2
1
7539b86e9cd35a531aeecdf46a994c37e2cf2f34
1,169
tms-ktor-token-support
MIT License
android/AgilityFitTodayApp/app/src/main/java/com/laurenyew/agilityfittodayapp/features/settings/SettingsViewModel.kt
laurenyew
442,915,907
false
{"Kotlin": 133691, "Swift": 39914, "Shell": 1143}
package com.laurenyew.agilityfittodayapp.features.settings import android.content.Context import android.content.Intent import androidx.lifecycle.ViewModel import com.laurenyew.agilityfittodayapp.devsettings.DevSettingsActivity import timber.log.Timber class SettingsViewModel : ViewModel() { val shouldShowDevSettingsButton: Boolean = true fun openDevSettings(context: Context) { Timber.d("Open DevSettings") val intent = Intent(context, DevSettingsActivity::class.java) context.startActivity(intent) } }
0
Kotlin
0
1
c7a0b7628d3861330d8c27936432a96795b43391
545
AgilityFitTodayApp
MIT License
src/test/java/kotlinx/reflect/lite/testData/parameters/instanceExtensionReceiverAndValueParameters.kt
Kotlin
41,860,868
false
{"Kotlin": 516851, "Java": 75}
/* * Copyright 2016-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package tests.parameters.instanceExtensionReceiverAndValueParameters import kotlinx.reflect.lite.* import kotlinx.reflect.lite.jvm.* import kotlinx.reflect.lite.tests.* import kotlin.test.assertEquals class A { fun String.memExt(param: Int) {} } fun topLevel() {} fun Int.ext(vararg o: Any) {} fun KParameter.check(name: String?, kind: KParameter.Kind) { assertEquals(name, this.name) assertEquals(kind, this.kind) } fun box(): String { (A::class.java).kDeclarationContainer.getMemberByName("memExt").let { assertEquals(3, it.parameters.size) it.parameters[0].check(null, KParameter.Kind.INSTANCE) it.parameters[1].check(null, KParameter.Kind.EXTENSION_RECEIVER) it.parameters[2].check("param", KParameter.Kind.VALUE) } Class.forName("tests.parameters.instanceExtensionReceiverAndValueParameters.InstanceExtensionReceiverAndValueParametersKt") .kDeclarationContainer.getMemberByName("topLevel").let { assertEquals(0, it.parameters.size) } Class.forName("tests.parameters.instanceExtensionReceiverAndValueParameters.InstanceExtensionReceiverAndValueParametersKt") .kDeclarationContainer.getMemberByName("ext").let { assertEquals(2, it.parameters.size) it.parameters[0].check(null, KParameter.Kind.EXTENSION_RECEIVER) it.parameters[1].check("o", KParameter.Kind.VALUE) } return "OK" }
3
Kotlin
13
156
32ffe53981eb559939b6c2f15661138661b31bc6
1,547
kotlinx.reflect.lite
Apache License 2.0
app/src/main/java/com/aamaulana10/moviecompose/feature/home/core/domain/model/MovieModel.kt
aamaulana10
851,107,989
false
{"Kotlin": 45992}
package com.aamaulana10.moviecompose.feature.home.core.domain.model data class MovieVideosResponse( val id: Int, val results: List<MovieVideosModel> ) data class MovieVideosModel( val id: String, val title: String, val adult: Boolean, val backdrop_path: String, val genre_ids: List<Int>, val original_language: String, val original_title: String, val overview: String, val popularity: Double, val poster_path: String, val release_date: String, )
0
Kotlin
0
0
5a6c62ea5796e56962044722583494e5e6923965
499
movie-compose
MIT License
app/src/main/java/com/project/farmingapp/viewmodel/AuthViewModel.kt
hetsuthar028
325,234,399
false
null
package com.example.techfarming.viewmodel import android.content.Intent import android.util.Log import android.view.View import androidx.lifecycle.ViewModel import com.example.techfarming.model.AuthRepository import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.common.api.ApiException class AuthViewModel : ViewModel() { var name: String? = null var mobNo: String? = null var email: String? = null var city: String? = null var password: String? = null var confPassword: String? = null var userType: String? = "normal" var authListener: AuthListener? = null //login var loginmail:String?=null var loginpwd:String?=null lateinit var authRepository: AuthRepository lateinit var googleSignInClient: GoogleSignInClient companion object { private const val TAG = "GoogleActivity" private const val RC_SIGN_IN = 9001 } val userPosts = arrayListOf<String>() fun signupButtonClicked(view: View) { authListener!!.onStarted() if (name.isNullOrEmpty() || mobNo.toString().length != 10 || mobNo == null || password.isNullOrEmpty() || confPassword.isNullOrEmpty() || city.isNullOrEmpty()) { // Failure authListener!!.onFailure("Error Occurred") return } // Success var data = hashMapOf( "name" to name, "mobNo" to mobNo, "email" to email, "city" to city, "userType" to userType, "posts" to userPosts, "profileImage" to "" ) val authRepo = AuthRepository().signInWithEmail(email!!, password!!, data) authListener?.onSuccess(authRepo) } fun returnActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { authListener!!.onStarted() if (requestCode == RC_SIGN_IN) { val task = GoogleSignIn.getSignedInAccountFromIntent(data) val exception = task.exception if (task.isSuccessful) { try { val account = task.getResult(ApiException::class.java)!! var data2 = hashMapOf( "userType" to userType, "posts" to userPosts, "name" to account.displayName.toString(), "profileImage" to account.photoUrl.toString() ) authRepository = AuthRepository() var returned = authRepository.signInToGoogle( account.idToken!!, account.email.toString(), data2 ) Log.d("AuthView", returned.value.toString()) authListener?.onSuccess(returned) } catch (e: ApiException) { authListener!!.onFailure(e.message.toString()) } } else { } } } //login btn function //login btn function fun loginButtonClicked(view: View?) { authListener!!.onStarted() if (loginmail.isNullOrEmpty() || loginpwd.isNullOrEmpty()) { // Failure authListener!!.onFailure("Error Occurred") return } // Success val authRepo = AuthRepository().logInWithEmail(loginmail!!, loginpwd!!) authListener?.onSuccess(authRepo) } }
9
null
25
58
53cf61fe4158db356d1c7741065820deea7104ce
3,526
Farming-App
MIT License
src/org/chorusmc/chorus/nodes/popup/ImagePopup.kt
franga2000
246,333,834
true
{"Kotlin": 324702, "CSS": 90948, "Java": 50010, "JavaScript": 19888}
package org.chorusmc.chorus.nodes.popup import org.chorusmc.chorus.util.area import javafx.geometry.Pos import javafx.scene.Node import javafx.scene.image.Image import javafx.scene.image.ImageView import javafx.scene.layout.StackPane import javafx.stage.Popup import org.fxmisc.richtext.event.MouseOverTextEvent /** * @author Gio */ class ImagePopup : Popup() { lateinit var image: Image override fun show(ownerNode: Node?, anchorX: Double, anchorY: Double) { val pane = StackPane(ImageView(image)) pane.styleClass += "image-popup" pane.style += "-fx-padding: 10; -fx-background-radius: 360" pane.alignment = Pos.CENTER content += pane super.show(ownerNode, anchorX - image.width, anchorY) area!!.addEventHandler(MouseOverTextEvent.MOUSE_OVER_TEXT_END) {_ -> this.hide() } } }
0
null
0
0
fb0faa7277e90242c9f16ba7174baf18bed24e6f
871
chorus
Apache License 2.0
app/src/main/java/com/example/mytrainingpal/model/daos/ExerciseDao.kt
MichaelBuessemeyer
572,939,495
false
{"Kotlin": 256987}
package com.example.mytrainingpal.model.daos import androidx.lifecycle.LiveData import androidx.room.* import com.example.mytrainingpal.model.entities.Exercise @Dao abstract class ExerciseDao { @Insert abstract fun insert(exercise: Exercise): Long @Query("SELECT * FROM Exercise") abstract fun getAllExercises(): LiveData<List<Exercise>> @Query("SELECT * FROM Exercise WHERE exerciseId=:exerciseId") abstract fun getExerciseById(exerciseId: Long): Exercise @Update abstract fun updateExercise(exercise: Exercise) @Delete abstract fun deleteExercise(exercise: Exercise) }
14
Kotlin
0
2
5ef8c98c684bf2bb863dc6781a457c16ab8bb6e1
617
MyTrainingsPal
Apache License 2.0
kobalt/src/Build.kt
cbeust
43,665,276
false
null
import com.beust.kobalt.TaskResult import com.beust.kobalt.api.License import com.beust.kobalt.api.Project import com.beust.kobalt.api.Scm import com.beust.kobalt.api.annotation.Task import com.beust.kobalt.homeDir import com.beust.kobalt.plugin.application.application import com.beust.kobalt.plugin.java.javaCompiler import com.beust.kobalt.plugin.kotlin.kotlinCompiler import com.beust.kobalt.plugin.packaging.assemble import com.beust.kobalt.plugin.publish.bintray import com.beust.kobalt.plugin.publish.github import com.beust.kobalt.project import com.beust.kobalt.test import java.io.File import java.nio.file.Files import java.nio.file.Paths import java.nio.file.StandardCopyOption object Versions { val okhttp = "3.2.0" val okio = "1.6.0" val retrofit = "2.0.2" val gson = "2.6.2" val aether = "1.1.0" val sonatypeAether = "1.13.1" val maven = "3.3.9" val jersey = "2.22.2" val jetty = "8.1.19.v20160209" // "9.3.9.M1" } val wrapper = project { name = "kobalt-wrapper" group = "com.beust" artifactId = name version = readVersion() directory = "modules/wrapper" javaCompiler { args("-source", "1.7", "-target", "1.7") } assemble { jar { name = projectName + ".jar" manifest { attributes("Main-Class", "com.beust.kobalt.wrapper.Main") } } } application { mainClass = "com.beust.kobalt.wrapper.Main" } } val kobaltPluginApi = project { name = "kobalt-plugin-api" group = "com.beust" artifactId = name version = readVersion() directory = "modules/kobalt-plugin-api" description = "A build system in Kotlin" url = "http://beust.com/kobalt" licenses = listOf(License("Apache 2.0", "http://www.apache.org/licenses/LICENSE-2.0")) scm = Scm(url = "http://github.com/cbeust/kobalt", connection = "https://github.com/cbeust/kobalt.git", developerConnection = "<EMAIL>:cbeust/kobalt.git") dependencies { compile("org.jetbrains.kotlinx:kotlinx.dom:0.0.10", "com.google.inject:guice:4.0", "com.google.inject.extensions:guice-assistedinject:4.0", "javax.inject:javax.inject:1", "com.google.guava:guava:19.0-rc2", "org.apache.maven:maven-model:${Versions.maven}", "io.reactivex:rxjava:1.0.16", "com.google.code.gson:gson:${Versions.gson}", "com.squareup.okio:okio:${Versions.okio}", "com.squareup.retrofit2:retrofit:${Versions.retrofit}", "com.squareup.retrofit2:converter-gson:${Versions.retrofit}", "com.beust:jcommander:1.48", "org.slf4j:slf4j-nop:1.6.0", "org.eclipse.aether:aether-spi:${Versions.aether}", "org.eclipse.aether:aether-impl:${Versions.aether}", "org.eclipse.aether:aether-connector-basic:${Versions.aether}", "org.eclipse.aether:aether-transport-file:${Versions.aether}", "org.eclipse.aether:aether-transport-http:${Versions.aether}", "org.sonatype.aether:aether-api:${Versions.sonatypeAether}", "org.sonatype.aether:aether-connector-wagon:1.13.1", "org.apache.maven:maven-aether-provider:${Versions.maven}" ) } assemble { mavenJars { fatJar = true manifest { attributes("Main-Class", "com.beust.kobalt.MainKt") } } } // install { // libDir = "lib-test" // } kotlinCompiler { args("-nowarn") } bintray { publish = true } } val kobaltApp = project(kobaltPluginApi, wrapper) { name = "kobalt" group = "com.beust" artifactId = name version = readVersion() dependencies { // Used by the plugins compile("org.jetbrains.kotlin:kotlin-compiler-embeddable:1.0.2") // Used by the main app compile("com.github.spullara.mustache.java:compiler:0.9.1", "javax.inject:javax.inject:1", "com.google.inject:guice:4.0", "com.google.inject.extensions:guice-assistedinject:4.0", "com.beust:jcommander:1.48", "org.apache.maven:maven-model:${Versions.maven}", "com.google.code.findbugs:jsr305:3.0.1", "com.google.code.gson:gson:${Versions.gson}", "com.squareup.okhttp3:okhttp:${Versions.okhttp}", "com.squareup.retrofit2:retrofit:${Versions.retrofit}", "com.squareup.retrofit2:converter-gson:${Versions.retrofit}", "org.codehaus.plexus:plexus-utils:3.0.22", "biz.aQute.bnd:bndlib:2.4.0", "com.squareup.okhttp3:logging-interceptor:3.2.0", "com.sparkjava:spark-core:2.5" // "org.eclipse.jetty:jetty-server:${Versions.jetty}", // "org.eclipse.jetty:jetty-servlet:${Versions.jetty}", // "org.glassfish.jersey.core:jersey-server:${Versions.jersey}", // "org.glassfish.jersey.containers:jersey-container-servlet-core:${Versions.jersey}", // "org.glassfish.jersey.containers:jersey-container-jetty-http:${Versions.jersey}", // "org.glassfish.jersey.media:jersey-media-moxy:${Versions.jersey}", // "org.wasabi:wasabi:0.1.182" ) } dependenciesTest { compile("org.testng:testng:6.9.10", "org.assertj:assertj-core:3.4.1") } assemble { mavenJars { fatJar = true manifest { attributes("Main-Class", "com.beust.kobalt.MainKt") } } zip { val dir = "kobalt-$version" include(from("dist"), to("$dir/bin"), "kobaltw") include(from("dist"), to("$dir/bin"), "kobaltw.bat") include(from("$buildDirectory/libs"), to("$dir/kobalt/wrapper"), "$projectName-$version.jar") include(from("modules/wrapper/$buildDirectory/libs"), to("$dir/kobalt/wrapper"), "$projectName-wrapper.jar") } } kotlinCompiler { args("-nowarn") } bintray { publish = true } github { file("$buildDirectory/libs/$name-$version.zip", "$name/$version/$name-$version.zip") } test { args("-log", "2", "src/test/resources/testng.xml") } } fun readVersion() : String { val localFile = listOf("src/main/resources/kobalt.properties", homeDir("kotlin", "kobalt", "src/main/resources/kobalt.properties")).first { File(it).exists() } with(java.util.Properties()) { load(java.io.FileReader(localFile)) return getProperty("kobalt.version") } } @Task(name = "copyVersionForWrapper", reverseDependsOn = arrayOf("assemble")) fun taskCopyVersionForWrapper(project: Project) : TaskResult { if (project.name == "kobalt-wrapper") { val toString = "modules/wrapper/kobaltBuild/classes" File(toString).mkdirs() val from = Paths.get("src/main/resources/kobalt.properties") val to = Paths.get("$toString/kobalt.properties") Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING) } return TaskResult() }
75
null
60
426
1cf19e17733dd09814d0b97c9ee5bd53edc258a9
7,458
kobalt
Apache License 2.0
graphql/src/test/kotlin/com/trib3/graphql/resources/GraphQLSseResourceIntegrationTest.kt
trib3
191,460,324
false
{"Kotlin": 493635, "Java": 73011, "HTML": 7300}
package com.trib3.graphql.resources import assertk.assertThat import assertk.assertions.contains import assertk.assertions.hasSize import assertk.assertions.isEmpty import assertk.assertions.isEqualTo import assertk.assertions.isGreaterThanOrEqualTo import assertk.assertions.isLessThan import assertk.assertions.isNotNull import assertk.assertions.isNull import com.expediagroup.graphql.generator.SchemaGeneratorConfig import com.expediagroup.graphql.generator.TopLevelObject import com.expediagroup.graphql.generator.execution.FlowSubscriptionExecutionStrategy import com.expediagroup.graphql.generator.hooks.FlowSubscriptionSchemaGeneratorHooks import com.expediagroup.graphql.generator.toSchema import com.trib3.config.ConfigLoader import com.trib3.graphql.GraphQLConfig import com.trib3.graphql.execution.CustomDataFetcherExceptionHandler import com.trib3.graphql.execution.RequestIdInstrumentation import com.trib3.json.ObjectMapperProvider import com.trib3.testing.server.JettyWebTestContainerFactory import com.trib3.testing.server.ResourceTestBase import graphql.GraphQL import graphql.execution.AsyncExecutionStrategy import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.runBlocking import org.glassfish.jersey.media.sse.EventInput import org.glassfish.jersey.test.spi.TestContainerFactory import org.testng.annotations.Test import java.util.UUID import javax.ws.rs.client.Entity import javax.ws.rs.core.MediaType class SseQuery { fun hello(): String { return "world" } fun error(): String { throw IllegalStateException("Forced Error") } } class SseSubscription { fun three(): Flow<Int> { return flowOf(1, 2, 3) } fun inf(): Flow<Int> { return flow { var i = 0 while (true) { delay(10) emit(i++) } } } fun serror(): Flow<Int> { throw IllegalStateException("Forced Error") } } class GraphQLSseResourceIntegrationTest : ResourceTestBase<GraphQLSseResource>() { override fun getResource(): GraphQLSseResource { return rawResource } override fun getContainerFactory(): TestContainerFactory { return JettyWebTestContainerFactory() } private val graphQL = GraphQL.newGraphQL( toSchema( SchemaGeneratorConfig( listOf(this::class.java.packageName), hooks = FlowSubscriptionSchemaGeneratorHooks() ), listOf(TopLevelObject(SseQuery())), listOf(), listOf(TopLevelObject(SseSubscription())) ) ) .queryExecutionStrategy(AsyncExecutionStrategy(CustomDataFetcherExceptionHandler())) .subscriptionExecutionStrategy(FlowSubscriptionExecutionStrategy(CustomDataFetcherExceptionHandler())) .instrumentation(RequestIdInstrumentation()) .build() private val rawResource = GraphQLSseResource( graphQL, GraphQLConfig(ConfigLoader("GraphSSEQLResourceIntegrationTest")), ObjectMapperProvider().get() ) private val target by lazy { resource.target("/graphql/stream") } private fun readEventInput(eventInput: EventInput, completePayload: String): List<String> { val events = mutableListOf<String>() while (!eventInput.isClosed) { val event = eventInput.read() if (event?.name == "complete") { assertThat(event.readData()).isEqualTo(completePayload) eventInput.close() } else if (event?.name == "next") { events.add(event.readData()) } } return events } private fun waitForStreamReady(tokenUUID: UUID) { // wait up to 4 seconds for the stream to be ready val now = System.currentTimeMillis() while (rawResource.activeStreams[tokenUUID] == null) { assertThat(System.currentTimeMillis() - now).isLessThan(4000) Thread.sleep(10) } } @Test fun testSseQuery() { val result = target.request().accept(MediaType.SERVER_SENT_EVENTS) .post(Entity.json("""{"query":"query {hello}"}"""), EventInput::class.java) val events = readEventInput(result, "") assertThat(events).hasSize(1) assertThat(events[0]).contains(""""data":{"hello":"world"}""") } @Test fun testSseSubscription() { val result = target.request().accept(MediaType.SERVER_SENT_EVENTS) .post(Entity.json("""{"query":"subscription {three}"}"""), EventInput::class.java) val events = readEventInput(result, "") assertThat(events).hasSize(3) for (i in 0..2) { assertThat(events[i]).contains(""""data":{"three":${i + 1}}""") } } @Test fun testSseError() { val result = target.request().accept(MediaType.SERVER_SENT_EVENTS) .post(Entity.json("""{"query":"query {error}"}"""), EventInput::class.java) val events = readEventInput(result, "") assertThat(events).hasSize(1) assertThat(events[0]).contains(""""message":"Forced Error"""") assertThat(events[0]).contains(""""data":null""") } @Test fun testSseSubError() { val result = target.request().accept(MediaType.SERVER_SENT_EVENTS) .post(Entity.json("""{"query":"subscription {serror}"}"""), EventInput::class.java) val events = readEventInput(result, "") assertThat(events).hasSize(1) assertThat(events[0]).contains(""""message":"Forced Error"""") assertThat(events[0]).contains(""""data":null""") } @Test fun testSingleConnQuery() { val tokenResponse = target.request().put(Entity.text("")) val token = tokenResponse.readEntity(String::class.java) assertThat(tokenResponse.status).isEqualTo(201) val tokenUUID = UUID.fromString(token) val eventInput = target.request().header("x-graphql-event-stream-token", token).get(EventInput::class.java) waitForStreamReady(tokenUUID) val query = target.request().header("x-graphql-event-stream-token", token) .post(Entity.json("""{"query":"query {hello}", "extensions":{"operationId":"clientspecified"}}""")) assertThat(query.status).isEqualTo(202) assertThat(rawResource.activeStreams[tokenUUID]).isNotNull() assertThat(rawResource.runningOperations[tokenUUID]).isNotNull() val query2 = target.request().header("x-graphql-event-stream-token", token) .post(Entity.json("""{"query":"query {hello}", "extensions":{"operationId":"clientspecified2"}}""")) assertThat(query2.status).isEqualTo(202) var completeEvents = 0 val events = mutableListOf<String>() while (!eventInput.isClosed) { val event = eventInput.read() if (event?.name == "complete") { completeEvents++ if (completeEvents >= 2) { eventInput.close() } } else if (event?.name == "next") { events.add(event.readData()) } } assertThat(events).hasSize(2) assertThat(events.first { it.contains("clientspecified\"") }).contains(""""data":{"hello":"world"}""") assertThat(events.first { it.contains("clientspecified2") }).contains(""""data":{"hello":"world"}""") val now = System.currentTimeMillis() // wait up to 4 seconds for the stream to be closed while (rawResource.activeStreams[tokenUUID] != null) { assertThat(System.currentTimeMillis() - now).isLessThan(4000) Thread.sleep(10) } assertThat(rawResource.activeStreams[tokenUUID]).isNull() assertThat(rawResource.runningOperations[tokenUUID]).isNull() } @Test fun testSingleConnSub() { val tokenResponse = target.request().put(Entity.text("")) val token = tokenResponse.readEntity(String::class.java) assertThat(tokenResponse.status).isEqualTo(201) val tokenUUID = UUID.fromString(token) val eventInput = target.queryParam("token", token).request().get(EventInput::class.java) waitForStreamReady(tokenUUID) val query = target.queryParam("token", token).request() .post(Entity.json("""{"query":"subscription {three}", "extensions":{"operationId":"clientspecified"}}""")) assertThat(query.status).isEqualTo(202) val events = readEventInput(eventInput, """{"id":"clientspecified"}""") assertThat(events).hasSize(3) for (i in 0..2) { assertThat(events[i]).contains(""""id":"clientspecified"""") assertThat(events[i]).contains(""""data":{"three":${i + 1}}""") } } @Test fun testSingleConnError() { val tokenResponse = target.request().put(Entity.text("")) val token = tokenResponse.readEntity(String::class.java) assertThat(tokenResponse.status).isEqualTo(201) val tokenUUID = UUID.fromString(token) val eventInput = target.request().header("x-graphql-event-stream-token", token).get(EventInput::class.java) waitForStreamReady(tokenUUID) val query = target.request().header("x-graphql-event-stream-token", token) .post(Entity.json("""{"query":"query {error}", "extensions":{"operationId":"clientspecified"}}""")) assertThat(query.status).isEqualTo(202) val events = readEventInput(eventInput, """{"id":"clientspecified"}""") assertThat(events).hasSize(1) assertThat(events[0]).contains(""""id":"clientspecified"""") assertThat(events[0]).contains(""""message":"Forced Error"""") } @Test fun testSingleConnSubError() { val tokenResponse = target.request().put(Entity.text("")) val token = tokenResponse.readEntity(String::class.java) assertThat(tokenResponse.status).isEqualTo(201) val tokenUUID = UUID.fromString(token) val eventInput = target.queryParam("token", token).request().get(EventInput::class.java) waitForStreamReady(tokenUUID) val query = target.queryParam("token", token).request() .post(Entity.json("""{"query":"subscription {serror}", "extensions":{"operationId":"clientspecified"}}""")) assertThat(query.status).isEqualTo(202) val events = readEventInput(eventInput, """{"id":"clientspecified"}""") assertThat(events).hasSize(1) assertThat(events[0]).contains(""""id":"clientspecified"""") assertThat(events[0]).contains(""""message":"Forced Error"""") } @Test fun testSingleConnCancellation() { val tokenResponse = target.request().put(Entity.text("")) val token = tokenResponse.readEntity(String::class.java) assertThat(tokenResponse.status).isEqualTo(201) val tokenUUID = UUID.fromString(token) val eventInput = target.request().header("x-graphql-event-stream-token", token).get(EventInput::class.java) waitForStreamReady(tokenUUID) val query = target.request().header("x-graphql-event-stream-token", token) .post(Entity.json("""{"query":"subscription {inf}", "extensions":{"operationId":"infinitequery"}}""")) assertThat(query.status).isEqualTo(202) while (!eventInput.isClosed) { val event = eventInput.read() if (event?.name == "next") { break } } val cancel = target.queryParam("operationId", "infinitequery") .request() .header("x-graphql-event-stream-token", token) .delete() assertThat(cancel.status).isEqualTo(204) val moreEvents = readEventInput(eventInput, """{"id":"infinitequery"}""") assertThat(moreEvents.size).isGreaterThanOrEqualTo(0) } @Test fun testSingleConnEndpointsNoToken() { val eventInput = target.request().get(EventInput::class.java) val events = readEventInput(eventInput, "") assertThat(events).isEmpty() val query = target.request() .post(Entity.json("""{"query":"subscription {serror}", "extensions":{"operationId":"clientspecified"}}""")) assertThat(query.status).isEqualTo(401) } @Test fun testSingleConnEndpointsBadToken() { val eventInput = target.queryParam("token", UUID.randomUUID().toString()).request().get(EventInput::class.java) val events = readEventInput(eventInput, "") assertThat(events).isEmpty() val query = target.queryParam("token", UUID.randomUUID().toString()).request() .post(Entity.json("""{"query":"subscription {serror}", "extensions":{"operationId":"clientspecified"}}""")) assertThat(query.status).isEqualTo(401) } @Test fun testSingleConnBadCancellation() = runBlocking { val cancelNoToken = target.queryParam("operationId", "badValue") .request() .delete() assertThat(cancelNoToken.status).isEqualTo(401) val cancelBadTokenHeader = target.queryParam("operationId", "badValue") .request() .header("x-graphql-event-stream-token", UUID.randomUUID()) .delete() assertThat(cancelBadTokenHeader.status).isEqualTo(204) val cancelBadTokenQueryParam = target.queryParam("operationId", "badValue") .queryParam("token", UUID.randomUUID()) .request() .delete() assertThat(cancelBadTokenQueryParam.status).isEqualTo(204) val tokenResponse = target.request().put(Entity.text("")) val token = tokenResponse.readEntity(String::class.java) val tokenUUID = UUID.fromString(token) assertThat(tokenResponse.status).isEqualTo(201) val eventInput = target.request().header("x-graphql-event-stream-token", token).get(EventInput::class.java) waitForStreamReady(tokenUUID) val query = target.request().header("x-graphql-event-stream-token", token) .post(Entity.json("""{"query":"query {hello}", "extensions":{"operationId":"clientspecified"}}""")) assertThat(query.status).isEqualTo(202) val cancelGoodTokenBadOperationId = target.queryParam("operationId", "badValue") .queryParam("token", token) .request() .delete() assertThat(cancelGoodTokenBadOperationId.status).isEqualTo(204) eventInput.close() } }
58
Kotlin
3
9
540e895a9afa4ddf9b9879c505ec9856a88a4a9b
14,584
leakycauldron
Apache License 2.0
test/dev/eakin/dao/dataValadition/NutGroupTests.kt
GregEakin
244,196,646
false
null
/* * Copyright (c) 2020. Greg Eakin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.eakin.dao.dataValadition import dev.eakin.dao.entities.FoodDescription import dev.eakin.dao.entities.FoodGroup import dev.eakin.dao.utilities.NutrishRepositoryExtension import org.hibernate.Session import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(NutrishRepositoryExtension::class) class NutGroupTests internal constructor(private val session: Session) { @Test fun Test1() { val foodGroup = session.load(FoodGroup::class.java, "1200") Assertions.assertEquals("1200", foodGroup.fdGrp_Cd) Assertions.assertEquals("Nut and Seed Products", foodGroup.fdGrp_Desc) val foodDescriptionSet: Set<FoodDescription> = foodGroup.getFoodDescriptionSet() Assertions.assertEquals(137, foodDescriptionSet.size) } }
0
Kotlin
0
0
0cb708fc2c6f83cd2c1619001691c404d1603659
1,448
NutrishSr28.Kotlin
Apache License 2.0
compiler/testData/writeFlags/innerClass/visibility/publicClassObject.kt
JakeWharton
99,388,807
false
null
class Foo { default object { } } // TESTED_OBJECT_KIND: innerClass // TESTED_OBJECTS: Foo, Default // FLAGS: ACC_FINAL, ACC_PUBLIC, ACC_STATIC
179
null
5640
83
4383335168338df9bbbe2a63cb213a68d0858104
148
kotlin
Apache License 2.0
src/main/kotlin/br/com/paulo/projetos/tasksmanagement/dtos/ErroDTO.kt
paulodaluz
433,932,072
false
{"Kotlin": 12549}
package br.com.paulo.projetos.tasksmanagement.dtos class ErroDTO (val status: Int, val erro: String? = null, val erros: List<String>? = null)
0
Kotlin
0
0
dd00d6a8098de84ce5876c63d22adb02def4634b
142
TasksManagement
MIT License
projects/tier-to-delius/src/test/kotlin/uk/gov/justice/digital/hmpps/messaging/HandlerTest.kt
ministryofjustice
500,855,647
false
{"Kotlin": 4300338, "HTML": 70066, "D2": 42781, "Ruby": 25921, "Shell": 19356, "SCSS": 6370, "HCL": 2712, "Dockerfile": 2447, "JavaScript": 1372, "Python": 268}
package uk.gov.justice.digital.hmpps.messaging import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.mockito.InjectMocks import org.mockito.Mock import org.mockito.junit.jupiter.MockitoExtension import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import uk.gov.justice.digital.hmpps.converter.NotificationConverter import uk.gov.justice.digital.hmpps.integrations.tier.TierCalculation import uk.gov.justice.digital.hmpps.integrations.tier.TierClient import uk.gov.justice.digital.hmpps.integrations.tier.TierService import uk.gov.justice.digital.hmpps.message.HmppsDomainEvent import uk.gov.justice.digital.hmpps.prepMessage import uk.gov.justice.digital.hmpps.telemetry.TelemetryService import uk.gov.justice.digital.hmpps.telemetry.notificationReceived import java.net.URI import java.time.ZonedDateTime.now @ExtendWith(MockitoExtension::class) internal class HandlerTest { @Mock lateinit var telemetryService: TelemetryService @Mock lateinit var tierClient: TierClient @Mock lateinit var tierService: TierService @Mock lateinit var converter: NotificationConverter<HmppsDomainEvent> @InjectMocks lateinit var handler: Handler @Test fun `should update tier`() { // Given a message val message = prepMessage("tier-calculation", 1234) // And a calculation val calculation = TierCalculation("someScore", "calculationId", now()) whenever(tierClient.getTierCalculation(URI.create("http://localhost:1234/hmpps-tier/crn/A000001/tier/123e4567-e89b-12d3-a456-426614174000"))).thenReturn( calculation ) // When the message is received handler.handle(message) // Then it is updated in Delius and logged to Telemetry verify(telemetryService).notificationReceived(message) verify(tierClient).getTierCalculation(URI.create("http://localhost:1234/hmpps-tier/crn/A000001/tier/123e4567-e89b-12d3-a456-426614174000")) verify(tierService).updateTier("A000001", calculation) verify(telemetryService).trackEvent("TierUpdateSuccess", calculation.telemetryProperties("A000001")) } }
4
Kotlin
0
2
1636e67b6ad6ecfc36ac86a9b343bc4f85c1d9d9
2,196
hmpps-probation-integration-services
MIT License
modern-treasury-kotlin-core/src/main/kotlin/com/moderntreasury/api/models/LedgerEventHandler.kt
Modern-Treasury
665,762,762
false
null
// File generated from our OpenAPI spec by Stainless. package com.moderntreasury.api.models import com.fasterxml.jackson.annotation.JsonAnyGetter import com.fasterxml.jackson.annotation.JsonAnySetter import com.fasterxml.jackson.annotation.JsonProperty import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.moderntreasury.api.core.ExcludeMissing import com.moderntreasury.api.core.JsonField import com.moderntreasury.api.core.JsonMissing import com.moderntreasury.api.core.JsonValue import com.moderntreasury.api.core.NoAutoDetect import com.moderntreasury.api.core.toUnmodifiable import java.time.OffsetDateTime import java.util.Objects @JsonDeserialize(builder = LedgerEventHandler.Builder::class) @NoAutoDetect class LedgerEventHandler private constructor( private val id: JsonField<String>, private val object_: JsonField<String>, private val liveMode: JsonField<Boolean>, private val createdAt: JsonField<OffsetDateTime>, private val updatedAt: JsonField<OffsetDateTime>, private val discardedAt: JsonField<OffsetDateTime>, private val name: JsonField<String>, private val description: JsonField<String>, private val ledgerId: JsonField<String>, private val variables: JsonField<LedgerEventHandlerVariables>, private val ledgerTransactionTemplate: JsonField<LedgerEventHandlerLedgerTransactionTemplate>, private val conditions: JsonField<LedgerEventHandlerConditions>, private val metadata: JsonField<Metadata>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false fun id(): String = id.getRequired("id") fun object_(): String = object_.getRequired("object") /** * This field will be true if this object exists in the live environment or false if it exists * in the test environment. */ fun liveMode(): Boolean = liveMode.getRequired("live_mode") fun createdAt(): OffsetDateTime = createdAt.getRequired("created_at") fun updatedAt(): OffsetDateTime = updatedAt.getRequired("updated_at") fun discardedAt(): OffsetDateTime? = discardedAt.getNullable("discarded_at") /** Name of the ledger event handler. */ fun name(): String = name.getRequired("name") /** An optional description. */ fun description(): String? = description.getNullable("description") /** The id of the ledger that this event handler belongs to. */ fun ledgerId(): String? = ledgerId.getNullable("ledger_id") fun variables(): LedgerEventHandlerVariables? = variables.getNullable("variables") fun ledgerTransactionTemplate(): LedgerEventHandlerLedgerTransactionTemplate = ledgerTransactionTemplate.getRequired("ledger_transaction_template") fun conditions(): LedgerEventHandlerConditions? = conditions.getNullable("conditions") /** Additional data represented as key-value pairs. Both the key and value must be strings. */ fun metadata(): Metadata? = metadata.getNullable("metadata") @JsonProperty("id") @ExcludeMissing fun _id() = id @JsonProperty("object") @ExcludeMissing fun _object_() = object_ /** * This field will be true if this object exists in the live environment or false if it exists * in the test environment. */ @JsonProperty("live_mode") @ExcludeMissing fun _liveMode() = liveMode @JsonProperty("created_at") @ExcludeMissing fun _createdAt() = createdAt @JsonProperty("updated_at") @ExcludeMissing fun _updatedAt() = updatedAt @JsonProperty("discarded_at") @ExcludeMissing fun _discardedAt() = discardedAt /** Name of the ledger event handler. */ @JsonProperty("name") @ExcludeMissing fun _name() = name /** An optional description. */ @JsonProperty("description") @ExcludeMissing fun _description() = description /** The id of the ledger that this event handler belongs to. */ @JsonProperty("ledger_id") @ExcludeMissing fun _ledgerId() = ledgerId @JsonProperty("variables") @ExcludeMissing fun _variables() = variables @JsonProperty("ledger_transaction_template") @ExcludeMissing fun _ledgerTransactionTemplate() = ledgerTransactionTemplate @JsonProperty("conditions") @ExcludeMissing fun _conditions() = conditions /** Additional data represented as key-value pairs. Both the key and value must be strings. */ @JsonProperty("metadata") @ExcludeMissing fun _metadata() = metadata @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): LedgerEventHandler = apply { if (!validated) { id() object_() liveMode() createdAt() updatedAt() discardedAt() name() description() ledgerId() variables()?.validate() ledgerTransactionTemplate().validate() conditions()?.validate() metadata()?.validate() validated = true } } fun toBuilder() = Builder().from(this) companion object { fun builder() = Builder() } class Builder { private var id: JsonField<String> = JsonMissing.of() private var object_: JsonField<String> = JsonMissing.of() private var liveMode: JsonField<Boolean> = JsonMissing.of() private var createdAt: JsonField<OffsetDateTime> = JsonMissing.of() private var updatedAt: JsonField<OffsetDateTime> = JsonMissing.of() private var discardedAt: JsonField<OffsetDateTime> = JsonMissing.of() private var name: JsonField<String> = JsonMissing.of() private var description: JsonField<String> = JsonMissing.of() private var ledgerId: JsonField<String> = JsonMissing.of() private var variables: JsonField<LedgerEventHandlerVariables> = JsonMissing.of() private var ledgerTransactionTemplate: JsonField<LedgerEventHandlerLedgerTransactionTemplate> = JsonMissing.of() private var conditions: JsonField<LedgerEventHandlerConditions> = JsonMissing.of() private var metadata: JsonField<Metadata> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(ledgerEventHandler: LedgerEventHandler) = apply { this.id = ledgerEventHandler.id this.object_ = ledgerEventHandler.object_ this.liveMode = ledgerEventHandler.liveMode this.createdAt = ledgerEventHandler.createdAt this.updatedAt = ledgerEventHandler.updatedAt this.discardedAt = ledgerEventHandler.discardedAt this.name = ledgerEventHandler.name this.description = ledgerEventHandler.description this.ledgerId = ledgerEventHandler.ledgerId this.variables = ledgerEventHandler.variables this.ledgerTransactionTemplate = ledgerEventHandler.ledgerTransactionTemplate this.conditions = ledgerEventHandler.conditions this.metadata = ledgerEventHandler.metadata additionalProperties(ledgerEventHandler.additionalProperties) } fun id(id: String) = id(JsonField.of(id)) @JsonProperty("id") @ExcludeMissing fun id(id: JsonField<String>) = apply { this.id = id } fun object_(object_: String) = object_(JsonField.of(object_)) @JsonProperty("object") @ExcludeMissing fun object_(object_: JsonField<String>) = apply { this.object_ = object_ } /** * This field will be true if this object exists in the live environment or false if it * exists in the test environment. */ fun liveMode(liveMode: Boolean) = liveMode(JsonField.of(liveMode)) /** * This field will be true if this object exists in the live environment or false if it * exists in the test environment. */ @JsonProperty("live_mode") @ExcludeMissing fun liveMode(liveMode: JsonField<Boolean>) = apply { this.liveMode = liveMode } fun createdAt(createdAt: OffsetDateTime) = createdAt(JsonField.of(createdAt)) @JsonProperty("created_at") @ExcludeMissing fun createdAt(createdAt: JsonField<OffsetDateTime>) = apply { this.createdAt = createdAt } fun updatedAt(updatedAt: OffsetDateTime) = updatedAt(JsonField.of(updatedAt)) @JsonProperty("updated_at") @ExcludeMissing fun updatedAt(updatedAt: JsonField<OffsetDateTime>) = apply { this.updatedAt = updatedAt } fun discardedAt(discardedAt: OffsetDateTime) = discardedAt(JsonField.of(discardedAt)) @JsonProperty("discarded_at") @ExcludeMissing fun discardedAt(discardedAt: JsonField<OffsetDateTime>) = apply { this.discardedAt = discardedAt } /** Name of the ledger event handler. */ fun name(name: String) = name(JsonField.of(name)) /** Name of the ledger event handler. */ @JsonProperty("name") @ExcludeMissing fun name(name: JsonField<String>) = apply { this.name = name } /** An optional description. */ fun description(description: String) = description(JsonField.of(description)) /** An optional description. */ @JsonProperty("description") @ExcludeMissing fun description(description: JsonField<String>) = apply { this.description = description } /** The id of the ledger that this event handler belongs to. */ fun ledgerId(ledgerId: String) = ledgerId(JsonField.of(ledgerId)) /** The id of the ledger that this event handler belongs to. */ @JsonProperty("ledger_id") @ExcludeMissing fun ledgerId(ledgerId: JsonField<String>) = apply { this.ledgerId = ledgerId } fun variables(variables: LedgerEventHandlerVariables) = variables(JsonField.of(variables)) @JsonProperty("variables") @ExcludeMissing fun variables(variables: JsonField<LedgerEventHandlerVariables>) = apply { this.variables = variables } fun ledgerTransactionTemplate( ledgerTransactionTemplate: LedgerEventHandlerLedgerTransactionTemplate ) = ledgerTransactionTemplate(JsonField.of(ledgerTransactionTemplate)) @JsonProperty("ledger_transaction_template") @ExcludeMissing fun ledgerTransactionTemplate( ledgerTransactionTemplate: JsonField<LedgerEventHandlerLedgerTransactionTemplate> ) = apply { this.ledgerTransactionTemplate = ledgerTransactionTemplate } fun conditions(conditions: LedgerEventHandlerConditions) = conditions(JsonField.of(conditions)) @JsonProperty("conditions") @ExcludeMissing fun conditions(conditions: JsonField<LedgerEventHandlerConditions>) = apply { this.conditions = conditions } /** * Additional data represented as key-value pairs. Both the key and value must be strings. */ fun metadata(metadata: Metadata) = metadata(JsonField.of(metadata)) /** * Additional data represented as key-value pairs. Both the key and value must be strings. */ @JsonProperty("metadata") @ExcludeMissing fun metadata(metadata: JsonField<Metadata>) = apply { this.metadata = metadata } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): LedgerEventHandler = LedgerEventHandler( id, object_, liveMode, createdAt, updatedAt, discardedAt, name, description, ledgerId, variables, ledgerTransactionTemplate, conditions, metadata, additionalProperties.toUnmodifiable(), ) } @JsonDeserialize(builder = LedgerEventHandlerConditions.Builder::class) @NoAutoDetect class LedgerEventHandlerConditions private constructor( private val field: JsonField<String>, private val operator: JsonField<String>, private val value: JsonField<String>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false /** The LHS of the conditional. */ fun field(): String = field.getRequired("field") /** What the operator between the `field` and `value` is. */ fun operator(): String = operator.getRequired("operator") /** The RHS of the conditional. */ fun value(): String = value.getRequired("value") /** The LHS of the conditional. */ @JsonProperty("field") @ExcludeMissing fun _field() = field /** What the operator between the `field` and `value` is. */ @JsonProperty("operator") @ExcludeMissing fun _operator() = operator /** The RHS of the conditional. */ @JsonProperty("value") @ExcludeMissing fun _value() = value @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): LedgerEventHandlerConditions = apply { if (!validated) { field() operator() value() validated = true } } fun toBuilder() = Builder().from(this) companion object { fun builder() = Builder() } class Builder { private var field: JsonField<String> = JsonMissing.of() private var operator: JsonField<String> = JsonMissing.of() private var value: JsonField<String> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(ledgerEventHandlerConditions: LedgerEventHandlerConditions) = apply { this.field = ledgerEventHandlerConditions.field this.operator = ledgerEventHandlerConditions.operator this.value = ledgerEventHandlerConditions.value additionalProperties(ledgerEventHandlerConditions.additionalProperties) } /** The LHS of the conditional. */ fun field(field: String) = field(JsonField.of(field)) /** The LHS of the conditional. */ @JsonProperty("field") @ExcludeMissing fun field(field: JsonField<String>) = apply { this.field = field } /** What the operator between the `field` and `value` is. */ fun operator(operator: String) = operator(JsonField.of(operator)) /** What the operator between the `field` and `value` is. */ @JsonProperty("operator") @ExcludeMissing fun operator(operator: JsonField<String>) = apply { this.operator = operator } /** The RHS of the conditional. */ fun value(value: String) = value(JsonField.of(value)) /** The RHS of the conditional. */ @JsonProperty("value") @ExcludeMissing fun value(value: JsonField<String>) = apply { this.value = value } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): LedgerEventHandlerConditions = LedgerEventHandlerConditions( field, operator, value, additionalProperties.toUnmodifiable(), ) } override fun equals(other: Any?): Boolean { if (this === other) { return true } return /* spotless:off */ other is LedgerEventHandlerConditions && this.field == other.field && this.operator == other.operator && this.value == other.value && this.additionalProperties == other.additionalProperties /* spotless:on */ } private var hashCode: Int = 0 override fun hashCode(): Int { if (hashCode == 0) { hashCode = /* spotless:off */ Objects.hash(field, operator, value, additionalProperties) /* spotless:on */ } return hashCode } override fun toString() = "LedgerEventHandlerConditions{field=$field, operator=$operator, value=$value, additionalProperties=$additionalProperties}" } @JsonDeserialize(builder = LedgerEventHandlerLedgerTransactionTemplate.Builder::class) @NoAutoDetect class LedgerEventHandlerLedgerTransactionTemplate private constructor( private val description: JsonField<String>, private val effectiveAt: JsonField<String>, private val status: JsonField<String>, private val ledgerEntries: JsonField<List<LedgerEventHandlerLedgerEntries>>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false /** An optional description for internal use. */ fun description(): String? = description.getNullable("description") /** * The timestamp (ISO8601 format) at which the ledger transaction happened for reporting * purposes. */ fun effectiveAt(): String? = effectiveAt.getNullable("effective_at") /** To post a ledger transaction at creation, use `posted`. */ fun status(): String? = status.getNullable("status") /** An array of ledger entry objects. */ fun ledgerEntries(): List<LedgerEventHandlerLedgerEntries> = ledgerEntries.getRequired("ledger_entries") /** An optional description for internal use. */ @JsonProperty("description") @ExcludeMissing fun _description() = description /** * The timestamp (ISO8601 format) at which the ledger transaction happened for reporting * purposes. */ @JsonProperty("effective_at") @ExcludeMissing fun _effectiveAt() = effectiveAt /** To post a ledger transaction at creation, use `posted`. */ @JsonProperty("status") @ExcludeMissing fun _status() = status /** An array of ledger entry objects. */ @JsonProperty("ledger_entries") @ExcludeMissing fun _ledgerEntries() = ledgerEntries @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): LedgerEventHandlerLedgerTransactionTemplate = apply { if (!validated) { description() effectiveAt() status() ledgerEntries().forEach { it.validate() } validated = true } } fun toBuilder() = Builder().from(this) companion object { fun builder() = Builder() } class Builder { private var description: JsonField<String> = JsonMissing.of() private var effectiveAt: JsonField<String> = JsonMissing.of() private var status: JsonField<String> = JsonMissing.of() private var ledgerEntries: JsonField<List<LedgerEventHandlerLedgerEntries>> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from( ledgerEventHandlerLedgerTransactionTemplate: LedgerEventHandlerLedgerTransactionTemplate ) = apply { this.description = ledgerEventHandlerLedgerTransactionTemplate.description this.effectiveAt = ledgerEventHandlerLedgerTransactionTemplate.effectiveAt this.status = ledgerEventHandlerLedgerTransactionTemplate.status this.ledgerEntries = ledgerEventHandlerLedgerTransactionTemplate.ledgerEntries additionalProperties( ledgerEventHandlerLedgerTransactionTemplate.additionalProperties ) } /** An optional description for internal use. */ fun description(description: String) = description(JsonField.of(description)) /** An optional description for internal use. */ @JsonProperty("description") @ExcludeMissing fun description(description: JsonField<String>) = apply { this.description = description } /** * The timestamp (ISO8601 format) at which the ledger transaction happened for reporting * purposes. */ fun effectiveAt(effectiveAt: String) = effectiveAt(JsonField.of(effectiveAt)) /** * The timestamp (ISO8601 format) at which the ledger transaction happened for reporting * purposes. */ @JsonProperty("effective_at") @ExcludeMissing fun effectiveAt(effectiveAt: JsonField<String>) = apply { this.effectiveAt = effectiveAt } /** To post a ledger transaction at creation, use `posted`. */ fun status(status: String) = status(JsonField.of(status)) /** To post a ledger transaction at creation, use `posted`. */ @JsonProperty("status") @ExcludeMissing fun status(status: JsonField<String>) = apply { this.status = status } /** An array of ledger entry objects. */ fun ledgerEntries(ledgerEntries: List<LedgerEventHandlerLedgerEntries>) = ledgerEntries(JsonField.of(ledgerEntries)) /** An array of ledger entry objects. */ @JsonProperty("ledger_entries") @ExcludeMissing fun ledgerEntries(ledgerEntries: JsonField<List<LedgerEventHandlerLedgerEntries>>) = apply { this.ledgerEntries = ledgerEntries } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): LedgerEventHandlerLedgerTransactionTemplate = LedgerEventHandlerLedgerTransactionTemplate( description, effectiveAt, status, ledgerEntries.map { it.toUnmodifiable() }, additionalProperties.toUnmodifiable(), ) } @JsonDeserialize(builder = LedgerEventHandlerLedgerEntries.Builder::class) @NoAutoDetect class LedgerEventHandlerLedgerEntries private constructor( private val amount: JsonField<String>, private val direction: JsonField<String>, private val ledgerAccountId: JsonField<String>, private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false /** The LHS of the conditional. */ fun amount(): String = amount.getRequired("amount") /** What the operator between the `field` and `value` is. */ fun direction(): String = direction.getRequired("direction") /** The RHS of the conditional. */ fun ledgerAccountId(): String = ledgerAccountId.getRequired("ledger_account_id") /** The LHS of the conditional. */ @JsonProperty("amount") @ExcludeMissing fun _amount() = amount /** What the operator between the `field` and `value` is. */ @JsonProperty("direction") @ExcludeMissing fun _direction() = direction /** The RHS of the conditional. */ @JsonProperty("ledger_account_id") @ExcludeMissing fun _ledgerAccountId() = ledgerAccountId @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): LedgerEventHandlerLedgerEntries = apply { if (!validated) { amount() direction() ledgerAccountId() validated = true } } fun toBuilder() = Builder().from(this) companion object { fun builder() = Builder() } class Builder { private var amount: JsonField<String> = JsonMissing.of() private var direction: JsonField<String> = JsonMissing.of() private var ledgerAccountId: JsonField<String> = JsonMissing.of() private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from( ledgerEventHandlerLedgerEntries: LedgerEventHandlerLedgerEntries ) = apply { this.amount = ledgerEventHandlerLedgerEntries.amount this.direction = ledgerEventHandlerLedgerEntries.direction this.ledgerAccountId = ledgerEventHandlerLedgerEntries.ledgerAccountId additionalProperties(ledgerEventHandlerLedgerEntries.additionalProperties) } /** The LHS of the conditional. */ fun amount(amount: String) = amount(JsonField.of(amount)) /** The LHS of the conditional. */ @JsonProperty("amount") @ExcludeMissing fun amount(amount: JsonField<String>) = apply { this.amount = amount } /** What the operator between the `field` and `value` is. */ fun direction(direction: String) = direction(JsonField.of(direction)) /** What the operator between the `field` and `value` is. */ @JsonProperty("direction") @ExcludeMissing fun direction(direction: JsonField<String>) = apply { this.direction = direction } /** The RHS of the conditional. */ fun ledgerAccountId(ledgerAccountId: String) = ledgerAccountId(JsonField.of(ledgerAccountId)) /** The RHS of the conditional. */ @JsonProperty("ledger_account_id") @ExcludeMissing fun ledgerAccountId(ledgerAccountId: JsonField<String>) = apply { this.ledgerAccountId = ledgerAccountId } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): LedgerEventHandlerLedgerEntries = LedgerEventHandlerLedgerEntries( amount, direction, ledgerAccountId, additionalProperties.toUnmodifiable(), ) } override fun equals(other: Any?): Boolean { if (this === other) { return true } return /* spotless:off */ other is LedgerEventHandlerLedgerEntries && this.amount == other.amount && this.direction == other.direction && this.ledgerAccountId == other.ledgerAccountId && this.additionalProperties == other.additionalProperties /* spotless:on */ } private var hashCode: Int = 0 override fun hashCode(): Int { if (hashCode == 0) { hashCode = /* spotless:off */ Objects.hash(amount, direction, ledgerAccountId, additionalProperties) /* spotless:on */ } return hashCode } override fun toString() = "LedgerEventHandlerLedgerEntries{amount=$amount, direction=$direction, ledgerAccountId=$ledgerAccountId, additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { if (this === other) { return true } return /* spotless:off */ other is LedgerEventHandlerLedgerTransactionTemplate && this.description == other.description && this.effectiveAt == other.effectiveAt && this.status == other.status && this.ledgerEntries == other.ledgerEntries && this.additionalProperties == other.additionalProperties /* spotless:on */ } private var hashCode: Int = 0 override fun hashCode(): Int { if (hashCode == 0) { hashCode = /* spotless:off */ Objects.hash(description, effectiveAt, status, ledgerEntries, additionalProperties) /* spotless:on */ } return hashCode } override fun toString() = "LedgerEventHandlerLedgerTransactionTemplate{description=$description, effectiveAt=$effectiveAt, status=$status, ledgerEntries=$ledgerEntries, additionalProperties=$additionalProperties}" } /** Additional data represented as key-value pairs. Both the key and value must be strings. */ @JsonDeserialize(builder = Metadata.Builder::class) @NoAutoDetect class Metadata private constructor( private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): Metadata = apply { if (!validated) { validated = true } } fun toBuilder() = Builder().from(this) companion object { fun builder() = Builder() } class Builder { private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(metadata: Metadata) = apply { additionalProperties(metadata.additionalProperties) } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): Metadata = Metadata(additionalProperties.toUnmodifiable()) } override fun equals(other: Any?): Boolean { if (this === other) { return true } return /* spotless:off */ other is Metadata && this.additionalProperties == other.additionalProperties /* spotless:on */ } private var hashCode: Int = 0 override fun hashCode(): Int { if (hashCode == 0) { hashCode = /* spotless:off */ Objects.hash(additionalProperties) /* spotless:on */ } return hashCode } override fun toString() = "Metadata{additionalProperties=$additionalProperties}" } @JsonDeserialize(builder = LedgerEventHandlerVariables.Builder::class) @NoAutoDetect class LedgerEventHandlerVariables private constructor( private val additionalProperties: Map<String, JsonValue>, ) { private var validated: Boolean = false @JsonAnyGetter @ExcludeMissing fun _additionalProperties(): Map<String, JsonValue> = additionalProperties fun validate(): LedgerEventHandlerVariables = apply { if (!validated) { validated = true } } fun toBuilder() = Builder().from(this) companion object { fun builder() = Builder() } class Builder { private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf() internal fun from(ledgerEventHandlerVariables: LedgerEventHandlerVariables) = apply { additionalProperties(ledgerEventHandlerVariables.additionalProperties) } fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.clear() this.additionalProperties.putAll(additionalProperties) } @JsonAnySetter fun putAdditionalProperty(key: String, value: JsonValue) = apply { this.additionalProperties.put(key, value) } fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply { this.additionalProperties.putAll(additionalProperties) } fun build(): LedgerEventHandlerVariables = LedgerEventHandlerVariables(additionalProperties.toUnmodifiable()) } override fun equals(other: Any?): Boolean { if (this === other) { return true } return /* spotless:off */ other is LedgerEventHandlerVariables && this.additionalProperties == other.additionalProperties /* spotless:on */ } private var hashCode: Int = 0 override fun hashCode(): Int { if (hashCode == 0) { hashCode = /* spotless:off */ Objects.hash(additionalProperties) /* spotless:on */ } return hashCode } override fun toString() = "LedgerEventHandlerVariables{additionalProperties=$additionalProperties}" } override fun equals(other: Any?): Boolean { if (this === other) { return true } return /* spotless:off */ other is LedgerEventHandler && this.id == other.id && this.object_ == other.object_ && this.liveMode == other.liveMode && this.createdAt == other.createdAt && this.updatedAt == other.updatedAt && this.discardedAt == other.discardedAt && this.name == other.name && this.description == other.description && this.ledgerId == other.ledgerId && this.variables == other.variables && this.ledgerTransactionTemplate == other.ledgerTransactionTemplate && this.conditions == other.conditions && this.metadata == other.metadata && this.additionalProperties == other.additionalProperties /* spotless:on */ } private var hashCode: Int = 0 override fun hashCode(): Int { if (hashCode == 0) { hashCode = /* spotless:off */ Objects.hash(id, object_, liveMode, createdAt, updatedAt, discardedAt, name, description, ledgerId, variables, ledgerTransactionTemplate, conditions, metadata, additionalProperties) /* spotless:on */ } return hashCode } override fun toString() = "LedgerEventHandler{id=$id, object_=$object_, liveMode=$liveMode, createdAt=$createdAt, updatedAt=$updatedAt, discardedAt=$discardedAt, name=$name, description=$description, ledgerId=$ledgerId, variables=$variables, ledgerTransactionTemplate=$ledgerTransactionTemplate, conditions=$conditions, metadata=$metadata, additionalProperties=$additionalProperties}" }
3
null
2
2
776a9b5bb0c3057643ba163b01fdcc14a92e3941
37,232
modern-treasury-kotlin
MIT License
composeApp/src/commonMain/kotlin/Guitar.kt
joshuaschori
833,395,858
false
{"Kotlin": 70958, "Swift": 594, "HTML": 336, "CSS": 102}
import androidx.compose.ui.graphics.Color // TODO @Serializable data class Guitar( val numberOfFrets: Int, // TODO convert mutable lists to regular lists var fretMemory: MutableList<FretMemory> = mutableListOf(), val isDefaultGuitar: Boolean = false ) { val lineColor: Color = Color.Black val lineThickness: Float = 1f val fretThickness: Float = 1f val fretboardLength: Float = 500f val stringSpacing: Float = 30f val fretSpacing: Float = fretboardLength / numberOfFrets val fretMarkers: List<Int> = listOf(3,5,7,9,12,15,17,19,21,24) val fretMarkerSize: Float = 6f val frettedNoteSize: Float = stringSpacing / 2f * 0.9f val unfrettedSize: Float = frettedNoteSize / 2f val strings: MutableList<GuitarString> = mutableListOf( GuitarString(Pitch(16)), GuitarString(Pitch(21)), GuitarString(Pitch(26)), GuitarString(Pitch(31)), GuitarString(Pitch(35)), GuitarString(Pitch(40)) ) val numberOfStrings: Int = strings.size val stringLocations: List<Float> = (1..numberOfStrings).map { stringSpacing * (it - 1) } val fretLocations: List<Float> = (0..numberOfFrets).map { (0f - fretSpacing * 0.5f) + (fretSpacing * it) } val fretSelectionRadius = 14f init { // add default open string hidden values to fretMemory for each string if (isDefaultGuitar) { repeat(numberOfStrings) {stringIndex -> fretMemory.add( FretMemory( x = stringSpacing * stringIndex, y = 0f - fretSpacing * 0.5f, fretSelected = 0 ) ) } } } }
0
Kotlin
0
1
ec1cdeb01c9307f7dc1be01e2d29d95782b5a8df
1,754
MagnumOpus
MIT License
app/src/main/java/com/duckduckgo/app/browser/downloader/FileDownloader.kt
andrey-p
164,923,819
false
null
/* * Copyright (c) 2018 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.app.browser.downloader import android.os.Environment import android.support.annotation.WorkerThread import android.webkit.URLUtil import java.io.File import javax.inject.Inject class FileDownloader @Inject constructor( private val dataUriDownloader: DataUriDownloader, private val networkDownloader: NetworkFileDownloader) { @WorkerThread fun download(pending: PendingFileDownload?, callback: FileDownloadListener?) { if (pending == null) { return } when { URLUtil.isNetworkUrl(pending.url) -> networkDownloader.download(pending) URLUtil.isDataUrl(pending.url) -> dataUriDownloader.download(pending, callback) else -> callback?.downloadFailed("Not supported") } } data class PendingFileDownload( val url: String, val contentDisposition: String? = null, val mimeType: String? = null, val subfolder: String, val directory: File = Environment.getExternalStoragePublicDirectory(subfolder) ) interface FileDownloadListener { fun downloadStarted() fun downloadFinished(file: File, mimeType: String?) fun downloadFailed(message: String) } }
1
null
1
1
e4328e68fda04b2e7d874fd0c974311014afe9fe
1,871
Android
Apache License 2.0
app/android/app/src/main/kotlin/com/blitzkrieg/polyess/MainActivity.kt
sreyom31
539,491,970
false
{"JavaScript": 173232, "Solidity": 52536, "Dart": 39724, "CSS": 21573, "HTML": 1477, "Kotlin": 1275, "Swift": 404, "Objective-C": 38}
package com.blitzkrieg.polyess import androidx.annotation.NonNull import io.flutter.embedding.android.FlutterActivity import io.flutter.embedding.engine.FlutterEngine import io.flutter.plugin.common.MethodChannel class MainActivity: FlutterActivity() { private val CHANNEL = "polyess.wallet/eth" override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) { super.configureFlutterEngine(flutterEngine) MethodChannel(flutterEngine.dartExecutor.binaryMessenger, CHANNEL).setMethodCallHandler { call, result -> if (call.method == "getWallet") { val seed : String = (call.argument("seed") as? String) ?: "" val eth = Wallet().getWallet(seed) result.success(eth) } else { result.notImplemented() } } } }
0
JavaScript
0
0
2d905d2acaf75252375f08ad11e3148d0c8fd90c
853
polyess
MIT License
app/src/main/java/io/github/jixiaoyong/muggle/viewmodel/bean/FileListBean.kt
jixiaoyong
182,269,717
false
null
package io.github.jixiaoyong.muggle.viewmodel.bean /** * author: jixiaoyong * email: [email protected] * website: https://jixiaoyong.github.io * date: 2019-04-27 * description: todo */ data class FileListBean(var fileName: String = "", var fileContent: String = "", var fileType: String = "", var fileState: Int = 0, var syncToCloud: Boolean = false, var fileData: String = "")
1
null
1
1
55ddb2e521cdfc0a985fb11475df24da561eec35
415
Muggle
MIT License
crunchycalendar/src/main/java/ru/cleverpumpkin/calendar/DateCellSelectedState.kt
CleverPumpkin
134,849,459
false
null
package ru.cleverpumpkin.calendar /** * @author Anatolii Shulipov ([email protected]) */ enum class DateCellSelectedState { NOT_SELECTED, SELECTED, SINGLE, SELECTION_START, SELECTION_END }
13
Kotlin
45
500
d625c21ab0f7837821782d35aeb3a55e3df68425
215
CrunchyCalendar
MIT License
src/test/kotlin/no/nav/helse/flex/FellesTestOppsett.kt
navikt
653,492,657
false
{"Kotlin": 16890, "Dockerfile": 267}
package no.nav.helse.flex import no.nav.security.token.support.spring.test.EnableMockOAuth2Server import okhttp3.mockwebserver.MockWebServer import org.apache.kafka.clients.producer.KafkaProducer import org.junit.jupiter.api.TestInstance import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.actuate.observability.AutoConfigureObservability import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc import org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrint import org.springframework.boot.test.context.SpringBootTest import org.springframework.test.web.servlet.MockMvc import org.testcontainers.containers.KafkaContainer import org.testcontainers.containers.PostgreSQLContainer import org.testcontainers.utility.DockerImageName import java.util.* import kotlin.concurrent.thread private class PostgreSQLContainer14 : PostgreSQLContainer<PostgreSQLContainer14>("postgres:14-alpine") @TestInstance(TestInstance.Lifecycle.PER_CLASS) @AutoConfigureObservability @EnableMockOAuth2Server @SpringBootTest(classes = [Application::class]) @AutoConfigureMockMvc(print = MockMvcPrint.NONE, printOnlyOnFailure = false) abstract class FellesTestOppsett { @Autowired lateinit var mockMvc: MockMvc @Autowired lateinit var kafkaProducer: KafkaProducer<String, String> companion object { private val yrkesskadeMockWebserver: MockWebServer init { val threads = mutableListOf<Thread>() thread { KafkaContainer(DockerImageName.parse("confluentinc/cp-kafka:7.3.2")).apply { start() System.setProperty("KAFKA_BROKERS", bootstrapServers) } }.also { threads.add(it) } thread { PostgreSQLContainer14().apply { start() System.setProperty("spring.datasource.url", "$jdbcUrl&reWriteBatchedInserts=true") System.setProperty("spring.datasource.username", username) System.setProperty("spring.datasource.password", <PASSWORD>) } }.also { threads.add(it) } yrkesskadeMockWebserver = MockWebServer().apply { System.setProperty("YRKESSKADE_URL", "http://localhost:$port") dispatcher = YrkesskadeMockDispatcher } threads.forEach { it.join() } } } }
4
Kotlin
0
0
d7cee7d461c6053d61254421fbb61eaebd04783f
2,487
sykepengesoknad-yrkesskade-analyse
MIT License
core/src/commonMain/kotlin/maryk/core/query/responses/statuses/AddSuccess.kt
marykdb
290,454,412
false
null
package maryk.core.query.responses.statuses import maryk.core.models.IsRootDataModel import maryk.core.models.SimpleQueryModel import maryk.core.properties.definitions.InternalMultiTypeDefinition import maryk.core.properties.definitions.list import maryk.core.properties.definitions.number import maryk.core.properties.types.Key import maryk.core.properties.types.TypedValue import maryk.core.properties.types.numeric.UInt64 import maryk.core.query.changes.ChangeType import maryk.core.query.changes.IsChange import maryk.core.query.changes.mapOfChangeDefinitions import maryk.core.query.responses.statuses.StatusType.ADD_SUCCESS import maryk.core.values.SimpleObjectValues /** Successful add of given object with [key], [version] and added [changes] */ data class AddSuccess<DM : IsRootDataModel>( val key: Key<DM>, val version: ULong, val changes: List<IsChange> ) : IsAddResponseStatus<DM> { override val statusType = ADD_SUCCESS internal companion object : SimpleQueryModel<AddSuccess<*>>() { val key by addKey(AddSuccess<*>::key) val version by number(2u, getter = AddSuccess<*>::version, type = UInt64) val changes by list( index = 3u, getter = AddSuccess<*>::changes, default = emptyList(), valueDefinition = InternalMultiTypeDefinition( typeEnum = ChangeType, definitionMap = mapOfChangeDefinitions ), toSerializable = { TypedValue(it.changeType, it) }, fromSerializable = { it.value } ) override fun invoke(values: SimpleObjectValues<AddSuccess<*>>) = AddSuccess<IsRootDataModel>( key = values(1u), version = values(2u), changes = values(3u) ) } }
1
null
1
8
287377518680ab59adeb3bb93d1e37f8329e5eb7
1,814
maryk
Apache License 2.0
app/src/main/java/com/techbeloved/hymnbook/playlists/AddToPlaylistDialogFragment.kt
techbeloved
133,724,406
false
null
package com.techbeloved.hymnbook.playlists import android.database.sqlite.SQLiteConstraintException import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import androidx.databinding.DataBindingUtil import androidx.fragment.app.viewModels import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.transition.Scene import androidx.transition.Slide import androidx.transition.TransitionManager import com.google.android.material.bottomsheet.BottomSheetDialogFragment import com.google.android.material.snackbar.Snackbar import com.google.android.material.textfield.TextInputEditText import com.jakewharton.rxbinding3.widget.textChanges import com.techbeloved.hymnbook.R import com.techbeloved.hymnbook.databinding.DialogFragmentAddToPlaylistBinding import com.techbeloved.hymnbook.hymnlisting.HymnItemModel import dagger.hilt.android.AndroidEntryPoint import io.reactivex.disposables.CompositeDisposable import timber.log.Timber import java.util.* const val EXTRA_SELECTED_HYMN_ID = "selectedHymnId" @AndroidEntryPoint class AddToPlaylistDialogFragment : BottomSheetDialogFragment() { private val clickListener: HymnItemModel.ClickListener<HymnItemModel> = object : HymnItemModel.ClickListener<HymnItemModel> { override fun onItemClick(view: View, item: HymnItemModel) { viewModel.addSelectedHymnToPlaylist(item.id) } } private val disposables = CompositeDisposable() private val viewModel: ManagePlaylistViewModel by viewModels() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val selectedHymnId = requireArguments().getInt(EXTRA_SELECTED_HYMN_ID) viewModel.updateSelectedHymnId(selectedHymnId) } private lateinit var playlistAdapter: SimplePlaylistsAdapter private lateinit var binding: DialogFragmentAddToPlaylistBinding override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = DataBindingUtil.inflate(inflater, R.layout.dialog_fragment_add_to_playlist, container, false) val sceneRoot: ViewGroup = binding.sceneRootAddToPlaylist val selectPlaylistScene = Scene.getSceneForLayout(sceneRoot, R.layout.dialog_select_playlist, requireContext()) val createPlaylistScene = Scene.getSceneForLayout(sceneRoot, R.layout.dialog_create_new_playlist, requireContext()) val slide = Slide() slide.slideEdge = Gravity.RIGHT binding.dialogSelectPlaylist.buttonSelectPlaylistAddNew.setOnClickListener { TransitionManager.go(createPlaylistScene, slide) } // setup create new playlist screen createPlaylistScene.setEnterAction { Timber.i("Enter create new playlist") val titleEdittext = sceneRoot.findViewById<TextInputEditText>(R.id.edittext_create_new_playlist_title) val descriptionEditText = sceneRoot.findViewById<TextInputEditText>(R.id.edittext_create_new_playlist_description) val saveButton = sceneRoot.findViewById<Button>(R.id.button_create_new_playlist_save) titleEdittext.textChanges().skipInitialValue() .subscribe({ title -> Timber.i("Title: %s", title) if (title.isNotEmpty() && !saveButton.isEnabled) { saveButton.isEnabled = true } }, { Timber.w(it) }) .let { disposables.add(it) } saveButton.setOnClickListener { if (titleEdittext.text != null) { val playlistCreate = PlaylistEvent.Create( titleEdittext.text.toString(), descriptionEditText.text?.toString(), Date()) viewModel.saveFavoriteInNewPlaylist(playlistCreate) } } } createPlaylistScene.setExitAction { if (!disposables.isDisposed) disposables.dispose() } playlistAdapter = SimplePlaylistsAdapter(clickListener) binding.dialogSelectPlaylist.recyclerviewSelectPlaylist.apply { adapter = playlistAdapter layoutManager = LinearLayoutManager(requireContext()) addItemDecoration(DividerItemDecoration(requireContext(), RecyclerView.VERTICAL)) } return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.playlists.observe(viewLifecycleOwner, { playlists -> playlistAdapter.submitList(playlists) }) viewModel.favoriteSaved.observe(viewLifecycleOwner, { saved -> showFavoriteSavedSnackbar(saved) }) } private fun showFavoriteSavedSnackbar(favoriteStatus: ManagePlaylistViewModel.SaveStatus) { when (favoriteStatus) { ManagePlaylistViewModel.SaveStatus.Saved -> { Snackbar.make(requireView().rootView, R.string.success_adding_to_playlist, Snackbar.LENGTH_SHORT) .show() } is ManagePlaylistViewModel.SaveStatus.SaveFailed -> { if (favoriteStatus.error is SQLiteConstraintException) { Snackbar.make(requireView().rootView, R.string.error_hymn_already_exist, Snackbar.LENGTH_SHORT) .show() } Timber.w(favoriteStatus.error) } ManagePlaylistViewModel.SaveStatus.Dismiss -> dismiss() } Timber.i("Added: %s", favoriteStatus) } override fun onDestroy() { super.onDestroy() if (!disposables.isDisposed) disposables.dispose() } }
4
Kotlin
8
8
0d92143b2fad211d0d75c49dfc5fec66f809e1c8
5,983
hymnbook
MIT License
app/src/main/java/com/example/landmarkexplorer/MainActivity.kt
mfundomthabela
870,098,108
false
{"Kotlin": 4837}
package com.example.landmarkexplorer import android.content.Intent import android.os.Bundle import android.widget.Button import androidx.appcompat.app.AppCompatActivity import com.google.android.gms.maps.CameraUpdateFactory import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.OnMapReadyCallback import com.google.android.gms.maps.SupportMapFragment import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import com.google.firebase.auth.FirebaseAuth class MainActivity : AppCompatActivity(), OnMapReadyCallback { private lateinit var mMap: GoogleMap private lateinit var auth: FirebaseAuth override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initialize Firebase Auth auth = FirebaseAuth.getInstance() // Get the SupportMapFragment and request notification when the map is ready to be used. val mapFragment = supportFragmentManager .findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync(this) val logoutButton: Button = findViewById(R.id.logoutButton) logoutButton.setOnClickListener { auth.signOut() startActivity(Intent(this, Login::class.java)) finish() } } override fun onMapReady(googleMap: GoogleMap) { mMap = googleMap val landmark = LatLng(-34.0, 151.0) // Sydney mMap.addMarker(MarkerOptions().position(landmark).title("Sydney")) mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(landmark, 10f)) } }
0
Kotlin
0
0
85e5da2989f5790c1651e86e9127a8c1d1109ec3
1,674
LandmarkExplorer
MIT License
Demos/Ktor/src/main/kotlin/com/groupdocs/ui/comparison/ktor/status/GeneralStatusPages.kt
groupdocs-comparison
65,550,714
false
null
package com.groupdocs.ui.viewer.ktor.status import io.ktor.http.* import io.ktor.server.plugins.statuspages.* import io.ktor.server.response.* fun StatusPagesConfig.generalStatusPages() { exception<Throwable> { call, cause -> call.application.environment.log.error("Something unexpected happened!", cause) call.respondText(text = "Something unexpected happened!", status = HttpStatusCode.InternalServerError) } }
8
null
9
7
4d289958d8fc6ab338bbcfca8e82d237b71838be
438
GroupDocs.Comparison-for-Java
MIT License
src/main/kotlin/no/nav/amt_altinn_acl/service/RolleService.kt
navikt
497,788,149
false
null
package no.nav.amt_altinn_acl.service import no.nav.amt_altinn_acl.domain.AltinnRettighet import no.nav.amt_altinn_acl.domain.TiltaksarrangorRolleType import no.nav.amt_altinn_acl.domain.TiltaksarrangorRoller import org.springframework.beans.factory.annotation.Value import org.springframework.stereotype.Service @Service class RolleService( @Value("\${altinn.koordinator-service-code}") private val altinnKoordinatorServiceCode: String, @Value("\${altinn.veileder-service-code}") private val altinnVeilederServiceCode: String, private val rettigheterService: RettigheterService ) { fun hentTiltaksarrangorRoller(norskIdent: String): List<TiltaksarrangorRoller> { val rettigheter = rettigheterService.hentAlleRettigheter(norskIdent) return hentTiltaksarrangorRoller(rettigheter) } private fun hentTiltaksarrangorRoller(rettigheter: List<AltinnRettighet>): List<TiltaksarrangorRoller> { val altinnRollerMap = mutableMapOf<String, MutableList<TiltaksarrangorRolleType>>() rettigheter.forEach { val rolle = mapAltinnRettighetTilRolle(it.serviceCode) ?: return@forEach val roller = altinnRollerMap.computeIfAbsent(it.organisasjonsnummer) { mutableListOf() } roller.add(rolle) } return altinnRollerMap.map { TiltaksarrangorRoller(it.key, it.value) } } private fun mapAltinnRettighetTilRolle(rettighetId: String): TiltaksarrangorRolleType? { return when(rettighetId) { altinnKoordinatorServiceCode -> TiltaksarrangorRolleType.KOORDINATOR altinnVeilederServiceCode -> TiltaksarrangorRolleType.VEILEDER else -> null } } }
0
Kotlin
0
0
af4ba8bda89a5a1f5b0149b9343019d2240ca903
1,573
amt-altinn-acl
MIT License
myandroidutil/src/main/java/com/starsoft/myandroidutil/linkClickUtils/LinkHelperFun.kt
DmitryStarkin
315,625,438
false
null
/* * Copyright (c) 2021. Dmitry Starkin Contacts: [email protected] * * 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 * //www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an «AS IS» BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("LinkClickUtils") package com.starsoft.myandroidutil.linkClickUtils import android.content.ActivityNotFoundException import android.content.Context import android.content.Intent import android.content.pm.ResolveInfo import android.net.Uri import android.text.Spannable import android.text.method.LinkMovementMethod import android.text.style.URLSpan import android.text.util.Linkify import android.view.MotionEvent import android.widget.TextView import com.starsoft.myandroidutil.linkClickUtils.TextViewLinkHandler.DispatchNoLinkTouchBehavior.* import com.starsoft.myandroidutil.stringext.EMPTY_STRING import com.starsoft.myandroidutil.stringext.LINK_PREFIX import com.starsoft.myandroidutil.stringext.WEB_PROTOCOL_REGEX_STRING import java.util.regex.Pattern /** * Created by Dmitry Starkin on 08.05.2021 13:35. */ abstract class TextViewLinkHandler(private val consumeTouch: DispatchNoLinkTouchBehavior = CONSUME_NO_LINK_TOUCH) : LinkMovementMethod() { override fun onTouchEvent(widget: TextView, buffer: Spannable, event: MotionEvent): Boolean { if (event.action != MotionEvent.ACTION_UP && event.action != MotionEvent.ACTION_DOWN) return consumeTouch.behavior var x = event.x.toInt() var y = event.y.toInt() x -= widget.totalPaddingLeft y -= widget.totalPaddingTop x += widget.scrollX y += widget.scrollY val off: Int = widget.layout.let { it.getOffsetForHorizontal(it.getLineForVertical(y), x.toFloat()) } val link = buffer.getSpans(off, off, URLSpan::class.java) if (!link.isNullOrEmpty()) { return if(event.action == MotionEvent.ACTION_UP){ onLinkClick(link[0].url) true } else { true } } return consumeTouch.behavior } abstract fun onLinkClick(link: String) enum class DispatchNoLinkTouchBehavior(val behavior: Boolean){ CONSUME_NO_LINK_TOUCH(true), DISPATCH_NO_LINK_TOUCH(false) } } class ExternalLinkHandler(dispatchTouch: DispatchNoLinkTouchBehavior = CONSUME_NO_LINK_TOUCH, private val action: (String) -> Unit) : TextViewLinkHandler(dispatchTouch) { override fun onLinkClick(link: String) { action(link) } } class LinkHandlerStub( dispatchTouch: DispatchNoLinkTouchBehavior = CONSUME_NO_LINK_TOUCH ) : TextViewLinkHandler(dispatchTouch) { override fun onLinkClick(link: String) { // Stub } } fun TextView.highlightLinks(pattern: Pattern) { Linkify.addLinks(this, pattern, null) } fun String.extractProtocol(): String { return Regex(WEB_PROTOCOL_REGEX_STRING).find(this)?.value ?: EMPTY_STRING } fun Context.openWebLink(link: String, choicerMessage: String = EMPTY_STRING) { val linkToOpen = if (link.extractProtocol().isEmpty()) { "$LINK_PREFIX$link" } else { link } val intent = Intent(Intent.ACTION_VIEW, Uri.parse(linkToOpen)) intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // needed for call Activity using context outside other Activity this.packageManager?.apply { intent.resolveActivity(this)?.apply { try { [email protected](intent) } catch (e: ActivityNotFoundException) { [email protected]( Intent.createChooser( intent, choicerMessage ) ) } } } } fun Context.sendEmail(eMails: Array<String>, fields: EmailsField = EmailsField() ) { if(eMails.isNotEmpty()) { val intent = Intent() intent.action = Intent.ACTION_SEND intent.type = "message/rfc822" intent.putExtra(Intent.EXTRA_EMAIL, eMails) // TODO Dmitry intent.putExtra(Intent.EXTRA_SUBJECT, fields.sender) intent.putExtra(Intent.EXTRA_TEXT, fields.caption) val packageManager = this.applicationContext.packageManager val matches: List<ResolveInfo> = packageManager.queryIntentActivities(intent, 0) if (matches.isNotEmpty()) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) val choicer = Intent.createChooser(intent, fields.choicerMessage) choicer.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) this.applicationContext.startActivity(choicer); } else if (fields.reserveLink.isNotEmpty()) { this.openWebLink(fields.reserveLink) } } } data class EmailsField( val choicerMessage: String = EMPTY_STRING, val sender : String = EMPTY_STRING, val caption : String = EMPTY_STRING, val reserveLink: String = EMPTY_STRING )
0
Kotlin
0
3
81499c5f97421bbe892c47fa1e46bab569f641d2
5,412
my_android_utils
Apache License 2.0
HW9/src/main/kotlin/ru/otus/spring/kushchenko/hw9/service/AuthorServiceImpl.kt
ElenaKushchenko
139,555,821
false
{"Kotlin": 821703, "HTML": 46397, "TypeScript": 32941, "CSS": 751, "Dockerfile": 203}
package ru.otus.spring.kushchenko.hw9.service import org.springframework.stereotype.Service import ru.otus.spring.kushchenko.hw9.repository.AuthorRepository /** * Created by Елена on Июль, 2018 */ @Service class AuthorServiceImpl(private val repository: AuthorRepository) : AuthorService { override fun getAll(): List<String> = repository.getAll() }
0
Kotlin
0
0
0286627b4e66873c28d18174d125b63e5723e4f7
357
otus-spring-2018-06-hw
MIT License
livekit-android-test/src/test/java/io/livekit/android/room/RoomReconnectionMockE2ETest.kt
livekit
339,892,560
false
null
/* * Copyright 2023 LiveKit, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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 io.livekit.android.room import io.livekit.android.MockE2ETest import io.livekit.android.mock.MockAudioStreamTrack import io.livekit.android.mock.MockPeerConnection import io.livekit.android.room.track.LocalAudioTrack import io.livekit.android.util.toPBByteString import kotlinx.coroutines.ExperimentalCoroutinesApi import livekit.LivekitRtc import org.junit.Assert import org.junit.Assert.assertEquals import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.webrtc.PeerConnection /** * For tests that only target one reconnection type. * * Tests that cover all connection types should be put in [RoomReconnectionTypesMockE2ETest]. */ @ExperimentalCoroutinesApi @RunWith(RobolectricTestRunner::class) class RoomReconnectionMockE2ETest : MockE2ETest() { private fun prepareForReconnect() { wsFactory.onOpen = { wsFactory.listener.onOpen(wsFactory.ws, createOpenResponse(wsFactory.request)) val softReconnectParam = wsFactory.request.url .queryParameter(SignalClient.CONNECT_QUERY_RECONNECT) ?.toIntOrNull() ?: 0 if (softReconnectParam == 0) { simulateMessageFromServer(SignalClientTest.JOIN) } else { simulateMessageFromServer(SignalClientTest.RECONNECT) } } } @Test fun softReconnectSendsSyncState() = runTest { room.setReconnectionType(ReconnectType.FORCE_SOFT_RECONNECT) connect() prepareForReconnect() disconnectPeerConnection() // Wait so that the reconnect job properly starts first. testScheduler.advanceTimeBy(1000) connectPeerConnection() testScheduler.advanceUntilIdle() val sentRequests = wsFactory.ws.sentRequests val sentSyncState = sentRequests.any { requestString -> val sentRequest = LivekitRtc.SignalRequest.newBuilder() .mergeFrom(requestString.toPBByteString()) .build() return@any sentRequest.hasSyncState() } Assert.assertTrue(sentSyncState) } @Test fun softReconnectConfiguration() = runTest { room.setReconnectionType(ReconnectType.FORCE_SOFT_RECONNECT) connect() prepareForReconnect() disconnectPeerConnection() // Wait so that the reconnect job properly starts first. testScheduler.advanceTimeBy(1000) connectPeerConnection() val rtcEngine = component.rtcEngine() val rtcConfig = (rtcEngine.subscriber.peerConnection as MockPeerConnection).rtcConfig assertEquals(PeerConnection.IceTransportsType.RELAY, rtcConfig.iceTransportsType) val sentIceServers = SignalClientTest.RECONNECT.reconnect.iceServersList .map { server -> server.toWebrtc() } assertEquals(sentIceServers, rtcConfig.iceServers) } @Test fun fullReconnectRepublishesTracks() = runTest { room.setReconnectionType(ReconnectType.FORCE_FULL_RECONNECT) connect() // publish track room.localParticipant.publishAudioTrack( LocalAudioTrack( "", MockAudioStreamTrack(id = SignalClientTest.LOCAL_TRACK_PUBLISHED.trackPublished.cid), ), ) prepareForReconnect() disconnectPeerConnection() // Wait so that the reconnect job properly starts first. testScheduler.advanceTimeBy(1000) connectPeerConnection() testScheduler.advanceUntilIdle() val sentRequests = wsFactory.ws.sentRequests val sentAddTrack = sentRequests.any { requestString -> val sentRequest = LivekitRtc.SignalRequest.newBuilder() .mergeFrom(requestString.toPBByteString()) .build() return@any sentRequest.hasAddTrack() } println(sentRequests) Assert.assertTrue(sentAddTrack) } }
64
null
70
176
bee0a1e1e23725c77b97b2b94e3c1be3b9d12e8a
4,598
client-sdk-android
Apache License 2.0
app/src/main/java/com/dawinder/customshapes_jc/ui/shapes/HexagonShape.kt
DawinderGill
670,214,470
false
null
package com.dawinder.customshapes_jc.ui.shapes import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.Outline import androidx.compose.ui.graphics.Path import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Density import androidx.compose.ui.unit.LayoutDirection import kotlin.math.min import kotlin.math.sqrt /** * Custom [Shape] implementation representing the shape of a hexagon. * * The hexagon shape is created using a [Path] with lines connecting its points based * on the provided [size] of the hexagon. */ class HexagonShape : Shape { /** * Creates the [Outline] for the hexagon shape. * * @param size The [Size] of the hexagon. * @param layoutDirection The [LayoutDirection] of the hexagon. * @param density The [Density] of the hexagon. * @return The [Outline] representing the hexagon shape. */ override fun createOutline( size: Size, layoutDirection: LayoutDirection, density: Density ): Outline { return Outline.Generic( path = drawCustomHexagonPath(size) ) } } /** * Draws the path for the hexagon shape. * * @param size The [Size] of the hexagon. * @return The [Path] representing the hexagon shape. */ private fun drawCustomHexagonPath(size: Size): Path { return Path().apply { val radius = min(size.width / 2f, size.height / 2f) val triangleHeight = (sqrt(3.0) * radius / 2) val centerX = size.width / 2 val centerY = size.height / 2 moveTo(x = centerX, y = centerY + radius) lineTo(x = (centerX - triangleHeight).toFloat(), y = centerY + radius / 2) lineTo(x = (centerX - triangleHeight).toFloat(), y = centerY - radius / 2) lineTo(x = centerX, y = centerY - radius) lineTo(x = (centerX + triangleHeight).toFloat(), y = centerY - radius / 2) lineTo(x = (centerX + triangleHeight).toFloat(), y = centerY + radius / 2) close() } }
0
Kotlin
0
1
3dac4209ccbaa15a5d423a2c99e08b18decfb660
2,001
CustomShapes-JetpackCompose
Apache License 2.0
lightbulb-application/src/main/java/com/github/rooneyandshadows/lightbulb/application/activity/service/foreground/ForegroundServiceWrapper.kt
RooneyAndShadows
423,132,153
false
null
package com.github.rooneyandshadows.lightbulb.application.activity.service.foreground import android.content.* import android.os.Build import android.os.Bundle import android.os.IBinder import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner import com.github.rooneyandshadows.lightbulb.application.BuildConfig import com.github.rooneyandshadows.lightbulb.application.activity.BaseActivity import com.github.rooneyandshadows.lightbulb.application.activity.receivers.InternetConnectionStatusBroadcastReceiver import com.github.rooneyandshadows.lightbulb.application.activity.service.NOTIFICATION_CHANNEL_DESCRIPTION_KEY import com.github.rooneyandshadows.lightbulb.application.activity.service.NOTIFICATION_CHANNEL_ID_KEY import com.github.rooneyandshadows.lightbulb.application.activity.service.NOTIFICATION_CHANNEL_NAME_KEY import com.github.rooneyandshadows.lightbulb.application.activity.service.configuration.ForegroundServiceRegistry import com.github.rooneyandshadows.lightbulb.application.activity.service.foreground.ForegroundService.ForegroundServiceBinder import com.github.rooneyandshadows.lightbulb.application.activity.service.foreground.ForegroundService.ForegroundServiceConfiguration class ForegroundServiceWrapper( private val activity: BaseActivity, val serviceRegistry: ForegroundServiceRegistry ) : DefaultLifecycleObserver { private var isBound = false private var boundService: ForegroundService? = null private val foregroundServiceConnection: ServiceConnection = object : ServiceConnection { @Override override fun onServiceConnected(name: ComponentName, service: IBinder) { val binder = service as ForegroundServiceBinder [email protected] = binder.getService() isBound = true } @Override override fun onServiceDisconnected(name: ComponentName?) { isBound = false } } @Override override fun onCreate(owner: LifecycleOwner) { super.onCreate(owner) startService() } private fun startService() { val configuration = serviceRegistry.configuration val intent = Intent(activity, serviceRegistry.foregroundServiceClass).apply { putExtra( NOTIFICATION_CHANNEL_ID_KEY, configuration.notificationChannelId ) putExtra( NOTIFICATION_CHANNEL_NAME_KEY, configuration.notificationChannelName ) putExtra( NOTIFICATION_CHANNEL_DESCRIPTION_KEY, configuration.notificationChannelDescription ) } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { activity.startForegroundService(intent) } else { activity.startService(intent) } activity.bindService(intent, foregroundServiceConnection, Context.BIND_AUTO_CREATE) } private fun stopService() { activity.unbindService(foregroundServiceConnection) activity.stopService(Intent(activity, serviceRegistry.foregroundServiceClass)) } }
0
Kotlin
0
0
cbc27a1919a4ac68ff322e036f1b02248b62dd99
3,179
lightbulb-application
Apache License 2.0
core/src/main/kotlin/materialui/styles/transitions/options/TransitionsOptions.kt
subroh0508
167,797,152
false
null
package materialui.styles.transitions.options import kotlinext.js.jsObject import kotlinx.css.properties.Timing import kotlinx.css.properties.Transitions import materialui.styles.transitions.* import materialui.styles.transitions.create external interface TransitionsOptions { var easing: EasingOptions? var duration: DurationOptions? var getAutoHeightDuration: ((Number) -> Number)? } internal var TransitionsOptions.create: TransitionsCreate? by TransitionsCreateDelegate fun TransitionsOptions.create(func: (Array<out String>, TransitionCreateOptions) -> Transitions) { create = { props, options -> func(props, toTransitionCreateOptions(options)) } } fun TransitionsOptions.easing(block: EasingOptions.() -> Unit) { easing = (easing ?: jsObject { }).apply(block) } fun TransitionsOptions.duration(block: DurationOptions.() -> Unit) { duration = (duration ?: jsObject { }).apply(block) } private fun toTransitionCreateOptions(obj: dynamic): TransitionCreateOptions = jsObject { duration = obj["duration"] as? Int easing = (obj["easing"] as? String)?.let(::Timing) delay = obj["delay"] as? Int }
14
Kotlin
27
81
a959a951ace3b9bd49dc5405bea150d4d53cf162
1,131
kotlin-material-ui
MIT License
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/apple/XcodeDirectIntegrationIT.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.gradle.apple import org.gradle.util.GradleVersion import org.jetbrains.kotlin.gradle.testbase.* import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.condition.OS import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsSource import java.util.stream.Stream @OsCondition(supportedOn = [OS.MAC], enabledOnCI = [OS.MAC]) @DisplayName("Tests for Xcode <-> Kotlin direct integration") @NativeGradlePluginTests class XcodeDirectIntegrationIT : KGPBaseTest() { @DisplayName("Xcode direct integration") @ParameterizedTest(name = "{displayName} with {1}, {0} and isStatic={2}") @ArgumentsSource(XcodeArgumentsProvider::class) fun test( gradleVersion: GradleVersion, iosApp: String, isStatic: Boolean, ) { project("xcodeDirectIntegration", gradleVersion) { projectPath.resolve("shared/build.gradle.kts") .modify { it.replace(".framework {", ".framework {\n isStatic = $isStatic") } buildXcodeProject(xcodeproj = projectPath.resolve("iosApp$iosApp/iosApp.xcodeproj")) } } internal class XcodeArgumentsProvider : GradleArgumentsProvider() { override fun provideArguments(context: ExtensionContext): Stream<out Arguments> { return super.provideArguments(context).flatMap { arguments -> val gradleVersion = arguments.get().first() Stream.of("BuildPhase", "SchemePreAction", "SchemePreActionSpm").flatMap { iosApp -> Stream.of(true, false).map { isStatic -> Arguments.of(gradleVersion, iosApp, isStatic) } } } } } }
182
null
5706
48,889
c46c3c26038158cf80a739431ac8807ac4bbbc0c
2,083
kotlin
Apache License 2.0
shuttle/icons/data/src/main/kotlin/shuttle/icons/data/IconPacksRepositoryImpl.kt
4face-studi0
462,194,990
false
null
package shuttle.icons.data import android.content.pm.PackageManager import android.content.res.Resources import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Paint import android.graphics.PorterDuff import android.graphics.PorterDuffXfermode import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.Drawable import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserException import org.xmlpull.v1.XmlPullParserFactory import shuttle.apps.domain.model.AppId import shuttle.icons.data.model.IconPack import shuttle.icons.domain.IconPacksRepository import java.io.IOException import java.util.Locale import java.util.Random @Suppress("DEPRECATION") class IconPacksRepositoryImpl( private val packageManager: PackageManager, private val dispatcher: CoroutineDispatcher ) : IconPacksRepository { private var cache = mutableMapOf<AppId, IconPack>() override suspend fun getDrawableIcon(iconPackId: AppId, appId: AppId, defaultDrawable: Drawable): Drawable = getDrawableIcon(loadIconPack(iconPackId), appId, defaultDrawable) override suspend fun getBitmapIcon(iconPackId: AppId, appId: AppId, defaultBitmap: Bitmap): Bitmap = getBitmapIcon(loadIconPack(iconPackId), appId, defaultBitmap) @Suppress("LongMethod", "ComplexMethod", "SwallowedException") // Copied from SO, to be refactored private suspend fun loadIconPack(id: AppId): IconPack = withContext(dispatcher) { cache[id]?.let { return@withContext it } val packageName = id.value var iconPackResources: Resources? = null val drawables = mutableMapOf<AppId, IconPack.DrawableName>() var frontImage: Bitmap? = null val backImages: MutableList<Bitmap> = ArrayList() var maskImage: Bitmap? = null var factor = 1.0f var totalIcons = 0 fun loadBitmap(drawableName: String): Bitmap? { val iconPackId = iconPackResources!!.getIdentifier(drawableName, "drawable", packageName) if (iconPackId > 0) { val bitmap = iconPackResources!!.getDrawable(iconPackId) if (bitmap is BitmapDrawable) return bitmap.bitmap } return null } // load appfilter.xml from the icon pack package try { var xpp: XmlPullParser? = null iconPackResources = packageManager.getResourcesForApplication(packageName) val appFilterId = iconPackResources.getIdentifier("appfilter", "xml", packageName) if (appFilterId > 0) { xpp = iconPackResources.getXml(appFilterId) } else { // no resource found, try to open it from assets folder try { val appFilterStream = iconPackResources.assets.open("appfilter.xml") val factory = XmlPullParserFactory.newInstance() factory.isNamespaceAware = true xpp = factory.newPullParser() xpp.setInput(appFilterStream, "utf-8") } catch (e1: IOException) { //Ln.d("No appfilter.xml file"); } } if (xpp != null) { var eventType = xpp.eventType while (eventType != XmlPullParser.END_DOCUMENT) { if (eventType == XmlPullParser.START_TAG) { if (xpp.name == "iconback") { for (i in 0 until xpp.attributeCount) { if (xpp.getAttributeName(i).startsWith("img")) { val drawableName = xpp.getAttributeValue(i) val iconback = loadBitmap(drawableName) if (iconback != null) backImages.add(iconback) } } } else if (xpp.name == "iconmask") { if (xpp.attributeCount > 0 && xpp.getAttributeName(0) == "img1") { val drawableName = xpp.getAttributeValue(0) maskImage = loadBitmap(drawableName) } } else if (xpp.name == "iconupon") { if (xpp.attributeCount > 0 && xpp.getAttributeName(0) == "img1") { val drawableName = xpp.getAttributeValue(0) frontImage = loadBitmap(drawableName) } } else if (xpp.name == "scale") { // mFactor if (xpp.attributeCount > 0 && xpp.getAttributeName(0) == "factor") { factor = java.lang.Float.valueOf(xpp.getAttributeValue(0)) } } else if (xpp.name == "item") { var componentName: String? = null var drawableName: String? = null for (i in 0 until xpp.attributeCount) { if (xpp.getAttributeName(i) == "component") { componentName = xpp.getAttributeValue(i) } else if (xpp.getAttributeName(i) == "drawable") { drawableName = xpp.getAttributeValue(i) } } if (!drawables.containsKey(componentName?.id())) { drawables[componentName!!.id()] = drawableName!!.drawableName() totalIcons += 1 } } } eventType = xpp.next() } } } catch (e: PackageManager.NameNotFoundException) { //Ln.d("Cannot load icon pack"); } catch (e: XmlPullParserException) { //Ln.d("Cannot parse icon pack appfilter.xml"); } catch (e: IOException) { e.printStackTrace() } IconPack( id = id, resources = iconPackResources!!, drawables = drawables, frontImage = frontImage, backImages = backImages, maskImage = maskImage, factor = factor ).also { cache[id] = it } } private suspend fun getDrawableIcon( iconPack: IconPack, appId: AppId, defaultDrawable: Drawable ): Drawable = withContext(dispatcher) { val appPackageName = appId.value val drawables = iconPack.drawables val launchIntent = packageManager.getLaunchIntentForPackage(appPackageName) var componentName: String? = null if (launchIntent != null) componentName = packageManager.getLaunchIntentForPackage(appPackageName)!!.component.toString() var drawable = drawables[componentName?.id()]?.value if (drawable != null) { return@withContext loadDrawable(iconPack, drawable) ?: defaultDrawable } else { // try to get a resource with the component filename if (componentName != null) { val start = componentName.indexOf("{") + 1 val end = componentName.indexOf("}", start) if (end > start) { drawable = componentName .substring(start, end) .lowercase(Locale.getDefault()) .replace(".", "_") .replace("/", "_") if (iconPack.resources.getIdentifier(drawable, "drawable", iconPack.id.value) > 0) { return@withContext loadDrawable(iconPack, drawable) ?: defaultDrawable } } } } return@withContext defaultDrawable } private suspend fun getBitmapIcon( iconPack: IconPack, appId: AppId, defaultBitmap: Bitmap ): Bitmap = withContext(dispatcher) { val appPackageName = appId.value val resources = iconPack.resources val drawables = iconPack.drawables val componentName = packageManager.getLaunchIntentForPackage(appPackageName)?.component?.toString() var drawable = drawables[componentName?.id()]?.value if (drawable != null) { return@withContext loadBitmap(iconPack, drawable) ?: generateBitmap(iconPack, defaultBitmap) } else { // try to get a resource with the component filename if (componentName != null) { val start = componentName.indexOf("{") + 1 val end = componentName.indexOf("}", start) if (end > start) { drawable = componentName .substring(start, end) .lowercase(Locale.getDefault()) .replace(".", "_") .replace("/", "_") if (resources.getIdentifier(drawable, "drawable", iconPack.id.value) > 0) return@withContext loadBitmap(iconPack, drawable) ?: defaultBitmap } } return@withContext generateBitmap(iconPack, defaultBitmap) } } private fun loadBitmap(iconPack: IconPack, drawableName: String): Bitmap? { val resources = iconPack.resources val id = resources.getIdentifier(drawableName, "drawable", iconPack.id.value) if (id > 0) { val bitmap = resources.getDrawable(id) if (bitmap is BitmapDrawable) return bitmap.bitmap } return null } private fun loadDrawable(iconPack: IconPack, drawableName: String): Drawable? { val resources = iconPack.resources val id = resources.getIdentifier(drawableName, "drawable", iconPack.id.value) return if (id > 0) { resources.getDrawable(id) } else null } private fun generateBitmap(iconPack: IconPack, defaultBitmap: Bitmap): Bitmap { val frontImage = iconPack.frontImage val backImages = iconPack.backImages val maskImage = iconPack.maskImage val factor = iconPack.factor // if no support images in the icon pack return the bitmap itself if (backImages.isEmpty()) return defaultBitmap val r = Random() val backImageInd = r.nextInt(backImages.size) val backImage = backImages[backImageInd] val w = backImage.width val h = backImage.height // create a bitmap for the result val result = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) val mCanvas = Canvas(result) // draw the background first mCanvas.drawBitmap(backImage, 0f, 0f, null) // create a mutable mask bitmap with the same mask val scaledBitmap: Bitmap = if (defaultBitmap.width > w || defaultBitmap.height > h) { Bitmap.createScaledBitmap(defaultBitmap, (w * factor).toInt(), (h * factor).toInt(), false) } else { Bitmap.createBitmap(defaultBitmap) } if (maskImage != null) { // draw the scaled bitmap with mask val mutableMask = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) val maskCanvas = Canvas(mutableMask) maskCanvas.drawBitmap(maskImage, 0f, 0f, Paint()) // paint the bitmap with mask into the result val paint = Paint(Paint.ANTI_ALIAS_FLAG) paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_OUT) mCanvas.drawBitmap( scaledBitmap, ((w - scaledBitmap.width) / 2).toFloat(), ((h - scaledBitmap.height) / 2).toFloat(), null ) mCanvas.drawBitmap(mutableMask, 0f, 0f, paint) paint.xfermode = null } else // draw the scaled bitmap with the back image as mask { val mutableMask = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888) val maskCanvas = Canvas(mutableMask) maskCanvas.drawBitmap(backImage, 0f, 0f, Paint()) // paint the bitmap with mask into the result val paint = Paint(Paint.ANTI_ALIAS_FLAG) paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.DST_IN) mCanvas.drawBitmap( scaledBitmap, ((w - scaledBitmap.width) / 2).toFloat(), ((h - scaledBitmap.height) / 2).toFloat(), null ) mCanvas.drawBitmap(mutableMask, 0f, 0f, paint) paint.xfermode = null } // paint the front if (frontImage != null) { mCanvas.drawBitmap(frontImage, 0f, 0f, null) } // store the bitmap in cache // BitmapCache.getInstance(mContext).putBitmap(key, result); // return it return result } private fun String.id() = AppId(this) private fun String.drawableName() = IconPack.DrawableName(this) }
12
Kotlin
0
14
bd4faa49be9c3787b5b8786edc2a014a45969c1e
13,291
Shuttle
Apache License 2.0
runtime/src/main/java/io/novafoundation/nova/runtime/storage/source/query/api/QueryableModule.kt
novasamatech
415,834,480
false
{"Kotlin": 11121812, "Rust": 25308, "Java": 17664, "JavaScript": 425}
package io.novafoundation.nova.runtime.storage.source.query.api import io.novafoundation.nova.runtime.storage.source.query.StorageQueryContext import io.novasama.substrate_sdk_android.runtime.metadata.module.Module import io.novasama.substrate_sdk_android.runtime.metadata.storage typealias QueryableStorageKeyBinder<K> = (keyInstance: Any) -> K typealias QueryableStorageKeyBinder2<K1, K2> = (keyInstance: Any) -> Pair<K1, K2> interface QueryableModule { val module: Module } context(StorageQueryContext) fun <T : Any> QueryableModule.storage0(name: String, binding: QueryableStorageBinder0<T>): QueryableStorageEntry0<T> { return RealQueryableStorageEntry0(module.storage(name), binding) } context(StorageQueryContext) fun <I, T> QueryableModule.storage1( name: String, binding: QueryableStorageBinder1<I, T>, keyBinding: QueryableStorageKeyBinder<I>? = null ): QueryableStorageEntry1<I, T> { return RealQueryableStorageEntry1(module.storage(name), binding, keyBinding) } context(StorageQueryContext) fun <I1, I2, T : Any> QueryableModule.storage2( name: String, binding: QueryableStorageBinder2<I1, I2, T>, ): QueryableStorageEntry2<I1, I2, T> { return RealQueryableStorageEntry2(module.storage(name), binding) }
13
Kotlin
7
50
127f8739ca86dc74d006f018237daed0de5095a1
1,258
nova-wallet-android
Apache License 2.0
src/test/kotlin/dev/shtanko/algorithms/leetcode/WildcardMatchingTest.kt
ashtanko
203,993,092
false
{"Kotlin": 6608183, "Shell": 1168, "Makefile": 961}
/* * Copyright 2020 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.shtanko.algorithms.leetcode import java.util.stream.Stream import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.extension.ExtensionContext import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.Arguments import org.junit.jupiter.params.provider.ArgumentsProvider import org.junit.jupiter.params.provider.ArgumentsSource class WildcardMatchingTest { @ParameterizedTest @ArgumentsSource(InputArgumentsProvider::class) fun `simple test`(str1: String, str2: String, expected: Boolean) { val pair = str1 to str2 val actual = pair.isMatch() assertEquals(expected, actual) } private class InputArgumentsProvider : ArgumentsProvider { override fun provideArguments(context: ExtensionContext?): Stream<out Arguments> = Stream.of( Arguments.of( "aa", "a", false, ), Arguments.of( "aa", "*", true, ), Arguments.of( "cb", "?a", false, ), Arguments.of( "adceb", "*a*b", true, ), Arguments.of( "acdcb", "a*c?b", false, ), Arguments.of( "", "", true, ), Arguments.of( "1", "1", true, ), Arguments.of( "1", "2", false, ), ) } }
4
Kotlin
0
19
d7f842ebc3041ed6a407782d4f5da2e6a53c34df
2,325
kotlab
Apache License 2.0
app/src/main/java/design/bosson/spookyhalloweensounds/SoundManager.kt
PretzelJones
209,155,390
false
{"Kotlin": 38765, "Java": 1217}
package design.bosson.spookyhalloweensounds import android.content.Context import android.content.res.ColorStateList import android.graphics.drawable.Drawable import android.media.MediaPlayer import android.view.View import android.widget.Button import android.widget.Toast import androidx.core.content.ContextCompat class SoundManager { private val mediaPlayerMap = mutableMapOf<View, MediaPlayer>() private val originalDrawableMap = mutableMapOf<Button, Drawable>() private var currentPlayingMediaPlayer: MediaPlayer? = null private var currentPlayingButton: Button? = null // Method for playing short sounds (like in ScrollingActivity) fun playShortSound(context: Context, soundId: Int, button: View) { try { val buttonWithDrawable = button as Button val existingMediaPlayer = mediaPlayerMap[buttonWithDrawable] if (existingMediaPlayer != null) { // If the sound is already playing, do nothing if (!existingMediaPlayer.isPlaying) { existingMediaPlayer.start() setButtonColorPlaying(context, buttonWithDrawable) // Set color when playing } } else { // Create and start a new MediaPlayer for short sound val mediaPlayer = MediaPlayer.create(context, soundId) mediaPlayer.setOnCompletionListener { it.release() mediaPlayerMap.remove(buttonWithDrawable) resetButtonColor(context, buttonWithDrawable) // Reset button color when done } mediaPlayerMap[buttonWithDrawable] = mediaPlayer setButtonColorPlaying(context, buttonWithDrawable) // Set color to indicate playing mediaPlayer.start() } } catch (e: Exception) { e.printStackTrace() } } // Method for playing long sounds (like in MovieActivity) fun playLongSound(context: Context, soundId: Int, button: View) { try { // Cast the View to Button val buttonWithDrawable = button as Button // If a sound is already playing, handle pause/resume logic if (currentPlayingMediaPlayer != null && currentPlayingButton != null) { if (currentPlayingButton == buttonWithDrawable) { if (currentPlayingMediaPlayer!!.isPlaying) { // Pause the audio currentPlayingMediaPlayer!!.pause() // Revert the icon to the original drawable but keep the color changed resetButtonDrawable(context, currentPlayingButton!!) // Revert to original drawable setButtonColorPaused(context, currentPlayingButton!!) // Keep the color changed to indicate paused } else { // Resume the audio currentPlayingMediaPlayer!!.start() // Set the icon to ic_pause and keep the color changed setPauseDrawable(context, currentPlayingButton!!) // Set pause drawable setButtonColorPlaying(context, currentPlayingButton!!) // Keep the color changed to indicate playing } return } else { // Release the current media player and reset the previous button's drawable and color currentPlayingMediaPlayer!!.release() resetButtonDrawable(context, currentPlayingButton!!) resetButtonColor(context, currentPlayingButton!!) // Reset the color of the previous button currentPlayingMediaPlayer = null } } // Store the original drawable if not already stored if (!originalDrawableMap.containsKey(buttonWithDrawable)) { val originalDrawable = buttonWithDrawable.compoundDrawables[1] // Top drawable originalDrawableMap[buttonWithDrawable] = originalDrawable } // Create a new MediaPlayer instance for long sound val mediaPlayer = MediaPlayer.create(context, soundId) mediaPlayer.setOnCompletionListener { it.release() resetButtonDrawable(context, buttonWithDrawable) // Revert to original drawable when sound finishes resetButtonColor(context, buttonWithDrawable) // Reset the button color when sound finishes } // Change the button color and icon to indicate sound is playing setButtonColorPlaying(context, buttonWithDrawable) setPauseDrawable(context, buttonWithDrawable) // Set pause drawable mediaPlayer.start() // Long press to restart the sound buttonWithDrawable.setOnLongClickListener { try { mediaPlayer.seekTo(0) mediaPlayer.start() } catch (e: IllegalStateException) { e.printStackTrace() Toast.makeText(context, "Unable to restart sound", Toast.LENGTH_SHORT).show() } true } // Set the current media player and button currentPlayingMediaPlayer = mediaPlayer currentPlayingButton = buttonWithDrawable } catch (e: Exception) { e.printStackTrace() } } // Helper function to set button color when sound is paused (icon reverts to original) private fun setButtonColorPaused(context: Context, button: Button) { button.backgroundTintList = ColorStateList.valueOf( ContextCompat.getColor(context, R.color.colorButtonPressed) // Paused state color ) } // Helper function to set button color when sound is playing private fun setButtonColorPlaying(context: Context, button: Button) { button.backgroundTintList = ColorStateList.valueOf( ContextCompat.getColor(context, R.color.colorButtonPressed) // Playing state color ) } // Helper function to set the pause drawable on the button private fun setPauseDrawable(context: Context, button: Button) { val pauseDrawable = ContextCompat.getDrawable(context, R.drawable.ic_pause) pauseDrawable?.setTint(ContextCompat.getColor(context, android.R.color.black)) button.setCompoundDrawablesWithIntrinsicBounds(null, pauseDrawable, null, null) } // Helper function to reset the button's drawable to its original state fun resetButtonDrawable(context: Context, button: Button) { val originalDrawable = originalDrawableMap[button] if (originalDrawable != null) { button.setCompoundDrawablesWithIntrinsicBounds(null, originalDrawable, null, null) } } // Helper to reset button color fun resetButtonColor(context: Context, button: Button) { button.backgroundTintList = ColorStateList.valueOf( ContextCompat.getColor(context, R.color.colorButton) ) } fun releaseAllSounds() { // Release all media players mediaPlayerMap.values.forEach { mediaPlayer -> mediaPlayer.stop() mediaPlayer.release() } mediaPlayerMap.clear() // Reset the current playing long sound if any if (currentPlayingMediaPlayer != null) { currentPlayingMediaPlayer!!.stop() currentPlayingMediaPlayer!!.release() currentPlayingMediaPlayer = null currentPlayingButton = null } } }
0
Kotlin
0
0
6a02052132ca56f2c93659a69ee64c78480702aa
7,721
SpookyHalloweenSounds
Apache License 2.0
app/src/main/java/com/jakting/shareclean/utils/MessageExt.kt
TigerBeanst
259,865,941
false
null
package com.jakting.shareclean.utils import android.content.Context import android.util.Log import android.view.View import android.widget.Toast import com.google.android.material.snackbar.Snackbar fun Context?.logd(message: String) = if (isDebug()) { Log.d("TigerBeanst", message) } else { } fun Context?.toast(message: Any, isStringResId: Boolean = false) = if (isStringResId) { Toast.makeText(this, this!!.getString(message as Int), Toast.LENGTH_SHORT).show() } else { Toast.makeText(this, message.toString(), Toast.LENGTH_SHORT).show() } fun Context?.longtoast(message: CharSequence) = Toast.makeText(this, message, Toast.LENGTH_LONG).show() fun View.sbar(message: CharSequence) = Snackbar.make(this, message, Snackbar.LENGTH_SHORT) fun View.sbarlong(message: CharSequence) = Snackbar.make(this, message, Snackbar.LENGTH_LONG) fun View.sbarin(message: CharSequence) = Snackbar.make(this, message, Snackbar.LENGTH_INDEFINITE)
10
Kotlin
14
133
7825c8d6b8563cd57317fc9180bfe28a3a3d375a
1,001
TigerInTheWall
Apache License 2.0
Module/DebugToolsNoOp/src/main/java/com/lwh/debugtools/view/floatingview/FloatingMagnetView.kt
l-w-h
224,768,316
false
null
package com.lwh.debugtools.view.floatingview import android.content.Context import android.util.AttributeSet import android.widget.FrameLayout /** * @author lwh * @Date 2019/11/21 18:00 * @description 磁力吸附悬浮窗 */ open class FloatingMagnetView constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : FrameLayout(context, attrs, defStyleAttr) { }
1
Kotlin
1
1
cd9ccb97577f17d77884643942a0c642be03dae8
394
DebugTools
Apache License 2.0
extensions/src/main/java/com/google/android/apps/muzei/util/LivecycleJob.kt
lovetuzitong
184,654,520
false
null
/* * Copyright 2018 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.google.android.apps.muzei.util import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job private fun Lifecycle.createJob(): Job = Job().also { job -> addObserver(object : DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { removeObserver(this) job.cancel() } }) } private val lifecycleCoroutineScopes = mutableMapOf<Lifecycle, CoroutineScope>() val Lifecycle.coroutineScope: CoroutineScope get() = lifecycleCoroutineScopes[this] ?: createJob().let { job -> val newScope = CoroutineScope(job + Dispatchers.Main) lifecycleCoroutineScopes[this] = newScope job.invokeOnCompletion { lifecycleCoroutineScopes -= this } newScope } val LifecycleOwner.coroutineScope get() = lifecycle.coroutineScope
1
null
1
1
af52c6c40e9824aaf34c7cff024b99e1f67bc20b
1,594
muzei
Apache License 2.0
app/src/main/java/com/example/template/utils/mainScreen/AppState.kt
098suraj
591,545,007
false
null
package com.example.template.utils.mainScreen sealed class AppState() { object Empty : AppState() object Loading : AppState() data class Success(var data: List<*>) : AppState() data class Error(var error: String) : AppState() }
0
Kotlin
0
0
9276bb61b54d3b089a4585b77bd4365fc765dcb3
246
GreedyGameAssignment
Apache License 2.0
core/data/src/test/kotlin/com/ekezet/othello/core/data/serialize/PositionSerializerKtTest.kt
atomgomba
754,770,216
false
{"Kotlin": 209676}
package com.ekezet.othello.core.data.serialize import com.ekezet.othello.core.data.models.Position import kotlin.test.Test import kotlin.test.assertEquals internal class PositionSerializerKtTest { @Test fun asString_NonNull() { assertEquals("A1", Position(0, 0).asString()) assertEquals("H8", Position(7, 7).asString()) } @Test fun asString_Null() { val position: Position? = null assertEquals("passed", position.asString()) } @Test(expected = IndexOutOfBoundsException::class) fun asString_Error() { Position(8, 8).asString() } }
0
Kotlin
0
1
5f76e3b36e25fedb124f62f3f4a3b54659273e08
611
othello
Apache License 2.0
app/src/main/java/com/valmiraguiar/wefit/WeFitApp.kt
valmiraguiar
538,635,080
false
{"Kotlin": 30416, "Java": 216}
package com.valmiraguiar.wefit import android.app.Application import com.valmiraguiar.wefit.di.MainModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin class WeFitApp : Application() { override fun onCreate() { super.onCreate() startKoin { androidLogger() androidContext(this@WeFitApp) } MainModule.load() } }
0
Kotlin
0
0
521048d9ad8537d9c0099a56c89830efc11bc0ce
466
wefit-challenge
Apache License 2.0
integration-tests/hibernate-orm-panache-kotlin/src/main/kotlin/io/quarkus/it/panache/kotlin/Status.kt
quarkusio
139,914,932
false
null
package io.quarkus.it.panache.kotlin enum class Status { LIVING, DECEASED }
1,824
null
1699
9,440
9755810c17969df15dfc3a04f162d4083dfb7400
80
quarkus
Apache License 2.0
solar/src/main/java/com/chiksmedina/solar/outline/notes/DocumentAdd.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.outline.notes import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.chiksmedina.solar.outline.NotesGroup val NotesGroup.DocumentAdd: ImageVector get() { if (_documentAdd != null) { return _documentAdd!! } _documentAdd = Builder( name = "DocumentAdd", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd ) { moveTo(10.9436f, 1.25f) horizontalLineTo(13.0564f) curveTo(14.8942f, 1.25f, 16.3498f, 1.25f, 17.489f, 1.4031f) curveTo(18.6614f, 1.5608f, 19.6104f, 1.8929f, 20.3588f, 2.6412f) curveTo(20.6516f, 2.9341f, 20.6516f, 3.409f, 20.3588f, 3.7019f) curveTo(20.0659f, 3.9948f, 19.591f, 3.9948f, 19.2981f, 3.7019f) curveTo(18.8749f, 3.2787f, 18.2952f, 3.025f, 17.2892f, 2.8898f) curveTo(16.2615f, 2.7516f, 14.9068f, 2.75f, 13.0f, 2.75f) horizontalLineTo(11.0f) curveTo(9.0932f, 2.75f, 7.7385f, 2.7516f, 6.7108f, 2.8898f) curveTo(5.7048f, 3.025f, 5.1251f, 3.2787f, 4.7019f, 3.7019f) curveTo(4.2787f, 4.1251f, 4.025f, 4.7048f, 3.8898f, 5.7108f) curveTo(3.7516f, 6.7385f, 3.75f, 8.0932f, 3.75f, 10.0f) verticalLineTo(14.0f) curveTo(3.75f, 15.9068f, 3.7516f, 17.2615f, 3.8898f, 18.2892f) curveTo(4.025f, 19.2952f, 4.2787f, 19.8749f, 4.7019f, 20.2981f) curveTo(5.1251f, 20.7213f, 5.7048f, 20.975f, 6.7108f, 21.1102f) curveTo(7.7385f, 21.2484f, 9.0932f, 21.25f, 11.0f, 21.25f) horizontalLineTo(13.0f) curveTo(14.9068f, 21.25f, 16.2615f, 21.2484f, 17.2892f, 21.1102f) curveTo(18.2952f, 20.975f, 18.8749f, 20.7213f, 19.2981f, 20.2981f) curveTo(19.994f, 19.6022f, 20.2048f, 18.5208f, 20.2414f, 15.9892f) curveTo(20.2474f, 15.575f, 20.588f, 15.2441f, 21.0022f, 15.2501f) curveTo(21.4163f, 15.2561f, 21.7472f, 15.5967f, 21.7412f, 16.0108f) curveTo(21.7061f, 18.4383f, 21.549f, 20.1685f, 20.3588f, 21.3588f) curveTo(19.6104f, 22.1071f, 18.6614f, 22.4392f, 17.489f, 22.5969f) curveTo(16.3498f, 22.75f, 14.8942f, 22.75f, 13.0564f, 22.75f) horizontalLineTo(10.9436f) curveTo(9.1058f, 22.75f, 7.6502f, 22.75f, 6.511f, 22.5969f) curveTo(5.3386f, 22.4392f, 4.3896f, 22.1071f, 3.6412f, 21.3588f) curveTo(2.8929f, 20.6104f, 2.5608f, 19.6614f, 2.4031f, 18.489f) curveTo(2.25f, 17.3498f, 2.25f, 15.8942f, 2.25f, 14.0564f) verticalLineTo(9.9436f) curveTo(2.25f, 8.1058f, 2.25f, 6.6502f, 2.4031f, 5.511f) curveTo(2.5608f, 4.3386f, 2.8929f, 3.3896f, 3.6412f, 2.6412f) curveTo(4.3896f, 1.8929f, 5.3386f, 1.5608f, 6.511f, 1.4031f) curveTo(7.6502f, 1.25f, 9.1058f, 1.25f, 10.9436f, 1.25f) close() moveTo(18.1131f, 7.0456f) curveTo(19.1739f, 5.9848f, 20.8937f, 5.9848f, 21.9544f, 7.0456f) curveTo(23.0152f, 8.1063f, 23.0152f, 9.8261f, 21.9544f, 10.8869f) lineTo(17.1991f, 15.6422f) curveTo(16.9404f, 15.901f, 16.7654f, 16.076f, 16.5693f, 16.2289f) curveTo(16.3387f, 16.4088f, 16.0892f, 16.563f, 15.8252f, 16.6889f) curveTo(15.6007f, 16.7958f, 15.3659f, 16.8741f, 15.0187f, 16.9897f) lineTo(12.9351f, 17.6843f) curveTo(12.4751f, 17.8376f, 11.9679f, 17.7179f, 11.625f, 17.375f) curveTo(11.2821f, 17.0321f, 11.1624f, 16.5249f, 11.3157f, 16.0649f) lineTo(11.9963f, 14.0232f) curveTo(12.001f, 14.0091f, 12.0056f, 13.9951f, 12.0102f, 13.9813f) curveTo(12.1259f, 13.6342f, 12.2042f, 13.3993f, 12.3111f, 13.1748f) curveTo(12.437f, 12.9108f, 12.5912f, 12.6613f, 12.7711f, 12.4307f) curveTo(12.924f, 12.2346f, 13.099f, 12.0596f, 13.3578f, 11.8009f) curveTo(13.3681f, 11.7906f, 13.3785f, 11.7802f, 13.3891f, 11.7696f) lineTo(18.1131f, 7.0456f) close() moveTo(20.8938f, 8.1062f) curveTo(20.4188f, 7.6313f, 19.6488f, 7.6313f, 19.1738f, 8.1062f) lineTo(18.992f, 8.288f) curveTo(19.0019f, 8.3215f, 19.0132f, 8.3571f, 19.0262f, 8.3945f) curveTo(19.1202f, 8.6657f, 19.2988f, 9.0243f, 19.6372f, 9.3628f) curveTo(19.9757f, 9.7013f, 20.3343f, 9.8798f, 20.6055f, 9.9738f) curveTo(20.6429f, 9.9868f, 20.6785f, 9.9981f, 20.712f, 10.008f) lineTo(20.8938f, 9.8262f) curveTo(21.3687f, 9.3512f, 21.3687f, 8.5812f, 20.8938f, 8.1062f) close() moveTo(19.5664f, 11.1536f) curveTo(19.2485f, 10.9866f, 18.9053f, 10.7521f, 18.5766f, 10.4234f) curveTo(18.2479f, 10.0947f, 18.0134f, 9.7515f, 17.8464f, 9.4336f) lineTo(14.4497f, 12.8303f) curveTo(14.1487f, 13.1314f, 14.043f, 13.2388f, 13.9538f, 13.3532f) curveTo(13.841f, 13.4979f, 13.7442f, 13.6545f, 13.6652f, 13.8202f) curveTo(13.6028f, 13.9511f, 13.5539f, 14.0936f, 13.4193f, 14.4976f) lineTo(13.019f, 15.6985f) lineTo(13.3015f, 15.981f) lineTo(14.5024f, 15.5807f) curveTo(14.9064f, 15.4461f, 15.0489f, 15.3972f, 15.1798f, 15.3348f) curveTo(15.3455f, 15.2558f, 15.5021f, 15.159f, 15.6468f, 15.0462f) curveTo(15.7612f, 14.957f, 15.8686f, 14.8513f, 16.1697f, 14.5503f) lineTo(19.5664f, 11.1536f) close() moveTo(7.25f, 9.0f) curveTo(7.25f, 8.5858f, 7.5858f, 8.25f, 8.0f, 8.25f) horizontalLineTo(14.5f) curveTo(14.9142f, 8.25f, 15.25f, 8.5858f, 15.25f, 9.0f) curveTo(15.25f, 9.4142f, 14.9142f, 9.75f, 14.5f, 9.75f) horizontalLineTo(8.0f) curveTo(7.5858f, 9.75f, 7.25f, 9.4142f, 7.25f, 9.0f) close() moveTo(7.25f, 13.0f) curveTo(7.25f, 12.5858f, 7.5858f, 12.25f, 8.0f, 12.25f) horizontalLineTo(10.5f) curveTo(10.9142f, 12.25f, 11.25f, 12.5858f, 11.25f, 13.0f) curveTo(11.25f, 13.4142f, 10.9142f, 13.75f, 10.5f, 13.75f) horizontalLineTo(8.0f) curveTo(7.5858f, 13.75f, 7.25f, 13.4142f, 7.25f, 13.0f) close() moveTo(7.25f, 17.0f) curveTo(7.25f, 16.5858f, 7.5858f, 16.25f, 8.0f, 16.25f) horizontalLineTo(9.5f) curveTo(9.9142f, 16.25f, 10.25f, 16.5858f, 10.25f, 17.0f) curveTo(10.25f, 17.4142f, 9.9142f, 17.75f, 9.5f, 17.75f) horizontalLineTo(8.0f) curveTo(7.5858f, 17.75f, 7.25f, 17.4142f, 7.25f, 17.0f) close() } } .build() return _documentAdd!! } private var _documentAdd: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
8,039
SolarIconSetAndroid
MIT License