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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/Utopia.kt | brillenheini | 123,725,036 | false | null | import io.reactivex.Flowable
import io.reactivex.rxkotlin.Flowables
import io.reactivex.rxkotlin.subscribeBy
import io.reactivex.schedulers.Schedulers
import mu.KotlinLogging
import print.LinePrinter
import search.createArchiveSearcher
import java.awt.Desktop
import java.io.File
import java.io.FileNotFoundException
import java.net.URI
import java.util.concurrent.TimeUnit
private const val DEBUG = false
private const val DATA_DIR = "../utopia2-data"
private const val INTERVAL = 90L
private val searchTerms = listOf("utopia", "utopie")
private val logger = KotlinLogging.logger {}
/**
* The Utopia Machine 2.0.
*
* Repeatedly search crawl data from http://commoncrawl.org/ for _utopia_
* and send the result to a printer and a web browser.
*/
fun main(args: Array<String>) {
logger.warn("Starting Utopia Machine 2.0")
val printer = LinePrinter(DEBUG, searchTerms)
printer.printIntro()
val searcher = Flowable.merge(
listFiles(DATA_DIR).map { createArchiveSearcher(it, searchTerms) }
)
val timer = Flowable.interval(INTERVAL, TimeUnit.SECONDS, Schedulers.computation())
.onBackpressureDrop()
Flowables.zip(
timer,
searcher,
{ tick, pair ->
logger.trace { "tick $tick" }
pair
})
.repeat()
.subscribeOn(Schedulers.computation())
.subscribeBy(
onNext = { (url, snippet) ->
if (url != null && snippet != null) {
logger.debug(url)
val uri = URI(url)
uri.browse()
printer.printSnippet(uri, snippet)
}
},
onComplete = { exit() },
onError = {
logger.error("error processing archives", it)
exit()
}
)
waitForExit()
}
private fun listFiles(dirName: String): List<File> {
val data = File(dirName)
if (data.exists()) {
val files = data.listFiles()
if (files != null && files.isNotEmpty()) {
logger.info { "found ${files.size} files in $dirName" }
return files.toList()
}
}
throw FileNotFoundException("$dirName does not exist or is empty, run ./gradlew downloadCrawls")
}
/**
* Open this URI in the desktop's web browser.
*/
private fun URI.browse() {
if (!DEBUG && Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(this)
}
}
private val lock = java.lang.Object()
private fun waitForExit() {
synchronized(lock) {
lock.wait()
}
}
private fun exit() {
synchronized(lock) {
lock.notify()
}
}
| 0 | Kotlin | 0 | 1 | cd7e158fc5604c8175fa58b63053392c9ad991d6 | 2,660 | utopia2 | Apache License 2.0 |
src/main/kotlin/server/ExpressApp.kt | mesoneer-ag | 139,211,166 | false | {"Kotlin": 17697, "Shell": 307} | package server
external class ExpressApp {
fun get(route: String, handle: (req: dynamic, res: Response) -> Unit)
fun post(route: String, handle: (req: dynamic, res: Response) -> Unit)
fun put(route: String, handle: (req: dynamic, res: Response) -> Unit)
fun listen(i: Int, function: () -> Unit)
}
external interface Response {
fun send(data: Any?)
fun status(code: Int)
} | 0 | Kotlin | 0 | 0 | 63508fb590332de9afe7de05a814b52cbad4e5c7 | 398 | antjs-engine | MIT License |
src/main/kotlin/ru/scisolutions/scicmscore/api/graphql/CustomScalarsRegistration.kt | borisblack | 737,700,232 | false | {"Kotlin": 709559, "HTML": 4440, "Shell": 282, "Dockerfile": 123} | package ru.scisolutions.scicmscore.api.graphql
import com.netflix.graphql.dgs.DgsComponent
import com.netflix.graphql.dgs.DgsRuntimeWiring
import graphql.scalars.ExtendedScalars
import graphql.schema.idl.RuntimeWiring
import java.util.regex.Pattern
@DgsComponent
class CustomScalarsRegistration {
@DgsRuntimeWiring
fun addScalars(builder: RuntimeWiring.Builder): RuntimeWiring.Builder =
builder
.scalar(
ExtendedScalars.newRegexScalar("Email")
.addPattern(Pattern.compile("\\w+@\\w+\\.\\w+"))
.build()
)
} | 0 | Kotlin | 0 | 4 | 586b6bbe338cc3ea678b1116f9d095a276d20d99 | 603 | scicms-core | Apache License 2.0 |
basick/src/main/java/com/mozhimen/basick/utilk/app/UtilKAppInstall.kt | mozhimen | 353,952,154 | false | null | package com.mozhimen.basick.utilk.android.content
import android.app.Activity
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInstaller
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.annotation.RequiresPermission
import com.mozhimen.basick.elemk.android.os.cons.CVersCode
import com.mozhimen.basick.lintk.optin.OptInDeviceRoot
import com.mozhimen.basick.manifestk.annors.AManifestKRequire
import com.mozhimen.basick.manifestk.cons.CPermission
import com.mozhimen.basick.utilk.bases.BaseUtilK
import com.mozhimen.basick.utilk.android.app.UtilKPermission
import com.mozhimen.basick.utilk.android.app.UtilKLaunchActivity
import com.mozhimen.basick.utilk.android.os.UtilKBuildVersion
import java.io.*
import java.nio.charset.Charset
/**
* @ClassName UtilKAppInstall
* @Description TODO
* @Author mozhimen / <NAME>
* @Date 2023/1/4 23:29
* @Version 1.0
*/
@AManifestKRequire(
CPermission.INSTALL_PACKAGES,
CPermission.REQUEST_INSTALL_PACKAGES,
CPermission.READ_INSTALL_SESSIONS,
CPermission.REPLACE_EXISTING_PACKAGE
)
object UtilKAppInstall : BaseUtilK() {
/**
* 是否有包安装权限
* @return Boolean
*/
@JvmStatic
@RequiresPermission(CPermission.REQUEST_INSTALL_PACKAGES)
fun isAppInstallsPermissionEnable(): Boolean {
return UtilKPermission.hasPackageInstalls().also { Log.d(TAG, "isAppInstallsPermissionEnable: $it") }
}
///////////////////////////////////////////////////////////////////////////
/**
* 打开包安装权限
* @param activity Activity
*/
@JvmStatic
fun openSettingAppInstall(activity: Activity) {
UtilKLaunchActivity.startManageInstallSource(activity)
}
/**
* 打开包安装权限
* @param context Context
*/
@JvmStatic
fun openSettingAppInstall(context: Context) {
UtilKLaunchActivity.startManageInstallSource(context)
}
@JvmStatic
@Throws(Exception::class)
@OptInDeviceRoot
@RequiresPermission(CPermission.INSTALL_PACKAGES)
fun installRoot(apkPathWithName: String): Boolean {
require(apkPathWithName.isNotEmpty()) { "$TAG please check apk file path" }
var result = false
var process: Process? = null
var outputStream: OutputStream? = null
var bufferedReader: BufferedReader? = null
try {
process = Runtime.getRuntime().exec("su")
outputStream = process.outputStream
val command = "pm install -r $apkPathWithName\n"
outputStream.write(command.toByteArray())
outputStream.flush()
outputStream.write("exit\n".toByteArray())
outputStream.flush()
process.waitFor()
bufferedReader = BufferedReader(InputStreamReader(process.errorStream))
val msg = StringBuilder()
var line: String?
while (bufferedReader.readLine().also { line = it } != null) {
msg.append(line)
}
Log.d(TAG, "installRoot msg is $msg")
if (!msg.toString().contains("Failure", ignoreCase = true)) {
result = true
}
} catch (e: Exception) {
throw e
} finally {
outputStream?.flush()
outputStream?.close()
bufferedReader?.close()
process?.destroy()
}
return result.also { Log.d(TAG, "installRoot: result $it apkPathWithName $apkPathWithName") }
}
/**
* 手动安装
* if sdk >= 24 add provider
* @param apkPathWithName String
*/
@JvmStatic
@RequiresPermission(CPermission.INSTALL_PACKAGES)
fun installHand(apkPathWithName: String) {
UtilKLaunchActivity.startInstall(_context, apkPathWithName)
}
/**
* 静默安装
* @param apkPathWithName String 绝对路径
* @param pkgName String
* @return Boolean
*/
@JvmStatic
@RequiresPermission(CPermission.INSTALL_PACKAGES)
fun installSilence(apkPathWithName: String, pkgName: String): Boolean {
var result = "EMPTY"
val cmd =
if (UtilKBuildVersion.isAfterV_24_7_N()) {
arrayOf("pm", "install", "-r", "-i", pkgName, "--user", "0", apkPathWithName)
} else {
arrayOf("pm", "install", "-i", pkgName, "-r", apkPathWithName)
}
val processBuilder = ProcessBuilder(*cmd)
var process: Process? = null
var inputStream: InputStream? = null
val byteArrayOutputStream = ByteArrayOutputStream()
try {
var readCount: Int
process = processBuilder.start()
byteArrayOutputStream.write('/'.code)
inputStream = process.inputStream
while (inputStream.read().also { readCount = it } != -1) {
byteArrayOutputStream.write(readCount)
}
result = String(byteArrayOutputStream.toByteArray(), Charset.forName("UTF-8"))
Log.d(TAG, "installSilence result $result")
} catch (e: IOException) {
e.printStackTrace()
Log.e(TAG, "installSilence IOException ${e.message}")
} catch (e: Exception) {
e.printStackTrace()
Log.e(TAG, "installSilence Exception ${e.message}")
} finally {
byteArrayOutputStream.close()
inputStream?.close()
process?.destroy()
}
return result.contains("success", ignoreCase = true)
}
/**
* 静默安装
* @param apkPathWithName String
* @param receiver Class<LoadKReceiverInstall>
*/
@JvmStatic
@RequiresPermission(CPermission.INSTALL_PACKAGES)
fun installSilence(apkPathWithName: String, receiver: Class<*>) {
if (UtilKBuildVersion.isAfterV_28_9_P()) {
installSilenceAfter28(apkPathWithName, receiver)
} else {
installSilenceBefore28(apkPathWithName)
}
}
/**
* 静默安装适配 SDK28 之前的安装方法
* @param apkPathWithName String
* @return Boolean
*/
@JvmStatic
@RequiresPermission(CPermission.INSTALL_PACKAGES)
fun installSilenceBefore28(apkPathWithName: String): Boolean {
var process: Process? = null
var resSuccessBufferedReader: BufferedReader? = null
var resErrorBufferedReader: BufferedReader? = null
val msgSuccess = StringBuilder()
val msgError = StringBuilder()
val cmd: Array<String> =
if (UtilKBuildVersion.isAfterV_24_7_N()) {
arrayOf("pm", "install", "-i", UtilKPackage.getPackageName(), "-r", apkPathWithName)
} else {
arrayOf("pm", "install", "-r", apkPathWithName)
}
try {
process = ProcessBuilder(*cmd).start()
resSuccessBufferedReader = BufferedReader(InputStreamReader(process.inputStream))
resErrorBufferedReader = BufferedReader(InputStreamReader(process.errorStream))
var msg: String?
while (resSuccessBufferedReader.readLine().also { msg = it } != null) {
msgSuccess.append(msg)
}
while (resErrorBufferedReader.readLine().also { msg = it } != null) {
msgError.append(msg)
}
} catch (e: Exception) {
e.printStackTrace()
Log.e(TAG, "installSilenceBefore28: Exception ${e.message}")
} finally {
resSuccessBufferedReader?.close()
resErrorBufferedReader?.close()
process?.destroy()
}
return msgSuccess.toString().contains("success", ignoreCase = true) //如果含有success单词则认为安装成功
}
/**
* 静默安装 SDK28 之后的
* @param apkPathWithName String
* @param receiver Class<LoadKReceiverInstall>
*/
@JvmStatic
@RequiresApi(CVersCode.V_28_9_P)
@RequiresPermission(CPermission.INSTALL_PACKAGES)
fun installSilenceAfter28(apkPathWithName: String, receiver: Class<*>) {
Log.d(TAG, "installSilenceAfter28 pathApk $apkPathWithName")
val apkFile = File(apkPathWithName)
val packageInstaller = UtilKPackageManager.getPackageInstaller(_context)
val sessionParams = PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL)
sessionParams.setSize(apkFile.length())
val sessionId: Int = createSession(packageInstaller, sessionParams)
Log.d(TAG, "installSilenceAfter28 sessionId $sessionId")
if (sessionId != -1) {
val isCopySuccess = copyApkFile(packageInstaller, sessionId, apkPathWithName)
Log.d(TAG, "installSilenceAfter28 copySuccess $isCopySuccess")
if (isCopySuccess) {
execInstall(packageInstaller, sessionId, receiver)
}
}
}
/**
* 命令安装
* @param packageInstaller PackageInstaller
* @param sessionId Int
* @param receiver Class<*>
*/
@JvmStatic
@RequiresPermission(CPermission.INSTALL_PACKAGES)
fun execInstall(packageInstaller: PackageInstaller, sessionId: Int, receiver: Class<*>) {
var session: PackageInstaller.Session? = null
try {
session = packageInstaller.openSession(sessionId)
val pendingIntent = PendingIntent.getBroadcast(_context, 1, Intent(_context, receiver), PendingIntent.FLAG_UPDATE_CURRENT)
session.commit(pendingIntent.intentSender)
Log.d(TAG, "execInstall begin")
} catch (e: IOException) {
e.printStackTrace()
Log.e(TAG, "execInstall: IOException ${e.message}")
} catch (e: Exception) {
e.printStackTrace()
Log.e(TAG, "execInstall: Exception ${e.message}")
} finally {
session?.close()
}
}
/**
* createSession
* @param packageInstaller PackageInstaller
* @param sessionParams SessionParams
* @return Int
*/
fun createSession(packageInstaller: PackageInstaller, sessionParams: PackageInstaller.SessionParams): Int {
var sessionId = -1
try {
sessionId = packageInstaller.createSession(sessionParams)
} catch (e: IOException) {
Log.e(TAG, "createSession: ${e.message}")
e.printStackTrace()
}
return sessionId
}
/**
* 拷贝
* @param packageInstaller PackageInstaller
* @param sessionId Int
* @param apkFilePathWithName String
* @return Boolean
*/
fun copyApkFile(packageInstaller: PackageInstaller, sessionId: Int, apkFilePathWithName: String): Boolean {
var fileInputStream: FileInputStream? = null
var outputStream: OutputStream? = null
var session: PackageInstaller.Session? = null
var success = false
try {
val apkFile = File(apkFilePathWithName)
session = packageInstaller.openSession(sessionId)
outputStream = session.openWrite("base.apk", 0, apkFile.length())
fileInputStream = FileInputStream(apkFile)
var total = 0
var count: Int
val buffer = ByteArray(65536)
while (fileInputStream.read(buffer).also { count = it } != -1) {
total += count
outputStream.write(buffer, 0, count)
}
session.fsync(outputStream)
success = true
Log.d(TAG, "copyApkFile success")
} catch (e: IOException) {
e.printStackTrace()
Log.e(TAG, "copyApkFile: IOException ${e.message}")
} finally {
session?.close()
outputStream?.flush()
outputStream?.close()
fileInputStream?.close()
}
return success
}
} | 0 | null | 6 | 2 | 5077b41303c564a4f7acd8e7df03133ebf1e04f2 | 11,783 | SwiftKit | Apache License 2.0 |
src/main/kotlin/dev/shtanko/algorithms/leetcode/DiffWaysToCompute.kt | ashtanko | 203,993,092 | false | {"Kotlin": 7380373, "Shell": 1168, "Makefile": 1144} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
/**
* 241. Different Ways to Add Parentheses
* @see <a href="https://leetcode.com/problems/different-ways-to-add-parentheses/">Source</a>
*/
fun interface DiffWaysToCompute {
fun compute(expression: String): List<Int>
}
class DiffWaysToComputeRecursive : DiffWaysToCompute {
// function to get the result of the operation
operator fun invoke(x: Int, y: Int, op: Char): Int {
if (op == '+') return x + y
if (op == '-') return x - y
return if (op == '*') x * y else 0
}
override fun compute(expression: String): List<Int> {
val results: MutableList<Int> = ArrayList()
if (expression.isBlank()) return results
var isNumber = true
for (i in expression.indices) {
// check if current character is an operator
if (!Character.isDigit(expression[i])) {
// if current character is not a digit then
// exp is not purely a number
isNumber = false
// list of first operands
val left = compute(expression.substring(0, i))
// list of second operands
val right = compute(expression.substring(i + 1))
// performing operations
for (x in left) {
for (y in right) {
val value = invoke(x, y, expression[i])
results.add(value)
}
}
}
}
if (isNumber) results.add(Integer.valueOf(expression))
return results
}
}
class DiffWaysToComputeDivideAndConquer : DiffWaysToCompute {
override fun compute(expression: String): List<Int> {
if (expression.isEmpty()) return emptyList()
return mutableListOf<Int>().apply {
expression.toCharArray().forEachIndexed { index, char ->
if (char in listOf('+', '-', '*')) {
val left = expression.substring(0, index)
val right = expression.substring(index + 1)
val leftNums = compute(left)
val rightNums = compute(right)
leftNums.forEach { num1 ->
rightNums.forEach { num2 ->
add(char.calculate(num1, num2))
}
}
}
}
if (isEmpty()) add(expression.toInt())
}
}
private fun Char.calculate(num1: Int, num2: Int) = when (this) {
'+' -> num1 + num2
'-' -> num1 - num2
'*' -> num1 * num2
else -> throw IllegalArgumentException("Symbol is not allowed")
}
}
| 6 | Kotlin | 0 | 19 | edb06efcddd1fb4989db0f6f2c624c098f563883 | 3,323 | kotlab | Apache License 2.0 |
http4k-openapi/src/main/kotlin/org/http4k/util/builders/NullableListBuilder.kt | savagematt | 251,337,496 | true | {"Kotlin": 1938601, "JavaScript": 133282, "Java": 31515, "Shell": 10427, "HTML": 2049, "Handlebars": 1130, "Pug": 944, "CSS": 832} | package org.http4k.util.builders
import kotlin.reflect.KFunction1
/**
* toList() will return null if the initial value was null and
* no items have been assigned
*/
class NullableListBuilder<T, Dsl : Builder<T, Dsl>>(
private val initial: List<T>?,
private val toBuilder: (T) -> Dsl
) {
constructor(initial: List<T>?, toBuilder: KFunction1<T, Dsl>) : this(initial, { toBuilder.call(it) })
private var all: MutableList<Dsl>? = initial?.map(toBuilder)?.toMutableList()
fun ensureValue(): MutableList<Dsl> {
if (all == null) all = mutableListOf()
return all!!
}
operator fun plusAssign(t: T) {
ensureValue() += toBuilder(t)
}
operator fun plusAssign(t: Collection<T>) {
ensureValue() += t.map(toBuilder)
}
fun map(fn: Dsl.() -> Unit) {
if (all == null) return
all!!
// run fn on each builder
.map { it.also(fn) }
.toMutableList()
}
fun build(): List<T>? = all?.map { it.build() }?.toList() ?: initial
} | 0 | Kotlin | 0 | 0 | 9cc8ef11121bfbe10a1cd0ca58a17885c297af52 | 1,046 | http4k | Apache License 2.0 |
http4k-openapi/src/main/kotlin/org/http4k/util/builders/NullableListBuilder.kt | savagematt | 251,337,496 | true | {"Kotlin": 1938601, "JavaScript": 133282, "Java": 31515, "Shell": 10427, "HTML": 2049, "Handlebars": 1130, "Pug": 944, "CSS": 832} | package org.http4k.util.builders
import kotlin.reflect.KFunction1
/**
* toList() will return null if the initial value was null and
* no items have been assigned
*/
class NullableListBuilder<T, Dsl : Builder<T, Dsl>>(
private val initial: List<T>?,
private val toBuilder: (T) -> Dsl
) {
constructor(initial: List<T>?, toBuilder: KFunction1<T, Dsl>) : this(initial, { toBuilder.call(it) })
private var all: MutableList<Dsl>? = initial?.map(toBuilder)?.toMutableList()
fun ensureValue(): MutableList<Dsl> {
if (all == null) all = mutableListOf()
return all!!
}
operator fun plusAssign(t: T) {
ensureValue() += toBuilder(t)
}
operator fun plusAssign(t: Collection<T>) {
ensureValue() += t.map(toBuilder)
}
fun map(fn: Dsl.() -> Unit) {
if (all == null) return
all!!
// run fn on each builder
.map { it.also(fn) }
.toMutableList()
}
fun build(): List<T>? = all?.map { it.build() }?.toList() ?: initial
} | 0 | Kotlin | 0 | 0 | 9cc8ef11121bfbe10a1cd0ca58a17885c297af52 | 1,046 | http4k | Apache License 2.0 |
pagingk_paging3_data/src/main/java/com/mozhimen/pagingk/paging3/data/widgets/PagingKDataMultiAdapter.kt | mozhimen | 747,018,353 | false | {"Kotlin": 124487} | package com.mozhimen.pagingk.data.widgets
import android.annotation.SuppressLint
import android.content.Context
import com.mozhimen.basick.utilk.android.util.UtilKLogWrapper
import android.util.SparseArray
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil.ItemCallback
import androidx.recyclerview.widget.RecyclerView
import com.mozhimen.basick.utilk.commons.IUtilK
import com.mozhimen.pagingk.data.R
import com.mozhimen.pagingk.data.bases.BasePagingKVHKProvider
import com.mozhimen.xmlk.vhk.VHKLifecycle
import java.lang.ref.WeakReference
/**
* @ClassName PagingKPagedListMultiAdapter
* @Description TODO
* @Author Mozhimen & <NAME>
* @Date 2023/10/11 11:44
* @Version 1.0
*/
open class PagingKDataMultiAdapter<DATA : Any, VH : VHKLifecycle>(itemCallback: ItemCallback<DATA>) : PagingKDataAdapter<DATA, VH>(itemCallback), IUtilK {
private val _pagingKVHKProviders by lazy(LazyThreadSafetyMode.NONE) { SparseArray<BasePagingKVHKProvider<DATA, VH>>() }
val pagingKVHKProviders get() = _pagingKVHKProviders
/////////////////////////////////////////////////////////////////////////////////
/**Fe
* 通过 ViewType 获取 BaseItemProvider
* 例如:如果ViewType经过特殊处理,可以重写此方法,获取正确的Provider
* (比如 ViewType 通过位运算进行的组合的)
*/
fun getPagingKVHKProvider(tag: String, viewType: Int): BasePagingKVHKProvider<DATA, VH>? =
_pagingKVHKProviders.get(viewType).also { UtilKLogWrapper.d(TAG, "getPagingKVHKProvider tag $tag viewType $viewType provider $it") }
fun getPagingKVHKProvider(holder: VH): BasePagingKVHKProvider<DATA, VH>? {
return holder.itemView.getTag(R.id.PagingKDataMultiAdapter_Key) as? BasePagingKVHKProvider<DATA, VH>?
}
/**
* 必须通过此方法,添加 provider
*/
fun addPagingKVHKProvider(item: BasePagingKVHKProvider<DATA, VH>) = apply {
item._adapterRef = WeakReference(this@PagingKDataMultiAdapter)
_pagingKVHKProviders.put(item.itemViewType, item)
}
/////////////////////////////////////////////////////////////////////////////////
override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): VH {
val recyclerKPageItem = getPagingKVHKProvider("onCreateViewHolder",viewType)
checkNotNull(recyclerKPageItem) { "ViewType: $viewType no such provider found,please use addItemProvider() first!" }
return recyclerKPageItem.onCreateViewHolder(parent.context, parent, viewType).apply {
itemView.setTag(R.id.PagingKDataMultiAdapter_Key, recyclerKPageItem)
}
}
@SuppressLint("MissingSuperCall")
override fun onBindViewHolder(holder: VH, item: DATA?, position: Int) {
getPagingKVHKProvider(holder)?.onBindViewHolder(holder, item, position)
?.also { UtilKLogWrapper.d(TAG, "onBindViewHolderInner: holder $holder item $item position $position") }
}
override fun onBindViewHolder(holder: VH, item: DATA?, position: Int, payloads: List<Any>) {
getPagingKVHKProvider(holder)?.onBindViewHolder(holder, item, position, payloads)
?.also { UtilKLogWrapper.d(TAG, "onBindViewHolderInner: holder $holder item $item position $position payloads $payloads") }
}
/////////////////////////////////////////////////////////////////////////////////
override fun onViewAttachedToWindow(holder: VH) {
val position = getPosition(holder)
getPagingKVHKProvider(holder)?.onViewAttachedToWindow(holder, position?.let { getItem(it) }, position)
}
override fun onViewDetachedFromWindow(holder: VH) {
val position = getPosition(holder)
getPagingKVHKProvider(holder)?.onViewDetachedFromWindow(holder, position?.let { getItem(it) }, position)
}
override fun onViewRecycled(holder: VH) {
val position = getPosition(holder)
getPagingKVHKProvider(holder)?.onViewRecycled(holder, position?.let { getItem(it) }, position)
}
} | 0 | Kotlin | 2 | 2 | 5d38803bddf5e5a70ee5f70408f7e7b5c152762e | 3,916 | APagingKit | Apache License 2.0 |
src/commonMain/kotlin/net/notjustanna/tartar/api/dsl/LexerFunctionTypes.kt | adriantodt | 251,127,025 | false | null | package net.notjustanna.tartar.api.dsl
import net.notjustanna.tartar.api.lexer.LexerContext
/**
* Function which receives a [LexerContext] as its receiver and a matched [Char] as its parameter.
*/
public typealias MatchFunction<T> = LexerContext<T>.(char: Char) -> Unit
/**
* Function which receives a [LexerDSL] as its receiver.
*/
public typealias LexerConfig<T> = LexerDSL<T>.() -> Unit
| 2 | Kotlin | 0 | 2 | dc839c08ae3801d5fd07787943b8e99039ce28c9 | 397 | tartar | Apache License 2.0 |
app/src/main/java/com/sik/sikcomposehub/ui/main/ProgressIndicatorLayout.kt | SilverIceKey | 807,532,704 | false | {"Kotlin": 25609} | package com.sik.sikcomposehub.ui.main
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.keyframes
import androidx.compose.animation.core.tween
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.sik.sikcomposeui.component.ProgressIndicator
import com.sik.sikcomposeui.component.VerticalProgressIndicator
@Composable
fun ProgressIndicatorLayout(navController: NavHostController, contentPadding: PaddingValues) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(contentPadding),
horizontalAlignment = Alignment.CenterHorizontally
) {
Button(onClick = {
navController.navigate("details") {
launchSingleTop = true
}
}) {
Text("Go to Details")
}
Spacer(modifier = Modifier.height(16.dp))
ProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.height(50.dp),
color = Color.Green,
strokeWidth = 15f,
initialProgress = 0f,
targetProgress = 1f,
animationSpec = tween(
durationMillis = 2000,
easing = LinearEasing
)
)
Spacer(modifier = Modifier.height(16.dp))
VerticalProgressIndicator(
modifier = Modifier
.width(50.dp)
.height(200.dp),
color = Color.Red,
strokeWidth = 15f,
initialProgress = 0f,
targetProgress = 1f,
animationSpec = keyframes {
durationMillis = 2000
0f at 0
0.5f at 500
1f at 2000
}
)
}
} | 0 | Kotlin | 0 | 1 | 3a2cda19491479ae7d4de65d9ce3ede4c4b52a04 | 2,440 | SIKComposeHub | MIT License |
compiler/testData/codegen/boxAgainstJava/sam/adapters/operators/compareTo.kt | JakeWharton | 99,388,807 | false | null | // FILE: JavaClass.java
class JavaClass {
int compareTo(Runnable i) {
i.run();
return 239;
}
}
// FILE: 1.kt
fun box(): String {
val obj = JavaClass()
var v1 = "FAIL"
obj < { v1 = "OK" }
if (v1 != "OK") return "<: $v1"
var v2 = "FAIL"
obj > { v2 = "OK" }
if (v2 != "OK") return ">: $v2"
var v3 = "FAIL"
obj <= { v3 = "OK" }
if (v3 != "OK") return "<=: $v3"
var v4 = "FAIL"
obj >= { v4 = "OK" }
if (v4 != "OK") return ">=: $v4"
return "OK"
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 529 | kotlin | Apache License 2.0 |
api/src/main/kotlin/br/com/strn/erp/api/database/entities/financeiro/CentroCusto.kt | IvoSestren | 331,951,557 | false | null | package br.com.strn.erp.api.database.entities.financeiro
import br.com.strn.erp.api.database.entities.BaseEntity
import br.com.strn.erp.api.database.util.newHandle
import org.hibernate.annotations.Where
import javax.persistence.*
@Entity
@Table(name = "centrocusto")
@Where(clause = "deleted_at is null")
class CentroCusto(
var codigo: String?,
var nome: String?,
@ManyToOne
@JoinColumn(name = "id_centrocustopai")
var centroCustoPai: CentroCusto? = null,
@Id
@SequenceGenerator(name = "sq_centrocusto", sequenceName = "sq_centrocusto", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sq_centrocusto")
@Column(name = "id", unique = true, nullable = false)
var id: Long? = null,
override var handle: String? = newHandle()
) : BaseEntity(handle = handle) | 0 | Kotlin | 0 | 0 | a955b4a4b8b4e4f2b746bbe5bc4fe3674ab9caf1 | 882 | erp_001 | The Unlicense |
feature/ui/edit-note/core/src/main/kotlin/ru/maksonic/beresta/feature/ui/edit_note/core/screen/ContentExpanded.kt | maksonic | 580,058,579 | false | {"Kotlin": 1619980} | package ru.maksonic.beresta.feature.ui.edit_note.core.screen
import androidx.activity.SystemBarStyle
import androidx.activity.enableEdgeToEdge
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.SheetState
import androidx.compose.material3.SheetValue
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.State
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.NestedScrollSource
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import org.koin.compose.koinInject
import ru.maksonic.beresta.common.ui_kit.bar.system.SystemNavigationBarHeight
import ru.maksonic.beresta.common.ui_kit.sheet.ModalBottomSheetContainer
import ru.maksonic.beresta.common.ui_theme.Theme
import ru.maksonic.beresta.common.ui_theme.provide.dp24
import ru.maksonic.beresta.common.ui_theme.provide.dp8
import ru.maksonic.beresta.feature.folders_list.ui.api.FoldersChipsRowUiApi
import ru.maksonic.beresta.feature.folders_list.ui.api.FoldersFeature
import ru.maksonic.beresta.feature.folders_list.ui.api.LocalCurrentSelectedFolderState
import ru.maksonic.beresta.feature.marker_color_picker.ui.api.MarkerPickerUiApi
import ru.maksonic.beresta.feature.tags_list.ui.api.TagsListUiApi
import ru.maksonic.beresta.feature.ui.add_folder_dialog.api.AddFolderDialogUiApi
import ru.maksonic.beresta.feature.ui.edit_note.core.LocalAppEditorColors
import ru.maksonic.beresta.feature.ui.edit_note.core.Model
import ru.maksonic.beresta.feature.ui.edit_note.core.Msg
import ru.maksonic.beresta.feature.ui.edit_note.core.provideEditorColors
import ru.maksonic.beresta.feature.ui.edit_note.core.rememberColorCreator
import ru.maksonic.beresta.feature.ui.edit_note.core.widget.ImagesCarousel
import ru.maksonic.beresta.feature.ui.edit_note.core.widget.MultipleModalBottomSheetContent
import ru.maksonic.beresta.feature.ui.edit_note.core.widget.NoteMessageInputFieldWidget
import ru.maksonic.beresta.feature.ui.edit_note.core.widget.NoteTitleInputFieldWidget
import ru.maksonic.beresta.feature.ui.edit_note.core.widget.TopControlBar
import ru.maksonic.beresta.feature.ui.edit_note.core.widget.TopWithBottomBars
import ru.maksonic.beresta.feature.wallpaper_picker.domain.wallpaper.BaseWallpaper
import ru.maksonic.beresta.feature.wallpaper_picker.domain.wallpaper.WallpaperColor
import ru.maksonic.beresta.feature.wallpaper_picker.domain.wallpaper.WallpaperGradient
import ru.maksonic.beresta.feature.wallpaper_picker.domain.wallpaper.WallpaperImage
import ru.maksonic.beresta.feature.wallpaper_picker.domain.wallpaper.WallpaperTexture
import ru.maksonic.beresta.feature.wallpaper_picker.ui.api.WallpaperPickerUiApi
import ru.maksonic.beresta.platform.core.ui.findActivity
/**
* @Author maksonic on 16.10.2023
*/
private const val TRANSPARENT_COLOR = android.graphics.Color.TRANSPARENT
@OptIn(ExperimentalMaterial3Api::class)
@Composable
internal fun ContentExpanded(
model: Model,
send: Send,
modifier: Modifier = Modifier,
currentFolderStoreUiApi: FoldersChipsRowUiApi.CurrentSelectedFolderStore,
addFolderDialogApi: AddFolderDialogUiApi,
markerColorPickerUiApi: MarkerPickerUiApi = koinInject(),
tagsListUiApi: TagsListUiApi = koinInject(),
wallpaperPickerUiApi: WallpaperPickerUiApi = koinInject(),
wallpaper: WallpaperPickerUiApi.Wallpaper = koinInject(),
isHiddenNote: Boolean,
modalBottomSheetState: SheetState,
focusRequester: FocusRequester,
) {
CompositionLocalProvider(
LocalCurrentSelectedFolderState provides currentFolderStoreUiApi.id.value
) {
val scrollState = rememberScrollState()
val isVisibleBars = remember { mutableStateOf(true) }
val scrollOffset = remember { mutableFloatStateOf(0f) }
val canScrollBackward = remember { derivedStateOf { scrollState.canScrollBackward } }
val colorCreator = rememberColorCreator(model.currentWallpaper, canScrollBackward)
val currentFolder = FoldersFeature.currentSelected
val isNoneWallpaper = isInitialByCategoryWallpaper(model.currentWallpaper)
val modalSheetShape = animateDpAsState(
if (modalBottomSheetState.targetValue == SheetValue.Expanded) 0.dp else dp24, label = ""
)
SystemBarColorEffect(model, isNoneWallpaper.value)
LaunchedEffect(Unit) {
if (!model.isFetchedNote) {
send(Msg.Inner.FetchedPassedNote)
}
}
LaunchedEffect(model.isFetchedFolders) {
if (model.isFetchedFolders) {
send(Msg.Inner.FetchedCurrentFolderId(currentFolder))
}
}
LaunchedEffect(FoldersFeature.currentSelected) {
if (model.isFetchedFolders) {
send(Msg.Inner.FetchedCurrentFolderId(currentFolder))
}
}
Box(Modifier.fillMaxSize()) {
wallpaper.Widget(
wallpaper = model.currentWallpaper,
isCardContainer = false,
modifier = Modifier.fillMaxSize()
)
BoxWithConstraints(
modifier
.fillMaxSize()
// .imePadding()
) {
val maxHeight = this.maxHeight
val nestedScrollConnection = remember {
object : NestedScrollConnection {
override fun onPreScroll(
available: Offset, source: NestedScrollSource
): Offset {
val delta = available.y
scrollOffset.floatValue = delta
val newOffset = scrollOffset.floatValue + delta
isVisibleBars.value = when {
!scrollState.canScrollBackward -> true
!scrollState.canScrollForward -> true
else -> newOffset > scrollOffset.floatValue
}
return Offset.Zero
}
}
}
CompositionLocalProvider(
LocalAppEditorColors provides provideEditorColors(
isDarkAppTheme = model.currentWallpaper.isDark,
isNoneWallpaper = isNoneWallpaper.value
)
) {
Column(
Modifier
.fillMaxSize()
.nestedScroll(nestedScrollConnection)
.verticalScroll(scrollState)
) {
val messageModifier = if (model.editableNote.images.data.isNotEmpty())
Modifier.padding(bottom = dp8) else
Modifier
.imePadding()
.padding(
bottom = Theme.size.bottomMainBarHeight.plus(
SystemNavigationBarHeight
)
)
TopControlBar(
model = model,
send = send,
colorCreator = colorCreator,
isHiddenNote = isHiddenNote
)
NoteTitleInputFieldWidget(model.editableNote.title, send, focusRequester)
NoteMessageInputFieldWidget(
message = model.editableNote.message,
send = send,
modifier = messageModifier
)
ImagesCarousel(
images = model.editableNote.images,
onPositionChanged = { from, to ->
send(Msg.Ui.UpdateNoteImageInCarouselPosition(from, to))
},
modifier = Modifier.heightIn(max = maxHeight)
)
}
TopWithBottomBars(
model = model,
send = send,
colorCreator = colorCreator,
isVisibleBars = isVisibleBars,
isHiddenNote = isHiddenNote
)
}
if (model.modalSheet.isVisible) {
ModalBottomSheetContainer(
sheetState = modalBottomSheetState,
isEnableDragHandle = false,
shape = RoundedCornerShape(
topStart = modalSheetShape.value,
topEnd = modalSheetShape.value
),
onDismissRequest = { send(Msg.Inner.HiddenModalBottomSheet) },
) {
MultipleModalBottomSheetContent(model, send)
}
}
markerColorPickerUiApi.Widget(
state = model.markerState,
onUpdateCurrentColorSelectionClicked = {
send(Msg.Inner.UpdatedCurrentNoteMarkerColor(it))
},
hideDialog = { send(Msg.Ui.HiddenMarkerColorPickerDialog) }
)
tagsListUiApi.SheetContent(
isVisible = model.isVisibleTagPickerSheet,
passedNoteTagsIds = model.editableNote.tags.data.map { it.id },
updatedNoteTags = { tags -> send(Msg.Inner.UpdatedCurrentNoteTags(tags)) },
hideSheet = { send(Msg.Inner.UpdatedTagPickerSheetState(false)) }
)
wallpaperPickerUiApi.SheetContent(
isVisible = model.isVisibleWallpaperPickerSheet,
currentWallpaper = model.currentWallpaper,
hideSheet = { send(Msg.Ui.UpdatedWallpaperPickerSheetVisibility(false)) },
updateWallpaper = { send(Msg.Inner.UpdatedNoteWallpaper(it)) }
)
addFolderDialogApi.Widget(
isVisible = model.isVisibleAddFolderDialog,
hideDialog = { send(Msg.Ui.OnCloseAddFolderDialogClicked) }
)
}
}
}
}
@Composable
private fun SystemBarColorEffect(model: Model, isNoneWallpaper: Boolean) {
val activity = LocalContext.current.findActivity()
val isDarkTheme = Theme.darkMode.value
DisposableEffect(model.currentWallpaper) {
activity.enableEdgeToEdge(
statusBarStyle = setSystemBarColorByWallpaperColor(
isNoneWallpaper = isNoneWallpaper,
isDarkWallpaper = model.currentWallpaper.isDark,
isDarkTheme = isDarkTheme
),
navigationBarStyle = setSystemBarColorByWallpaperColor(
isNoneWallpaper = isNoneWallpaper,
isDarkWallpaper = model.currentWallpaper.isDark,
isDarkTheme = isDarkTheme
)
)
onDispose {
val navigationBarStyle = if (isDarkTheme) SystemBarStyle.dark(TRANSPARENT_COLOR)
else SystemBarStyle.light(TRANSPARENT_COLOR, TRANSPARENT_COLOR)
activity.enableEdgeToEdge(
statusBarStyle = SystemBarStyle.auto(
lightScrim = TRANSPARENT_COLOR,
darkScrim = TRANSPARENT_COLOR,
detectDarkMode = { isDarkTheme }
),
navigationBarStyle = navigationBarStyle
)
}
}
LaunchedEffect(model.isVisibleTagPickerSheet) {
activity.enableEdgeToEdge(
statusBarStyle = setSystemBarColorByWallpaperColor(
isNoneWallpaper = isNoneWallpaper,
isDarkWallpaper = model.currentWallpaper.isDark,
isDarkTheme = isDarkTheme
),
navigationBarStyle = setSystemBarColorByWallpaperColor(
isNoneWallpaper = isNoneWallpaper,
isDarkWallpaper = model.currentWallpaper.isDark,
isDarkTheme = isDarkTheme
)
)
}
}
@Composable
private fun isInitialByCategoryWallpaper(wallpaper: BaseWallpaper<Color>): State<Boolean> {
var state by remember { mutableStateOf(true) }
state = when (wallpaper) {
is WallpaperColor -> wallpaper.id == 100000L
is WallpaperGradient -> false
is WallpaperTexture -> wallpaper.backgroundColor.id == 0L
is WallpaperImage -> false
else -> true
}
return remember { derivedStateOf { state } }
}
private fun setSystemBarColorByWallpaperColor(
isNoneWallpaper: Boolean,
isDarkWallpaper: Boolean,
isDarkTheme: Boolean
): SystemBarStyle {
val lightStatusBar = SystemBarStyle.light(TRANSPARENT_COLOR, TRANSPARENT_COLOR)
val darkStatusBar = SystemBarStyle.dark(TRANSPARENT_COLOR)
val noneWallpaperSystemBarsColor = if (isDarkTheme) darkStatusBar else lightStatusBar
val hasWallpaperSystemBarsColor = if (isDarkWallpaper) darkStatusBar else lightStatusBar
return if (isNoneWallpaper) noneWallpaperSystemBarsColor else hasWallpaperSystemBarsColor
} | 0 | Kotlin | 0 | 0 | d9a53cc50c6e149923fc5bc6fc2c38013bfadb9d | 14,707 | Beresta | MIT License |
lite/examples/hand_tracking/android/app/src/main/java/org/tensorflow/lite/examples/handtracking/MainActivity.kt | hannesa2 | 345,906,548 | true | {"Jupyter Notebook": 1733035, "Python": 1232274, "Kotlin": 682381, "Swift": 553535, "Java": 305092, "C++": 106227, "Shell": 41573, "JavaScript": 24461, "Starlark": 17498, "Objective-C": 14639, "Objective-C++": 14293, "HTML": 12491, "CSS": 4746, "Ruby": 3744, "CMake": 1553, "Dockerfile": 467} | package org.tensorflow.lite.examples.handtracking
import android.app.Activity
import android.content.Intent
import android.graphics.*
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.exifinterface.media.ExifInterface
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.tensorflow.lite.examples.handtracking.handlandmark.HandDetector
import org.tensorflow.lite.examples.handtracking.handlandmark.data.HandLandmark
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.math.max
import kotlin.math.min
class MainActivity : AppCompatActivity() {
companion object {
private const val TAG = "Hand detection"
private const val REQUEST_IMAGE_CAPTURE = 1
// This list defines the lines that are drawn when visualizing the hand landmark detection
// results. These lines connect:
// landmarkConnections[2*n] and landmarkConnections[2*n+1]
private val landmarkConnections = listOf(
HandLandmark.WRIST,
HandLandmark.THUMB_CMC,
HandLandmark.THUMB_CMC,
HandLandmark.THUMB_MCP,
HandLandmark.THUMB_MCP,
HandLandmark.THUMB_IP,
HandLandmark.THUMB_IP,
HandLandmark.THUMB_TIP,
HandLandmark.WRIST,
HandLandmark.INDEX_FINGER_MCP,
HandLandmark.INDEX_FINGER_MCP,
HandLandmark.INDEX_FINGER_PIP,
HandLandmark.INDEX_FINGER_PIP,
HandLandmark.INDEX_FINGER_DIP,
HandLandmark.INDEX_FINGER_DIP,
HandLandmark.INDEX_FINGER_TIP,
HandLandmark.INDEX_FINGER_MCP,
HandLandmark.MIDDLE_FINGER_MCP,
HandLandmark.MIDDLE_FINGER_MCP,
HandLandmark.MIDDLE_FINGER_PIP,
HandLandmark.MIDDLE_FINGER_PIP,
HandLandmark.MIDDLE_FINGER_DIP,
HandLandmark.MIDDLE_FINGER_DIP,
HandLandmark.MIDDLE_FINGER_TIP,
HandLandmark.MIDDLE_FINGER_MCP,
HandLandmark.RING_FINGER_MCP,
HandLandmark.RING_FINGER_MCP,
HandLandmark.RING_FINGER_PIP,
HandLandmark.RING_FINGER_PIP,
HandLandmark.RING_FINGER_DIP,
HandLandmark.RING_FINGER_DIP,
HandLandmark.RING_FINGER_TIP,
HandLandmark.RING_FINGER_MCP,
HandLandmark.PINKY_MCP,
HandLandmark.WRIST,
HandLandmark.PINKY_MCP,
HandLandmark.PINKY_MCP,
HandLandmark.PINKY_PIP,
HandLandmark.PINKY_PIP,
HandLandmark.PINKY_DIP,
HandLandmark.PINKY_DIP,
HandLandmark.PINKY_TIP
)
}
private lateinit var captureImageFab: Button
private lateinit var inputImageView: ImageView
private lateinit var currentPhotoPath: String
private lateinit var handDetector: HandDetector
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
handDetector = HandDetector.create(this)
captureImageFab = findViewById(R.id.captureImageFab)
inputImageView = findViewById(R.id.imageView)
captureImageFab.setOnClickListener {
dispatchTakePictureIntent()
}
}
/**
* Run hand landmark detection on the input image
*/
private fun handLandmarkDetection(bitmap: Bitmap) {
val landmarks = handDetector.process(bitmap)
if (landmarks.isNotEmpty()) {
showLandmarks(bitmap, landmarks).let {
runOnUiThread {
inputImageView.setImageBitmap(it)
}
}
}
}
/**
* Make a copy of the input image and draw hand landmarks on top ut.
*/
private fun showLandmarks(inputImage: Bitmap, landmarks: List<HandLandmark>): Bitmap {
val drawBitmap = inputImage.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(drawBitmap)
val penStroke = Paint().apply {
color = Color.GREEN
strokeWidth = 20f
}
val penPoint = Paint().apply {
color = Color.RED
strokeWidth = 20f
style = Paint.Style.FILL
}
val lines = mutableListOf<Float>()
val points = mutableListOf<Float>()
for (i in landmarkConnections.indices step 2) {
val startX =
landmarks[landmarkConnections[i]].x * drawBitmap.width
val startY =
landmarks[landmarkConnections[i]].y * drawBitmap.height
val endX =
landmarks[landmarkConnections[i + 1]].x * drawBitmap.width
val endY =
landmarks[landmarkConnections[i + 1]].y * drawBitmap.height
lines.add(startX)
lines.add(startY)
lines.add(endX)
lines.add(endY)
points.add(startX)
points.add(startY)
}
canvas.drawLines(lines.toFloatArray(), penStroke)
canvas.drawPoints(points.toFloatArray(), penPoint)
return drawBitmap
}
private fun dispatchTakePictureIntent() {
Intent(MediaStore.ACTION_IMAGE_CAPTURE).also { takePictureIntent ->
// Ensure that there's a camera activity to handle the intent
takePictureIntent.resolveActivity(packageManager)?.also {
// Create the File where the photo should go
val photoFile: File? = try {
createImageFile()
} catch (e: IOException) {
Log.e(TAG, e.message.toString())
null
}
// Continue only if the File was successfully created
photoFile?.also {
val photoURI: Uri = FileProvider.getUriForFile(
this,
"org.tensorflow.lite.examples.handtracking.fileprovider",
it
)
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI)
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE)
}
}
}
}
@Throws(IOException::class)
private fun createImageFile(): File {
// Create an image file name
val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val storageDir: File? = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
return File.createTempFile(
"JPEG_${timeStamp}_", /* prefix */
".jpg", /* suffix */
storageDir /* directory */
).apply {
// Save a file: path for use with ACTION_VIEW intents
currentPhotoPath = absolutePath
}
}
/**
* getCapturedImage():
* Decodes and crops the captured image from camera.
*/
private fun getCapturedImage(): Bitmap {
// Get the dimensions of the View
val targetW: Int = inputImageView.width
val targetH: Int = inputImageView.height
val bmOptions = BitmapFactory.Options().apply {
// Get the dimensions of the bitmap
inJustDecodeBounds = true
BitmapFactory.decodeFile(currentPhotoPath, this)
val photoW: Int = outWidth
val photoH: Int = outHeight
// Determine how much to scale down the image
val scaleFactor: Int = max(1, min(photoW / targetW, photoH / targetH))
// Decode the image file into a Bitmap sized to fill the View
inJustDecodeBounds = false
inSampleSize = scaleFactor
inMutable = true
}
val exifInterface = ExifInterface(currentPhotoPath)
val orientation = exifInterface.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED
)
val bitmap = BitmapFactory.decodeFile(currentPhotoPath, bmOptions)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> {
rotateImage(bitmap, 90f)
}
ExifInterface.ORIENTATION_ROTATE_180 -> {
rotateImage(bitmap, 180f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> {
rotateImage(bitmap, 270f)
}
else -> {
bitmap
}
}
}
private fun rotateImage(source: Bitmap, angle: Float): Bitmap {
val matrix = Matrix()
matrix.postRotate(angle)
return Bitmap.createBitmap(
source, 0, 0, source.width, source.height,
matrix, true
)
}
@Deprecated("Deprecated in Java")
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_IMAGE_CAPTURE &&
resultCode == Activity.RESULT_OK
) {
lifecycleScope.launch(Dispatchers.Default) {
getCapturedImage().let {
runOnUiThread {
inputImageView.setImageBitmap(it)
}
handLandmarkDetection(it)
}
}
}
}
override fun onDestroy() {
super.onDestroy()
handDetector.close()
}
}
| 1 | Jupyter Notebook | 0 | 0 | b5f93b7eef5467fb24d6860385962930fa2a66d9 | 9,716 | tensorflowExamples | Apache License 2.0 |
modules/library-logging-api/src/main/kotlin/com/leinardi/forlago/library/logging/api/CrashlyticsTree.kt | leinardi | 405,185,933 | false | {"Kotlin": 631450, "Shell": 3032} | /*
* Copyright 2021 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.leinardi.forlago.core.logging
import android.util.Log
import com.google.firebase.crashlytics.FirebaseCrashlytics
import timber.log.Timber
class CrashlyticsTree : Timber.Tree() {
@Suppress("IDENTIFIER_LENGTH") // The identifier name is coming from Timber
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (priority == Log.VERBOSE || priority == Log.DEBUG || priority == Log.INFO) {
return
}
val crashlytics = FirebaseCrashlytics.getInstance()
crashlytics.setCustomKey(CRASHLYTICS_KEY_PRIORITY, priority)
crashlytics.setCustomKey(CRASHLYTICS_KEY_TAG, tag.orEmpty())
crashlytics.setCustomKey(CRASHLYTICS_KEY_MESSAGE, message)
if (t == null) {
crashlytics.recordException(Exception(message))
} else {
crashlytics.recordException(t)
}
}
companion object {
private const val CRASHLYTICS_KEY_MESSAGE = "message"
private const val CRASHLYTICS_KEY_PRIORITY = "priority"
private const val CRASHLYTICS_KEY_TAG = "tag"
}
}
| 77 | Kotlin | 6259 | 9 | d3592f7e270fbf10878a5d540f646c4010fddf69 | 1,706 | Forlago | Apache License 2.0 |
subprojects/gradle/impact-shared/src/main/java/com/avito/impact/configuration/sets/AndroidSourceSets.kt | avito-tech | 230,265,582 | false | null | package com.avito.impact.configuration.sets
import com.android.build.gradle.api.AndroidSourceSet
internal fun AndroidSourceSet.isImplementation() = !(isTest() or isAndroidTest())
internal fun AndroidSourceSet.isTest(): Boolean = name.startsWith("test")
internal fun AndroidSourceSet.isAndroidTest(): Boolean = name.startsWith("androidTest")
| 10 | null | 50 | 414 | bc94abf5cbac32ac249a653457644a83b4b715bb | 343 | avito-android | MIT License |
src/main/kotlin/pw/modder/mgt2helper/parser/savegame/SaveGame.kt | Nik-mmzd | 445,708,703 | false | null | package pw.modder.mgt2helper.parser.savegame
import kotlinx.serialization.*
import kotlinx.serialization.json.*
import pw.modder.mgt2helper.parser.*
import java.io.InputStream
import java.nio.file.*
import kotlin.io.path.*
@Serializable
data class SaveGame(
@SerialName("genres_TARGETGROUP") val genreTargets: Object<List<Boolean>>,
@SerialName("genres_GAMEPLAY") val genreGameplay: Object<Int>,
@SerialName("genres_GRAPHIC") val genreGraphics: Object<Int>,
@SerialName("genres_SOUND") val genreSound: Object<Int>,
@SerialName("genres_CONTROL") val genreControl: Object<Int>,
@SerialName("genres_COMBINATION") val genreCombination: Object<List<Boolean>>,
@SerialName("genres_FOCUS") val genreFocus: Object<List<Int>>,
@SerialName("genres_ALIGN") val genreAlign: Object<List<Int>>,
) {
@Serializable
data class Object<T>(
@SerialName("__type") val type: String,
@SerialName("value") val values: List<T>
) {
operator fun get(id: Int) = values[id]
val size: Int
get() = values.size
}
private fun createProperties(id: Int): Genre.Properties {
return Genre.Properties(
targets = Genre.Targets.values().filter { genreTargets[id][it.ordinal] }.toSet(),
gameplay = genreGameplay[id],
graphics = genreGraphics[id],
sound = genreSound[id],
control = genreControl[id],
length = genreFocus[id][0],
depth = genreFocus[id][1],
friendliness = genreFocus[id][2],
innovation = genreFocus[id][3],
story = genreFocus[id][4],
characters = genreFocus[id][5],
levels = genreFocus[id][6],
missions = genreFocus[id][7],
hardcore = genreAlign[id][0],
cruelty = genreAlign[id][1],
complexity = genreAlign[id][2]
)
}
fun updateFromSave(genres: List<Genre>): List<Genre> {
return genres.map { orig ->
orig.copy(
properties = createProperties(orig.id),
subgenres = genreCombination[orig.id].mapIndexedNotNull { index, b -> if (b) index else null }.toSet()
)
}
}
companion object {
private val JSON = Json { ignoreUnknownKeys = true }
@OptIn(ExperimentalSerializationApi::class)
fun loadFrom(inputStream: InputStream): SaveGame {
return JSON.decodeFromStream(serializer(), inputStream)
}
fun loadFrom(path: Path): SaveGame {
return loadFrom(path.inputStream())
}
}
}
| 0 | Kotlin | 0 | 0 | ad25cda4f242befcb3ecf6f1d1873b0c2a1c95a9 | 2,612 | mgt2-tool | MIT License |
wow-openapi/src/main/kotlin/me/ahoo/wow/openapi/event/ArchiveAggregateIdRouteSpec.kt | Ahoo-Wang | 628,167,080 | false | null | /*
* Copyright [2021-present] [<NAME> <<EMAIL>> (https://github.com/Ahoo-Wang)].
* 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 me.ahoo.wow.openapi.event
import io.swagger.v3.oas.models.parameters.Parameter
import io.swagger.v3.oas.models.responses.ApiResponses
import me.ahoo.wow.api.naming.NamedBoundedContext
import me.ahoo.wow.modeling.matedata.AggregateMetadata
import me.ahoo.wow.modeling.toStringWithAlias
import me.ahoo.wow.openapi.AbstractAggregateRouteSpecFactory
import me.ahoo.wow.openapi.AggregateRouteSpec
import me.ahoo.wow.openapi.Https
import me.ahoo.wow.openapi.ResponseRef.Companion.withRequestTimeout
class ArchiveAggregateIdRouteSpec(
override val currentContext: NamedBoundedContext,
override val aggregateMetadata: AggregateMetadata<*, *>
) : AggregateRouteSpec {
override val id: String
get() = "${aggregateMetadata.toStringWithAlias()}.archiveAggregateId"
override val method: String
get() = Https.Method.PUT
override val summary: String
get() = "Archive AggregateId"
override val appendPathSuffix: String
get() = "event/aggregateId"
override val responses: ApiResponses
get() = ApiResponses().withRequestTimeout()
override val parameters: List<Parameter>
get() = emptyList()
}
class ArchiveAggregateIdRouteSpecFactory : AbstractAggregateRouteSpecFactory() {
override fun create(
currentContext: NamedBoundedContext,
aggregateMetadata: AggregateMetadata<*, *>
): List<AggregateRouteSpec> {
return listOf(ArchiveAggregateIdRouteSpec(currentContext, aggregateMetadata))
}
}
| 7 | null | 13 | 133 | 4d0e9fb736f08e002f2426f5609c0e0130ea9f2c | 2,136 | Wow | Apache License 2.0 |
envoy-control-tests/src/main/kotlin/pl/allegro/tech/servicemesh/envoycontrol/EnvoyControlTest.kt | misiek08 | 304,321,182 | true | {"Kotlin": 730663, "Java": 42479, "Lua": 13505, "Shell": 2436, "Dockerfile": 2406} | package pl.allegro.tech.servicemesh.envoycontrol
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeAll
import org.junit.jupiter.api.Test
import pl.allegro.tech.servicemesh.envoycontrol.config.Ads
import pl.allegro.tech.servicemesh.envoycontrol.config.AdsWithStaticListeners
import pl.allegro.tech.servicemesh.envoycontrol.config.EnvoyControlTestConfiguration
import pl.allegro.tech.servicemesh.envoycontrol.config.Xds
internal class AdsWithStaticListenersEnvoyControlTest : EnvoyControlTest() {
companion object {
@JvmStatic
@BeforeAll
fun adsSetup() {
setup(envoyConfig = AdsWithStaticListeners)
}
}
}
internal class AdsEnvoyControlTest : EnvoyControlTest() {
companion object {
@JvmStatic
@BeforeAll
fun adsSetup() {
setup(envoyConfig = Ads)
}
}
}
internal class XdsEnvoyControlTest : EnvoyControlTest() {
companion object {
@JvmStatic
@BeforeAll
fun nonAdsSetup() {
setup(envoyConfig = Xds)
}
}
}
internal abstract class EnvoyControlTest : EnvoyControlTestConfiguration() {
@Test
fun `should allow proxy-ing request using envoy`() {
// given
registerService(name = "echo")
untilAsserted {
// when
val response = callEcho()
// then
assertThat(response).isOk().isFrom(echoContainer)
}
}
@Test
fun `should route traffic to the second instance when first is deregistered`() {
// given
val id = registerService(name = "echo")
untilAsserted {
// when
val response = callEcho()
// then
assertThat(response).isOk().isFrom(echoContainer)
}
checkTrafficRoutedToSecondInstance(id)
}
@Test
fun `should assign endpoints to correct zones`() {
// given
registerService(name = "echo")
untilAsserted {
// when
val adminInstance = envoyContainer1.admin().zone(cluster = "echo", ip = echoContainer.ipAddress())
// then
assertThat(adminInstance).isNotNull
assertThat(adminInstance!!.zone).isEqualTo("dc1")
}
}
}
| 0 | null | 0 | 0 | 430c5a1357b3cd030de7469403072dd5dd68a51f | 2,300 | envoy-control | Apache License 2.0 |
compiler/testData/codegen/box/annotations/annotatedEnumEntry.kt | JakeWharton | 99,388,807 | false | null | // TARGET_BACKEND: JVM
// WITH_RUNTIME
// KT-5665
@Retention(AnnotationRetention.RUNTIME)
annotation class First
@Retention(AnnotationRetention.RUNTIME)
annotation class Second(val value: String)
enum class E {
@First
E1 {
fun foo() = "something"
},
@Second("OK")
E2
}
fun box(): String {
val e = E::class.java
val e1 = e.getDeclaredField(E.E1.toString()).getAnnotations()
if (e1.size != 1) return "Fail E1 size: ${e1.toList()}"
if (e1[0].annotationClass.java != First::class.java) return "Fail E1: ${e1.toList()}"
val e2 = e.getDeclaredField(E.E2.toString()).getAnnotations()
if (e2.size != 1) return "Fail E2 size: ${e2.toList()}"
if (e2[0].annotationClass.java != Second::class.java) return "Fail E2: ${e2.toList()}"
return (e2[0] as Second).value
}
| 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 822 | kotlin | Apache License 2.0 |
app/src/main/java/com/ryunen344/twikot/mediaViewer/MediaViewerActivity.kt | RyuNen344 | 168,919,467 | false | null | package com.ryunen344.twikot.mediaViewer
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.ryunen344.twikot.R.layout.activity_media_viewer
import com.ryunen344.twikot.util.LogUtil
import com.ryunen344.twikot.util.replaceFragmentInActivity
import kotlinx.android.synthetic.main.activity_media_viewer.*
import org.koin.android.ext.android.inject
class MediaViewerActivity : AppCompatActivity() {
private val mediaViewerFragment : MediaViewerFragment by inject()
companion object {
val REQUEST_SHOW_MEDIA: Int = 20
val INTENT_KEY_MEDIA_URL: String = "key_media_url"
}
override fun onCreate(savedInstanceState: Bundle?) {
LogUtil.d()
super.onCreate(savedInstanceState)
setContentView(activity_media_viewer)
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), 0)
}
//requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),0)
var bundle : Bundle = Bundle()
bundle.putString(INTENT_KEY_MEDIA_URL, intent.getStringExtra(INTENT_KEY_MEDIA_URL))
mediaViewerFragment.arguments = bundle
supportFragmentManager.findFragmentById(mediaViewerFrame.id) as MediaViewerFragment?
?: mediaViewerFragment.also {
replaceFragmentInActivity(supportFragmentManager, it, mediaViewerFrame.id)
}
}
override fun finish() {
super.finish()
overridePendingTransition(0, 0)
}
} | 0 | Kotlin | 0 | 0 | 21fb417513674a6273ef8ce823bc5fddfb1a7e93 | 1,699 | TwiKot | Apache License 2.0 |
app/src/main/java/core/ApplicationLauncher.kt | Mnemotechnician | 454,707,533 | false | null | package com.github.mnemotechnician.game
import arc.*
import arc.util.*
import arc.scene.*
import arc.scene.ui.layout.*
import arc.assets.*
import arc.graphics.*
import arc.graphics.g2d.*
class ApplicationLauncher : ApplicationCore() {
override fun setup() {
//halp wat do i do here QwQ
Log.info("GL Version: @", Core.graphics.getGLVersion());
Log.info("Max texture size: @", Gl.getInt(Gl.maxTextureSize));
Log.info("Using @ Context", if (Core.gl30 != null) "OpenGL 3" else "OpenGL 2");
Core.assets = AssetManager();
Core.batch = SortedSpriteBatch();
Core.camera = Camera();
Core.batch = SortedSpriteBatch();
Core.atlas = TextureAtlas.blankAtlas();
Core.scene.root.fill { it: Table ->
it.left().top().add("AMOGUS")
}
}
} | 0 | Kotlin | 0 | 0 | 4d1cc46be481c3ab18845ba680df1c424aca26f2 | 768 | something | MIT License |
ui/src/main/kotlin/team/duckie/quackquack/ui/util/numberbuilder.kt | duckie-team | 523,387,054 | false | {"Kotlin": 901061, "MDX": 51559, "JavaScript": 6871, "CSS": 1060} | /*
* Designed and developed by Duckie Team 2023.
*
* Licensed under the MIT.
* Please see full license: https://github.com/duckie-team/quack-quack-android/blob/main/LICENSE
*/
@file:Suppress("unused")
package team.duckie.quackquack.ui.util
/** builder api와 유사하게 [Number]를 build합니다. */
internal interface NumberBuilder<T : Number> {
/** build할 [Number]의 초기 값 */
var value: T
/** [value]에 더하기 연산을 적용합니다. */
operator fun plus(number: T): T
/** [value]에 빼기 연산을 적용합니다. */
operator fun minus(number: T): T
}
/** [NumberBuilder]의 [Float] 버전을 구현합니다. 초기 값으로 0f를 사용합니다. */
internal fun buildFloat(builder: NumberBuilder<Float>.() -> Unit): Float {
val scope = object : NumberBuilder<Float> {
override var value = 0f
override fun minus(number: Float): Float {
value -= number
return value
}
override fun plus(number: Float): Float {
value += number
return value
}
}
.also(builder)
return scope.value
}
/** [buildFloat] 연산에 [Int] 더하기 연산을 허용합니다. */
internal operator fun NumberBuilder<Float>.plus(number: Int): Float {
value += number
return value
}
/** [buildFloat] 연산에 [Int] 빼기 연산을 허용합니다. */
internal operator fun NumberBuilder<Float>.minus(number: Int): Float {
value -= number
return value
}
/** [NumberBuilder]의 [Int] 버전을 구현합니다. 초기 값으로 0를 사용합니다. */
internal fun buildInt(builder: NumberBuilder<Int>.() -> Unit): Int {
val scope = object : NumberBuilder<Int> {
override var value = 0
override fun minus(number: Int): Int {
value -= number
return value
}
override fun plus(number: Int): Int {
value += number
return value
}
}
.also(builder)
return scope.value
}
| 45 | Kotlin | 8 | 99 | 24d44663cf5bea29fc73595b5f60be03b08e162b | 1,700 | quack-quack-android | MIT License |
app/src/main/java/danielabbott/personalorganiser/data/TimetableEvent.kt | gaptab | 307,991,387 | false | null | package danielabbott.personalorganiser.data
class TimetableEvent(
val id: Long,
val timetable_id: Long,
var startTime: Int,
var duration: Int, // In minutes
var days: Int,
var name: String,
var notes: String?,
var remind30Mins: Boolean,
var remind1Hr: Boolean,
var remind2Hrs: Boolean,
var remindMorning: Boolean,
var goal_id: Long?,
// Set when data is loaded from database, ignored when storing in database
var goal_colour: Int? = null
)
| 0 | Kotlin | 0 | 0 | 51fc73672aa20d69f3efefb5d6b71c6aaef32ed4 | 498 | timetable-allinone | MIT License |
src/main/kotlin/io/acari/memory/tactical/PomodoroSettingsEffectListener.kt | Unthrottled | 178,487,158 | false | {"Kotlin": 109281, "TypeScript": 68140, "Dockerfile": 687, "Shell": 624, "JavaScript": 272} | package io.acari.memory.tactical
import io.acari.http.UPDATED_POMODORO_SETTINGS
import io.acari.memory.Effect
import io.acari.memory.TacticalSettingsSchema
import io.acari.memory.user.UserMemoryWorkers
import io.acari.util.toMaybe
import io.reactivex.Completable
import io.vertx.core.Handler
import io.vertx.ext.mongo.UpdateOptions
import io.vertx.kotlin.core.json.jsonObjectOf
import io.vertx.reactivex.core.Vertx
import io.vertx.reactivex.core.eventbus.Message
import io.vertx.reactivex.ext.mongo.MongoClient
class PomodoroSettingsEffectListener(private val mongoClient: MongoClient, private val vertx: Vertx) :
Handler<Message<Effect>> {
override fun handle(message: Message<Effect>) {
val effect = message.body()
effect.toMaybe()
.filter { isPomodoroSettings(it) }
.flatMapCompletable { writePomodoroSettings(it) }
.subscribe({}) {
UserMemoryWorkers.log.warn("Unable to save tactical settings for reasons.", it)
}
}
private fun writePomodoroSettings(pomodoroEffect: Effect): Completable {
val pomodoroContent = pomodoroEffect.content
return mongoClient.rxReplaceDocumentsWithOptions(
TacticalSettingsSchema.COLLECTION,
jsonObjectOf(TacticalSettingsSchema.GLOBAL_USER_IDENTIFIER to pomodoroEffect.guid),
jsonObjectOf(
TacticalSettingsSchema.GLOBAL_USER_IDENTIFIER to pomodoroEffect.guid,
TacticalSettingsSchema.POMODORO_SETTINGS to pomodoroContent
),
UpdateOptions(true)
).ignoreElement()
}
private fun isPomodoroSettings(effect: Effect) =
effect.name == UPDATED_POMODORO_SETTINGS
}
| 0 | Kotlin | 0 | 1 | 6dc41adc14b6aaf332a6d98b7b4a6b086e077e5c | 1,604 | SOGoS-API | MIT License |
compiler/testData/diagnostics/tests/generics/tpAsReified/InProperty.kt | JakeWharton | 99,388,807 | true | null | val <<!REIFIED_TYPE_PARAMETER_NO_INLINE!>reified<!> T> T.v: T
get() = throw UnsupportedOperationException()
| 181 | Kotlin | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 112 | kotlin | Apache License 2.0 |
app/src/main/java/com/openso/weatherapp/utils/AxisBarFormatter.kt | mahdihassani-dev | 670,042,466 | false | null | package com.openso.weatherapp.utils
import com.github.mikephil.charting.components.AxisBase
import com.github.mikephil.charting.formatter.ValueFormatter
class AxisBarFormatter(private val values: ArrayList<String>) : ValueFormatter() {
override fun getFormattedValue(value: Float, axis: AxisBase?): String? {
return values[value.toInt()]
}
} | 0 | null | 0 | 3 | a3a40f01f550d4cc878d43ffb76a3e288c19ca30 | 363 | WeatherForecastApp | MIT License |
LayoutCompoundLabel/src/main/kotlin/example/App.kt | aterai | 158,348,575 | false | null | package example
import java.awt.*
import java.awt.event.MouseEvent
import javax.swing.*
fun makeUI(): Component {
val icon = UIManager.getIcon("OptionPane.informationIcon")
val label = object : JLabel("OptionPane.informationIcon", icon, SwingConstants.LEADING) {
private val viewRect = Rectangle()
private val iconRect = Rectangle()
private val textRect = Rectangle()
override fun getToolTipText(e: MouseEvent): String? {
SwingUtilities.calculateInnerArea(this, viewRect)
SwingUtilities.layoutCompoundLabel(
this,
this.getFontMetrics(this.font),
this.text,
this.icon,
this.verticalAlignment,
this.horizontalAlignment,
this.verticalTextPosition,
this.horizontalTextPosition,
viewRect,
iconRect,
textRect,
this.iconTextGap
)
val tip = super.getToolTipText(e)
return when {
tip == null -> null
iconRect.contains(e.point) -> "Icon: $tip"
textRect.contains(e.point) -> "Text: $tip"
else -> "Border: $tip"
}
}
}
label.isOpaque = true
label.background = Color.GREEN
label.border = BorderFactory.createMatteBorder(20, 10, 50, 30, Color.RED)
label.toolTipText = "ToolTipText ToolTipText"
val item = IconTooltipItem("Information", icon)
item.toolTipText = "Information item"
val menu = JMenu("Menu")
menu.add(item)
val menuBar = JMenuBar()
menuBar.add(menu)
return JPanel().also {
EventQueue.invokeLater { it.rootPane.jMenuBar = menuBar }
it.add(label)
it.preferredSize = Dimension(320, 240)
}
}
private class IconTooltipItem(text: String?, icon: Icon?) : JMenuItem(text, icon) {
override fun getToolTipText(e: MouseEvent): String? {
SwingUtilities.calculateInnerArea(this, VIEW_RECT)
SwingUtilities.layoutCompoundLabel(
this,
getFontMetrics(font),
text,
this.icon,
verticalAlignment,
horizontalAlignment,
verticalTextPosition,
horizontalTextPosition,
VIEW_RECT,
ICON_RECT,
TEXT_RECT,
iconTextGap
)
return super.getToolTipText(e)?.let {
val type = if (ICON_RECT.contains(e.point)) "Icon" else "Text"
"$type: $it"
}
}
companion object {
private val VIEW_RECT = Rectangle()
private val ICON_RECT = Rectangle()
private val TEXT_RECT = Rectangle()
}
}
fun main() {
EventQueue.invokeLater {
runCatching {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName())
}.onFailure {
it.printStackTrace()
Toolkit.getDefaultToolkit().beep()
}
JFrame().apply {
defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
contentPane.add(makeUI())
pack()
setLocationRelativeTo(null)
isVisible = true
}
}
}
| 0 | null | 5 | 9 | 47a0c684f64c3db2c8b631b2c20c6c7f9205bcab | 2,815 | kotlin-swing-tips | MIT License |
app/src/main/java/org/obd/graphs/ui/metrics/MetricsFragment.kt | tzebrowski | 326,375,780 | false | null | package org.obd.graphs.ui.metrics
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.obd.graphs.R
import org.obd.graphs.bl.datalogger.DATA_LOGGER_CONNECTING_EVENT
import org.obd.graphs.bl.datalogger.DataLogger
import org.obd.graphs.bl.datalogger.dataLogger
import org.obd.graphs.bl.datalogger.dataLoggerPreferences
import org.obd.graphs.ui.common.MetricsProvider
import org.obd.graphs.ui.common.ToggleToolbarDoubleClickListener
class MetricsFragment : Fragment() {
lateinit var adapter: MetricsViewAdapter
@SuppressLint("NotifyDataSetChanged")
private var receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
adapter.let {
it.data.clear()
it.data.addAll(MetricsProvider().findMetrics(dataLoggerPreferences.getPIDsToQuery(), emptyMap()))
it.notifyDataSetChanged()
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.fragment_metrics, container, false)
val data = MetricsProvider().findMetrics(dataLoggerPreferences.getPIDsToQuery(), emptyMap())
adapter = MetricsViewAdapter(root.context, data)
dataLogger.observe(this){
val indexOf = data.indexOf(it)
if (indexOf == -1) {
data.add(it)
adapter.notifyItemInserted(data.indexOf(it))
} else {
data[indexOf] = it
adapter.notifyItemChanged(indexOf, it)
}
}
val recyclerView: RecyclerView = root.findViewById(R.id.recycler_view)
recyclerView.layoutManager = GridLayoutManager(root.context, 1)
recyclerView.adapter = adapter
recyclerView.addOnItemTouchListener(
ToggleToolbarDoubleClickListener(
requireContext()
)
)
return root
}
override fun onAttach(context: Context) {
super.onAttach(context)
activity?.registerReceiver(receiver, IntentFilter().apply {
addAction(DATA_LOGGER_CONNECTING_EVENT)
})
}
override fun onDetach() {
super.onDetach()
activity?.unregisterReceiver(receiver)
}
} | 0 | Kotlin | 2 | 7 | 5d1cf0530aaebb60bfe846e51d804bea58541c6d | 2,735 | ObdGraphs | Apache License 2.0 |
app/shared/relationships/public/src/commonMain/kotlin/build/wallet/relationships/RelationshipsFakeKeys.kt | proto-at-block | 761,306,853 | false | {"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.relationships
import build.wallet.bitkey.relationships.DelegatedDecryptionKey
import build.wallet.bitkey.relationships.PakeCode
import com.github.michaelbull.result.getOrThrow
import io.ktor.utils.io.core.toByteArray
import okio.ByteString.Companion.toByteString
val DelegatedDecryptionKeyFake =
RelationshipsCryptoFake().generateAsymmetricKey<DelegatedDecryptionKey>().getOrThrow()
val EnrollmentPakeCodeFake = PakeCode("F00DBAR".toByteArray().toByteString())
val ProtectedCustomerEnrollmentPakeKeyFake =
RelationshipsCryptoFake().generateProtectedCustomerEnrollmentPakeKey(EnrollmentPakeCodeFake)
.getOrThrow()
| 3 | C | 16 | 113 | 694c152387c1fdb2b6be01ba35e0a9c092a81879 | 646 | bitkey | MIT License |
coworker-core/src/test/kotlin/org/camunda/community/extension/coworker/zeebe/worker/JobCoworkerTest.kt | camunda-community-hub | 574,492,193 | false | null | package org.camunda.community.extension.coworker.zeebe.worker
import io.camunda.zeebe.client.api.response.ActivatedJob
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.mockk
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.slf4j.MDCContext
import org.assertj.core.api.Assertions.assertThat
import org.camunda.community.extension.coworker.zeebe.worker.builder.DEFAULT_BACKOFF_SUPPLIER
import org.camunda.community.extension.coworker.zeebe.worker.handler.JobExecutableFactory
import org.junit.jupiter.api.Test
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
import kotlin.math.roundToInt
import kotlin.time.Duration.Companion.days
import kotlin.time.Duration.Companion.milliseconds
class JobCoworkerTest {
@Test
fun `should be polled expected counts`() {
// given
val standardDelay: Long = 100
val jobExecutableFactory =
mockk<JobExecutableFactory> {
every {
create(any(), any())
} answers {
val doneCallback = this.args[1] as suspend () -> Unit
object : suspend CoroutineScope.() -> Unit {
override suspend fun invoke(coroutineScope: CoroutineScope) {
delay(standardDelay * 3)
doneCallback()
}
}
}
}
val firstWaitPeriod = standardDelay * 3
val standardWaitPeriod = standardDelay * 2
val jobPoller =
mockk<JobPoller> {
coEvery {
poll(any(), any(), any(), any(), any())
} coAnswers {
val jobConsumer = args[1] as suspend (ActivatedJob) -> Unit
val doneCallback = args[2] as suspend (Int) -> Unit
delay(firstWaitPeriod)
jobConsumer(mockk())
jobConsumer(mockk())
doneCallback(2)
} coAndThen {
val doneCallback = args[2] as suspend (Int) -> Unit
delay(standardWaitPeriod)
doneCallback(0)
}
}
// when
JobCoworker(
maxJobsActive = 32,
scheduledCoroutineContext = Executors.newScheduledThreadPool(1).asCoroutineDispatcher(),
additionalCoroutineContextProvider = { MDCContext() },
backoffSupplier = DEFAULT_BACKOFF_SUPPLIER,
initialPollInterval = standardDelay.milliseconds,
jobExecutableFactory = jobExecutableFactory,
jobPoller = jobPoller,
)
val waitPeriod: Long = 5000
TimeUnit.MILLISECONDS.sleep(waitPeriod)
val expectedCountOfPolling =
((waitPeriod - standardDelay - firstWaitPeriod) / (standardWaitPeriod + standardDelay)).toInt()
// then
coVerify(
atLeast = expectedCountOfPolling - (expectedCountOfPolling * 0.1).roundToInt(),
atMost = expectedCountOfPolling + (expectedCountOfPolling * 0.1).roundToInt(),
) { jobPoller.poll(any(), any(), any(), any(), any()) }
coVerify(exactly = 2) { jobExecutableFactory.create(any(), any()) }
}
@Test
fun `should not poll if reach maximum job limit`() {
// given
val jobExecutableFactory =
mockk<JobExecutableFactory> {
every { create(any(), any()) } answers {
object : suspend CoroutineScope.() -> Unit {
override suspend fun invoke(coroutineScope: CoroutineScope) {
// should never be executed in test
delay(2.days)
throw error("should be never executed")
}
}
}
}
val latch = CountDownLatch(2)
val maxJobsActive = 4
val activatedJobs = CopyOnWriteArrayList<ActivatedJob>(ArrayList(maxJobsActive))
val jobPoller =
mockk<JobPoller> {
coEvery { poll(any(), any(), any(), any(), any()) } coAnswers {
val maxJobToPoll = args[0] as Int
val jobConsumer = args[1] as suspend (ActivatedJob) -> Unit
val doneCallback = args[2] as suspend (Int) -> Unit
delay(50.milliseconds)
repeat((1..maxJobToPoll).count()) {
val activatedJob = mockk<ActivatedJob>()
activatedJobs.add(activatedJob)
jobConsumer(activatedJob)
}
doneCallback(maxJobToPoll)
latch.countDown()
}
}
// when
JobCoworker(
maxJobsActive = maxJobsActive,
scheduledCoroutineContext = Executors.newScheduledThreadPool(1).asCoroutineDispatcher(),
additionalCoroutineContextProvider = { MDCContext() },
backoffSupplier = DEFAULT_BACKOFF_SUPPLIER,
initialPollInterval = 50.milliseconds,
jobExecutableFactory = jobExecutableFactory,
jobPoller = jobPoller,
)
// then
latch.await(5, TimeUnit.SECONDS)
assertThat(activatedJobs).hasSize(maxJobsActive)
}
}
| 16 | null | 5 | 7 | 4dfe2520bc7bfbba076818d985911a0053bc9cbc | 5,607 | kotlin-coworker | Apache License 2.0 |
kotlin-client/src/main/kotlin/com/couchbase/client/kotlin/env/dsl/LoggerConfigDslBuilder.kt | munisekharneeru7 | 391,487,493 | true | {"Groovy": 1, "Shell": 1, "Maven POM": 15, "Batchfile": 1, "Markdown": 8, "Text": 22, "HOCON": 1, "Ignore List": 2, "Makefile": 1, "Kotlin": 99, "Java Properties": 12, "XML": 13, "Java": 1183, "Scala": 256, "JSON": 68, "INI": 3, "AsciiDoc": 1, "CSS": 1} | /*
* Copyright 2021 Couchbase, 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.couchbase.client.kotlin.env.dsl
import com.couchbase.client.core.cnc.LoggingEventConsumer
import com.couchbase.client.core.env.LoggerConfig
import com.couchbase.client.core.env.LoggerConfig.Defaults.DEFAULT_DIAGNOSTIC_CONTEXT_ENABLED
import com.couchbase.client.core.env.LoggerConfig.Defaults.DEFAULT_DISABLE_SLF4J
import com.couchbase.client.core.env.LoggerConfig.Defaults.DEFAULT_FALLBACK_TO_CONSOLE
import com.couchbase.client.core.env.LoggerConfig.Defaults.DEFAULT_LOGGER_NAME
import kotlin.properties.Delegates.observable
/**
* DSL counterpart to [LoggerConfig.Builder].
*/
@ClusterEnvironmentDslMarker
public class LoggerConfigDslBuilder(private val wrapped: LoggerConfig.Builder) {
internal var customLogger: LoggingEventConsumer.Logger?
by observable(null) { _, _, it -> wrapped.customLogger(it) }
/**
* @see LoggerConfig.Builder.fallbackToConsole
*/
public var fallbackToConsole: Boolean
by observable(DEFAULT_FALLBACK_TO_CONSOLE) { _, _, it -> wrapped.fallbackToConsole(it) }
/**
* @see LoggerConfig.Builder.disableSlf4J
*/
public var disableSlf4J: Boolean
by observable(DEFAULT_DISABLE_SLF4J) { _, _, it -> wrapped.disableSlf4J(it) }
/**
* @see LoggerConfig.Builder.loggerName
*/
public val loggerName: String
by observable(DEFAULT_LOGGER_NAME) { _, _, it -> wrapped.loggerName(it) }
/**
* @see LoggerConfig.Builder.enableDiagnosticContext
*/
public val enableDiagnosticContext: Boolean
by observable(DEFAULT_DIAGNOSTIC_CONTEXT_ENABLED) { _, _, it -> wrapped.enableDiagnosticContext(it) }
}
| 0 | null | 0 | 0 | 3b88e11fdd42019f761575c2c5d28a4a04922e14 | 2,255 | couchbase-jvm-clients | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/EmailOutlined.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/EmailOutlined")
package mui.icons.material
@JsName("default")
external val EmailOutlined: SvgIconComponent
| 12 | Kotlin | 5 | 983 | a99345a0160a80a7a90bf1adfbfdc83a31a18dd6 | 190 | kotlin-wrappers | Apache License 2.0 |
src/main/kotlin/net/starlegacy/cache/trade/CargoCrates.kt | hafarooki | 437,384,015 | false | null | package net.starlegacy.cache.trade
import com.google.gson.Gson
import net.starlegacy.cache.ManualCache
import net.starlegacy.database.Oid
import net.starlegacy.database.schema.economy.CargoCrate
import net.starlegacy.feature.economy.cargotrade.CrateItems
import net.starlegacy.feature.economy.cargotrade.ShipmentManager
import net.starlegacy.util.redisaction.RedisAction
import net.starlegacy.util.redisaction.RedisActions
import org.bukkit.Material
import org.bukkit.block.ShulkerBox
import org.bukkit.inventory.ItemStack
import org.litote.kmongo.`in`
import org.litote.kmongo.nin
import org.litote.kmongo.set
import org.litote.kmongo.setTo
import java.io.File
import java.io.FileReader
import java.time.ZoneId
import java.util.Date
object CargoCrates : ManualCache() {
private lateinit var refreshGlobal: RedisAction<Long>
override fun load() {
refreshGlobal = RedisActions.register("trade-reload-all-crate-data", runSync = false) { time: Long ->
log.info("Received Reload Request Initiated At ${Date(time).toInstant().atZone(ZoneId.systemDefault())}")
refreshLocal()
}
refreshLocal()
}
private fun refreshLocal() {
crates = CargoCrate.all()
CrateItems.invalidateAll()
ITEM_MAP = crates.map {
(it.color.shulkerMaterial to CrateItems[it].itemMeta!!.displayName) to it
}.toMap()
NAME_MAP = crates.map {
it.name.uppercase() to it
}.toMap()
ID_MAP = crates.map {
it._id to it
}.toMap()
// state of crates has changed, so regenerate shipments
ShipmentManager.regenerateShipmentsAsync()
}
private const val fileName = "crateData.json"
private class CrateListWrapper(val crates: List<CargoCrate>)
var crates = listOf<CargoCrate>()
/**
* Loads cargo crate data from file if it exists.
* If there is data to load, it parses crates, then clears old crates, then imports supplied crates.
* If there is any data attached to crates that are removed, e.g. shipments, it also disposes of that.
*
* @return True if there was a file to load, else false
*/
internal fun reloadData() {
import()
refreshGlobal(System.currentTimeMillis())
}
private fun import() {
val file = File(plugin.dataFolder, fileName).takeIf(File::exists) ?: return
val data = FileReader(file).use { Gson().fromJson(it, CrateListWrapper::class.java) }
val oldCrates = CargoCrate.all()
val newNames = data.crates.map { it.name }
val newCrates = data.crates.associate { it.name to it }
// remove crates that are not in the imported list
for (removed in CargoCrate.find(CargoCrate::name nin newNames).toList()) {
CargoCrate.delete(removed._id)
}
// used for storing ids from both updated and adding
val idMap = mutableMapOf<String, Oid<CargoCrate>>()
// update crates that already exist
for (crate in CargoCrate.find(CargoCrate::name `in` newNames)) {
val name = crate.name
val id = crate._id
idMap[name] = id
val newCrate = checkNotNull(newCrates[name]) { "Missing map entry for crate $name" }
val newColor = newCrate.color
val newValues = newCrate.values
CargoCrate.updateById(id, set(CargoCrate::color setTo newColor, CargoCrate::values setTo newValues))
}
// add crates that didn't exist before
for (name in newNames.filter { name -> oldCrates.none { it.name == name } }) {
val newCrate = checkNotNull(newCrates[name]) { "Missing map entry for crate $name" }
idMap[name] = CargoCrate.create(name, newCrate.color, newCrate.values)
}
file.delete()
}
//region CACHES
private lateinit var ITEM_MAP: Map<Pair<Material, String>, CargoCrate>
private lateinit var NAME_MAP: Map<String, CargoCrate>
private lateinit var ID_MAP: Map<Oid<CargoCrate>, CargoCrate>
operator fun get(itemStack: ItemStack?): CargoCrate? {
val type = itemStack?.type ?: return null
val displayName = itemStack.itemMeta?.displayName ?: return null
return ITEM_MAP[type to displayName]
}
operator fun get(box: ShulkerBox): CargoCrate? = ITEM_MAP[box.type to box.customName]
operator fun get(name: String?): CargoCrate? = NAME_MAP[name?.uppercase()]
operator fun get(id: Oid<CargoCrate>): CargoCrate = ID_MAP[id] ?: error("Crate $id not cached!")
//endregion CACHES
}
| 0 | null | 5 | 4 | c830eb40180c935e8bfff599da0f9310eeccfb5c | 4,168 | StarLegacy | MIT License |
kotlin-mui-icons/src/main/generated/mui/icons/material/BathroomSharp.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/BathroomSharp")
package mui.icons.material
@JsName("default")
external val BathroomSharp: SvgIconComponent
| 12 | Kotlin | 5 | 983 | a99345a0160a80a7a90bf1adfbfdc83a31a18dd6 | 190 | kotlin-wrappers | Apache License 2.0 |
app/src/main/java/com/plcoding/stockmarketapp/data/local/StockDao.kt | shubham230523 | 533,838,711 | false | null | package com.plcoding.stockmarketapp.data.local
import androidx.room.*
@Dao
interface StockDao {
@Query(
"""
SELECT *
FROM companylistingentity
WHERE LOWER(name) LIKE '%' || LOWER(:query) || '%' OR
UPPER(:query) == symbol
"""
)
suspend fun searchCompanyListing(query: String) : List<CompanyListingEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCompanyListings(
companyListingEntities: List<CompanyListingEntity>
)
@Query("DELETE FROM companylistingentity")
suspend fun clearCompanyListings()
} | 0 | Kotlin | 0 | 0 | fbe46892c71ebf6b6d4dfc266a43c5b807ce686a | 629 | JetPack_StockMarketApp | MIT License |
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/BusSolid.kt | DevSrSouza | 311,134,756 | false | {"Kotlin": 36719092} | package compose.icons.lineawesomeicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.BusSolid: ImageVector
get() {
if (_busSolid != null) {
return _busSolid!!
}
_busSolid = Builder(name = "BusSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp,
viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(9.0f, 4.0f)
curveTo(6.801f, 4.0f, 5.0f, 5.801f, 5.0f, 8.0f)
lineTo(5.0f, 13.0f)
lineTo(3.0f, 13.0f)
lineTo(3.0f, 16.0f)
lineTo(5.0f, 16.0f)
lineTo(5.0f, 27.0f)
curveTo(5.0f, 27.551f, 5.449f, 28.0f, 6.0f, 28.0f)
lineTo(9.0f, 28.0f)
lineTo(9.344f, 27.0f)
lineTo(22.656f, 27.0f)
lineTo(23.0f, 28.0f)
lineTo(26.0f, 28.0f)
curveTo(26.551f, 28.0f, 27.0f, 27.551f, 27.0f, 27.0f)
lineTo(27.0f, 16.0f)
lineTo(29.0f, 16.0f)
lineTo(29.0f, 13.0f)
lineTo(27.0f, 13.0f)
lineTo(27.0f, 8.0f)
curveTo(27.0f, 5.801f, 25.199f, 4.0f, 23.0f, 4.0f)
close()
moveTo(9.0f, 6.0f)
lineTo(23.0f, 6.0f)
curveTo(24.117f, 6.0f, 25.0f, 6.883f, 25.0f, 8.0f)
lineTo(7.0f, 8.0f)
curveTo(7.0f, 6.883f, 7.883f, 6.0f, 9.0f, 6.0f)
close()
moveTo(7.0f, 10.0f)
lineTo(15.0f, 10.0f)
lineTo(15.0f, 17.0f)
lineTo(7.0f, 17.0f)
close()
moveTo(17.0f, 10.0f)
lineTo(25.0f, 10.0f)
lineTo(25.0f, 17.0f)
lineTo(17.0f, 17.0f)
close()
moveTo(7.0f, 19.0f)
lineTo(25.0f, 19.0f)
lineTo(25.0f, 25.0f)
lineTo(7.0f, 25.0f)
close()
moveTo(8.0f, 21.0f)
lineTo(8.0f, 23.0f)
lineTo(12.0f, 23.0f)
lineTo(12.0f, 21.0f)
close()
moveTo(20.0f, 21.0f)
lineTo(20.0f, 23.0f)
lineTo(24.0f, 23.0f)
lineTo(24.0f, 21.0f)
close()
}
}
.build()
return _busSolid!!
}
private var _busSolid: ImageVector? = null
| 17 | Kotlin | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 3,204 | compose-icons | MIT License |
app/src/main/java/com/simbiri/equityjamii/ui/main_activity/people_page/PersonInfoFragment.kt | SimbaSimbiri | 706,250,529 | false | {"Kotlin": 145092} | package com.simbiri.equityjamii.ui.main_activity.people_page
import android.app.Dialog
import android.content.Context
import android.net.Uri
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.util.DisplayMetrics
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import com.simbiri.equityjamii.R
import com.simbiri.equityjamii.adapters.SocialAdapter
import com.simbiri.equityjamii.data.model.Person
import com.simbiri.equityjamii.databinding.DialogPeopleDetailBinding
class PersonInfoFragment : BottomSheetDialogFragment() {
companion object {
private const val ARGS_PERSON_INFO = "person"
fun newInstance(person: Person) :PersonInfoFragment{
val fragment = PersonInfoFragment()
val argumentBundle= Bundle()
argumentBundle.putParcelable(ARGS_PERSON_INFO, person)
fragment.arguments = argumentBundle
return fragment
}
}
private lateinit var viewModel: PersonInfoViewModel
private var _binding: DialogPeopleDetailBinding? = null
private val binding get() = _binding
private lateinit var listsSocials : ArrayList<String>
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = DialogPeopleDetailBinding.inflate(layoutInflater, container, false)
val view = binding!!.root
adjustSize()
val personParceled = arguments?.getParcelable<Person>(ARGS_PERSON_INFO)
personParceled?.let {
binding!!.nameOnPeople.text= it.name
binding!!.designationOnPeople.text = it.designation + " at " + it.branch
binding!!.aboutTextContent.text = it.social.about
binding!!.textCounty.text= it.city
binding!!.countryEmojiText.text = it.country
listsSocials = arrayListOf(it.social.linkedin, it.social.insta, it.social.webs, it.social.faceb)
if (it.profileUri != "null") {
Glide.with(this).load(Uri.parse(it.profileUri))
.into(binding!!.profileOnPeopleImageV)
}
if (it.backGUri != "null") {
Glide.with(this).load(Uri.parse(it.backGUri))
.into(binding!!.detailBackImageV)
}
}
setRecyclerViewSocials()
return view
}
private fun setRecyclerViewSocials() {
val context = requireContext()
val filtered = listsSocials.filter { it != "" }
val socialAdapter = SocialAdapter(context,filtered)
val layoutManager = LinearLayoutManager(context)
layoutManager.orientation = LinearLayoutManager.HORIZONTAL
binding!!.recyclerSocials.adapter = socialAdapter
binding!!.recyclerSocials.layoutManager = layoutManager
binding!!.recyclerSocials.hasFixedSize()
}
private fun adjustSize() {
val layoutParamsProfileCardOut = binding!!.materialCardView.layoutParams
val layoutParamsBackG = binding!!.detailBackImageV.layoutParams
val displayMetrics = DisplayMetrics()
val windowManager =
requireActivity().getSystemService(Context.WINDOW_SERVICE) as WindowManager
windowManager.defaultDisplay.getMetrics(displayMetrics)
val screenWidth = displayMetrics.widthPixels
layoutParamsProfileCardOut.width = screenWidth / 5+ 80
layoutParamsProfileCardOut.height = screenWidth / 5 + 80
layoutParamsBackG.height = screenWidth / 4 + 100
layoutParamsBackG.width = screenWidth
binding!!.materialCardView.layoutParams = layoutParamsProfileCardOut
binding!!.detailBackImageV.layoutParams = layoutParamsBackG
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.setContentView(R.layout.dialog_people_detail)
dialog.setCanceledOnTouchOutside(true)
dialog.setOnShowListener { dialogInterface ->
val bottomSheetDialog = dialogInterface as BottomSheetDialog
val bottomSheet = bottomSheetDialog.findViewById<View>(com.google.android.material.R.id.design_bottom_sheet)
bottomSheet?.let {
val behavior = BottomSheetBehavior.from(bottomSheet)
behavior.isDraggable = true
behavior.isHideable = true
behavior.peekHeight = 1000
}
}
return dialog
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this).get(PersonInfoViewModel::class.java)
// TODO: Use the ViewModel
}
} | 0 | Kotlin | 0 | 0 | 8e65d4085c96872ce055dc8f4c0484b8dda4ce35 | 5,277 | EquiJamii | Apache License 2.0 |
app/src/main/java/com/babylon/wallet/android/presentation/settings/linkedconnectors/LinkedConnectorsScreen.kt | radixdlt | 513,047,280 | false | {"Kotlin": 5059334, "HTML": 215350, "Ruby": 2757, "Shell": 1963} | package com.babylon.wallet.android.presentation.settings.linkedconnectors
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.ime
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.union
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.babylon.wallet.android.R
import com.babylon.wallet.android.designsystem.composable.RadixSecondaryButton
import com.babylon.wallet.android.designsystem.composable.RadixTextField
import com.babylon.wallet.android.designsystem.theme.RadixTheme
import com.babylon.wallet.android.designsystem.theme.RadixWalletTheme
import com.babylon.wallet.android.presentation.dialogs.info.GlossaryItem
import com.babylon.wallet.android.presentation.settings.linkedconnectors.LinkedConnectorsUiState.ConnectorUiItem
import com.babylon.wallet.android.presentation.ui.composables.AddLinkConnectorScreen
import com.babylon.wallet.android.presentation.ui.composables.BasicPromptAlertDialog
import com.babylon.wallet.android.presentation.ui.composables.BottomSheetDialogWrapper
import com.babylon.wallet.android.presentation.ui.composables.DSR
import com.babylon.wallet.android.presentation.ui.composables.RadixBottomBar
import com.babylon.wallet.android.presentation.ui.composables.RadixCenteredTopAppBar
import com.babylon.wallet.android.presentation.ui.composables.RadixSnackbarHost
import com.babylon.wallet.android.presentation.ui.composables.statusBarsAndBanner
import com.radixdlt.sargon.PublicKeyHash
import com.radixdlt.sargon.annotation.UsesSampleValues
import com.radixdlt.sargon.samples.sample
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toPersistentList
@Composable
fun LinkedConnectorsScreen(
viewModel: LinkedConnectorsViewModel,
addLinkConnectorViewModel: AddLinkConnectorViewModel,
onInfoClick: (GlossaryItem) -> Unit,
onBackClick: () -> Unit,
modifier: Modifier = Modifier,
) {
val state by viewModel.state.collectAsStateWithLifecycle()
val addLinkConnectorState by addLinkConnectorViewModel.state.collectAsStateWithLifecycle()
LaunchedEffect(Unit) {
viewModel.oneOffEvent.collect { event ->
when (event) {
Event.Close -> onBackClick()
}
}
}
LaunchedEffect(Unit) {
addLinkConnectorViewModel.oneOffEvent.collect { event ->
when (event) {
is AddLinkConnectorViewModel.Event.Close -> viewModel.onNewConnectorCloseClick()
}
}
}
if (state.showAddLinkConnectorScreen) {
AddLinkConnectorScreen(
modifier = modifier,
state = addLinkConnectorState,
onQrCodeScanned = addLinkConnectorViewModel::onQrCodeScanned,
onQrCodeScanFailure = addLinkConnectorViewModel::onQrCodeScanFailure,
onConnectorDisplayNameChanged = addLinkConnectorViewModel::onConnectorDisplayNameChanged,
onInfoClick = onInfoClick,
onContinueClick = addLinkConnectorViewModel::onContinueClick,
onCloseClick = addLinkConnectorViewModel::onCloseClick,
onErrorDismiss = addLinkConnectorViewModel::onErrorDismiss
)
} else {
LinkedConnectorsContent(
modifier = modifier,
isAddingNewLinkConnectorInProgress = addLinkConnectorState.isAddingNewLinkConnectorInProgress,
activeLinkedConnectorsList = state.activeConnectors,
isLinkConnectorNameUpdated = state.isLinkConnectorNameUpdated,
onSnackbarMessageShown = viewModel::onSnackbarMessageShown,
onLinkNewConnectorClick = viewModel::onLinkNewConnectorClick,
onRenameConnectorClick = { viewModel.setRenameConnectorSheetVisible(true, it) },
onDeleteConnectorClick = viewModel::onDeleteConnectorClick,
onBackClick = onBackClick
)
state.renameLinkConnectorItem?.let {
RenameActiveLinkedConnectorSheet(
input = it,
onNewNameChange = viewModel::onNewConnectorNameChanged,
onUpdateNameClick = viewModel::onUpdateConnectorNameClick,
onDismiss = { viewModel.setRenameConnectorSheetVisible(false) }
)
}
}
}
@Composable
private fun LinkedConnectorsContent(
modifier: Modifier = Modifier,
isAddingNewLinkConnectorInProgress: Boolean,
activeLinkedConnectorsList: ImmutableList<ConnectorUiItem>,
isLinkConnectorNameUpdated: Boolean,
onSnackbarMessageShown: () -> Unit,
onLinkNewConnectorClick: () -> Unit,
onRenameConnectorClick: (connectorUiItem: ConnectorUiItem) -> Unit,
onDeleteConnectorClick: (id: PublicKeyHash) -> Unit,
onBackClick: () -> Unit
) {
val snackbarHostState = remember { SnackbarHostState() }
val message = stringResource(R.string.linkedConnectors_renameConnector_successHud)
LaunchedEffect(isLinkConnectorNameUpdated) {
if (isLinkConnectorNameUpdated) {
snackbarHostState.showSnackbar(
message = message,
duration = SnackbarDuration.Short,
withDismissAction = true
)
onSnackbarMessageShown()
}
}
Scaffold(
modifier = modifier,
topBar = {
RadixCenteredTopAppBar(
title = stringResource(R.string.linkedConnectors_title),
onBackClick = onBackClick,
windowInsets = WindowInsets.statusBarsAndBanner
)
},
snackbarHost = {
RadixSnackbarHost(
modifier = Modifier.padding(RadixTheme.dimensions.paddingDefault),
hostState = snackbarHostState
)
}
) { padding ->
var connectionLinkToDelete by remember { mutableStateOf<PublicKeyHash?>(null) }
Column(modifier = Modifier.padding(padding)) {
HorizontalDivider(color = RadixTheme.colors.gray4)
Box(modifier = Modifier.fillMaxSize().background(color = RadixTheme.colors.gray5)) {
ActiveLinkedConnectorsListContent(
modifier = Modifier.fillMaxWidth(),
activeLinkedConnectorsList = activeLinkedConnectorsList,
onLinkNewConnectorClick = onLinkNewConnectorClick,
onRenameConnectorClick = onRenameConnectorClick,
onDeleteConnectorClick = { connectionLinkToDelete = it },
isAddingNewLinkConnectorInProgress = isAddingNewLinkConnectorInProgress
)
if (connectionLinkToDelete != null) {
@Suppress("UnsafeCallOnNullableType")
BasicPromptAlertDialog(
finish = {
if (it) {
onDeleteConnectorClick(connectionLinkToDelete!!)
}
connectionLinkToDelete = null
},
title = {
Text(
text = stringResource(id = R.string.linkedConnectors_removeConnectionAlert_title),
style = RadixTheme.typography.body2Header,
color = RadixTheme.colors.gray1
)
},
message = {
Text(
text = stringResource(id = R.string.linkedConnectors_removeConnectionAlert_message),
style = RadixTheme.typography.body2Regular,
color = RadixTheme.colors.gray1
)
},
confirmText = stringResource(id = R.string.common_remove)
)
}
}
}
}
}
@Composable
private fun ActiveLinkedConnectorsListContent(
modifier: Modifier = Modifier,
activeLinkedConnectorsList: ImmutableList<ConnectorUiItem>,
onRenameConnectorClick: (connectorUiItem: ConnectorUiItem) -> Unit,
onDeleteConnectorClick: (id: PublicKeyHash) -> Unit,
isAddingNewLinkConnectorInProgress: Boolean,
onLinkNewConnectorClick: () -> Unit
) {
LazyColumn(modifier) {
item {
Text(
modifier = Modifier.padding(RadixTheme.dimensions.paddingDefault),
text = stringResource(R.string.linkedConnectors_subtitle),
style = RadixTheme.typography.body1Header,
color = RadixTheme.colors.gray2
)
}
itemsIndexed(activeLinkedConnectorsList) { index, activeLinkedConnector ->
ActiveLinkedConnectorContent(
activeLinkedConnector = activeLinkedConnector,
onRenameConnectorClick = onRenameConnectorClick,
onDeleteConnectorClick = onDeleteConnectorClick
)
if (remember(activeLinkedConnectorsList.size) { index < activeLinkedConnectorsList.size - 1 }) {
HorizontalDivider(
color = RadixTheme.colors.gray4,
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = RadixTheme.dimensions.paddingDefault)
)
}
}
item {
HorizontalDivider(
color = RadixTheme.colors.gray4,
modifier = Modifier.fillMaxWidth()
)
}
item {
Column {
Spacer(modifier = Modifier.height(RadixTheme.dimensions.paddingXLarge))
RadixSecondaryButton(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = RadixTheme.dimensions.paddingMedium)
.padding(bottom = RadixTheme.dimensions.paddingDefault),
text = stringResource(id = R.string.linkedConnectors_linkNewConnector),
onClick = onLinkNewConnectorClick,
leadingContent = {
Icon(
painter = painterResource(id = DSR.ic_qr_code_scanner),
contentDescription = null
)
},
isLoading = isAddingNewLinkConnectorInProgress,
enabled = isAddingNewLinkConnectorInProgress.not()
)
}
}
}
}
@Composable
private fun ActiveLinkedConnectorContent(
activeLinkedConnector: ConnectorUiItem,
modifier: Modifier = Modifier,
onRenameConnectorClick: (connectorUiItem: ConnectorUiItem) -> Unit,
onDeleteConnectorClick: (id: PublicKeyHash) -> Unit,
) {
Column(modifier = modifier.background(color = RadixTheme.colors.white)) {
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = RadixTheme.dimensions.paddingDefault),
verticalAlignment = Alignment.CenterVertically
) {
Text(
modifier = Modifier.weight(1f),
text = activeLinkedConnector.name,
style = RadixTheme.typography.body1Header,
color = RadixTheme.colors.gray1,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
IconButton(
onClick = { onRenameConnectorClick(activeLinkedConnector) }
) {
Icon(
painter = painterResource(id = com.babylon.wallet.android.designsystem.R.drawable.ic_account_label),
contentDescription = null,
tint = RadixTheme.colors.gray1
)
}
IconButton(onClick = {
onDeleteConnectorClick(activeLinkedConnector.id)
}) {
Icon(
painter = painterResource(id = com.babylon.wallet.android.designsystem.R.drawable.ic_delete_outline),
contentDescription = null,
tint = RadixTheme.colors.gray1
)
}
}
}
}
@Composable
private fun RenameActiveLinkedConnectorSheet(
input: LinkedConnectorsUiState.RenameConnectorInput,
onNewNameChange: (String) -> Unit,
onUpdateNameClick: () -> Unit,
onDismiss: () -> Unit
) {
val inputFocusRequester = remember { FocusRequester() }
LaunchedEffect(Unit) {
inputFocusRequester.requestFocus()
}
BottomSheetDialogWrapper(
addScrim = true,
showDragHandle = true,
onDismiss = onDismiss
) {
Column(
modifier = Modifier.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.Center,
) {
Text(
modifier = Modifier.fillMaxWidth(),
text = stringResource(id = R.string.linkedConnectors_renameConnector_title),
style = RadixTheme.typography.title,
color = RadixTheme.colors.gray1,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(RadixTheme.dimensions.paddingSemiLarge))
Text(
modifier = Modifier.fillMaxWidth(),
text = stringResource(id = R.string.linkedConnectors_renameConnector_subtitle),
style = RadixTheme.typography.body1Regular,
color = RadixTheme.colors.gray1,
textAlign = TextAlign.Center
)
Spacer(modifier = Modifier.height(RadixTheme.dimensions.paddingLarge))
RadixTextField(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = RadixTheme.dimensions.paddingXXLarge)
.focusRequester(focusRequester = inputFocusRequester),
onValueChanged = onNewNameChange,
keyboardOptions = KeyboardOptions.Default.copy(capitalization = KeyboardCapitalization.Words),
value = input.name,
singleLine = true,
error = if (input.isNameEmpty) {
stringResource(R.string.linkedConnectors_renameConnector_errorEmpty)
} else {
null
},
hintColor = RadixTheme.colors.gray2
)
Spacer(modifier = Modifier.height(RadixTheme.dimensions.paddingXXLarge))
}
RadixBottomBar(
onClick = onUpdateNameClick,
text = stringResource(R.string.accountSettings_renameAccount_button),
insets = WindowInsets.navigationBars.union(WindowInsets.ime),
enabled = input.isNameEmpty.not()
)
}
}
@UsesSampleValues
@Preview(showBackground = true)
@Preview("large font", fontScale = 2f, showBackground = true)
@Composable
fun LinkedConnectorsContentWithActiveLinkedConnectorsPreview() {
RadixWalletTheme {
LinkedConnectorsContent(
activeLinkedConnectorsList = listOf(
ConnectorUiItem(
id = PublicKeyHash.sample.invoke(),
name = "chrome connection"
),
ConnectorUiItem(
id = PublicKeyHash.sample.other(),
name = "firefox connection"
)
).toPersistentList(),
isAddingNewLinkConnectorInProgress = false,
isLinkConnectorNameUpdated = false,
onSnackbarMessageShown = {},
onLinkNewConnectorClick = {},
onBackClick = {},
onRenameConnectorClick = {},
onDeleteConnectorClick = {}
)
}
}
@UsesSampleValues
@Preview(showBackground = true)
@Composable
fun RenameActiveLinkedConnectorSheetPreview() {
RadixWalletTheme {
RenameActiveLinkedConnectorSheet(
input = LinkedConnectorsUiState.RenameConnectorInput(
id = PublicKeyHash.sample(),
name = "name",
isNameEmpty = false
),
onNewNameChange = {},
onUpdateNameClick = {},
onDismiss = {}
)
}
}
@UsesSampleValues
@Preview(showBackground = true)
@Composable
fun RenameActiveLinkedConnectorSheetEmptyPreview() {
RadixWalletTheme {
RenameActiveLinkedConnectorSheet(
input = LinkedConnectorsUiState.RenameConnectorInput(
id = PublicKeyHash.sample(),
name = "",
isNameEmpty = true
),
onNewNameChange = {},
onUpdateNameClick = {},
onDismiss = {}
)
}
}
@Preview(showBackground = true)
@Composable
fun LinkedConnectorsContentWithoutActiveLinkedConnectorsPreview() {
RadixWalletTheme {
LinkedConnectorsContent(
activeLinkedConnectorsList = persistentListOf(),
isAddingNewLinkConnectorInProgress = false,
isLinkConnectorNameUpdated = false,
onLinkNewConnectorClick = {},
onSnackbarMessageShown = {},
onBackClick = {},
onRenameConnectorClick = {},
onDeleteConnectorClick = {}
)
}
}
| 7 | Kotlin | 6 | 11 | b21ad9d25e186649f3631a83d0d87dafaafc5fdb | 19,211 | babylon-wallet-android | Apache License 2.0 |
app/src/main/java/dev/kingbond/notify/ui/event/AlarmReceiver.kt | Kingbond470 | 429,672,171 | false | null | package dev.kingbond.notify.ui.event
import android.app.NotificationChannel
import android.app.PendingIntent
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import dev.kingbond.notify.R
import dev.kingbond.notify.ui.home.HomeActivity
class AlarmReceiver : BroadcastReceiver() {
@RequiresApi(Build.VERSION_CODES.O)
override fun onReceive(context: Context?, intent: Intent?) {
//music
var mp: MediaPlayer = MediaPlayer.create(context, R.raw.alarm_tone)
mp.start()
val i = Intent(context, HomeActivity::class.java)
intent!!.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK
/*Handler().postDelayed({
}, 15000)*/
val pendingIntent = PendingIntent.getActivity(context, 0, i, 0)
val notificationManager = NotificationManagerCompat.from(context!!)
val builder = NotificationCompat.Builder(context!!, "notify")
.setSmallIcon(R.drawable.ic_home_icon)
.setContentTitle(notificationManager.getNotificationChannel("notify")?.name)
.setContentText(notificationManager.getNotificationChannel("notify")?.description)
.setAutoCancel(false)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
notificationManager.notify(123, builder.build())
}
} | 0 | Kotlin | 3 | 5 | a663e7c2390279a6ff1661c38d31a8f49b9673d1 | 1,665 | Notify | MIT License |
core/network/src/commonMain/kotlin/com/cdcoding/network/client/cosmo/CosmosFee.kt | Christophe-DC | 822,562,468 | false | {"Kotlin": 728291, "Ruby": 4739, "Swift": 617} | package com.cdcoding.network.client.cosmo
import com.cdcoding.model.AssetId
import com.cdcoding.model.Chain
import com.cdcoding.model.Fee
import com.cdcoding.model.GasFee
import com.cdcoding.model.TransactionType
import com.ionspin.kotlin.bignum.integer.BigInteger
class CosmosFee(
private val txType: TransactionType,
) {
operator fun invoke(chain: Chain): Fee {
val assetId = AssetId(chain)
val maxGasFee = when (chain) {
Chain.Cosmos -> when (txType) {
TransactionType.Transfer, TransactionType.Swap -> BigInteger(5_000L)
else -> BigInteger(17_000L)
}
Chain.Osmosis -> when (txType) {
TransactionType.Transfer, TransactionType.Swap -> BigInteger(50_000L)
else -> BigInteger(100_000L)
}
Chain.Thorchain -> BigInteger(4_000_000)
Chain.Celestia -> when (txType){
TransactionType.Transfer, TransactionType.Swap -> BigInteger(3_000L)
else -> BigInteger(10_000L)
}
Chain.Injective -> when (txType){
TransactionType.Transfer, TransactionType.Swap -> BigInteger(1_000_000_000_000_000L)
else -> BigInteger(500_000_000_000_000L)
}
Chain.Sei -> when (txType){
TransactionType.Transfer, TransactionType.Swap -> BigInteger(200_000L)
else -> BigInteger(100_000L)
}
Chain.Noble -> BigInteger(25_000)
else -> throw IllegalArgumentException()
}
val limit = when (txType) {
TransactionType.Transfer -> BigInteger(200_000L)
TransactionType.Swap,
TransactionType.TokenApproval -> throw IllegalArgumentException()
else -> throw IllegalArgumentException()
}
return GasFee(
feeAssetId = assetId,
maxGasPrice = maxGasFee,
amount = maxGasFee,
limit = limit,
)
}
} | 0 | Kotlin | 0 | 0 | bc7c3eb161ee18db83402ded314e2e0b72196974 | 2,026 | secureWallet | Apache License 2.0 |
app/src/main/java/com/pt/mysociety/login/view/LoginViewModel.kt | Prathy | 528,724,668 | false | null | package com.pt.mysociety.login.view
import android.app.Activity
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import android.util.Patterns
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.pt.mysociety.R
import com.pt.mysociety.login.data.LoginFormState
import com.pt.mysociety.login.model.User
import com.pt.mysociety.login.model.LoginResult
class LoginViewModel : ViewModel() {
private val _loginForm = MutableLiveData<LoginFormState>()
val loginFormState: LiveData<LoginFormState> = _loginForm
private val _loginResult = MutableLiveData<LoginResult>()
val loginResult: LiveData<LoginResult> = _loginResult
fun login(activity: Activity, username: String, password: String) {
Firebase.auth.signInWithEmailAndPassword(username, password)
.addOnCompleteListener(activity) { task ->
if (task.isSuccessful) {
_loginResult.value =
LoginResult(success = task.result.user?.let { User(it.uid, it.email) })
} else {
_loginResult.value = LoginResult(error = task.exception?.message.toString())
}
}
}
fun loginDataChanged(username: String, password: String) {
if (!isUserNameValid(username)) {
_loginForm.value = LoginFormState(usernameError = R.string.invalid_username)
} else if (!isPasswordValid(password)) {
_loginForm.value = LoginFormState(passwordError = R.string.invalid_password)
} else {
_loginForm.value = LoginFormState(isDataValid = true)
}
}
private fun isUserNameValid(username: String): Boolean {
return if (username.contains('@')) {
Patterns.EMAIL_ADDRESS.matcher(username).matches()
} else {
username.isNotBlank()
}
}
private fun isPasswordValid(password: String): Boolean {
return password.length > 5
}
} | 0 | Kotlin | 0 | 0 | 2261e245887f46063b37e9dfbfbd851c9380cf7a | 2,048 | MySociety | Apache License 2.0 |
app/src/main/java/com/gaugustini/vort/repository/ResultRepository.kt | gaugustini | 416,395,415 | false | null | package com.gaugustini.vort.repository
import com.gaugustini.vort.database.ResultDao
import com.gaugustini.vort.model.Result
import javax.inject.Inject
class ResultRepository @Inject constructor(private val resultDao: ResultDao) {
suspend fun insert(resultList: List<Result>) = resultDao.insert(resultList)
suspend fun clear() = resultDao.clear()
fun getResultList() = resultDao.getResultList()
}
| 0 | Kotlin | 0 | 0 | 2f26bb863801caab95733511c6683b527ef33f35 | 415 | vort | MIT License |
ktor-legacy/ktor-client-legacy/common/src/io/ktor/client/features/cache/storage/HttpCacheStorage.kt | ktorio | 40,136,600 | false | null | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
@file:Suppress("DEPRECATION_ERROR")
package io.ktor.client.features.cache.storage
@Deprecated(
message = "Moved to io.ktor.client.plugins.cache",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("HttpCacheStorage", "io.ktor.client.plugins.cache.*")
)
public abstract class HttpCacheStorage
| 303 | Kotlin | 755 | 9,053 | 240363d6760754c325e0022f48eb5ea3069bc060 | 441 | ktor | Apache License 2.0 |
livingdoc-engine/src/main/kotlin/org/livingdoc/engine/execution/examples/scenarios/ScenarioFixtureModel.kt | LivingDoc | 85,412,044 | false | null | package org.livingdoc.engine.execution.examples.scenarios
import org.livingdoc.api.fixtures.scenarios.Step
import org.livingdoc.engine.execution.ScopedFixtureModel
import org.livingdoc.engine.execution.examples.scenarios.matching.ScenarioStepMatcher
import org.livingdoc.engine.execution.examples.scenarios.matching.ScenarioStepMatcher.MatchingResult
import org.livingdoc.engine.execution.examples.scenarios.matching.StepTemplate
import java.lang.reflect.Method
import kotlin.reflect.KClass
internal class ScenarioFixtureModel(
val fixtureClass: Class<*>
) : ScopedFixtureModel(fixtureClass) {
val stepMethods: List<Method>
val stepTemplateToMethod: Map<StepTemplate, Method>
private val stepMatcher: ScenarioStepMatcher
init {
// method analysis
val stepMethods = mutableListOf<Method>()
fixtureClass.declaredMethods.forEach { method ->
if (method.isAnnotatedWith(Step::class)) stepMethods.add(method)
if (method.isAnnotatedWith(Step.Steps::class)) stepMethods.add(method)
}
this.stepMethods = stepMethods
// step alias analysis
val stepAliases = mutableSetOf<String>()
val stepTemplateToMethod = mutableMapOf<StepTemplate, Method>()
stepMethods.forEach { method ->
method.getAnnotationsByType(Step::class.java)
.flatMap { it.value.asIterable() }
.forEach { alias ->
stepAliases.add(alias)
stepTemplateToMethod[StepTemplate.parse(alias)] = method
}
}
this.stepTemplateToMethod = stepTemplateToMethod
this.stepMatcher = ScenarioStepMatcher(stepTemplateToMethod.keys.toList())
}
fun getMatchingStepTemplate(step: String): MatchingResult = stepMatcher.match(step)
fun getStepMethod(template: StepTemplate): Method = stepTemplateToMethod[template]!!
private fun Method.isAnnotatedWith(annotationClass: KClass<out Annotation>): Boolean {
return this.isAnnotationPresent(annotationClass.java)
}
}
| 34 | Kotlin | 16 | 14 | f3d52b8bacbdf81905e4b4a753d75f584329b297 | 2,073 | livingdoc | Apache License 2.0 |
src/Day06Alternate.kt | aneroid | 572,802,061 | false | {"Kotlin": 27313} | class Day06Alternate(private val input: String) {
private fun String.indexForUniqSeqLen(size: Int): Int {
val checkArray = IntArray(26) { 0 }
return withIndex().first { (index, char) ->
checkArray[char - 'a']++
if (index >= size) {
checkArray[elementAt(index - size) - 'a']--
}
index >= size - 1 && checkArray.none { it > 1 }
}.index + 1
}
fun partOne(): Int = input.indexForUniqSeqLen(4)
fun partTwo(): Int = input.indexForUniqSeqLen(14)
}
fun main() {
val testInputs = readInput("Day06_test")
val input = readInput("Day06").first()
println("part One:")
assertThat(testInputs.map { Day06Alternate(it).partOne() }).isEqualTo(listOf(7, 5, 6, 10, 11))
println("actual: ${Day06Alternate(input).partOne()}\n")
println("part Two:")
assertThat(testInputs.map { Day06Alternate(it).partTwo() }).isEqualTo(listOf(19, 23, 23, 29, 26))
println("actual: ${Day06Alternate(input).partTwo()}\n")
}
| 0 | Kotlin | 0 | 0 | cf4b2d8903e2fd5a4585d7dabbc379776c3b5fbd | 1,040 | advent-of-code-2022-kotlin | Apache License 2.0 |
app/src/main/java/com/kshitijpatil/tazabazar/util/EditTextUtils.kt | Kshitij09 | 395,308,440 | false | null | package com.kshitijpatil.tazabazar.util
import android.text.Editable
import android.text.TextWatcher
import android.util.Patterns
import android.widget.EditText
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.onStart
fun EditText.textChanges(): Flow<CharSequence?> {
return callbackFlow<CharSequence?> {
val listener = object : TextWatcher {
override fun afterTextChanged(s: Editable?) = Unit
override fun beforeTextChanged(s: CharSequence?, start: Int, end: Int, count: Int) =
Unit
override fun onTextChanged(s: CharSequence?, start: Int, end: Int, count: Int) {
trySend(s)
}
}
addTextChangedListener(listener)
awaitClose { removeTextChangedListener(listener) }
}.onStart { emit(text) }
}
fun CharSequence?.isValidEmail() =
!isNullOrEmpty() && Patterns.EMAIL_ADDRESS.matcher(this).matches() | 8 | Kotlin | 2 | 1 | d709b26d69cf46c3d6123a217190f098b79a6562 | 1,028 | TazaBazar | Apache License 2.0 |
apps/student/src/androidTest/java/com/instructure/student/ui/pages/SubmissionDetailsPage.kt | instructure | 179,290,947 | false | null | /*
* Copyright (C) 2019 - present Instructure, 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.instructure.student.ui.pages
import androidx.test.espresso.Espresso
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.espresso.web.assertion.WebViewAssertions.webMatches
import androidx.test.espresso.web.sugar.Web.onWebView
import androidx.test.espresso.web.webdriver.DriverAtoms.findElement
import androidx.test.espresso.web.webdriver.DriverAtoms.getText
import androidx.test.espresso.web.webdriver.Locator
import com.instructure.canvas.espresso.clickCoordinates
import com.instructure.canvas.espresso.containsTextCaseInsensitive
import com.instructure.canvas.espresso.scrollRecyclerView
import com.instructure.canvas.espresso.withCustomConstraints
import com.instructure.canvasapi2.models.RubricCriterion
import com.instructure.canvasapi2.models.User
import com.instructure.dataseeding.model.CanvasUserApiModel
import com.instructure.espresso.OnViewWithStringTextIgnoreCase
import com.instructure.espresso.assertDisplayed
import com.instructure.espresso.click
import com.instructure.espresso.page.*
import com.instructure.espresso.replaceText
import com.instructure.student.R
import com.instructure.student.ui.pages.renderPages.SubmissionCommentsRenderPage
import org.hamcrest.Matchers.allOf
import org.hamcrest.Matchers.anyOf
import org.hamcrest.Matchers.containsString
import java.lang.Thread.sleep
open class SubmissionDetailsPage : BasePage(R.id.submissionDetails) {
private val commentsButton by OnViewWithStringTextIgnoreCase("comments")
private val submissionCommentsRenderPage = SubmissionCommentsRenderPage()
fun assertPdfAnnotationSelected() {
waitForViewWithId(R.id.commentsButton).assertDisplayed()
}
fun clickSubmissionContentAtPosition(percentX: Float, percentY: Float) {
sleep(1000) // Sometimes the pdf/annotations aren't fully ready when we click
onViewWithId(R.id.submissionContent).perform(clickCoordinates(percentX, percentY))
}
fun openPdfComments() {
waitForViewWithId(R.id.commentsButton).click()
}
fun addFirstAnnotationComment(text: String) {
waitForViewWithId(R.id.commentsButton).click()
waitForViewWithId(R.id.freeTextInput).replaceText(text)
onView(containsTextCaseInsensitive("OK")).click()
}
fun openComments() {
commentsButton.click()
}
fun openFiles() {
onView(allOf(containsTextCaseInsensitive("files"), isDisplayed())).click()
}
fun openRubric() {
onView(allOf(containsTextCaseInsensitive("rubric"), isDisplayed())).click()
}
/**
* Assert that a comment is displayed
* [description] contains some text that is in the comment
* [user] is the author of the comment
*/
fun assertCommentDisplayed(description: String, user: CanvasUserApiModel) {
assertCommentDisplayedCommon(description, user.shortName)
}
/**
* Assert that a comment is displayed
* [description] contains some text that is in the comment
* [user] is the author of the comment
*/
fun assertCommentDisplayed(description: String, user: User) {
assertCommentDisplayedCommon(description, user.shortName!!)
}
private fun assertCommentDisplayedCommon(description: String, shortUserName: String) {
val commentMatcher = allOf(
withId(R.id.commentHolder),
hasDescendant(allOf(withText(shortUserName), withId(R.id.userNameTextView))),
hasDescendant(allOf(withText(containsString(description)), anyOf(withId(R.id.titleTextView), withId(R.id.commentTextView))))
)
submissionCommentsRenderPage.scrollAndAssertDisplayed(commentMatcher)
}
fun assertTextSubmissionDisplayedAsComment() {
onView(allOf(withId(R.id.subtitleTextView), withParent(withId(R.id.commentSubmissionAttachmentView)), hasSibling(withId(R.id.titleTextView) + withText("Text Submission")))).assertDisplayed()
}
fun assertCommentNotDisplayed(comment: String, user: User) {
assertCommentNotDisplayed(comment, user.shortName!!)
}
fun assertCommentNotDisplayed(comment: String, user: CanvasUserApiModel) {
assertCommentNotDisplayed(comment, user.shortName)
}
fun assertCommentNotDisplayed(comment: String, userShortName: String) {
val commentMatcher = allOf(
withId(R.id.commentHolder),
hasDescendant(allOf(withText(userShortName), withId(R.id.userNameTextView))),
hasDescendant(allOf(withText(containsString(comment)), anyOf(withId(R.id.titleTextView), withId(R.id.commentTextView))))
)
onView(commentMatcher).check(doesNotExist())
}
/**
* Assert that the comment stream contains a video comment
*/
fun assertVideoCommentDisplayed() {
val commentMatcher = allOf(
withId(R.id.commentHolder),
hasDescendant(allOf(containsTextCaseInsensitive("video"), withId(R.id.attachmentNameTextView)))
)
submissionCommentsRenderPage.scrollAndAssertDisplayed(commentMatcher)
}
/**
* Assert that the comment stream contains an audio comment
*/
fun assertAudioCommentDisplayed() {
val commentMatcher = allOf(
withId(R.id.commentHolder),
hasDescendant(allOf(containsTextCaseInsensitive("audio"), withId(R.id.attachmentNameTextView)))
)
submissionCommentsRenderPage.scrollAndAssertDisplayed(commentMatcher)
}
/**
* Assert that a comment is displayed
* [fileName] is the name of the attached file
* [user] is the author of the comment
*/
fun assertCommentAttachmentDisplayed(fileName: String, user: CanvasUserApiModel) {
assertCommentAttachmentDisplayedCommon(fileName, user.shortName, false)
}
/**
* Assert that a comment is displayed
* [fileName] is the name of the attached file
* [user] is the author of the comment
*/
fun assertCommentAttachmentDisplayed(fileName: String, user: User) {
assertCommentAttachmentDisplayedCommon(fileName, user.shortName!!, false)
}
/**
* Open a comment attachment
*/
fun openCommentAttachment(fileName: String, user: User) {
assertCommentAttachmentDisplayedCommon(fileName, user.shortName!!, true)
}
/**
* Utility method to scroll to (and optionally click) a comment attachment
*/
private fun assertCommentAttachmentDisplayedCommon(fileName: String, displayName: String, click:Boolean = false) {
val commentMatcher = allOf(
withId(R.id.commentHolder),
hasDescendant(allOf(withText(displayName), withId(R.id.userNameTextView))),
hasDescendant(allOf(withText(fileName), withId(R.id.attachmentNameTextView)))
)
submissionCommentsRenderPage.scrollAndAssertDisplayed(commentMatcher)
if(click) {
//onView(commentMatcher).click()
onView(allOf(withId(R.id.attachmentNameTextView), withText(fileName)))
.perform(withCustomConstraints(click(), isDisplayingAtLeast(5)))
}
}
fun assertFileDisplayed(fileName: String) {
val matcher = allOf(withId(R.id.fileName),withText(fileName))
openFiles() // Make sure that the files tab is open
scrollRecyclerView(R.id.recyclerView, matcher)
onView(matcher).assertDisplayed()
}
fun addAndSendComment(comment: String) {
submissionCommentsRenderPage.addAndSendComment(comment)
}
fun addAndSendVideoComment() {
submissionCommentsRenderPage.addAndSendVideoComment()
}
fun addAndSendAudioComment() {
submissionCommentsRenderPage.addAndSendAudioComment()
}
/**
* Check that the RubricCriterion is displayed, and clicking on each rating
* results in its description and longDescription being displayed.
*/
fun assertRubricCriterionDisplayed(rc: RubricCriterion) {
rc.ratings.forEach { rating ->
val matcher = allOf(withParent(withId(R.id.ratingLayout)), withText(rating.points.toInt().toString()))
scrollRecyclerView(R.id.recyclerView, matcher)
onView(matcher).assertDisplayed()
onView(matcher).click()
val descriptionMatcher = allOf(withId(R.id.ratingTitle), withText(rating.description))
scrollRecyclerView(R.id.recyclerView, descriptionMatcher)
onView(descriptionMatcher).check(matches(isDisplayingAtLeast(10)))
if(rating.longDescription != null) {
val longDescriptionMatcher = allOf(withId(R.id.ratingDescription), withText(rating.longDescription))
scrollRecyclerView(R.id.recyclerView, longDescriptionMatcher)
onView(longDescriptionMatcher).check(matches(isDisplayingAtLeast(10)))
}
}
}
/**
* Checks that pressing the "Description" button pops up a webview with the longDescription text
*/
fun assertRubricDescriptionDisplays(rc: RubricCriterion) {
val matcher = allOf(withId(R.id.descriptionButton), containsTextCaseInsensitive("description"))
scrollRecyclerView(R.id.recyclerView, matcher)
onView(matcher).assertDisplayed() // probably unnecessary
onView(matcher).click()
onWebView(withId(R.id.webView))
.withElement(findElement(Locator.ID, "content"))
.check(webMatches(getText(), containsString(rc.longDescription)))
Espresso.pressBack() // return from web page
}
fun assertNoSubmissionEmptyView() {
onView(allOf(withId(R.id.title), withText(R.string.submissionDetailsNoSubmissionYet), withAncestor(withId(R.id.submissionDetailsEmptyContent)))).assertDisplayed()
}
fun selectAttempt(attemptName: String) {
onView(withId(R.id.submissionVersionsSpinner)).click()
waitForView(withId(R.id.attemptTitle) + withText(attemptName)).click()
}
fun assertSelectedAttempt(attemptName: String) {
onView(withId(R.id.attemptTitle) + withText(attemptName) + withAncestor(withId(R.id.slidingUpPanelLayout))).assertDisplayed()
}
}
| 5 | null | 85 | 99 | 1bac9958504306c03960bdce7fbb87cc63bc6845 | 11,008 | canvas-android | Apache License 2.0 |
core/model/src/main/kotlin/com/xeladevmobile/medicalassistant/core/model/data/Audio.kt | Alexminator99 | 702,145,143 | false | {"Kotlin": 534097} | package com.xeladevmobile.medicalassistant.core.model.data
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID
data class Audio(
val id: String,
val extension: String,
val duration: Int,
val path: String,
val createdDate: Long,
val emotion: Emotion,
)
enum class Emotion {
Neutral, Anger, Happiness, Disgust, Fear, Sadness
}
fun List<Audio>.groupByCreatedDate(): Map<String, List<Audio>> {
val dateFormat = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()) // Change the pattern if needed
// Group by the formatted date string
return this.groupBy { audio ->
dateFormat.format(Date(audio.createdDate))
}
}
val audiosPreview = listOf(
Audio(
extension = "mp3",
duration = 433,
path = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-1.mp3",
createdDate = System.currentTimeMillis().minus(1000 * 60 * 60 * 24),
emotion = Emotion.Anger,
id = UUID.randomUUID().toString(),
),
Audio(
extension = "mp3",
duration = 200,
path = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-2.mp3",
createdDate = System.currentTimeMillis().minus(2000 * 60 * 60 * 24),
emotion = Emotion.Disgust,
id = UUID.randomUUID().toString(),
),
Audio(
extension = "mp3",
duration = 156,
path = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-3.mp3",
createdDate = System.currentTimeMillis().minus(3000 * 60 * 60 * 24),
emotion = Emotion.Neutral,
id = UUID.randomUUID().toString(),
),
Audio(
extension = "mp3",
duration = 200,
path = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-4.mp3",
createdDate = System.currentTimeMillis().minus(4000 * 60 * 60 * 24),
emotion = Emotion.Happiness,
id = UUID.randomUUID().toString(),
),
Audio(
extension = "mp3",
duration = 11,
path = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-5.mp3",
createdDate = System.currentTimeMillis().minus(5000 * 60 * 60 * 24),
emotion = Emotion.Anger,
id = UUID.randomUUID().toString(),
),
Audio(
extension = "mp3",
duration = 12,
path = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-6.mp3",
createdDate = System.currentTimeMillis().minus(6000 * 60 * 60 * 24),
emotion = Emotion.Fear,
id = UUID.randomUUID().toString(),
),
Audio(
extension = "mp3",
duration = 13,
path = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-7.mp3",
createdDate = System.currentTimeMillis().minus(1500 * 60 * 60 * 24),
emotion = Emotion.Fear,
id = UUID.randomUUID().toString(),
),
Audio(
extension = "mp3",
duration = 14,
path = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-8.mp3",
createdDate = System.currentTimeMillis().minus(2500 * 60 * 60 * 24),
emotion = Emotion.Disgust,
id = UUID.randomUUID().toString(),
),
Audio(
extension = "wav",
duration = 1000,
path = "https://www.soundhelix.com/examples/mp3/SoundHelix-Song-9.mp3",
createdDate = System.currentTimeMillis().minus(3500 * 60 * 60 * 24),
emotion = Emotion.Anger,
id = UUID.randomUUID().toString(),
),
) | 0 | Kotlin | 0 | 0 | 37a35835a2562b0c6b4129e7b86cfca081a24783 | 3,466 | Medical_Assistant | MIT License |
android/src/main/java/dev/sergiobelda/todometer/ui/components/ToDometerTopAppBar.kt | serbelga | 301,817,067 | false | null | /*
* Copyright 2021 <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.sergiobelda.todometer.ui.components
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.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Menu
import androidx.compose.material.icons.rounded.MoreVert
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import dev.sergiobelda.todometer.common.compose.ui.components.TaskListProgress
import dev.sergiobelda.todometer.common.compose.ui.theme.TodometerColors
import dev.sergiobelda.todometer.common.compose.ui.theme.onSurfaceMediumEmphasis
import dev.sergiobelda.todometer.common.domain.model.Task
import dev.sergiobelda.todometer.ui.theme.ToDometerTheme
@Composable
fun ToDometerTopAppBar(
onMenuClick: () -> Unit,
onMoreClick: () -> Unit,
taskListName: String?,
tasks: List<Task>
) {
Box {
Column {
TopAppBar(
title = {},
navigationIcon = {
IconButton(onClick = onMenuClick) {
Icon(
Icons.Rounded.Menu,
contentDescription = "Menu",
tint = TodometerColors.onSurfaceMediumEmphasis
)
}
},
actions = {
IconButton(onClick = onMoreClick) {
Icon(
Icons.Rounded.MoreVert,
contentDescription = "More",
tint = TodometerColors.onSurfaceMediumEmphasis
)
}
},
backgroundColor = TodometerColors.surface,
elevation = 0.dp
)
TaskListProgress(taskListName, tasks)
}
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxWidth().height(56.dp)
) {
ToDometerTitle()
}
}
}
@Preview
@Composable
fun ToDometerTopAppBarPreview() {
ToDometerTheme {
ToDometerTopAppBar({}, {}, "", emptyList())
}
}
| 7 | Kotlin | 16 | 219 | cb365f363a018db8381de5cce6e010aa0d870102 | 3,278 | ToDometerKotlinMultiplatform | Apache License 2.0 |
app/src/androidTest/kotlin/com/mvvmclean/trendingrepos/sample/SampleData.kt | anoopmaddasseri | 254,618,197 | false | null | package com.mvvmclean.trendingrepos.sample
val searchSuccess = """
[
{
"author": "goldbergyoni",
"name": "nodebestpractices",
"avatar": "https://github.com/goldbergyoni.png",
"url": "https://github.com/goldbergyoni/nodebestpractices",
"description": " The largest Node.js best practices list (January 2020)",
"language": "JavaScript",
"languageColor": "#f1e05a",
"stars": 39477,
"forks": 3467,
"currentPeriodStars": 159,
"builtBy": [
{
"username": "goldbergyoni",
"href": "https://github.com/goldbergyoni",
"avatar": "https://avatars1.githubusercontent.com/u/8571500"
},
{
"username": "idori",
"href": "https://github.com/idori",
"avatar": "https://avatars2.githubusercontent.com/u/9084421"
},
{
"username": "js-kyle",
"href": "https://github.com/js-kyle",
"avatar": "https://avatars0.githubusercontent.com/u/23022619"
},
{
"username": "BrunoScheufler",
"href": "https://github.com/BrunoScheufler",
"avatar": "https://avatars2.githubusercontent.com/u/4772980"
}
]
},
{
"author": "Shpota",
"name": "goxygen",
"avatar": "https://github.com/Shpota.png",
"url": "https://github.com/Shpota/goxygen",
"description": "Generate a modern web project with Go, React and MongoDB in seconds.",
"language": "Go",
"languageColor": "#00ADD8",
"stars": 256,
"forks": 19,
"currentPeriodStars": 81,
"builtBy": [
{
"username": "Shpota",
"href": "https://github.com/Shpota",
"avatar": "https://avatars1.githubusercontent.com/u/5640984"
}
]
},
{
"author": "Awesome-Windows",
"name": "Awesome",
"avatar": "https://github.com/Awesome-Windows.png",
"url": "https://github.com/Awesome-Windows/Awesome",
"description": "💻 🎉 An awesome & curated list of best applications and tools for Windows.",
"stars": 12245,
"forks": 1422,
"currentPeriodStars": 164,
"builtBy": [
{
"username": "rahulkapoor90",
"href": "https://github.com/rahulkapoor90",
"avatar": "https://avatars0.githubusercontent.com/u/11207756"
},
{
"username": "alex-lit",
"href": "https://github.com/alex-lit",
"avatar": "https://avatars1.githubusercontent.com/u/5243967"
},
{
"username": "fvilers",
"href": "https://github.com/fvilers",
"avatar": "https://avatars2.githubusercontent.com/u/1009621"
},
{
"username": "hervehobbes",
"href": "https://github.com/hervehobbes",
"avatar": "https://avatars2.githubusercontent.com/u/117427"
},
{
"username": "yernhi",
"href": "https://github.com/yernhi",
"avatar": "https://avatars0.githubusercontent.com/u/34468720"
}
]
},
{
"author": "woltapp",
"name": "blurhash",
"avatar": "https://github.com/woltapp.png",
"url": "https://github.com/woltapp/blurhash",
"description": "A very compact representation of a placeholder for an image.",
"language": "C",
"languageColor": "#555555",
"stars": 2419,
"forks": 60,
"currentPeriodStars": 901,
"builtBy": [
{
"username": "DagAgren",
"href": "https://github.com/DagAgren",
"avatar": "https://avatars1.githubusercontent.com/u/11536828"
},
{
"username": "omahlama",
"href": "https://github.com/omahlama",
"avatar": "https://avatars3.githubusercontent.com/u/1110213"
},
{
"username": "nygardk",
"href": "https://github.com/nygardk",
"avatar": "https://avatars3.githubusercontent.com/u/2855908"
},
{
"username": "hangduykhiem",
"href": "https://github.com/hangduykhiem",
"avatar": "https://avatars0.githubusercontent.com/u/8597129"
},
{
"username": "serushakov",
"href": "https://github.com/serushakov",
"avatar": "https://avatars3.githubusercontent.com/u/35096061"
}
]
},
{
"author": "utmapp",
"name": "UTM",
"avatar": "https://github.com/utmapp.png",
"url": "https://github.com/utmapp/UTM",
"description": "Virtual machines for iOS",
"language": "Objective-C",
"languageColor": "#438eff",
"stars": 886,
"forks": 43,
"currentPeriodStars": 521,
"builtBy": [
{
"username": "osy86",
"href": "https://github.com/osy86",
"avatar": "https://avatars3.githubusercontent.com/u/50960678"
}
]
},
{
"author": "PostHog",
"name": "posthog",
"avatar": "https://github.com/PostHog.png",
"url": "https://github.com/PostHog/posthog",
"description": "🦔 PostHog is developer-friendly, open-source product analytics.",
"language": "Python",
"languageColor": "#3572A5",
"stars": 651,
"forks": 21,
"currentPeriodStars": 251,
"builtBy": [
{
"username": "timgl",
"href": "https://github.com/timgl",
"avatar": "https://avatars1.githubusercontent.com/u/1727427"
},
{
"username": "jamesefhawkins",
"href": "https://github.com/jamesefhawkins",
"avatar": "https://avatars0.githubusercontent.com/u/47497682"
},
{
"username": "Tannergoods",
"href": "https://github.com/Tannergoods",
"avatar": "https://avatars1.githubusercontent.com/u/60791437"
},
{
"username": "ellmh",
"href": "https://github.com/ellmh",
"avatar": "https://avatars3.githubusercontent.com/u/53315310"
}
]
},
{
"author": "The-Art-of-Hacking",
"name": "h4cker",
"avatar": "https://github.com/The-Art-of-Hacking.png",
"url": "https://github.com/The-Art-of-Hacking/h4cker",
"description": "This repository is primarily maintained by <NAME> and includes thousands of resources related to ethical hacking / penetration testing, digital forensics and incident response (DFIR), vulnerability research, exploit development, reverse engineering, and more.",
"language": "Rich Text Format",
"languageColor": "#ccc",
"stars": 3941,
"forks": 712,
"currentPeriodStars": 280,
"builtBy": [
{
"username": "santosomar",
"href": "https://github.com/santosomar",
"avatar": "https://avatars0.githubusercontent.com/u/1690898"
},
{
"username": "chris-mccoy",
"href": "https://github.com/chris-mccoy",
"avatar": "https://avatars0.githubusercontent.com/u/3452940"
},
{
"username": "Luci-d",
"href": "https://github.com/Luci-d",
"avatar": "https://avatars3.githubusercontent.com/u/55981308"
},
{
"username": "jesusmoraleda",
"href": "https://github.com/jesusmoraleda",
"avatar": "https://avatars1.githubusercontent.com/u/45268817"
},
{
"username": "nicksherron",
"href": "https://github.com/nicksherron",
"avatar": "https://avatars2.githubusercontent.com/u/20023313"
}
]
},
{
"author": "luong-komorebi",
"name": "Awesome-Linux-Software",
"avatar": "https://github.com/luong-komorebi.png",
"url": "https://github.com/luong-komorebi/Awesome-Linux-Software",
"description": "A list of awesome applications, software, tools and other materials for Linux distros.",
"language": "Python",
"languageColor": "#3572A5",
"stars": 13419,
"forks": 1357,
"currentPeriodStars": 62,
"builtBy": [
{
"username": "luong-komorebi",
"href": "https://github.com/luong-komorebi",
"avatar": "https://avatars0.githubusercontent.com/u/15828926"
},
{
"username": "SaintFenix",
"href": "https://github.com/SaintFenix",
"avatar": "https://avatars2.githubusercontent.com/u/29680981"
},
{
"username": "chrunchyjesus",
"href": "https://github.com/chrunchyjesus",
"avatar": "https://avatars2.githubusercontent.com/u/20382692"
},
{
"username": "alim0x",
"href": "https://github.com/alim0x",
"avatar": "https://avatars2.githubusercontent.com/u/4954007"
},
{
"username": "iFaceless",
"href": "https://github.com/iFaceless",
"avatar": "https://avatars1.githubusercontent.com/u/43306860"
}
]
},
{
"author": "threedr3am",
"name": "learnjavabug",
"avatar": "https://github.com/threedr3am.png",
"url": "https://github.com/threedr3am/learnjavabug",
"description": "Java安全相关的漏洞和技术demo,其中包括原生Java、Fastjson、Jackson、Hessian2以及XML反序列化漏洞利用和Dubbo(Hessian2反序列化)、Shiro(PaddingOracleCBC)等框架的exploits,并且还有Java Security Manager绕过、Dubbo-Hessian2安全加固、RMI、tomcat漏洞利用等等实践代码。",
"language": "Java",
"languageColor": "#b07219",
"stars": 365,
"forks": 68,
"currentPeriodStars": 157,
"builtBy": [
{
"username": "threedr3am",
"href": "https://github.com/threedr3am",
"avatar": "https://avatars1.githubusercontent.com/u/19884279"
}
]
},
{
"author": "jasonmayes",
"name": "Real-Time-Person-Removal",
"avatar": "https://github.com/jasonmayes.png",
"url": "https://github.com/jasonmayes/Real-Time-Person-Removal",
"description": "Removing people from complex backgrounds in real time using TensorFlow.js in the web browser",
"language": "JavaScript",
"languageColor": "#f1e05a",
"stars": 2362,
"forks": 225,
"currentPeriodStars": 475,
"builtBy": [
{
"username": "jasonmayes",
"href": "https://github.com/jasonmayes",
"avatar": "https://avatars2.githubusercontent.com/u/4972997"
}
]
},
{
"author": "thedaviddias",
"name": "Front-End-Checklist",
"avatar": "https://github.com/thedaviddias.png",
"url": "https://github.com/thedaviddias/Front-End-Checklist",
"description": "🗂 The perfect Front-End Checklist for modern websites and meticulous developers",
"language": "JavaScript",
"languageColor": "#f1e05a",
"stars": 37811,
"forks": 3741,
"currentPeriodStars": 67,
"builtBy": [
{
"username": "thedaviddias",
"href": "https://github.com/thedaviddias",
"avatar": "https://avatars1.githubusercontent.com/u/237229"
},
{
"username": "jochenkirstaetter",
"href": "https://github.com/jochenkirstaetter",
"avatar": "https://avatars2.githubusercontent.com/u/7329802"
},
{
"username": "miya0001",
"href": "https://github.com/miya0001",
"avatar": "https://avatars2.githubusercontent.com/u/309946"
},
{
"username": "antarestupin",
"href": "https://github.com/antarestupin",
"avatar": "https://avatars2.githubusercontent.com/u/7022740"
}
]
},
{
"author": "h5bp",
"name": "html5-boilerplate",
"avatar": "https://github.com/h5bp.png",
"url": "https://github.com/h5bp/html5-boilerplate",
"description": "A professional front-end template for building fast, robust, and adaptable web apps or sites.",
"language": "JavaScript",
"languageColor": "#f1e05a",
"stars": 44107,
"forks": 10556,
"currentPeriodStars": 42,
"builtBy": [
{
"username": "paulirish",
"href": "https://github.com/paulirish",
"avatar": "https://avatars2.githubusercontent.com/u/39191"
},
{
"username": "necolas",
"href": "https://github.com/necolas",
"avatar": "https://avatars1.githubusercontent.com/u/239676"
},
{
"username": "alrra",
"href": "https://github.com/alrra",
"avatar": "https://avatars0.githubusercontent.com/u/1223565"
},
{
"username": "roblarsen",
"href": "https://github.com/roblarsen",
"avatar": "https://avatars1.githubusercontent.com/u/361421"
},
{
"username": "coliff",
"href": "https://github.com/coliff",
"avatar": "https://avatars2.githubusercontent.com/u/1212885"
}
]
},
{
"author": "gothinkster",
"name": "realworld",
"avatar": "https://github.com/gothinkster.png",
"url": "https://github.com/gothinkster/realworld",
"description": "\"The mother of all demo apps\" — Exemplary fullstack Medium.com clone powered by React, Angular, Node, Django, and many more 🏅",
"language": "JavaScript",
"languageColor": "#f1e05a",
"stars": 37006,
"forks": 2792,
"currentPeriodStars": 95,
"builtBy": [
{
"username": "EricSimons",
"href": "https://github.com/EricSimons",
"avatar": "https://avatars2.githubusercontent.com/u/556934"
},
{
"username": "anishkny",
"href": "https://github.com/anishkny",
"avatar": "https://avatars3.githubusercontent.com/u/357499"
},
{
"username": "Cameron-C-Chapman",
"href": "https://github.com/Cameron-C-Chapman",
"avatar": "https://avatars0.githubusercontent.com/u/1323581"
},
{
"username": "sandeesh",
"href": "https://github.com/sandeesh",
"avatar": "https://avatars1.githubusercontent.com/u/16877877"
},
{
"username": "apai4",
"href": "https://github.com/apai4",
"avatar": "https://avatars1.githubusercontent.com/u/1776432"
}
]
},
{
"author": "saadpasta",
"name": "react-blog-github",
"avatar": "https://github.com/saadpasta.png",
"url": "https://github.com/saadpasta/react-blog-github",
"description": "React + Github Issues 👉 Your Personal Blog 🔥",
"language": "JavaScript",
"languageColor": "#f1e05a",
"stars": 296,
"forks": 23,
"currentPeriodStars": 185,
"builtBy": [
{
"username": "saadpasta",
"href": "https://github.com/saadpasta",
"avatar": "https://avatars1.githubusercontent.com/u/23307811"
},
{
"username": "Muhammad-Hammad",
"href": "https://github.com/Muhammad-Hammad",
"avatar": "https://avatars3.githubusercontent.com/u/37264033"
},
{
"username": "jvm-odoo",
"href": "https://github.com/jvm-odoo",
"avatar": "https://avatars3.githubusercontent.com/u/9156538"
}
]
},
{
"author": "521xueweihan",
"name": "HelloGitHub",
"avatar": "https://github.com/521xueweihan.png",
"url": "https://github.com/521xueweihan/HelloGitHub",
"description": "Find pearls on open-source seashore 分享 GitHub 上有趣、入门级的开源项目",
"language": "Python",
"languageColor": "#3572A5",
"stars": 26618,
"forks": 3799,
"currentPeriodStars": 89,
"builtBy": [
{
"username": "521xueweihan",
"href": "https://github.com/521xueweihan",
"avatar": "https://avatars2.githubusercontent.com/u/8255800"
},
{
"username": "daixiang0",
"href": "https://github.com/daixiang0",
"avatar": "https://avatars1.githubusercontent.com/u/26538619"
},
{
"username": "yaowenqiang",
"href": "https://github.com/yaowenqiang",
"avatar": "https://avatars3.githubusercontent.com/u/994371"
},
{
"username": "FradSer",
"href": "https://github.com/FradSer",
"avatar": "https://avatars0.githubusercontent.com/u/1439628"
},
{
"username": "ChungZH",
"href": "https://github.com/ChungZH",
"avatar": "https://avatars2.githubusercontent.com/u/42088872"
}
]
},
{
"author": "material-components",
"name": "material-components-android",
"avatar": "https://github.com/material-components.png",
"url": "https://github.com/material-components/material-components-android",
"description": "Modular and customizable Material Design UI components for Android",
"language": "Java",
"languageColor": "#b07219",
"stars": 9435,
"forks": 1646,
"currentPeriodStars": 61,
"builtBy": [
{
"username": "chrisbanes",
"href": "https://github.com/chrisbanes",
"avatar": "https://avatars2.githubusercontent.com/u/227486"
},
{
"username": "ymarian",
"href": "https://github.com/ymarian",
"avatar": "https://avatars3.githubusercontent.com/u/38727469"
},
{
"username": "cketcham",
"href": "https://github.com/cketcham",
"avatar": "https://avatars1.githubusercontent.com/u/16722"
},
{
"username": "dsn5ft",
"href": "https://github.com/dsn5ft",
"avatar": "https://avatars3.githubusercontent.com/u/1420597"
},
{
"username": "wcshi",
"href": "https://github.com/wcshi",
"avatar": "https://avatars3.githubusercontent.com/u/38438920"
}
]
},
{
"author": "man-group",
"name": "dtale",
"avatar": "https://github.com/man-group.png",
"url": "https://github.com/man-group/dtale",
"description": "Flask/React client for visualizing pandas data structures",
"language": "JavaScript",
"languageColor": "#f1e05a",
"stars": 609,
"forks": 30,
"currentPeriodStars": 183,
"builtBy": [
{
"username": "aschonfeld",
"href": "https://github.com/aschonfeld",
"avatar": "https://avatars2.githubusercontent.com/u/11547371"
},
{
"username": "jasonkholden",
"href": "https://github.com/jasonkholden",
"avatar": "https://avatars1.githubusercontent.com/u/6685128"
},
{
"username": "DominikMChrist",
"href": "https://github.com/DominikMChrist",
"avatar": "https://avatars3.githubusercontent.com/u/20108097"
},
{
"username": "ogabrielluiz",
"href": "https://github.com/ogabrielluiz",
"avatar": "https://avatars3.githubusercontent.com/u/24829397"
},
{
"username": "Juanlu001",
"href": "https://github.com/Juanlu001",
"avatar": "https://avatars0.githubusercontent.com/u/316517"
}
]
},
{
"author": "deepmind",
"name": "dm-haiku",
"avatar": "https://github.com/deepmind.png",
"url": "https://github.com/deepmind/dm-haiku",
"description": "JAX-based neural network library",
"language": "Python",
"languageColor": "#3572A5",
"stars": 273,
"forks": 13,
"currentPeriodStars": 86,
"builtBy": [
{
"username": "tomhennigan",
"href": "https://github.com/tomhennigan",
"avatar": "https://avatars0.githubusercontent.com/u/28017"
},
{
"username": "trevorcai",
"href": "https://github.com/trevorcai",
"avatar": "https://avatars1.githubusercontent.com/u/5669227"
},
{
"username": "aslanides",
"href": "https://github.com/aslanides",
"avatar": "https://avatars1.githubusercontent.com/u/5697617"
},
{
"username": "chris-chris",
"href": "https://github.com/chris-chris",
"avatar": "https://avatars2.githubusercontent.com/u/3013964"
},
{
"username": "ibab",
"href": "https://github.com/ibab",
"avatar": "https://avatars3.githubusercontent.com/u/890531"
}
]
},
{
"author": "terryum",
"name": "awesome-deep-learning-papers",
"avatar": "https://github.com/terryum.png",
"url": "https://github.com/terryum/awesome-deep-learning-papers",
"description": "The most cited deep learning papers",
"language": "TeX",
"languageColor": "#3D6117",
"stars": 20660,
"forks": 4009,
"currentPeriodStars": 18,
"builtBy": [
{
"username": "terryum",
"href": "https://github.com/terryum",
"avatar": "https://avatars0.githubusercontent.com/u/12528769"
},
{
"username": "miguelballesteros",
"href": "https://github.com/miguelballesteros",
"avatar": "https://avatars3.githubusercontent.com/u/11093488"
},
{
"username": "jdoerrie",
"href": "https://github.com/jdoerrie",
"avatar": "https://avatars2.githubusercontent.com/u/4552310"
},
{
"username": "Jeet1994",
"href": "https://github.com/Jeet1994",
"avatar": "https://avatars1.githubusercontent.com/u/7398229"
},
{
"username": "flukeskywalker",
"href": "https://github.com/flukeskywalker",
"avatar": "https://avatars2.githubusercontent.com/u/3215768"
}
]
},
{
"author": "macrozheng",
"name": "mall",
"avatar": "https://github.com/macrozheng.png",
"url": "https://github.com/macrozheng/mall",
"description": "mall项目是一套电商系统,包括前台商城系统及后台管理系统,基于SpringBoot+MyBatis实现,采用Docker容器化部署。 前台商城系统包含首页门户、商品推荐、商品搜索、商品展示、购物车、订单流程、会员中心、客户服务、帮助中心等模块。 后台管理系统包含商品管理、订单管理、会员管理、促销管理、运营管理、内容管理、统计报表、财务管理、权限管理、设置等模块。",
"language": "Java",
"languageColor": "#b07219",
"stars": 29923,
"forks": 12463,
"currentPeriodStars": 63,
"builtBy": [
{
"username": "macrozheng",
"href": "https://github.com/macrozheng",
"avatar": "https://avatars1.githubusercontent.com/u/15903809"
}
]
},
{
"author": "haotian-wang",
"name": "google-access-helper",
"avatar": "https://github.com/haotian-wang.png",
"url": "https://github.com/haotian-wang/google-access-helper",
"description": "谷歌访问助手破解版",
"language": "JavaScript",
"languageColor": "#f1e05a",
"stars": 6594,
"forks": 1878,
"currentPeriodStars": 55,
"builtBy": [
{
"username": "haotian-wang",
"href": "https://github.com/haotian-wang",
"avatar": "https://avatars3.githubusercontent.com/u/17632009"
}
]
},
{
"author": "airbnb",
"name": "javascript",
"avatar": "https://github.com/airbnb.png",
"url": "https://github.com/airbnb/javascript",
"description": "JavaScript Style Guide",
"language": "JavaScript",
"languageColor": "#f1e05a",
"stars": 92846,
"forks": 18053,
"currentPeriodStars": 62,
"builtBy": [
{
"username": "ljharb",
"href": "https://github.com/ljharb",
"avatar": "https://avatars3.githubusercontent.com/u/45469"
},
{
"username": "hshoff",
"href": "https://github.com/hshoff",
"avatar": "https://avatars2.githubusercontent.com/u/339208"
},
{
"username": "lencioni",
"href": "https://github.com/lencioni",
"avatar": "https://avatars3.githubusercontent.com/u/195534"
},
{
"username": "goatslacker",
"href": "https://github.com/goatslacker",
"avatar": "https://avatars3.githubusercontent.com/u/10632"
},
{
"username": "justjake",
"href": "https://github.com/justjake",
"avatar": "https://avatars1.githubusercontent.com/u/296279"
}
]
},
{
"author": "flutter",
"name": "packages",
"avatar": "https://github.com/flutter.png",
"url": "https://github.com/flutter/packages",
"description": "A collection of useful packages maintained by the Flutter team",
"language": "Dart",
"languageColor": "#00B4AB",
"stars": 239,
"forks": 69,
"currentPeriodStars": 83,
"builtBy": [
{
"username": "dnfield",
"href": "https://github.com/dnfield",
"avatar": "https://avatars3.githubusercontent.com/u/8620741"
},
{
"username": "gspencergoog",
"href": "https://github.com/gspencergoog",
"avatar": "https://avatars0.githubusercontent.com/u/8867023"
},
{
"username": "yjbanov",
"href": "https://github.com/yjbanov",
"avatar": "https://avatars2.githubusercontent.com/u/211513"
},
{
"username": "goderbauer",
"href": "https://github.com/goderbauer",
"avatar": "https://avatars2.githubusercontent.com/u/1227763"
},
{
"username": "shihaohong",
"href": "https://github.com/shihaohong",
"avatar": "https://avatars0.githubusercontent.com/u/27032613"
}
]
},
{
"author": "getify",
"name": "You-Dont-Know-JS",
"avatar": "https://github.com/getify.png",
"url": "https://github.com/getify/You-Dont-Know-JS",
"description": "A book series on JavaScript. @YDKJS on twitter.",
"stars": 117655,
"forks": 23544,
"currentPeriodStars": 107,
"builtBy": [
{
"username": "getify",
"href": "https://github.com/getify",
"avatar": "https://avatars3.githubusercontent.com/u/150330"
},
{
"username": "machineloop",
"href": "https://github.com/machineloop",
"avatar": "https://avatars3.githubusercontent.com/u/3682072"
},
{
"username": "pdawyndt",
"href": "https://github.com/pdawyndt",
"avatar": "https://avatars2.githubusercontent.com/u/5736113"
},
{
"username": "4thana",
"href": "https://github.com/4thana",
"avatar": "https://avatars2.githubusercontent.com/u/8932386"
},
{
"username": "zackgao",
"href": "https://github.com/zackgao",
"avatar": "https://avatars3.githubusercontent.com/u/1768718"
}
]
}
]
""".trimIndent() | 0 | Kotlin | 12 | 50 | ecfeff5efdf073944e68f22668cbd51bfc415316 | 25,436 | GithubTrendingRepos | Apache License 2.0 |
src/main/java/club/cpsslab/ruskonert/sql/TableColumn.kt | Ruskonert | 218,726,160 | false | null | package club.cpsslab.ruskonert.sql
@MustBeDocumented
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FIELD)
/**
* TableColumn 클래스는 [AsyncTableElement]에 의해서 동기화 작업이 수행될 때, 동기화하고자 하는 필드를
* 지정할 수 있습니다. [ref]은 필드의 이름이 클래스에서 정의한 필드와 이름이 다를때, 개별적으로 설정해줄 수
* 있습니다.
*
* @param ref 참조하고자 하는 필드
* @param sizeOf 참조하는 필드 사이즈
* @author ruskonert
*/
annotation class TableColumn(val ref : String = "", val sizeOf : Int = -1) | 2 | null | 1 | 1 | 365619a598db6702ed096f641f7892124e1c7d00 | 436 | Project.DBP | MIT License |
modules/paket/src/commonMain/kotlin/com/handtruth/mc/paket/codec/UIntCodec.kt | handtruth | 282,440,433 | false | null | package com.handtruth.mc.paket.codec
import com.handtruth.mc.paket.Paket
import com.handtruth.mc.paket.field.UIntField
import com.handtruth.mc.paket.util.INT_SIZE
import io.ktor.utils.io.core.*
import kotlin.reflect.KProperty
public object UIntCodec : Codec<UInt> {
override fun measure(value: UInt): Int = INT_SIZE
override fun read(input: Input): UInt = input.readUInt()
override fun write(output: Output, value: UInt): Unit = output.writeUInt(value)
public operator fun provideDelegate(paket: Paket, property: KProperty<*>): UIntField {
return paket.field(UIntField())
}
}
| 0 | Kotlin | 0 | 0 | fa6d230dc1f7e62cd75b91ad4798a763ca7e78f1 | 607 | mc-tools | MIT License |
project/Application/src/main/kotlin/cga/exercise/components/geometry/mesh/Renderable.kt | DennisGoss99 | 397,846,380 | true | {"Kotlin": 147862, "GLSL": 9453} | package cga.exercise.components.geometry.mesh
import cga.exercise.components.geometry.RenderCategory
import cga.exercise.components.geometry.transformable.Transformable
import cga.exercise.components.shader.ShaderProgram
import org.joml.Matrix4f
open class Renderable(val shouldRender : List<RenderCategory>, renderable : RenderableBase) : RenderableBase(renderable.meshes, renderable.modelMatrix, renderable.parent) | 0 | Kotlin | 0 | 0 | eb988c98528bf26a3362e74bae2b2b250d6255dd | 418 | CGA_Project | MIT License |
database/src/androidUnitTest/kotlin/uk/co/sentinelweb/cuer/db/util/MultiPlatformPreferencesWrapperDbTestImpl.kt | sentinelweb | 220,796,368 | false | {"Kotlin": 2383617, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170} | package uk.co.sentinelweb.cuer.db.util
import uk.co.sentinelweb.cuer.app.util.prefs.multiplatfom_settings.MultiPlatformPreferences
import uk.co.sentinelweb.cuer.app.util.prefs.multiplatfom_settings.MultiPlatformPreferences.DATABASE_VERSION
import uk.co.sentinelweb.cuer.app.util.prefs.multiplatfom_settings.MultiPlatformPreferencesWrapper
// used for testing DatabaseFactory
class MultiPlatformPreferencesWrapperDbTestImpl : MultiPlatformPreferencesWrapper {
private val map: MutableMap<MultiPlatformPreferences, Any> = mutableMapOf()
override fun getInt(field: MultiPlatformPreferences, def: Int): Int =
if (DATABASE_VERSION == field) {
map.get(field) as? Int ?: def
} else throw IllegalStateException("not implemented")
override fun getInt(field: MultiPlatformPreferences): Int? =
if (DATABASE_VERSION == field) {
map.get(field) as? Int
} else throw IllegalStateException("not implemented")
override fun putInt(field: MultiPlatformPreferences, value: Int) {
if (DATABASE_VERSION == field) {
map.put(field, value)
} else throw IllegalStateException("not implemented")
}
override fun getFloat(field: MultiPlatformPreferences): Float? =
if (DATABASE_VERSION == field) {
map.get(field) as? Float
} else throw IllegalStateException("not implemented")
override fun getFloat(field: MultiPlatformPreferences, def: Float): Float =
if (DATABASE_VERSION == field) {
map.get(field) as? Float ?: def
} else throw IllegalStateException("not implemented")
override fun putFloat(field: MultiPlatformPreferences, value: Float) {
if (DATABASE_VERSION == field) {
map.put(field, value)
} else throw IllegalStateException("not implemented")
}
override fun getString(field: MultiPlatformPreferences, def: String?): String? {
TODO("Not yet implemented")
}
override fun getLong(field: MultiPlatformPreferences, def: Long): Long {
TODO("Not yet implemented")
}
override fun getLong(field: MultiPlatformPreferences): Long? {
TODO("Not yet implemented")
}
override fun putLong(field: MultiPlatformPreferences, value: Long) {
TODO("Not yet implemented")
}
override fun putString(field: MultiPlatformPreferences, value: String) {
TODO("Not yet implemented")
}
override fun putEnum(field: MultiPlatformPreferences, value: Enum<*>) {
TODO("Not yet implemented")
}
override fun <E : Enum<E>> getEnum(field: MultiPlatformPreferences, def: E): E {
TODO("Not yet implemented")
}
override fun getBoolean(field: MultiPlatformPreferences, def: Boolean): Boolean {
TODO("Not yet implemented")
}
override fun getBoolean(field: MultiPlatformPreferences, ext: String, def: Boolean): Boolean {
TODO("Not yet implemented")
}
override fun putBoolean(field: MultiPlatformPreferences, value: Boolean) {
TODO("Not yet implemented")
}
override fun putBoolean(field: MultiPlatformPreferences, ext: String, value: Boolean) {
TODO("Not yet implemented")
}
override fun remove(field: MultiPlatformPreferences) {
TODO("Not yet implemented")
}
override fun has(field: MultiPlatformPreferences): Boolean {
TODO("Not yet implemented")
}
override fun <T1, T2> putPair(field: MultiPlatformPreferences, pair: Pair<T1, T2>) {
TODO("Not yet implemented")
}
override fun <T1, T2> getPair(field: MultiPlatformPreferences, def: Pair<T1, T2>): Pair<T1, T2> {
TODO("Not yet implemented")
}
override fun <T1, T2> getPairNonNull(field: MultiPlatformPreferences, def: Pair<T1, T2>): Pair<T1, T2>? {
TODO("Not yet implemented")
}
}
| 94 | Kotlin | 0 | 2 | f74e211570fe3985ba45848b228e91a3a8593788 | 3,852 | cuer | Apache License 2.0 |
libraries/property-delegates/src/main/java/com/app/propertydelegates/bundle/Utils.kt | atulgpt | 314,638,411 | false | null | /*
* Copyright (C) 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE")
package com.app.propertydelegates.bundle
import android.os.Build
import android.os.Bundle
import com.app.propertydelegates.*
@PublishedApi
internal inline fun getBoolean(
receiver: Bundle,
name: String,
) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
receiver.readBoolean(
Bundle::containsKey,
Bundle::getBoolean,
name
)
} else {
receiver.readInt(
Bundle::containsKey,
Bundle::getInt,
name
) == 1
}
@PublishedApi
internal inline fun getInt(
receiver: Bundle,
name: String,
) =
receiver.readInt(
Bundle::containsKey,
Bundle::getInt,
name
)
@PublishedApi
internal inline fun getLong(
receiver: Bundle,
name: String,
) =
receiver.readLong(
Bundle::containsKey,
Bundle::getLong,
name
)
@PublishedApi
internal inline fun getShort(
receiver: Bundle,
name: String,
) =
receiver.readShort(
Bundle::containsKey,
Bundle::getShort,
name
)
@PublishedApi
internal inline fun getDouble(
receiver: Bundle,
name: String,
) =
receiver.readDouble(
Bundle::containsKey,
Bundle::getDouble,
name
)
@PublishedApi
internal inline fun getFloat(
receiver: Bundle,
name: String,
) =
receiver.readFloat(
Bundle::containsKey,
Bundle::getFloat,
name
)
@PublishedApi
internal inline fun getChar(
receiver: Bundle,
name: String,
) =
receiver.readChar(
Bundle::containsKey,
Bundle::getChar,
name
)
@PublishedApi
internal inline fun getByte(
receiver: Bundle,
name: String,
) =
receiver.readByte(
Bundle::containsKey,
Bundle::getByte,
name
)
@PublishedApi
internal inline fun putBoolean(
receiver: Bundle,
name: String,
value: Boolean?,
) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
receiver.putExtra(
Bundle::remove,
Bundle::putBoolean,
name,
value
)
} else {
receiver.putExtra(
Bundle::remove,
Bundle::putInt,
name,
if (value == true) 1 else 0
)
}
@PublishedApi
internal inline fun putInt(
receiver: Bundle,
name: String,
value: Int?,
) =
receiver.putExtra(
Bundle::remove,
Bundle::putInt,
name,
value
)
@PublishedApi
internal inline fun putLong(
receiver: Bundle,
name: String,
value: Long?,
) =
receiver.putExtra(
Bundle::remove,
Bundle::putLong,
name,
value
)
@PublishedApi
internal inline fun putShort(
receiver: Bundle,
name: String,
value: Short?,
) =
receiver.putExtra(
Bundle::remove,
Bundle::putShort,
name,
value
)
@PublishedApi
internal inline fun putDouble(
receiver: Bundle,
name: String,
value: Double?,
) =
receiver.putExtra(
Bundle::remove,
Bundle::putDouble,
name,
value
)
@PublishedApi
internal inline fun putFloat(
receiver: Bundle,
name: String,
value: Float?,
) =
receiver.putExtra(
Bundle::remove,
Bundle::putFloat,
name,
value
)
@PublishedApi
internal inline fun putChar(
receiver: Bundle,
name: String,
value: Char?,
) =
receiver.putExtra(
Bundle::remove,
Bundle::putChar,
name,
value
)
@PublishedApi
internal inline fun putByte(
receiver: Bundle,
name: String,
value: Byte?,
) =
receiver.putExtra(
Bundle::remove,
Bundle::putByte,
name,
value
)
| 0 | Kotlin | 2 | 8 | 95563901c0070c4a7be56a690de09abc7bdaa01c | 5,063 | LibTron | Apache License 2.0 |
app/src/main/java/com/example/tupicionario/PovosNativosActivity.kt | RubensZaes | 253,876,517 | false | null | package com.example.tupicionario
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.activity_povos_nativos.*
class PovosNativosActivity : AppCompatActivity(), OnItemClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_povos_nativos)
val arrayPovosNativos = resources.getStringArray(R.array.povos_nativos)
val arrayDescricao = resources.getStringArray(R.array.povos_nativos_desc)
val tamanhoLista = arrayPovosNativos.size
val listaCONVERTIDA = listaConvertida(tamanhoLista, arrayPovosNativos, arrayDescricao)
povosNativosRecycleView.adapter = ItemAdapter(listaCONVERTIDA, this)
povosNativosRecycleView.layoutManager = LinearLayoutManager(this)
}
fun listaConvertida(tamanhoLista: Int, name: Array<String>, description: Array<String>): List<Item> {
val listaDeItens = arrayListOf<Item>()
val color = resources.getColor(R.color.povos_nativos_categoria)
for (i in 0 until tamanhoLista) {
var item = Item(R.drawable.ic_povos_nativos, name[i], description[i], color)
listaDeItens += item
}
return listaDeItens
}
override fun onItemClick(itemList: Item, position: Int) {
Toast.makeText(this, itemList.description, Toast.LENGTH_LONG).show()
}
}
| 0 | Kotlin | 0 | 0 | 66a4aa68bba1c354ef56c606ebc623277cd68c45 | 1,536 | Tupicionario | MIT License |
app/src/main/java/com/jonnyhsia/storybook/page/main/timeline/TimelineContract.kt | jonnyhsia | 111,225,431 | false | null | package com.jonnyhsia.storybook.page.main.timeline
import android.support.annotation.StringRes
import com.jonnyhsia.storybook.biz.entity.Story
import com.jonnyhsia.storybook.page.base.BasePresenter
import com.jonnyhsia.storybook.page.base.BaseView
import me.drakeet.multitype.Items
/**
* Created by JonnyHsia on 17/10/29.
* 时间线的合同类
*/
class TimelineContract {
interface Presenter : BasePresenter {
/**
* 请求时间线数据
*/
fun requestTimeline()
/**
* 准备删除故事
* @param pos
*/
fun prepareToDeleteStory(pos: Int)
/**
* 取消删除故事
*/
fun cancelDeleteStory(pos: Int)
/**
* 删除故事
*/
fun deleteStory()
fun readStory(pos: Int)
fun clickSearchBar()
fun clickAvatar()
fun loadMoreStories()
fun refreshTimeline()
fun clickCreateStory()
}
interface View : BaseView<Presenter> {
fun showSubTitle(subTitle: String)
fun showEmptyState()
fun showLoading()
fun showLoadingError(@StringRes errorMsg: Int)
fun showLoadingSuccess(timelineData: List<Story>)
fun showCachedData(cachedTimelineData: List<Story>)
fun showRemoveStory(items: Items, pos: Int)
fun restoreStory(items: Items, pos: Int)
fun showLoadedComplete()
}
} | 0 | Kotlin | 0 | 1 | 0aa23c800b2a8b9a75a4806557a22e89c4fc18b0 | 1,394 | storybook-deprecated | Apache License 2.0 |
src/main/kotlin/com/imma/persist/mango/MongoMapperMaterial.kt | Indexical-Metrics-Measure-Advisory | 344,732,013 | false | null | package com.imma.persist.mango
import com.imma.persist.core.*
import com.imma.persist.defs.EntityDef
import com.imma.persist.defs.MapperMaterial
import org.bson.BsonInt32
import org.bson.Document
class MongoMapperMaterial(
entity: Any?,
entityClass: Class<*>? = null,
entityName: String? = null
) : MapperMaterial(entity, entityClass, entityName) {
private val def: MongoEntityDef = MongoEntityMapper.getDef(this)
override fun getDef(): EntityDef {
return this.def
}
fun toDocument(generateId: () -> Any): Document {
return def.toDocument(entity!!, generateId)
}
fun toDocument(): Document {
return def.toDocument(entity!!)
}
fun fromDocument(doc: Document): Any {
return def.fromDocument(doc)
}
fun generateIdFilter(): Document {
val filter = def.generateIdFilter(entity!!)
return Document(filter.first, filter.second)
}
/**
* when id is not passed, use id from given entity
*/
fun buildIdFilter(id: String? = null): Document {
val where = where { factor(getIdFieldName()) eq { value(id ?: getIdValue()) } }
return toFilter(where)
}
/**
* projection for aggregate
*/
fun toProjection(select: Select): Document {
return select.columns.map { column ->
when (column.element) {
is FactorElement -> fromFactorElement(column.element, ElementShouldBe.any, false)
else -> throw RuntimeException("Only plain factor column is supported in projection, but is [$column] now.")
}
}.associateWith {
BsonInt32(1)
}.let {
Document("\$project", it)
}
}
fun toUpdates(updates: Updates): List<Document> {
return updates.parts.map {
val factor = it.factor
val factorName = factor.factorIdOrName
if (factorName.isNullOrBlank()) {
throw RuntimeException("Factor name cannot be null or blank.")
}
val fieldName = toFieldName(factorName)
when (it.type) {
FactorUpdateType.SET -> "\$set" to mapOf(fieldName to it.value)
FactorUpdateType.PULL -> "\$pull" to mapOf(fieldName to it.value)
FactorUpdateType.PUSH -> "\$push" to mapOf(fieldName to it.value)
}
}.map { (key, value) -> Document(key, value) }
}
fun toFilter(where: Where): Document {
return Document("\$expr", fromJoint(where))
}
fun toMatch(where: Where): Document {
return Document("\$match", toFilter(where))
}
fun toMatch(filter: Document): Document {
return Document("\$match", filter)
}
fun toSkip(skipCount: Int): Document {
return Document("\$skip", skipCount)
}
fun toLimit(limitCount: Int): Document {
return Document("\$limit", limitCount)
}
@Suppress("DuplicatedCode")
private fun fromJoint(joint: Joint): Map<String, Any?> {
val parts = joint.parts
if (parts.isNullOrEmpty()) {
throw RuntimeException("No expression under joint[$joint].")
}
if (parts.size == 1) {
// only one sub part under current joint, ignore joint and return filter of sub part
return when (val first = parts[0]) {
is Joint -> fromJoint(first)
is Expression -> fromExpression(first)
else -> throw RuntimeException("Unsupported part[$first] of condition.")
}
}
val type = joint.type
val operator = if (type == JointType.and) "\$and" else "\$or"
val sub = parts.map { part ->
when (part) {
is Joint -> fromJoint(part)
is Expression -> fromExpression(part)
else -> throw RuntimeException("Unsupported part[$part] of condition.")
}
}
return mapOf(operator to sub)
}
@Suppress("DuplicatedCode")
private fun fromExpression(exp: Expression): Map<String, Any?> {
val left = exp.left ?: throw RuntimeException("Left of [$exp] cannot be null.")
val operator = exp.operator ?: throw RuntimeException("Operator of [$exp] cannot be null.")
val right = exp.right
if (operator != ExpressionOperator.empty && operator != ExpressionOperator.`not-empty` && right == null) {
throw RuntimeException("Right of [$exp] cannot be null when operator is neither empty nor not-empty.")
}
return when (operator) {
ExpressionOperator.empty -> MF.eq(fromElement(left), null)
ExpressionOperator.`not-empty` -> MF.notEq(fromElement(left), null)
ExpressionOperator.equals -> MF.eq(fromElement(left), fromElement(right!!))
ExpressionOperator.`not-equals` -> MF.notEq(fromElement(left), fromElement(right!!))
ExpressionOperator.less -> MF.lt(fromElement(left), fromElement(right!!))
ExpressionOperator.`less-equals` -> MF.lte(fromElement(left), fromElement(right!!))
ExpressionOperator.more -> MF.gt(fromElement(left), fromElement(right!!))
ExpressionOperator.`more-equals` -> MF.gte(fromElement(left), fromElement(right!!))
ExpressionOperator.`in` -> MF.exists(fromElement(left), fromElement(right!!))
ExpressionOperator.`not-in` -> MF.notExists(fromElement(left), fromElement(right!!))
ExpressionOperator.`has-text` -> MF.hasText(fromElement(left), fromElement(right!!))
ExpressionOperator.`has-one` -> MF.eq(fromElement(left), fromElement(right!!))
}
}
override fun fromComputedElement(element: ComputedElement, shouldBe: ElementShouldBe): Any {
val operator = element.operator ?: throw RuntimeException("Operator of [$element] cannot be null.")
val elements = element.elements.also {
if (it.size == 0) throw RuntimeException("Elements of [$element] cannot be null.")
}
this.checkElements(element)
return when (operator) {
ElementComputeOperator.add -> MF.add(elements.map { fromElement(it, ElementShouldBe.numeric) })
ElementComputeOperator.subtract -> MF.subtract(elements.map { fromElement(it, ElementShouldBe.numeric) })
ElementComputeOperator.multiply -> MF.multiply(elements.map { fromElement(it, ElementShouldBe.numeric) })
ElementComputeOperator.divide -> MF.divide(elements.map { fromElement(it, ElementShouldBe.numeric) })
ElementComputeOperator.modulus -> MF.mod(
fromElement(elements[0], ElementShouldBe.numeric),
fromElement(elements[1], ElementShouldBe.numeric)
)
ElementComputeOperator.`year-of` -> MF.year(fromElement(elements[0], ElementShouldBe.date))
ElementComputeOperator.`half-year-of` -> MF.halfYear(fromElement(elements[0], ElementShouldBe.date))
ElementComputeOperator.`quarter-of` -> MF.quarter(fromElement(elements[0], ElementShouldBe.date))
ElementComputeOperator.`month-of` -> MF.month(fromElement(elements[0], ElementShouldBe.date))
ElementComputeOperator.`week-of-year` -> MF.weekOfYear(fromElement(elements[0], ElementShouldBe.date))
ElementComputeOperator.`week-of-month` -> MF.weekOfMonth(fromElement(elements[0], ElementShouldBe.date))
ElementComputeOperator.`day-of-month` -> MF.dayOfMonth(fromElement(elements[0], ElementShouldBe.date))
ElementComputeOperator.`day-of-week` -> MF.dayOfWeek(fromElement(elements[0], ElementShouldBe.date))
ElementComputeOperator.`case-then` -> toCaseThenMatcher(elements, shouldBe)
}
}
private fun toCaseThenMatcher(
elements: MutableList<Element>,
shouldBe: ElementShouldBe
): Map<String, Map<String, Any?>> {
val caseElements = elements.filter { it.joint != null }
val firstThen = MF.case(MF.eq(fromJoint(elements[0].joint!!), true)).then(fromElement(elements[0], shouldBe))
val cases = caseElements.filterIndexed { index, _ -> index != 0 }.fold(firstThen) { previousThen, element ->
previousThen.case(MF.eq(fromJoint(element.joint!!), true)).then(fromElement(element, shouldBe))
}
// append default() to $switch when anyway element exists, otherwise finish it by done()
return elements.find { it.joint == null }?.let { cases.default(fromElement(it, shouldBe)) } ?: cases.done()
}
override fun toFieldNameInExpression(fieldName: String): String {
return "\$$fieldName"
}
override fun toFieldNameInSelection(fieldName: String): String {
return fieldName
}
}
class MongoMapperMaterialBuilder private constructor(private val entity: Any?) {
private var clazz: Class<*>? = null
private var name: String? = null
companion object {
fun create(entity: Any? = null): MongoMapperMaterialBuilder {
return MongoMapperMaterialBuilder(entity)
}
}
fun type(clazz: Class<*>): MongoMapperMaterialBuilder {
this.clazz = clazz
return this
}
fun name(name: String): MongoMapperMaterialBuilder {
this.name = name
return this
}
fun build(): MongoMapperMaterial {
return MongoMapperMaterial(entity, clazz, name)
}
} | 0 | Kotlin | 0 | 1 | c42a959826e72ac8cea7a8390ccc7825f047a591 | 8,266 | watchmen-ktor | MIT License |
src/main/kotlin/org/rust/lang/core/macros/RsMacroData.kt | intellij-rust | 42,619,487 | false | {"Gradle Kotlin DSL": 2, "Java Properties": 5, "Markdown": 11, "TOML": 19, "Shell": 2, "Text": 124, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "XML": 140, "Kotlin": 2284, "INI": 3, "ANTLR": 1, "Rust": 362, "YAML": 131, "RenderScript": 1, "JSON": 6, "HTML": 198, "SVG": 136, "JFlex": 1, "Java": 1, "Python": 37} | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros
import org.rust.cargo.project.workspace.CargoWorkspaceData
import org.rust.lang.core.macros.builtin.BuiltinMacroExpander
import org.rust.lang.core.psi.RsMacroBody
import org.rust.lang.core.psi.ext.RsMacroDefinitionBase
import org.rust.stdext.HashCode
sealed class RsMacroData
class RsDeclMacroData(val macroBody: Lazy<RsMacroBody?>): RsMacroData() {
constructor(def: RsMacroDefinitionBase) : this(lazy(LazyThreadSafetyMode.PUBLICATION) { def.macroBodyStubbed })
}
data class RsProcMacroData(val name: String, val artifact: CargoWorkspaceData.ProcMacroArtifact): RsMacroData()
class RsBuiltinMacroData(val name: String): RsMacroData() {
fun withHash(): RsMacroDataWithHash<RsBuiltinMacroData> =
RsMacroDataWithHash(this, HashCode.mix(HashCode.compute(name), BUILTIN_DEF_HASH))
companion object {
private val BUILTIN_DEF_HASH = HashCode.compute(BuiltinMacroExpander.EXPANDER_VERSION.toString())
}
}
| 1,841 | Kotlin | 380 | 4,528 | c6657c02bb62075bf7b7ceb84d000f93dda34dc1 | 1,078 | intellij-rust | MIT License |
plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigValueUniquenessInspection.kt | ingokegel | 284,920,751 | true | null | // Copyright 2000-2018 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.editorconfig.language.codeinsight.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import org.editorconfig.language.codeinsight.quickfixes.EditorConfigRemoveListValueQuickFix
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.EditorConfigOptionValueList
import org.editorconfig.language.psi.EditorConfigVisitor
import org.editorconfig.language.schema.descriptors.EditorConfigDescriptor
import org.editorconfig.language.schema.descriptors.impl.EditorConfigListDescriptor
class EditorConfigValueUniquenessInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() {
override fun visitOptionValueList(list: EditorConfigOptionValueList) {
val values = list.optionValueIdentifierList
val listDescriptor = list.getDescriptor(false) as? EditorConfigListDescriptor ?: return
if (listDescriptor.allowRepetitions) return
val message = EditorConfigBundle["inspection.value.uniqueness.message"]
values.groupByNotNull {
val descriptor = it.getDescriptor(false) ?: return@groupByNotNull null
findListChildDescriptor(descriptor)
}.values.filter { it.size > 1 }.flatMap { it }.forEach {
holder.registerProblem(it, message, EditorConfigRemoveListValueQuickFix())
}
}
}
private tailrec fun findListChildDescriptor(descriptor: EditorConfigDescriptor): EditorConfigDescriptor {
val parent = descriptor.parent ?: throw IllegalStateException()
if (parent is EditorConfigListDescriptor) return descriptor
return findListChildDescriptor(parent)
}
private inline fun <T, K : Any> Iterable<T>.groupByNotNull(keySelector: (T) -> K?): Map<K, List<T>> {
return groupByNotNullTo(LinkedHashMap(), keySelector)
}
private inline fun <T, K : Any, M : MutableMap<in K, MutableList<T>>> Iterable<T>.groupByNotNullTo(
destination: M,
keySelector: (T) -> K?
): M {
for (element in this) {
val key = keySelector(element) ?: continue
val list = destination.getOrPut(key) { ArrayList() }
list.add(element)
}
return destination
}
}
| 191 | null | 4372 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 2,392 | intellij-community | Apache License 2.0 |
src/main/kotlin/no/nav/bidrag/cucumber/aop/ExceptionLoggerAspect.kt | navikt | 426,232,197 | false | null | package no.nav.bidrag.cucumber.aop
import no.nav.bidrag.commons.ExceptionLogger
import no.nav.bidrag.cucumber.model.CucumberTestRun
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.AfterThrowing
import org.aspectj.lang.annotation.Aspect
import org.springframework.stereotype.Component
@Aspect
@Component
class ExceptionLoggerAspect(private val exceptionLogger: ExceptionLogger) {
@AfterThrowing(pointcut = "within (no.nav.bidrag.cucumber.controller..*)", throwing = "exception")
fun logException(joinPoint: JoinPoint, exception: Exception) {
val logMessages = exceptionLogger.logException(exception, joinPoint.sourceLocation.withinType.toString())
CucumberTestRun.hold(logMessages)
}
}
| 8 | Kotlin | 0 | 2 | fd15f9bd5dab142c55edb37abdf92cd4975fc0f2 | 737 | bidrag-cucumber-onprem | MIT License |
infobip-rtc-ui/src/main/java/com/infobip/webrtc/ui/InfobipRtcUiImpl.kt | infobip | 56,227,769 | false | null | package com.infobip.webrtc.ui
import android.content.Context
import android.util.Log
import com.infobip.webrtc.Cache
import com.infobip.webrtc.Injector
import com.infobip.webrtc.TAG
import com.infobip.webrtc.TokenProvider
import com.infobip.webrtc.sdk.api.InfobipRTC
import com.infobip.webrtc.sdk.api.model.push.Status
import com.infobip.webrtc.ui.delegate.CallsDelegate
import com.infobip.webrtc.ui.delegate.NotificationPermissionDelegate
import com.infobip.webrtc.ui.delegate.PushIdDelegate
import com.infobip.webrtc.ui.model.InCallButton
import com.infobip.webrtc.ui.model.ListenType
import com.infobip.webrtc.ui.model.RtcUiMode
import com.infobip.webrtc.ui.view.styles.InfobipRtcUiTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.Locale
internal class InfobipRtcUiImpl(
private val context: Context,
private val tokenProvider: TokenProvider,
private val cache: Cache,
private val callsDelegate: CallsDelegate,
private val callsScope: CoroutineScope,
private val pushIdDelegate: PushIdDelegate,
private val rtcInstance: InfobipRTC,
private val notificationPermissionDelegate: NotificationPermissionDelegate,
) : InfobipRtcUi {
private var rtcUiMode: RtcUiMode?
get() = cache.rtcUiMode
set(value) {
cache.rtcUiMode = value
}
override fun enableCalls(identity: String, listenType: ListenType, successListener: SuccessListener?, errorListener: ErrorListener?) {
//it can be called also from broadcast receivers when we already have mode
if (rtcUiMode == null)
rtcUiMode = RtcUiMode.CUSTOM.withListeners(successListener, errorListener)
callsScope.launch {
runCatching {
Log.d(TAG, "Enabling $rtcUiMode calls for identity $identity.")
cache.identity = identity
tokenProvider.getToken(identity)?.let { token ->
if (listenType == ListenType.PUSH) {
if (notificationPermissionDelegate.isPermissionNeeded()) {
withContext(Dispatchers.Main) {
notificationPermissionDelegate.request()
}
}
registerPush(token, errorListener, successListener)
} else {
registerActiveConnection(token, errorListener, successListener)
}
} ?: runOnUiThread {
errorListener?.onError(IllegalStateException("Could not create WebRTC token."))
cleanStoredCallbacks()
}
}.onFailure {
runOnUiThread { errorListener?.onError(it) }
cleanStoredCallbacks()
}
}
}
override fun enableCalls(successListener: SuccessListener?, errorListener: ErrorListener?) {
rtcUiMode = RtcUiMode.DEFAULT.withListeners(successListener, errorListener)
pushIdDelegate.getPushRegistrationId()?.let { pushRegId ->
enableCalls(
identity = pushRegId,
listenType = ListenType.PUSH,
successListener = successListener,
errorListener = errorListener
)
} ?: Log.d(TAG, "Could not obtain identity value(pushRegistrationId), waiting for broadcast.")
}
override fun enableInAppChatCalls(
successListener: SuccessListener?,
errorListener: ErrorListener?
) {
rtcUiMode = RtcUiMode.IN_APP_CHAT.withListeners(successListener, errorListener)
Log.d(TAG, "Waiting for broadcast with livechatRegistrationId.")
}
override fun disableCalls(successListener: SuccessListener?, errorListener: ErrorListener?) {
runCatching {
val identity = cache.identity
require(identity.isNotEmpty()) { "Calls are not registered." }
Log.d(TAG, "Disabling calls for identity $identity.")
callsScope.launch {
rtcInstance.disablePushNotification(tokenProvider.getToken(identity), context)
cache.clear()
successListener?.onSuccess()
callsScope.coroutineContext.cancelChildren()
}
}.onFailure {
errorListener?.onError(it)
}
}
override fun setLanguage(locale: Locale) {
Injector.locale = locale
}
override fun setInCallButtons(buttons: List<InCallButton>) {
Injector.inCallButtons = listOf(InCallButton.HangUp, *buttons.toTypedArray())
}
override fun setTheme(theme: InfobipRtcUiTheme) {
Injector.theme = theme
}
private fun registerPush(token: String, errorListener: ErrorListener?, successListener: SuccessListener?) {
callsDelegate.enablePush(token, cache.configurationId) {
Log.d(TAG, "Registration for calls push result: ${it.status}, ${it.description}")
runOnUiThread {
if (it.status != Status.SUCCESS) {
errorListener?.onError(IllegalStateException("Registration for calls push failed. Reason: ${it.description}"))
} else {
successListener?.onSuccess()
}
cleanStoredCallbacks()
}
}
}
private fun registerActiveConnection(token: String, errorListener: ErrorListener?, successListener: SuccessListener?) {
runCatching {
callsDelegate.registerActiveConnection(token)
}.onSuccess {
runOnUiThread { successListener?.onSuccess() }
}.onFailure {
runOnUiThread { errorListener?.onError(it) }
}
cleanStoredCallbacks()
}
private fun runOnUiThread(action: () -> Unit) {
callsScope.launch(Dispatchers.Main) {
action()
}
}
private fun cleanStoredCallbacks() {
with(Injector.cache) {
rtcUiMode?.cleanListeners()
}
}
}
| 5 | null | 16 | 44 | 4ada56a654f56f5bf73f1521bcbd8d66cdb2499f | 6,172 | mobile-messaging-sdk-android | Apache License 2.0 |
azure-communication-ui/calling/src/main/java/com/azure/android/communication/ui/calling/presentation/fragment/calling/support/SupportViewModel.kt | Azure | 429,521,705 | false | {"Kotlin": 2573728, "Java": 167445, "Shell": 3964, "HTML": 1856} | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.android.communication.ui.calling.presentation.fragment.calling.support
import com.azure.android.communication.ui.calling.redux.Dispatch
import com.azure.android.communication.ui.calling.redux.action.NavigationAction
import com.azure.android.communication.ui.calling.redux.state.NavigationState
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
internal class SupportViewModel(private val dispatch: Dispatch, private val onSubmit: (String) -> Unit) {
private var _isVisibleStateFlow: MutableStateFlow<Boolean> = MutableStateFlow(false)
private val _isSubmitEnabledStateFlow: MutableStateFlow<Boolean> = MutableStateFlow(false)
private var _userMessageStateFlow = MutableStateFlow<String>("")
private val _clearEditTextStateFlow = MutableStateFlow<Long>(0)
val clearEditTextStateFlow get() = _clearEditTextStateFlow as StateFlow<Long>
var userMessage: String get() = _userMessageStateFlow.value
set(value) {
_userMessageStateFlow.value = value
_isSubmitEnabledStateFlow.value = value.isNotEmpty()
}
val isVisibleStateFlow get() = _isVisibleStateFlow as StateFlow<Boolean>
val isSubmitEnabledStateFlow get() = _isSubmitEnabledStateFlow as StateFlow<Boolean>
var isVisible get() = _isVisibleStateFlow.value
set(value) {
_isVisibleStateFlow.value = value
}
fun init(navigationState: NavigationState) {
_isVisibleStateFlow = MutableStateFlow(navigationState.supportVisible)
}
fun update(navigationState: NavigationState) {
if (navigationState.supportVisible && !_isVisibleStateFlow.value) {
// Made visible, lets trigger a clear of the EditText
_clearEditTextStateFlow.value = System.currentTimeMillis()
_userMessageStateFlow.value = ""
}
_isVisibleStateFlow.value = navigationState.supportVisible
}
fun dismissForm() {
dispatch(NavigationAction.HideSupportForm())
_userMessageStateFlow.value = ""
}
fun forwardEventToUser() {
onSubmit(userMessage)
}
}
| 6 | Kotlin | 27 | 24 | 96a897fb62cf8ce39a30f8bb7232df8aa888e084 | 2,242 | communication-ui-library-android | MIT License |
src/main/kotlin/Main.kt | Rokucraft | 320,306,024 | false | {"Kotlin": 52866} | package com.rokucraft.rokubot
import com.rokucraft.rokubot.di.DaggerRokuBotComponent
fun main() {
val botComponent = DaggerRokuBotComponent.create()
botComponent.bot()
}
| 0 | Kotlin | 2 | 7 | 45dc9c138b267c236782d15c202d27e51bbfee60 | 180 | RokuBot | MIT License |
ui/homepage/src/main/java/org/kafka/homepage/components/Carousels.kt | vipulyaara | 612,950,214 | false | {"Kotlin": 635130, "JavaScript": 440999, "HTML": 11959, "CSS": 7888, "Shell": 2974} | package org.kafka.homepage.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.snapping.SnapLayoutInfoProvider
import androidx.compose.foundation.gestures.snapping.rememberSnapFlingBehavior
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.kafka.data.model.homepage.HomepageBanner
import kotlinx.collections.immutable.ImmutableList
import org.kafka.common.widgets.shadowMaterial
import ui.common.theme.theme.Dimens
@Composable
internal fun Carousels(
carouselItems: ImmutableList<HomepageBanner>,
onBannerClick: (HomepageBanner) -> Unit,
modifier: Modifier = Modifier,
lazyListState: LazyListState = rememberLazyListState()
) {
LazyRow(
modifier = modifier.padding(vertical = Dimens.Spacing04),
contentPadding = PaddingValues(horizontal = Dimens.Spacing12),
verticalAlignment = Alignment.CenterVertically,
state = lazyListState,
flingBehavior = rememberSnapFlingBehavior(
snapLayoutInfoProvider = remember(lazyListState) {
SnapLayoutInfoProvider(lazyListState = lazyListState)
},
)
) {
itemsIndexed(carouselItems) { _, item ->
CarouselItem(item = item, onBannerClick = onBannerClick)
}
}
}
@Composable
private fun CarouselItem(
item: HomepageBanner,
onBannerClick: (HomepageBanner) -> Unit,
modifier: Modifier = Modifier
) {
AsyncImage(
model = ImageRequest.Builder(LocalContext.current)
.data(item.imageUrl)
.crossfade(true)
.build(),
contentScale = ContentScale.Crop,
contentDescription = null,
modifier = modifier
.widthIn(min = 324.dp)
.height(184.dp)
.padding(Dimens.Spacing02)
.shadowMaterial(
elevation = Dimens.Spacing12,
shape = RoundedCornerShape(Dimens.Spacing08)
)
.clickable { onBannerClick(item) }
)
}
| 5 | Kotlin | 10 | 86 | fa64a43602eecac8b93ae9e8b713f6d29ba90727 | 2,798 | Kafka | Apache License 2.0 |
ivassistant/src/main/java/com/thoughtworks/ivassistant/abilities/wakeup/WakeUp.kt | TW-Smart-CoE | 679,741,051 | false | {"Kotlin": 95347} | package com.thoughtworks.ivassistant.abilities.wakeup
interface WakeUpCallback {
fun onSuccess() {}
fun onError(errorCode: Int, errorMessage: String) {}
fun onStop() {}
}
interface WakeUp {
fun initialize()
fun start(wakeUpCallback: WakeUpCallback? = null)
fun stop()
fun release()
} | 1 | Kotlin | 0 | 1 | c93dbb6528dfa980e19e28dfed09e6be4934e860 | 313 | ivassistant-android | Apache License 2.0 |
ivassistant/src/main/java/com/thoughtworks/ivassistant/abilities/wakeup/WakeUp.kt | TW-Smart-CoE | 679,741,051 | false | {"Kotlin": 95347} | package com.thoughtworks.ivassistant.abilities.wakeup
interface WakeUpCallback {
fun onSuccess() {}
fun onError(errorCode: Int, errorMessage: String) {}
fun onStop() {}
}
interface WakeUp {
fun initialize()
fun start(wakeUpCallback: WakeUpCallback? = null)
fun stop()
fun release()
} | 1 | Kotlin | 0 | 1 | c93dbb6528dfa980e19e28dfed09e6be4934e860 | 313 | ivassistant-android | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/batch/CfnJobQueue.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 142794926} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.batch
import io.cloudshiftdev.awscdk.CfnResource
import io.cloudshiftdev.awscdk.IInspectable
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.ITaggable
import io.cloudshiftdev.awscdk.TagManager
import io.cloudshiftdev.awscdk.TreeInspector
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.Number
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.collections.Map
import io.cloudshiftdev.constructs.Construct as CloudshiftdevConstructsConstruct
import software.constructs.Construct as SoftwareConstructsConstruct
/**
* The `AWS::Batch::JobQueue` resource specifies the parameters for an AWS Batch job queue
* definition.
*
* For more information, see [Job
* Queues](https://docs.aws.amazon.com/batch/latest/userguide/job_queues.html) in the ** .
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.batch.*;
* CfnJobQueue cfnJobQueue = CfnJobQueue.Builder.create(this, "MyCfnJobQueue")
* .computeEnvironmentOrder(List.of(ComputeEnvironmentOrderProperty.builder()
* .computeEnvironment("computeEnvironment")
* .order(123)
* .build()))
* .priority(123)
* // the properties below are optional
* .jobQueueName("jobQueueName")
* .jobStateTimeLimitActions(List.of(JobStateTimeLimitActionProperty.builder()
* .action("action")
* .maxTimeSeconds(123)
* .reason("reason")
* .state("state")
* .build()))
* .schedulingPolicyArn("schedulingPolicyArn")
* .state("state")
* .tags(Map.of(
* "tagsKey", "tags"))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html)
*/
public open class CfnJobQueue(
cdkObject: software.amazon.awscdk.services.batch.CfnJobQueue,
) : CfnResource(cdkObject), IInspectable, ITaggable {
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnJobQueueProps,
) :
this(software.amazon.awscdk.services.batch.CfnJobQueue(scope.let(CloudshiftdevConstructsConstruct.Companion::unwrap),
id, props.let(CfnJobQueueProps.Companion::unwrap))
)
public constructor(
scope: CloudshiftdevConstructsConstruct,
id: String,
props: CfnJobQueueProps.Builder.() -> Unit,
) : this(scope, id, CfnJobQueueProps(props)
)
/**
* Returns the job queue ARN, such as `batch: *us-east-1* : *111122223333* :job-queue/
* *JobQueueName*` .
*/
public open fun attrJobQueueArn(): String = unwrap(this).getAttrJobQueueArn()
/**
* The set of compute environments mapped to a job queue and their order relative to each other.
*/
public open fun computeEnvironmentOrder(): Any = unwrap(this).getComputeEnvironmentOrder()
/**
* The set of compute environments mapped to a job queue and their order relative to each other.
*/
public open fun computeEnvironmentOrder(`value`: IResolvable) {
unwrap(this).setComputeEnvironmentOrder(`value`.let(IResolvable.Companion::unwrap))
}
/**
* The set of compute environments mapped to a job queue and their order relative to each other.
*/
public open fun computeEnvironmentOrder(`value`: List<Any>) {
unwrap(this).setComputeEnvironmentOrder(`value`.map{CdkObjectWrappers.unwrap(it)})
}
/**
* The set of compute environments mapped to a job queue and their order relative to each other.
*/
public open fun computeEnvironmentOrder(vararg `value`: Any): Unit =
computeEnvironmentOrder(`value`.toList())
/**
* Examines the CloudFormation resource and discloses attributes.
*
* @param inspector tree inspector to collect and process attributes.
*/
public override fun inspect(inspector: TreeInspector) {
unwrap(this).inspect(inspector.let(TreeInspector.Companion::unwrap))
}
/**
* The name of the job queue.
*/
public open fun jobQueueName(): String? = unwrap(this).getJobQueueName()
/**
* The name of the job queue.
*/
public open fun jobQueueName(`value`: String) {
unwrap(this).setJobQueueName(`value`)
}
/**
* The set of actions that AWS Batch perform on jobs that remain at the head of the job queue in
* the specified state longer than specified times.
*/
public open fun jobStateTimeLimitActions(): Any? = unwrap(this).getJobStateTimeLimitActions()
/**
* The set of actions that AWS Batch perform on jobs that remain at the head of the job queue in
* the specified state longer than specified times.
*/
public open fun jobStateTimeLimitActions(`value`: IResolvable) {
unwrap(this).setJobStateTimeLimitActions(`value`.let(IResolvable.Companion::unwrap))
}
/**
* The set of actions that AWS Batch perform on jobs that remain at the head of the job queue in
* the specified state longer than specified times.
*/
public open fun jobStateTimeLimitActions(`value`: List<Any>) {
unwrap(this).setJobStateTimeLimitActions(`value`.map{CdkObjectWrappers.unwrap(it)})
}
/**
* The set of actions that AWS Batch perform on jobs that remain at the head of the job queue in
* the specified state longer than specified times.
*/
public open fun jobStateTimeLimitActions(vararg `value`: Any): Unit =
jobStateTimeLimitActions(`value`.toList())
/**
* The priority of the job queue.
*/
public open fun priority(): Number = unwrap(this).getPriority()
/**
* The priority of the job queue.
*/
public open fun priority(`value`: Number) {
unwrap(this).setPriority(`value`)
}
/**
* The Amazon Resource Name (ARN) of the scheduling policy.
*/
public open fun schedulingPolicyArn(): String? = unwrap(this).getSchedulingPolicyArn()
/**
* The Amazon Resource Name (ARN) of the scheduling policy.
*/
public open fun schedulingPolicyArn(`value`: String) {
unwrap(this).setSchedulingPolicyArn(`value`)
}
/**
* The state of the job queue.
*/
public open fun state(): String? = unwrap(this).getState()
/**
* The state of the job queue.
*/
public open fun state(`value`: String) {
unwrap(this).setState(`value`)
}
/**
* Tag Manager which manages the tags for this resource.
*/
public override fun tags(): TagManager = unwrap(this).getTags().let(TagManager::wrap)
/**
* The tags that are applied to the job queue.
*/
public open fun tagsRaw(): Map<String, String> = unwrap(this).getTagsRaw() ?: emptyMap()
/**
* The tags that are applied to the job queue.
*/
public open fun tagsRaw(`value`: Map<String, String>) {
unwrap(this).setTagsRaw(`value`)
}
/**
* A fluent builder for [io.cloudshiftdev.awscdk.services.batch.CfnJobQueue].
*/
@CdkDslMarker
public interface Builder {
/**
* The set of compute environments mapped to a job queue and their order relative to each other.
*
* The job scheduler uses this parameter to determine which compute environment runs a specific
* job. Compute environments must be in the `VALID` state before you can associate them with a job
* queue. You can associate up to three compute environments with a job queue. All of the compute
* environments must be either EC2 ( `EC2` or `SPOT` ) or Fargate ( `FARGATE` or `FARGATE_SPOT` );
* EC2 and Fargate compute environments can't be mixed.
*
*
* All compute environments that are associated with a job queue must share the same
* architecture. AWS Batch doesn't support mixing compute environment architecture types in a
* single job queue.
*
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-computeenvironmentorder)
* @param computeEnvironmentOrder The set of compute environments mapped to a job queue and
* their order relative to each other.
*/
public fun computeEnvironmentOrder(computeEnvironmentOrder: IResolvable)
/**
* The set of compute environments mapped to a job queue and their order relative to each other.
*
* The job scheduler uses this parameter to determine which compute environment runs a specific
* job. Compute environments must be in the `VALID` state before you can associate them with a job
* queue. You can associate up to three compute environments with a job queue. All of the compute
* environments must be either EC2 ( `EC2` or `SPOT` ) or Fargate ( `FARGATE` or `FARGATE_SPOT` );
* EC2 and Fargate compute environments can't be mixed.
*
*
* All compute environments that are associated with a job queue must share the same
* architecture. AWS Batch doesn't support mixing compute environment architecture types in a
* single job queue.
*
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-computeenvironmentorder)
* @param computeEnvironmentOrder The set of compute environments mapped to a job queue and
* their order relative to each other.
*/
public fun computeEnvironmentOrder(computeEnvironmentOrder: List<Any>)
/**
* The set of compute environments mapped to a job queue and their order relative to each other.
*
* The job scheduler uses this parameter to determine which compute environment runs a specific
* job. Compute environments must be in the `VALID` state before you can associate them with a job
* queue. You can associate up to three compute environments with a job queue. All of the compute
* environments must be either EC2 ( `EC2` or `SPOT` ) or Fargate ( `FARGATE` or `FARGATE_SPOT` );
* EC2 and Fargate compute environments can't be mixed.
*
*
* All compute environments that are associated with a job queue must share the same
* architecture. AWS Batch doesn't support mixing compute environment architecture types in a
* single job queue.
*
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-computeenvironmentorder)
* @param computeEnvironmentOrder The set of compute environments mapped to a job queue and
* their order relative to each other.
*/
public fun computeEnvironmentOrder(vararg computeEnvironmentOrder: Any)
/**
* The name of the job queue.
*
* It can be up to 128 letters long. It can contain uppercase and lowercase letters, numbers,
* hyphens (-), and underscores (_).
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-jobqueuename)
* @param jobQueueName The name of the job queue.
*/
public fun jobQueueName(jobQueueName: String)
/**
* The set of actions that AWS Batch perform on jobs that remain at the head of the job queue in
* the specified state longer than specified times.
*
* AWS Batch will perform each action after `maxTimeSeconds` has passed.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-jobstatetimelimitactions)
* @param jobStateTimeLimitActions The set of actions that AWS Batch perform on jobs that remain
* at the head of the job queue in the specified state longer than specified times.
*/
public fun jobStateTimeLimitActions(jobStateTimeLimitActions: IResolvable)
/**
* The set of actions that AWS Batch perform on jobs that remain at the head of the job queue in
* the specified state longer than specified times.
*
* AWS Batch will perform each action after `maxTimeSeconds` has passed.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-jobstatetimelimitactions)
* @param jobStateTimeLimitActions The set of actions that AWS Batch perform on jobs that remain
* at the head of the job queue in the specified state longer than specified times.
*/
public fun jobStateTimeLimitActions(jobStateTimeLimitActions: List<Any>)
/**
* The set of actions that AWS Batch perform on jobs that remain at the head of the job queue in
* the specified state longer than specified times.
*
* AWS Batch will perform each action after `maxTimeSeconds` has passed.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-jobstatetimelimitactions)
* @param jobStateTimeLimitActions The set of actions that AWS Batch perform on jobs that remain
* at the head of the job queue in the specified state longer than specified times.
*/
public fun jobStateTimeLimitActions(vararg jobStateTimeLimitActions: Any)
/**
* The priority of the job queue.
*
* Job queues with a higher priority (or a higher integer value for the `priority` parameter)
* are evaluated first when associated with the same compute environment. Priority is determined in
* descending order. For example, a job queue with a priority value of `10` is given scheduling
* preference over a job queue with a priority value of `1` . All of the compute environments must
* be either EC2 ( `EC2` or `SPOT` ) or Fargate ( `FARGATE` or `FARGATE_SPOT` ); EC2 and Fargate
* compute environments can't be mixed.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-priority)
* @param priority The priority of the job queue.
*/
public fun priority(priority: Number)
/**
* The Amazon Resource Name (ARN) of the scheduling policy.
*
* The format is `aws: *Partition* :batch: *Region* : *Account* :scheduling-policy/ *Name*` .
* For example, `aws:aws:batch:us-west-2:123456789012:scheduling-policy/MySchedulingPolicy` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-schedulingpolicyarn)
* @param schedulingPolicyArn The Amazon Resource Name (ARN) of the scheduling policy.
*/
public fun schedulingPolicyArn(schedulingPolicyArn: String)
/**
* The state of the job queue.
*
* If the job queue state is `ENABLED` , it is able to accept jobs. If the job queue state is
* `DISABLED` , new jobs can't be added to the queue, but jobs already in the queue can finish.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-state)
* @param state The state of the job queue.
*/
public fun state(state: String)
/**
* The tags that are applied to the job queue.
*
* For more information, see [Tagging your AWS Batch
* resources](https://docs.aws.amazon.com/batch/latest/userguide/using-tags.html) in *AWS Batch
* User Guide* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-tags)
* @param tags The tags that are applied to the job queue.
*/
public fun tags(tags: Map<String, String>)
}
private class BuilderImpl(
scope: SoftwareConstructsConstruct,
id: String,
) : Builder {
private val cdkBuilder: software.amazon.awscdk.services.batch.CfnJobQueue.Builder =
software.amazon.awscdk.services.batch.CfnJobQueue.Builder.create(scope, id)
/**
* The set of compute environments mapped to a job queue and their order relative to each other.
*
* The job scheduler uses this parameter to determine which compute environment runs a specific
* job. Compute environments must be in the `VALID` state before you can associate them with a job
* queue. You can associate up to three compute environments with a job queue. All of the compute
* environments must be either EC2 ( `EC2` or `SPOT` ) or Fargate ( `FARGATE` or `FARGATE_SPOT` );
* EC2 and Fargate compute environments can't be mixed.
*
*
* All compute environments that are associated with a job queue must share the same
* architecture. AWS Batch doesn't support mixing compute environment architecture types in a
* single job queue.
*
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-computeenvironmentorder)
* @param computeEnvironmentOrder The set of compute environments mapped to a job queue and
* their order relative to each other.
*/
override fun computeEnvironmentOrder(computeEnvironmentOrder: IResolvable) {
cdkBuilder.computeEnvironmentOrder(computeEnvironmentOrder.let(IResolvable.Companion::unwrap))
}
/**
* The set of compute environments mapped to a job queue and their order relative to each other.
*
* The job scheduler uses this parameter to determine which compute environment runs a specific
* job. Compute environments must be in the `VALID` state before you can associate them with a job
* queue. You can associate up to three compute environments with a job queue. All of the compute
* environments must be either EC2 ( `EC2` or `SPOT` ) or Fargate ( `FARGATE` or `FARGATE_SPOT` );
* EC2 and Fargate compute environments can't be mixed.
*
*
* All compute environments that are associated with a job queue must share the same
* architecture. AWS Batch doesn't support mixing compute environment architecture types in a
* single job queue.
*
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-computeenvironmentorder)
* @param computeEnvironmentOrder The set of compute environments mapped to a job queue and
* their order relative to each other.
*/
override fun computeEnvironmentOrder(computeEnvironmentOrder: List<Any>) {
cdkBuilder.computeEnvironmentOrder(computeEnvironmentOrder.map{CdkObjectWrappers.unwrap(it)})
}
/**
* The set of compute environments mapped to a job queue and their order relative to each other.
*
* The job scheduler uses this parameter to determine which compute environment runs a specific
* job. Compute environments must be in the `VALID` state before you can associate them with a job
* queue. You can associate up to three compute environments with a job queue. All of the compute
* environments must be either EC2 ( `EC2` or `SPOT` ) or Fargate ( `FARGATE` or `FARGATE_SPOT` );
* EC2 and Fargate compute environments can't be mixed.
*
*
* All compute environments that are associated with a job queue must share the same
* architecture. AWS Batch doesn't support mixing compute environment architecture types in a
* single job queue.
*
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-computeenvironmentorder)
* @param computeEnvironmentOrder The set of compute environments mapped to a job queue and
* their order relative to each other.
*/
override fun computeEnvironmentOrder(vararg computeEnvironmentOrder: Any): Unit =
computeEnvironmentOrder(computeEnvironmentOrder.toList())
/**
* The name of the job queue.
*
* It can be up to 128 letters long. It can contain uppercase and lowercase letters, numbers,
* hyphens (-), and underscores (_).
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-jobqueuename)
* @param jobQueueName The name of the job queue.
*/
override fun jobQueueName(jobQueueName: String) {
cdkBuilder.jobQueueName(jobQueueName)
}
/**
* The set of actions that AWS Batch perform on jobs that remain at the head of the job queue in
* the specified state longer than specified times.
*
* AWS Batch will perform each action after `maxTimeSeconds` has passed.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-jobstatetimelimitactions)
* @param jobStateTimeLimitActions The set of actions that AWS Batch perform on jobs that remain
* at the head of the job queue in the specified state longer than specified times.
*/
override fun jobStateTimeLimitActions(jobStateTimeLimitActions: IResolvable) {
cdkBuilder.jobStateTimeLimitActions(jobStateTimeLimitActions.let(IResolvable.Companion::unwrap))
}
/**
* The set of actions that AWS Batch perform on jobs that remain at the head of the job queue in
* the specified state longer than specified times.
*
* AWS Batch will perform each action after `maxTimeSeconds` has passed.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-jobstatetimelimitactions)
* @param jobStateTimeLimitActions The set of actions that AWS Batch perform on jobs that remain
* at the head of the job queue in the specified state longer than specified times.
*/
override fun jobStateTimeLimitActions(jobStateTimeLimitActions: List<Any>) {
cdkBuilder.jobStateTimeLimitActions(jobStateTimeLimitActions.map{CdkObjectWrappers.unwrap(it)})
}
/**
* The set of actions that AWS Batch perform on jobs that remain at the head of the job queue in
* the specified state longer than specified times.
*
* AWS Batch will perform each action after `maxTimeSeconds` has passed.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-jobstatetimelimitactions)
* @param jobStateTimeLimitActions The set of actions that AWS Batch perform on jobs that remain
* at the head of the job queue in the specified state longer than specified times.
*/
override fun jobStateTimeLimitActions(vararg jobStateTimeLimitActions: Any): Unit =
jobStateTimeLimitActions(jobStateTimeLimitActions.toList())
/**
* The priority of the job queue.
*
* Job queues with a higher priority (or a higher integer value for the `priority` parameter)
* are evaluated first when associated with the same compute environment. Priority is determined in
* descending order. For example, a job queue with a priority value of `10` is given scheduling
* preference over a job queue with a priority value of `1` . All of the compute environments must
* be either EC2 ( `EC2` or `SPOT` ) or Fargate ( `FARGATE` or `FARGATE_SPOT` ); EC2 and Fargate
* compute environments can't be mixed.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-priority)
* @param priority The priority of the job queue.
*/
override fun priority(priority: Number) {
cdkBuilder.priority(priority)
}
/**
* The Amazon Resource Name (ARN) of the scheduling policy.
*
* The format is `aws: *Partition* :batch: *Region* : *Account* :scheduling-policy/ *Name*` .
* For example, `aws:aws:batch:us-west-2:123456789012:scheduling-policy/MySchedulingPolicy` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-schedulingpolicyarn)
* @param schedulingPolicyArn The Amazon Resource Name (ARN) of the scheduling policy.
*/
override fun schedulingPolicyArn(schedulingPolicyArn: String) {
cdkBuilder.schedulingPolicyArn(schedulingPolicyArn)
}
/**
* The state of the job queue.
*
* If the job queue state is `ENABLED` , it is able to accept jobs. If the job queue state is
* `DISABLED` , new jobs can't be added to the queue, but jobs already in the queue can finish.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-state)
* @param state The state of the job queue.
*/
override fun state(state: String) {
cdkBuilder.state(state)
}
/**
* The tags that are applied to the job queue.
*
* For more information, see [Tagging your AWS Batch
* resources](https://docs.aws.amazon.com/batch/latest/userguide/using-tags.html) in *AWS Batch
* User Guide* .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-batch-jobqueue.html#cfn-batch-jobqueue-tags)
* @param tags The tags that are applied to the job queue.
*/
override fun tags(tags: Map<String, String>) {
cdkBuilder.tags(tags)
}
public fun build(): software.amazon.awscdk.services.batch.CfnJobQueue = cdkBuilder.build()
}
public companion object {
public val CFN_RESOURCE_TYPE_NAME: String =
software.amazon.awscdk.services.batch.CfnJobQueue.CFN_RESOURCE_TYPE_NAME
public operator fun invoke(
scope: CloudshiftdevConstructsConstruct,
id: String,
block: Builder.() -> Unit = {},
): CfnJobQueue {
val builderImpl = BuilderImpl(CloudshiftdevConstructsConstruct.unwrap(scope), id)
return CfnJobQueue(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.batch.CfnJobQueue): CfnJobQueue =
CfnJobQueue(cdkObject)
internal fun unwrap(wrapped: CfnJobQueue): software.amazon.awscdk.services.batch.CfnJobQueue =
wrapped.cdkObject as software.amazon.awscdk.services.batch.CfnJobQueue
}
/**
* The order that compute environments are tried in for job placement within a queue.
*
* Compute environments are tried in ascending order. For example, if two compute environments are
* associated with a job queue, the compute environment with a lower order integer value is tried for
* job placement first. Compute environments must be in the `VALID` state before you can associate
* them with a job queue. All of the compute environments must be either EC2 ( `EC2` or `SPOT` ) or
* Fargate ( `FARGATE` or `FARGATE_SPOT` ); Amazon EC2 and Fargate compute environments can't be
* mixed.
*
*
* All compute environments that are associated with a job queue must share the same architecture.
* AWS Batch doesn't support mixing compute environment architecture types in a single job queue.
*
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.batch.*;
* ComputeEnvironmentOrderProperty computeEnvironmentOrderProperty =
* ComputeEnvironmentOrderProperty.builder()
* .computeEnvironment("computeEnvironment")
* .order(123)
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-computeenvironmentorder.html)
*/
public interface ComputeEnvironmentOrderProperty {
/**
* The Amazon Resource Name (ARN) of the compute environment.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-computeenvironmentorder.html#cfn-batch-jobqueue-computeenvironmentorder-computeenvironment)
*/
public fun computeEnvironment(): String
/**
* The order of the compute environment.
*
* Compute environments are tried in ascending order. For example, if two compute environments
* are associated with a job queue, the compute environment with a lower `order` integer value is
* tried for job placement first.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-computeenvironmentorder.html#cfn-batch-jobqueue-computeenvironmentorder-order)
*/
public fun order(): Number
/**
* A builder for [ComputeEnvironmentOrderProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param computeEnvironment The Amazon Resource Name (ARN) of the compute environment.
*/
public fun computeEnvironment(computeEnvironment: String)
/**
* @param order The order of the compute environment.
* Compute environments are tried in ascending order. For example, if two compute environments
* are associated with a job queue, the compute environment with a lower `order` integer value is
* tried for job placement first.
*/
public fun order(order: Number)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.batch.CfnJobQueue.ComputeEnvironmentOrderProperty.Builder
=
software.amazon.awscdk.services.batch.CfnJobQueue.ComputeEnvironmentOrderProperty.builder()
/**
* @param computeEnvironment The Amazon Resource Name (ARN) of the compute environment.
*/
override fun computeEnvironment(computeEnvironment: String) {
cdkBuilder.computeEnvironment(computeEnvironment)
}
/**
* @param order The order of the compute environment.
* Compute environments are tried in ascending order. For example, if two compute environments
* are associated with a job queue, the compute environment with a lower `order` integer value is
* tried for job placement first.
*/
override fun order(order: Number) {
cdkBuilder.order(order)
}
public fun build():
software.amazon.awscdk.services.batch.CfnJobQueue.ComputeEnvironmentOrderProperty =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.batch.CfnJobQueue.ComputeEnvironmentOrderProperty,
) : CdkObject(cdkObject), ComputeEnvironmentOrderProperty {
/**
* The Amazon Resource Name (ARN) of the compute environment.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-computeenvironmentorder.html#cfn-batch-jobqueue-computeenvironmentorder-computeenvironment)
*/
override fun computeEnvironment(): String = unwrap(this).getComputeEnvironment()
/**
* The order of the compute environment.
*
* Compute environments are tried in ascending order. For example, if two compute environments
* are associated with a job queue, the compute environment with a lower `order` integer value is
* tried for job placement first.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-computeenvironmentorder.html#cfn-batch-jobqueue-computeenvironmentorder-order)
*/
override fun order(): Number = unwrap(this).getOrder()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): ComputeEnvironmentOrderProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.batch.CfnJobQueue.ComputeEnvironmentOrderProperty):
ComputeEnvironmentOrderProperty = CdkObjectWrappers.wrap(cdkObject) as?
ComputeEnvironmentOrderProperty ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: ComputeEnvironmentOrderProperty):
software.amazon.awscdk.services.batch.CfnJobQueue.ComputeEnvironmentOrderProperty =
(wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.batch.CfnJobQueue.ComputeEnvironmentOrderProperty
}
}
/**
* Specifies an action that AWS Batch will take after the job has remained at the head of the
* queue in the specified state for longer than the specified time.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.batch.*;
* JobStateTimeLimitActionProperty jobStateTimeLimitActionProperty =
* JobStateTimeLimitActionProperty.builder()
* .action("action")
* .maxTimeSeconds(123)
* .reason("reason")
* .state("state")
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-jobstatetimelimitaction.html)
*/
public interface JobStateTimeLimitActionProperty {
/**
* The action to take when a job is at the head of the job queue in the specified state for the
* specified period of time.
*
* The only supported value is `CANCEL` , which will cancel the job.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-jobstatetimelimitaction.html#cfn-batch-jobqueue-jobstatetimelimitaction-action)
*/
public fun action(): String
/**
* The approximate amount of time, in seconds, that must pass with the job in the specified
* state before the action is taken.
*
* The minimum value is 600 (10 minutes) and the maximum value is 86,400 (24 hours).
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-jobstatetimelimitaction.html#cfn-batch-jobqueue-jobstatetimelimitaction-maxtimeseconds)
*/
public fun maxTimeSeconds(): Number
/**
* The reason to log for the action being taken.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-jobstatetimelimitaction.html#cfn-batch-jobqueue-jobstatetimelimitaction-reason)
*/
public fun reason(): String
/**
* The state of the job needed to trigger the action.
*
* The only supported value is `RUNNABLE` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-jobstatetimelimitaction.html#cfn-batch-jobqueue-jobstatetimelimitaction-state)
*/
public fun state(): String
/**
* A builder for [JobStateTimeLimitActionProperty]
*/
@CdkDslMarker
public interface Builder {
/**
* @param action The action to take when a job is at the head of the job queue in the
* specified state for the specified period of time.
* The only supported value is `CANCEL` , which will cancel the job.
*/
public fun action(action: String)
/**
* @param maxTimeSeconds The approximate amount of time, in seconds, that must pass with the
* job in the specified state before the action is taken.
* The minimum value is 600 (10 minutes) and the maximum value is 86,400 (24 hours).
*/
public fun maxTimeSeconds(maxTimeSeconds: Number)
/**
* @param reason The reason to log for the action being taken.
*/
public fun reason(reason: String)
/**
* @param state The state of the job needed to trigger the action.
* The only supported value is `RUNNABLE` .
*/
public fun state(state: String)
}
private class BuilderImpl : Builder {
private val cdkBuilder:
software.amazon.awscdk.services.batch.CfnJobQueue.JobStateTimeLimitActionProperty.Builder
=
software.amazon.awscdk.services.batch.CfnJobQueue.JobStateTimeLimitActionProperty.builder()
/**
* @param action The action to take when a job is at the head of the job queue in the
* specified state for the specified period of time.
* The only supported value is `CANCEL` , which will cancel the job.
*/
override fun action(action: String) {
cdkBuilder.action(action)
}
/**
* @param maxTimeSeconds The approximate amount of time, in seconds, that must pass with the
* job in the specified state before the action is taken.
* The minimum value is 600 (10 minutes) and the maximum value is 86,400 (24 hours).
*/
override fun maxTimeSeconds(maxTimeSeconds: Number) {
cdkBuilder.maxTimeSeconds(maxTimeSeconds)
}
/**
* @param reason The reason to log for the action being taken.
*/
override fun reason(reason: String) {
cdkBuilder.reason(reason)
}
/**
* @param state The state of the job needed to trigger the action.
* The only supported value is `RUNNABLE` .
*/
override fun state(state: String) {
cdkBuilder.state(state)
}
public fun build():
software.amazon.awscdk.services.batch.CfnJobQueue.JobStateTimeLimitActionProperty =
cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.batch.CfnJobQueue.JobStateTimeLimitActionProperty,
) : CdkObject(cdkObject), JobStateTimeLimitActionProperty {
/**
* The action to take when a job is at the head of the job queue in the specified state for
* the specified period of time.
*
* The only supported value is `CANCEL` , which will cancel the job.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-jobstatetimelimitaction.html#cfn-batch-jobqueue-jobstatetimelimitaction-action)
*/
override fun action(): String = unwrap(this).getAction()
/**
* The approximate amount of time, in seconds, that must pass with the job in the specified
* state before the action is taken.
*
* The minimum value is 600 (10 minutes) and the maximum value is 86,400 (24 hours).
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-jobstatetimelimitaction.html#cfn-batch-jobqueue-jobstatetimelimitaction-maxtimeseconds)
*/
override fun maxTimeSeconds(): Number = unwrap(this).getMaxTimeSeconds()
/**
* The reason to log for the action being taken.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-jobstatetimelimitaction.html#cfn-batch-jobqueue-jobstatetimelimitaction-reason)
*/
override fun reason(): String = unwrap(this).getReason()
/**
* The state of the job needed to trigger the action.
*
* The only supported value is `RUNNABLE` .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-batch-jobqueue-jobstatetimelimitaction.html#cfn-batch-jobqueue-jobstatetimelimitaction-state)
*/
override fun state(): String = unwrap(this).getState()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): JobStateTimeLimitActionProperty {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal
fun wrap(cdkObject: software.amazon.awscdk.services.batch.CfnJobQueue.JobStateTimeLimitActionProperty):
JobStateTimeLimitActionProperty = CdkObjectWrappers.wrap(cdkObject) as?
JobStateTimeLimitActionProperty ?: Wrapper(cdkObject)
internal fun unwrap(wrapped: JobStateTimeLimitActionProperty):
software.amazon.awscdk.services.batch.CfnJobQueue.JobStateTimeLimitActionProperty =
(wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.batch.CfnJobQueue.JobStateTimeLimitActionProperty
}
}
}
| 1 | Kotlin | 0 | 4 | b1af417dc38eb29bba6244f8da914964c5e7fa3d | 40,498 | kotlin-cdk-wrapper | Apache License 2.0 |
eth/src/main/kotlin/com/d3/eth/deploy/main.kt | d3ledger | 184,047,300 | false | null | /*
* Copyright D3 Ledger, Inc. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
@file:JvmName("EthPreDeployMain")
package com.d3.eth.deploy
import com.d3.commons.config.loadLocalConfigs
import com.d3.commons.model.IrohaCredential
import com.d3.commons.sidechain.iroha.consumer.IrohaConsumer
import com.d3.commons.sidechain.iroha.consumer.IrohaConsumerImpl
import com.d3.commons.sidechain.iroha.util.ModelUtil
import integration.eth.config.loadEthPasswords
import com.d3.eth.constants.ETH_MASTER_ADDRESS_KEY
import com.d3.eth.constants.ETH_RELAY_IMPLEMENTATION_ADDRESS_KEY
import com.d3.eth.constants.ETH_RELAY_REGISTRY_KEY
import com.d3.eth.sidechain.util.DeployHelperBuilder
import com.github.kittinunf.result.failure
import com.github.kittinunf.result.fanout
import com.github.kittinunf.result.map
import jp.co.soramitsu.iroha.java.IrohaAPI
import mu.KLogging
private val logger = KLogging().logger
/**
* Entry point to deploy smart contracts.
* Contracts are deployed via UpgradableProxy.
* [args] should contain the list of notary ethereum addresses
*/
fun main(args: Array<String>) {
logger.info { "Run predeploy with notary addresses: ${args.toList()}" }
if (args.isEmpty()) {
logger.error { "No notary ethereum addresses are provided." }
System.exit(1)
}
loadLocalConfigs("predeploy", PredeployConfig::class.java, "predeploy.properties")
.fanout { loadEthPasswords("predeploy", "/eth/ethereum_password.properties") }
.map { (predeployConfig, passwordConfig) ->
val irohaApi = IrohaAPI(predeployConfig.iroha.hostname, predeployConfig.iroha.port)
val irohaConsumer =
IrohaConsumerImpl(IrohaCredential(predeployConfig.irohaCredential), irohaApi)
val deployHelper = DeployHelperBuilder(
predeployConfig.ethereum,
passwordConfig
)
.setFastTransactionManager()
.build()
val master = deployHelper.deployUpgradableMasterSmartContract(
args.toList()
)
saveContract(
master.contractAddress,
irohaConsumer,
predeployConfig.ethContractAddressStorageAccountId,
ETH_MASTER_ADDRESS_KEY
)
}
.failure { ex ->
logger.error("Cannot deploy smart contract", ex)
System.exit(1)
}
}
/**
* Save contract address both to file and Iroha account details
*/
private fun saveContract(
contractAddress: String,
irohaConsumer: IrohaConsumer,
storageAccountId: String,
key: String
) {
ModelUtil.setAccountDetail(
irohaConsumer,
storageAccountId,
key,
contractAddress
).failure { throw it }
}
| 2 | Kotlin | 3 | 2 | 5c246c32991e4a30194cc320b77641190f1497e5 | 2,805 | d3-eth | Apache License 2.0 |
plugin-build/plugin/src/main/java/io/github/anvell/keepass/gradle/plugin/GradleKeePassExtension.kt | Anvell | 566,407,138 | false | {"Kotlin": 14457} | @file:Suppress("UnnecessaryAbstractClass", "MemberVisibilityCanBePrivate")
package io.github.anvell.keepass.gradle.plugin
import app.keemobile.kotpass.constants.BasicField
import app.keemobile.kotpass.cryptography.EncryptedValue
import app.keemobile.kotpass.database.Credentials
import app.keemobile.kotpass.database.KeePassDatabase
import app.keemobile.kotpass.database.decode
import app.keemobile.kotpass.database.findEntryBy
import app.keemobile.kotpass.database.modifiers.binaries
import app.keemobile.kotpass.models.Entry
import io.github.anvell.keepass.gradle.plugin.extensions.toShortHexHash
import okio.ByteString.Companion.toByteString
import org.gradle.api.Project
import org.gradle.api.file.RegularFileProperty
import org.gradle.api.provider.Property
import java.io.File
import java.io.FileInputStream
import javax.inject.Inject
abstract class GradleKeePassExtension @Inject constructor(
project: Project
) {
private val objects = project.objects
private val database by lazy { loadVault() }
private val entriesByTitle: MutableMap<String, Entry> = mutableMapOf()
val sourceFile: RegularFileProperty = objects.fileProperty()
val keyfile: RegularFileProperty = objects.fileProperty()
val password: Property<String> = objects.property(String::class.java)
/**
* Searches for [Entry] with [title] and extracts binary data
* with [binaryName] to [parentDir].
* File name is based on SHA256 hash of the file.
*
* @param title [Entry] field with [BasicField.Title] key.
* @param parentDir new directory will be created if it does not exist.
* @param binaryName file name of binary data attached to the [Entry].
* @return [File] object referencing extracted file.
*/
fun entryBinary(
title: String,
parentDir: File,
binaryName: String
): File = entriesByTitle
.getOrElse(title) {
database
.findEntryBy { fields.title?.content == title }
?.also { entriesByTitle[title] = it }
?: error("Cannot find entry with title: $title.")
}.let { entryBinary(it, parentDir, binaryName) }
/**
* Searches for [Entry] which matches a given [predicate] and extracts
* binary data with [binaryName] to [parentDir].
* File name is based on SHA256 hash of the file.
*
* @param predicate allows to match [Entry] using custom checks.
* @param parentDir new directory will be created if it does not exist.
* @param binaryName file name of binary data attached to the [Entry].
* @return [File] object referencing extracted file.
*/
fun entryBinary(
predicate: Entry.() -> Boolean,
parentDir: File,
binaryName: String
): File = database
.findEntryBy(predicate)
?.let { entryBinary(it, parentDir, binaryName) }
?: error("Cannot find entry by predicate.")
private fun entryBinary(
entry: Entry,
parentDir: File,
binaryName: String
): File {
val binary = entry
.binaries
.find { it.name == binaryName }
?: error("Cannot find binary: $binaryName.")
if (!parentDir.exists()) parentDir.mkdirs()
val outputFile = File(parentDir, binary.hash.toShortHexHash())
if (outputFile.exists()) {
val hash = outputFile
.inputStream()
.use(FileInputStream::readBytes)
.toByteString()
.sha256()
if (hash == binary.hash) {
return outputFile
}
}
val rawData = database
.binaries[binary.hash]
?.getContent()
?: error("Database does not contain binary: $binaryName.")
outputFile
.outputStream()
.use { it.write(rawData) }
return outputFile
}
/**
* Searches for [Entry] with [title] and attempts
* to retrieve [field] content.
*
* @return [field] content.
*/
fun entryField(
title: String,
field: String
): String = entriesByTitle
.getOrElse(title) {
database
.findEntryBy { fields.title?.content == title }
?.also { entriesByTitle[title] = it }
?: error("Cannot find entry with title: $title.")
}.let { entryField(it, field) }
/**
* Searches for [Entry] which matches a given [predicate]
* and attempts to retrieve [field] content.
*
* @return [field] content.
*/
fun entryField(
predicate: Entry.() -> Boolean,
field: String
): String = database
.findEntryBy(predicate)
?.let { entryField(it, field) }
?: error("Cannot find entry by predicate.")
private fun entryField(
entry: Entry,
field: String
): String = with(entry) {
requireNotNull(fields[field]?.content) {
"Entry '${fields.title?.content}' does not have field with key: $field."
}
}
private fun loadVault(): KeePassDatabase {
check(sourceFile.isPresent) {
"KeePass source file is not defined."
}
val file = sourceFile.asFile.get()
val credentials = getCredentials()
return file.inputStream().use {
KeePassDatabase.decode(it, credentials)
}
}
private fun getCredentials(): Credentials = when {
keyfile.isPresent && password.isPresent -> {
Credentials.from(
passphrase = EncryptedValue.fromString(password.get()),
keyData = readKeyfile()
)
}
password.isPresent -> {
Credentials.from(
passphrase = EncryptedValue.fromString(password.get())
)
}
keyfile.isPresent -> {
Credentials.from(keyData = readKeyfile())
}
else -> error("No credentials specified.")
}
private fun readKeyfile() = keyfile
.asFile
.get()
.inputStream()
.use(FileInputStream::readBytes)
}
| 0 | Kotlin | 0 | 1 | 5a574075aab3782592dbf0a22f465e4afc51263c | 6,137 | keepass-gradle-plugin | MIT License |
app/src/main/java/com/git/gitapp/VideoListActivity.kt | aneri135 | 178,009,030 | false | {"Java": 193062, "Kotlin": 6942} | package com.git.gitapp
import android.app.Activity
import android.content.Intent
import android.databinding.DataBindingUtil
import android.databinding.ObservableArrayList
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.view.MenuItem
import android.view.WindowManager
import com.github.nitrico.lastadapter.LastAdapter
class VideoListActivity : Activity() {
/* override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_video_list)
}*/
lateinit var mBinding: com.git.gitapp.databinding.ActivityVideoListBinding
private var materialList: ObservableArrayList<MaterialData> = ObservableArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = DataBindingUtil.setContentView(this@VideoListActivity, R.layout.activity_video_list)
mBinding.recyclerViewMater.layoutManager = LinearLayoutManager(this@VideoListActivity)
actionBar?.setDisplayHomeAsUpEnabled(true)
actionBar?.setDisplayShowHomeEnabled(true)
setAdapter()
}
/* private fun getMaterialBySubjectId(subjectId: String?) {
// todo get subject id
val reqMap = HashMap<String, RequestBody>()
reqMap["subject_id"] = Utility.getRequestBody(subjectId.toString())
reqMap["id"] = Utility.getRequestBody(AppPreference.loginUserData.id.toString())
reqMap["device_id"] = Utility.getRequestBody(AppBasePref.DEVICE_ID)
ApiClient.service.getMaterailBySubjectId(ApiMethods.getmaterialbysubjectId, reqMap).enqueue(RetrofitCallback {
onCompleted { call, response, throwable ->
ProgressDialogUtility.dismiss()
}
on2xxSuccess { call, response ->
materialList.clear()
response?.body()?.data?.let { materialList.addAll(it) }
materialList.map { it.id }.sorted()
setAdapter()
}
onFailureCallback { call, throwable ->
Log.d("tag", "error............" + throwable.toString())
toast("Something went wrong")
}
on5xxServerError { call, response ->
Log.d("tag", "error1.." + response?.code())
}
})
}*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
finish()
}
return super.onOptionsItemSelected(item)
}
private fun setAdapter() {
materialList.add(MaterialData(1, "DBMS","https://firebasestorage.googleapis.com/v0/b/gitapp-151d2.appspot.com/o/dbms_tutorial.pdf?alt=media&token=<PASSWORD>"))
if (materialList.isNotEmpty()) {
LastAdapter(materialList, com.git.gitapp.BR.item).map<MaterialData, com.git.gitapp.databinding.ItemMaterialBinding>(R.layout.item_material) {
onBind {
val pos = it.adapterPosition
it.binding.layoutMaterial.setOnClickListener {
val inetnt = Intent(this@VideoListActivity, PDFViewerActivity::class.java)
inetnt.putExtra(PDFViewerActivity.EXTRA_PDF_URL, materialList[pos].material_url)
startActivity(inetnt)
}
}
}.into(mBinding.recyclerViewMater)
} else {
}
}
override fun onPause() {
window?.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
super.onPause()
}
companion object {
const val SUBJECT_ID = "suject_id"
const val SUBJECT_NAME = "subject_name"
}
}
data class MaterialResponse(
val data: List<MaterialData>,
val error: Boolean,
val message: String
)
data class MaterialData(
val id: Int,
val material_name: String,
val material_url: String
) | 1 | null | 1 | 1 | 0d2b6536ca8decd9d6420e068c9832a08e0fe4f9 | 4,087 | GIT_App2017-master | Apache License 2.0 |
tools/test_suite/src/main/java/com/grab/test/ClasspathSuite.kt | grab | 379,151,712 | false | {"Kotlin": 372586, "Starlark": 172838, "Java": 2517, "Smarty": 2052} | // Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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.grab.test
import org.junit.runners.Suite
import org.junit.runners.model.RunnerBuilder
class ClasspathSuite constructor(
klass: Class<*>,
builder: RunnerBuilder?
) : Suite(builder, klass, getClasses(klass)) {
companion object {
private fun getClasses(klass: Class<*>): Array<Class<*>> {
val result: Set<Class<*>> = TestSuiteBuilder()
.addPackageRecursive(klass.getPackage().name)
.create()
return result.toTypedArray()
}
}
} | 13 | Kotlin | 14 | 38 | 0540712597f4346f7573bbd01dfe1bd93a7060bb | 1,140 | grab-bazel-common | Apache License 2.0 |
app/src/main/java/com/rosen/timecraft/ui/components/BottomNavigationBar.kt | DerekWasswa | 734,374,493 | false | {"Kotlin": 40733} | package com.rosen.timecraft.ui.components
import androidx.compose.foundation.layout.RowScope
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.navigation.NavDestination
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavHostController
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.rosen.timecraft.R
import com.rosen.timecraft.navigation.Route
import com.rosen.timecraft.ui.theme.Black
import com.rosen.timecraft.ui.theme.TimeCraftTheme
@Composable
fun BottomNavigationBar(navController: NavHostController) {
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
val navBarScreens = listOf(
Route.HomeScreen,
Route.Favorites,
Route.ShoppingCart,
Route.Account
)
if (currentDestination?.route in navBarScreens.map { it.route })
NavigationBar(
containerColor = Black,
) {
AddNavigationBarItem(
iconResId = R.drawable.search_fill,
destinationRoute = Route.HomeScreen,
currentDestination = currentDestination,
navController = navController
)
AddNavigationBarItem(
iconResId = R.drawable.favorite_fill,
destinationRoute = Route.Favorites,
currentDestination = currentDestination,
navController = navController
)
AddNavigationBarItem(
iconResId = R.drawable.shopping_bag,
destinationRoute = Route.ShoppingCart,
currentDestination = currentDestination,
navController = navController
)
AddNavigationBarItem(
iconResId = R.drawable.person_fill,
destinationRoute = Route.Account,
currentDestination = currentDestination,
navController = navController
)
}
}
@Composable
private fun RowScope.AddNavigationBarItem(
iconResId: Int,
destinationRoute: Route,
currentDestination: NavDestination?,
navController: NavHostController
) {
NavigationBarItem(
icon = {
Icon(imageVector = ImageVector.vectorResource(id = iconResId), contentDescription = null)
},
selected = currentDestination?.route == destinationRoute.route,
onClick = {
navController.navigate(destinationRoute.route) {
popUpTo(navController.graph.findStartDestination().id)
launchSingleTop = true
}
}
)
}
@Preview(showBackground = true)
@Composable
fun BottomNavigationBarPreview() {
TimeCraftTheme {
val navController = rememberNavController()
BottomNavigationBar(navController = navController)
}
} | 0 | Kotlin | 0 | 0 | c28962cbdc902d1172a5d9f8821a9c84b21ddb69 | 3,297 | TimeCraft | Apache License 2.0 |
idea/tests/org/jetbrains/jet/completion/handlers/AbstractSmartCompletionHandlerTest.kt | craastad | 18,462,025 | false | {"Markdown": 18, "XML": 405, "Ant Build System": 23, "Ignore List": 7, "Maven POM": 34, "Kotlin": 10194, "Java": 3675, "CSS": 10, "Shell": 6, "Batchfile": 6, "Java Properties": 9, "Gradle": 61, "INI": 6, "JavaScript": 42, "HTML": 77, "Text": 875, "Roff": 53, "Roff Manpage": 8, "JFlex": 3, "JAR Manifest": 1, "Protocol Buffer": 2} | /*
* Copyright 2010-2013 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.jet.completion.handlers
import org.jetbrains.jet.plugin.JetLightCodeInsightFixtureTestCase
import com.intellij.codeInsight.completion.CompletionType
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import org.jetbrains.jet.plugin.formatter.JetCodeStyleSettings
import com.intellij.codeInsight.lookup.LookupElement
import java.io.File
import org.jetbrains.jet.plugin.PluginTestCaseBase
import com.intellij.codeInsight.lookup.impl.LookupImpl
import com.intellij.codeInsight.lookup.LookupEvent
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.codeInsight.lookup.LookupManager
import com.intellij.codeInsight.lookup.LookupElementPresentation
import org.junit.Assert
import com.intellij.openapi.application.Result
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import kotlin.properties.Delegates
import org.jetbrains.jet.InTextDirectivesUtils
abstract class AbstractSmartCompletionHandlerTest() : CompletionHandlerTestBase() {
private val INVOCATION_COUNT_PREFIX = "INVOCATION_COUNT:"
private val LOOKUP_STRING_PREFIX = "ELEMENT:"
private val TAIL_TEXT_PREFIX = "TAIL_TEXT:"
private val COMPLETION_CHAR_PREFIX = "CHAR:"
override val completionType: CompletionType = CompletionType.SMART
override val testDataRelativePath: String = "/completion/handlers/smart"
protected fun doTest(testPath: String) {
fixture.configureByFile(testPath)
val fileText = fixture.getFile()!!.getText()
val invocationCount = InTextDirectivesUtils.getPrefixedInt(fileText, INVOCATION_COUNT_PREFIX) ?: 1
val lookupString = InTextDirectivesUtils.findStringWithPrefixes(fileText, LOOKUP_STRING_PREFIX)
val tailText = InTextDirectivesUtils.findStringWithPrefixes(fileText, TAIL_TEXT_PREFIX)
val completionCharString = InTextDirectivesUtils.findStringWithPrefixes(fileText, COMPLETION_CHAR_PREFIX)
val completionChar = when(completionCharString) {
"\\n", null -> '\n'
"\\t" -> '\t'
else -> error("Uknown completion char")
}
doTestWithTextLoaded(invocationCount, lookupString, tailText, completionChar)
}
}
| 1 | null | 1 | 1 | f41f48b1124e2f162295718850426193ab55f43f | 2,800 | kotlin | Apache License 2.0 |
app/src/main/java/com/amalitec/moviesapp/domain/util/MovieType.kt | kclaudeeager | 639,718,284 | false | null | package com.amalitec.moviesapp.domain.util
sealed class MovieType {
object Latest : MovieType()
object TopRated :MovieType()
object Featured : MovieType()
object TvShow : MovieType()
} | 0 | Kotlin | 0 | 0 | f64dc5d88222542770b549b22e72e1f6eb40bd56 | 201 | MovieApp | Apache License 2.0 |
android-core/src/main/kotlin/dev/jonpoulton/alakazam/core/INotifier.kt | jonapoul | 375,762,483 | false | null | package dev.jonpoulton.alakazam.core
import android.view.View
import androidx.annotation.StringRes
interface INotifier {
data class Action(
@StringRes val actionText: Int,
val onClick: View.OnClickListener,
)
fun success(root: View, @StringRes message: Int, action: Action = EMPTY_ACTION)
fun caution(root: View, @StringRes message: Int, action: Action = EMPTY_ACTION)
fun warning(root: View, @StringRes message: Int, action: Action = EMPTY_ACTION)
fun info(root: View, @StringRes message: Int, action: Action = EMPTY_ACTION)
fun success(root: View, message: String, action: Action = EMPTY_ACTION)
fun caution(root: View, message: String, action: Action = EMPTY_ACTION)
fun warning(root: View, message: String, action: Action = EMPTY_ACTION)
fun info(root: View, message: String, action: Action = EMPTY_ACTION)
companion object {
val EMPTY_ACTION = Action(android.R.string.ok) { /* No-op */ }
}
}
| 0 | Kotlin | 0 | 0 | 14f111c8f1ea50be893a0af6f6eb21034cb574ee | 938 | alakazam | Apache License 2.0 |
core/src/main/kotlin/io/paddle/plugin/standard/tasks/CleanTask.kt | JetBrains-Research | 377,213,824 | false | null | package io.paddle.plugin.standard.tasks
import io.paddle.project.PaddleProject
import io.paddle.tasks.Task
import io.paddle.tasks.Tasks
import io.paddle.utils.deleteRecursivelyWithoutSymlinks
import io.paddle.utils.tasks.TaskDefaultGroups
import java.io.File
open class CleanTask(project: PaddleProject) : Task(project) {
var locations = ArrayList<File>()
override val id: String = "clean"
override val group: String = TaskDefaultGroups.BUILD
override fun initialize() {
locations.add(File(project.workDir, ".paddle"))
}
override fun act() {
for (location in locations) {
location.deleteRecursivelyWithoutSymlinks()
}
}
}
val Tasks.clean: CleanTask
get() = this.getOrFail("clean") as CleanTask
| 13 | Kotlin | 6 | 20 | 42a26a7f5815961d564f71e3606252fab7a87f82 | 769 | paddle | MIT License |
uitest-framework/testSrc/com/android/tools/idea/tests/gui/framework/fixture/ResourceDetailViewFixture.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 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 com.android.tools.idea.tests.gui.framework.fixture
import com.android.tools.idea.tests.gui.framework.GuiTests
import com.android.tools.idea.tests.gui.framework.matcher.Matchers
import com.android.tools.idea.ui.resourcemanager.explorer.ResourceDetailView
import com.android.tools.idea.ui.resourcemanager.widget.SingleAssetCard
import com.intellij.openapi.actionSystem.impl.ActionButton
import org.fest.swing.core.Robot
import org.fest.swing.core.TypeMatcher
import org.fest.swing.fixture.JPanelFixture
import javax.swing.JPanel
/**
* Test Fixture for the ResourceExplorerDetail view.
*/
class ResourceDetailViewFixture private constructor(robot: Robot, target: JPanel) : JPanelFixture(robot, target) {
companion object {
@JvmStatic
fun find(robot: Robot): ResourceDetailViewFixture {
val explorer = GuiTests.waitUntilShowing(robot, Matchers.byType(ResourceDetailView::class.java))
return ResourceDetailViewFixture(robot, explorer)
}
}
/**
* The number of resources visible in the explorer.
*/
@Suppress("UNCHECKED_CAST")
val resourcesCount: Int
get() {
val listViews = robot().finder().findAll(target(), TypeMatcher(SingleAssetCard::class.java)) as Collection<SingleAssetCard>
return listViews.size
}
/**
* Return back (<-) button in resource detail panel
*/
fun goBackToResourceList(): ActionButtonFixture{
// Verify 4 : A drawable named icon_category_entertainment should be showing
val button = robot().finder().find<ActionButton>(
target(), Matchers.byType(
ActionButton::class.java
)
)
return ActionButtonFixture(robot(), button)
}
}
| 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 2,281 | android | Apache License 2.0 |
src/main/kotlin/io/usoamic/validateutilkt/error/EmptyAppIdError.kt | usoamic | 260,280,238 | false | {"Kotlin": 10654} | package io.usoamic.validateutilkt.error
class EmptyAppIdError : ValidateUtilError() | 0 | Kotlin | 0 | 0 | 74e212822de4a8a45131add9798497f1031f4907 | 84 | validateutilkt | MIT License |
nftkit/src/main/java/io/horizontalsystems/nftkit/models/Eip721Event.kt | horizontalsystems | 152,531,605 | false | null | package io.horizontalsystems.nftkit.models
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import io.horizontalsystems.ethereumkit.core.toHexString
import io.horizontalsystems.ethereumkit.models.Address
import java.math.BigInteger
@Entity
data class Eip1155Event(
val hash: ByteArray,
val blockNumber: Long,
val contractAddress: Address,
val from: Address,
val to: Address,
val tokenId: BigInteger,
val tokenValue: Int,
val tokenName: String,
val tokenSymbol: String,
@PrimaryKey(autoGenerate = true) val id: Long = 0
) {
@delegate:Ignore
val hashString: String by lazy {
hash.toHexString()
}
}
| 10 | null | 53 | 98 | f4957a971be56ed15719cf640d27e514909be123 | 700 | ethereum-kit-android | MIT License |
app/src/main/java/com/mindorks/framework/mvp/data/network/ApiHeader.kt | janishar | 115,260,052 | false | null | package com.mindorks.framework.mvp.data.network
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import com.mindorks.framework.mvp.di.ApiKeyInfo
import javax.inject.Inject
/**
* Created by jyotidubey on 11/01/18.
*/
class ApiHeader @Inject constructor(internal val publicApiHeader: PublicApiHeader, internal val protectedApiHeader: ProtectedApiHeader) {
class PublicApiHeader @Inject constructor(@ApiKeyInfo
@Expose
@SerializedName
("api_key") val apiKey: String)
class ProtectedApiHeader @Inject constructor(@Expose
@SerializedName("api_key") val apiKey: String,
@Expose
@SerializedName("user_id") val userId: Long?,
@Expose
@SerializedName("access_token") val accessToken: String?)
} | 17 | null | 199 | 702 | 5ac97334d417aff636dd587c82ad97c661c38666 | 1,126 | android-kotlin-mvp-architecture | Apache License 2.0 |
app/src/main/java/com/harshalv/jetpackcompose/ui/screen/DetailScreen.kt | harshalkvibhandik | 737,453,397 | false | {"Kotlin": 55814} | package com.harshalv.jetpackcompose.ui.screen
import android.annotation.SuppressLint
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Edit
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.harshalv.jetpackcompose.R
import com.harshalv.jetpackcompose.data.models.TopNewsArticle
import com.harshalv.jetpackcompose.model.MockData
import com.harshalv.jetpackcompose.model.MockData.getTimeAgo
import com.skydoves.landscapist.coil.CoilImage
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun DetailScreen(article: TopNewsArticle, scrollState: ScrollState, navController: NavController) {
Scaffold(topBar = {
DetailTopAppBar(onBackPressed = { navController.popBackStack() })
}) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.verticalScroll(scrollState),
horizontalAlignment = Alignment.CenterHorizontally
) {
CoilImage(
imageModel = article.urlToImage,
// Crop, Fit, Inside, FillHeight, FillWidth, None
contentScale = ContentScale.Crop,
error = ImageBitmap.imageResource(R.drawable.breaking_news),
// shows a placeholder ImageBitmap when loading.
placeHolder = ImageBitmap.imageResource(R.drawable.breaking_news)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp), horizontalArrangement = Arrangement.SpaceBetween
) {
InfoWithIcon(Icons.Default.Edit, info = article.author ?: "Not Available")
InfoWithIcon(
icon = Icons.Default.DateRange,
info = MockData.stringToDate(article.publishedAt!!).getTimeAgo()
)
}
Text(text = article.title ?: "Not Available", fontWeight = FontWeight.Bold)
Text(
text = article.description ?: "Not Available",
modifier = Modifier.padding(top = 16.dp)
)
}
}
}
@Composable
fun DetailTopAppBar(onBackPressed: () -> Unit = {}) {
TopAppBar(title = { Text(text = "Detail Screen", fontWeight = FontWeight.SemiBold) },
navigationIcon = {
IconButton(onClick = { onBackPressed() }) {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Arrow Back")
}
}
)
}
@Composable
fun InfoWithIcon(icon: ImageVector, info: String) {
Row {
Icon(
icon,
contentDescription = "Author",
modifier = Modifier.padding(end = 8.dp),
colorResource(
id = R.color.purple_500
)
)
Text(text = info)
}
}
@Preview(showBackground = true)
@Composable
fun DetailScreenPreview() {
DetailScreen(
TopNewsArticle(
author = "<NAME>",
title = "Cleo Smith news — live: Kidnap suspect 'in hospital again' as 'hard police grind' credited for breakthrough - The Independent",
description = "The suspected kidnapper of four-year-old <NAME> has been treated in hospital for a second time amid reports he was “attacked” while in custody.",
publishedAt = "2021-11-04T04:42:40Z"
), rememberScrollState(),
rememberNavController()
)
} | 0 | Kotlin | 0 | 0 | 27118a34fc5fccf6672a7ade14b389c58ab683bf | 4,762 | Android_Jetpack_Compose_Learning | MIT License |
app/src/main/java/com/harshalv/jetpackcompose/ui/screen/DetailScreen.kt | harshalkvibhandik | 737,453,397 | false | {"Kotlin": 55814} | package com.harshalv.jetpackcompose.ui.screen
import android.annotation.SuppressLint
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TopAppBar
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.Edit
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.imageResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.harshalv.jetpackcompose.R
import com.harshalv.jetpackcompose.data.models.TopNewsArticle
import com.harshalv.jetpackcompose.model.MockData
import com.harshalv.jetpackcompose.model.MockData.getTimeAgo
import com.skydoves.landscapist.coil.CoilImage
@SuppressLint("UnusedMaterialScaffoldPaddingParameter")
@Composable
fun DetailScreen(article: TopNewsArticle, scrollState: ScrollState, navController: NavController) {
Scaffold(topBar = {
DetailTopAppBar(onBackPressed = { navController.popBackStack() })
}) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
.verticalScroll(scrollState),
horizontalAlignment = Alignment.CenterHorizontally
) {
CoilImage(
imageModel = article.urlToImage,
// Crop, Fit, Inside, FillHeight, FillWidth, None
contentScale = ContentScale.Crop,
error = ImageBitmap.imageResource(R.drawable.breaking_news),
// shows a placeholder ImageBitmap when loading.
placeHolder = ImageBitmap.imageResource(R.drawable.breaking_news)
)
Row(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp), horizontalArrangement = Arrangement.SpaceBetween
) {
InfoWithIcon(Icons.Default.Edit, info = article.author ?: "Not Available")
InfoWithIcon(
icon = Icons.Default.DateRange,
info = MockData.stringToDate(article.publishedAt!!).getTimeAgo()
)
}
Text(text = article.title ?: "Not Available", fontWeight = FontWeight.Bold)
Text(
text = article.description ?: "Not Available",
modifier = Modifier.padding(top = 16.dp)
)
}
}
}
@Composable
fun DetailTopAppBar(onBackPressed: () -> Unit = {}) {
TopAppBar(title = { Text(text = "Detail Screen", fontWeight = FontWeight.SemiBold) },
navigationIcon = {
IconButton(onClick = { onBackPressed() }) {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Arrow Back")
}
}
)
}
@Composable
fun InfoWithIcon(icon: ImageVector, info: String) {
Row {
Icon(
icon,
contentDescription = "Author",
modifier = Modifier.padding(end = 8.dp),
colorResource(
id = R.color.purple_500
)
)
Text(text = info)
}
}
@Preview(showBackground = true)
@Composable
fun DetailScreenPreview() {
DetailScreen(
TopNewsArticle(
author = "<NAME>",
title = "Cleo Smith news — live: Kidnap suspect 'in hospital again' as 'hard police grind' credited for breakthrough - The Independent",
description = "The suspected kidnapper of four-year-old <NAME> has been treated in hospital for a second time amid reports he was “attacked” while in custody.",
publishedAt = "2021-11-04T04:42:40Z"
), rememberScrollState(),
rememberNavController()
)
} | 0 | Kotlin | 0 | 0 | 27118a34fc5fccf6672a7ade14b389c58ab683bf | 4,762 | Android_Jetpack_Compose_Learning | MIT License |
src/net/sheltem/aoc/y2015/Day13.kt | jtheegarten | 572,901,679 | false | {"Kotlin": 169383} | package net.sheltem.aoc.y2015
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import net.sheltem.common.SearchGraph
import net.sheltem.common.SearchGraph.Edge
import net.sheltem.common.SearchGraph.Node
import net.sheltem.common.regexNumbers
import net.sheltem.common.weight
suspend fun main() {
Day13().run(true)
}
class Day13 : Day<Long>(330, 0) {
override suspend fun part1(input: List<String>): Long {
val graph = input.toSearchGraph()
graph.floydWarshall()
return coroutineScope {
graph
.nodes
.map { node ->
async {
graph.maxBfs(node)
}
}.awaitAll()
.maxOf { it.weight() }
}
}
override suspend fun part2(input: List<String>): Long {
val graph = input.plus(part2String.lines()).toSearchGraph()
println(graph)
return coroutineScope {
graph
.nodes
.map { node ->
async {
graph.maxBfs(node)
}
}.awaitAll()
.maxOf { it.weight() }
}
}
}
private fun List<String>.toSearchGraph(): SearchGraph<String> {
val nodes = this.map {
it.split(" ").first()
}.map { Node(it) }.toSet()
val edges = this.map { line ->
val positive = line.contains("gain")
val fromTo = line.dropLast(1).split(" ").let { it.first() to it.last() }
Edge(Node(fromTo.first), Node(fromTo.second), line.regexNumbers().single().let { if (positive) it else it * -1L })
}.toSet()
val combinedEdges = edges.map { edge ->
val oppositeDirectionEdge = edges.single { it.from == edge.to && it.to == edge.from }
Edge(edge.from, edge.to, edge.weight + oppositeDirectionEdge.weight)
}.toSet()
return SearchGraph<String>(nodes, combinedEdges, bidirectional = false, circular = true)
}
const val part2String = """Jon would lose 0 happiness units by sitting next to Alice.
Jon would lose 0 happiness units by sitting next to Bob.
Jon would lose 0 happiness units by sitting next to Carol.
Jon would lose 0 happiness units by sitting next to David.
Jon would lose 0 happiness units by sitting next to Eric.
Jon would lose 0 happiness units by sitting next to Frank.
Jon would lose 0 happiness units by sitting next to George.
Jon would lose 0 happiness units by sitting next to Mallory.
Alice gain 0 Jon.
Bob gain 0 Jon.
Carol gain 0 Jon.
David gain 0 Jon.
Eric gain 0 Jon.
Frank gain 0 Jon.
George gain 0 Jon.
Mallory gain 0 Jon."""
| 0 | Kotlin | 0 | 0 | 6837628fcf49db9fd8bac4291d861f761db55ddd | 2,695 | aoc | Apache License 2.0 |
report-generator/src/main/kotlin/dev/shreyaspatil/composeCompilerMetricsGenerator/generator/content/ComposableReport.kt | PatilShreyas | 481,097,747 | false | null | /**
* MIT License
*
* Copyright (c) 2022 Shreyas Patil
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.shreyaspatil.composeCompilerMetricsGenerator.generator.content
import dev.shreyaspatil.composeCompilerMetricsGenerator.core.model.Condition
import dev.shreyaspatil.composeCompilerMetricsGenerator.core.model.composables.ComposableDetail
import dev.shreyaspatil.composeCompilerMetricsGenerator.core.model.composables.ComposablesReport
import dev.shreyaspatil.composeCompilerMetricsGenerator.generator.content.common.CheckIconWithText
import dev.shreyaspatil.composeCompilerMetricsGenerator.generator.content.common.CollapsibleContent
import dev.shreyaspatil.composeCompilerMetricsGenerator.generator.content.common.CrossIconWithText
import dev.shreyaspatil.composeCompilerMetricsGenerator.generator.content.common.EmptyContent
import dev.shreyaspatil.composeCompilerMetricsGenerator.generator.style.Colors
import dev.shreyaspatil.composeCompilerMetricsGenerator.generator.style.setStyle
import dev.shreyaspatil.composeCompilerMetricsGenerator.generator.utils.forEachIndexedFromOne
import kotlinx.html.BODY
import kotlinx.html.FlowContent
import kotlinx.html.br
import kotlinx.html.h3
import kotlinx.html.h4
import kotlinx.html.section
import kotlinx.html.span
import kotlinx.html.table
import kotlinx.html.td
import kotlinx.html.th
import kotlinx.html.tr
@Suppress("ktlint:standard:function-naming")
fun BODY.ComposablesReport(
includeStableComposables: Boolean,
onlyUnstableComposables: Boolean = false,
composablesReport: ComposablesReport,
) {
if (composablesReport.composables.isEmpty()) {
EmptyContent("No Composables Report")
return
}
section {
if (onlyUnstableComposables) {
setStyle(backgroundColor = Colors.PINK_LIGHT, padding = "16px")
ComposablesReport(composablesReport.restartableButNotSkippableComposables)
return@section
}
CollapsibleContent("Composables Report") {
if (composablesReport.restartableButNotSkippableComposables.isNotEmpty()) {
CollapsibleContent(
summary = "Composables with issues (Restartable but Not Skippable)",
summaryAttr = {
setStyle(backgroundColor = Colors.RED_DARK, fontSize = "18px")
},
) {
setStyle(backgroundColor = Colors.PINK_LIGHT)
ComposablesReport(composablesReport.restartableButNotSkippableComposables)
}
} else {
EmptyContent("No composable found with issues 😁")
}
if (composablesReport.nonIssuesComposables.isNotEmpty() && includeStableComposables) {
CollapsibleContent(
summary = "Composibles without issues",
summaryAttr = {
setStyle(backgroundColor = Colors.GREEN_DARK, fontSize = "18px")
},
) {
setStyle(backgroundColor = Colors.ALABASTER)
ComposablesReport(composablesReport.nonIssuesComposables)
}
} else {
br { }
val message =
if (!includeStableComposables) {
"Report for stable composables is disabled in the options"
} else {
"No composable found without any issues"
}
EmptyContent(message)
}
}
}
}
@Suppress("ktlint:standard:function-naming")
fun FlowContent.ComposablesReport(composables: List<ComposableDetail>) =
table {
composables.forEachIndexedFromOne { index, detail ->
tr {
td {
+"$index."
}
td {
h3("code") {
if (detail.isInline) {
+"inline"
}
span { +" fun ${detail.functionName}" }
}
h4 {
span(if (detail.isSkippable) "status-success" else "status-failure") {
if (detail.isSkippable) {
CheckIconWithText("Skippable")
} else {
CrossIconWithText("Non Skippable")
}
}
span(if (detail.isRestartable) "status-success" else "status-failure") {
if (detail.isRestartable) {
CheckIconWithText("Restartable")
} else {
CrossIconWithText("Non Restartable")
}
}
}
table {
if (detail.params.isNotEmpty()) {
tr {
th { +"No." }
th { +"Stability" }
th { +"Parameter" }
th { +"Type" }
}
detail.params.forEachIndexedFromOne { index, param ->
tr(
when (param.condition) {
Condition.STABLE -> "background-status-success"
Condition.UNSTABLE -> "background-status-failure"
Condition.MISSING -> "background-status-missing"
},
) {
td { +index.toString() }
td { +param.condition.toString() }
td("code") { +param.name }
td("code") { +param.type }
}
}
}
}
}
}
}
}
@Suppress("ktlint:standard:function-naming")
fun BODY.OnlyUnstableComposables(composablesReport: ComposablesReport) {
h3 { +"Composables with issues (Restartable but Not Skippable)" }
ComposablesReport(
includeStableComposables = false,
onlyUnstableComposables = true,
composablesReport = composablesReport,
)
}
| 5 | null | 7 | 397 | 7be2856ffb9f72c1354180ff4283242a9cad8da8 | 7,573 | compose-report-to-html | MIT License |
ktor-samples/ktor-samples-post/src/org/jetbrains/ktor/samples/post/FormPostApplication.kt | hallefy | 94,839,121 | false | null | package org.jetbrains.ktor.samples.post
import kotlinx.html.*
import org.jetbrains.ktor.application.*
import org.jetbrains.ktor.features.*
import org.jetbrains.ktor.html.*
import org.jetbrains.ktor.http.*
import org.jetbrains.ktor.locations.*
import org.jetbrains.ktor.request.*
import org.jetbrains.ktor.response.*
import org.jetbrains.ktor.routing.*
@location("/") class index()
@location("/form") class post()
fun Application.main() {
install(DefaultHeaders)
install(CallLogging)
install(Locations)
routing {
get<index> {
val contentType = ContentType.Text.Html.withCharset(Charsets.UTF_8)
call.respondHtml {
head {
title { +"POST" }
meta {
httpEquiv = HttpHeaders.ContentType
content = contentType.toString()
}
}
body {
p {
+"File upload example"
}
form(feature(Locations).href(post()), encType = FormEncType.multipartFormData, method = FormMethod.post) {
acceptCharset = "utf-8"
textInput { name = "field1" }
fileInput { name = "file1" }
submitInput { value = "send" }
}
}
}
}
post<post> {
val multipart = call.receiveMultipart()
call.respondWrite {
if (!call.request.isMultipart()) {
appendln("Not a multipart request")
} else {
multipart.parts.forEach { part ->
when (part) {
is PartData.FormItem -> appendln("Form field: ${part.partName} = ${part.value}")
is PartData.FileItem -> appendln("File field: ${part.partName} -> ${part.originalFileName} of ${part.contentType}")
}
part.dispose()
}
}
}
}
}
}
| 0 | null | 0 | 1 | b5dcbe5b740c2d25c7704104e01e0a01bf53d675 | 2,147 | ktor | Apache License 2.0 |
app/src/main/java/cu/suitetecsa/sdkandroid/MainActivity.kt | suitetecsa | 676,273,066 | false | {"Kotlin": 48691, "Java": 45696, "HTML": 14924} | package cu.suitetecsa.sdkandroid
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.core.app.ActivityCompat
import cu.suitetecsa.sdkandroid.presentation.balance.BalanceRoute
import cu.suitetecsa.sdkandroid.presentation.balance.component.TopBar
import cu.suitetecsa.sdkandroid.ui.theme.SDKAndroidTheme
import dagger.hilt.android.AndroidEntryPoint
private const val RequestCode = 50
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (checkPermissions()) {
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.CALL_PHONE,
),
RequestCode
)
return
} else {
setContent {
SDKAndroidTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
var actions: @Composable (RowScope.() -> Unit) by remember { mutableStateOf({}) }
var title: String by remember { mutableStateOf("Balance") }
Scaffold(
topBar = { TopBar(title, actions) }
) { paddingValues ->
BalanceRoute(
onChangeTitle = { title = it },
onSetActions = { actions = it },
topPadding = paddingValues,
)
}
}
}
}
}
}
private fun checkPermissions(): Boolean {
return ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
this,
Manifest.permission.READ_PHONE_STATE
) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
this,
Manifest.permission.CALL_PHONE
) != PackageManager.PERMISSION_GRANTED
}
}
| 1 | Kotlin | 0 | 2 | c05299d74e9c1f571785c1de94629be7d5966b45 | 3,336 | sdk-android | MIT License |
app/src/main/java/cu/suitetecsa/sdkandroid/MainActivity.kt | suitetecsa | 676,273,066 | false | {"Kotlin": 48691, "Java": 45696, "HTML": 14924} | package cu.suitetecsa.sdkandroid
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.core.app.ActivityCompat
import cu.suitetecsa.sdkandroid.presentation.balance.BalanceRoute
import cu.suitetecsa.sdkandroid.presentation.balance.component.TopBar
import cu.suitetecsa.sdkandroid.ui.theme.SDKAndroidTheme
import dagger.hilt.android.AndroidEntryPoint
private const val RequestCode = 50
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (checkPermissions()) {
ActivityCompat.requestPermissions(
this,
arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.CALL_PHONE,
),
RequestCode
)
return
} else {
setContent {
SDKAndroidTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
var actions: @Composable (RowScope.() -> Unit) by remember { mutableStateOf({}) }
var title: String by remember { mutableStateOf("Balance") }
Scaffold(
topBar = { TopBar(title, actions) }
) { paddingValues ->
BalanceRoute(
onChangeTitle = { title = it },
onSetActions = { actions = it },
topPadding = paddingValues,
)
}
}
}
}
}
}
private fun checkPermissions(): Boolean {
return ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_COARSE_LOCATION
) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
this,
Manifest.permission.READ_PHONE_STATE
) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(
this,
Manifest.permission.CALL_PHONE
) != PackageManager.PERMISSION_GRANTED
}
}
| 1 | Kotlin | 0 | 2 | c05299d74e9c1f571785c1de94629be7d5966b45 | 3,336 | sdk-android | MIT License |
kt/godot-library/src/main/kotlin/godot/gen/godot/GraphNode.kt | utopia-rise | 289,462,532 | false | null | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY!
@file:Suppress("PackageDirectoryMismatch", "unused", "FunctionName", "RedundantModalityModifier",
"UNCHECKED_CAST", "JoinDeclarationAndAssignment", "USELESS_CAST",
"RemoveRedundantQualifierName", "NOTHING_TO_INLINE", "NON_FINAL_MEMBER_IN_OBJECT",
"RedundantVisibilityModifier", "RedundantUnitReturnType", "MemberVisibilityCanBePrivate")
package godot
import godot.`annotation`.GodotBaseType
import godot.core.Color
import godot.core.TypeManager
import godot.core.VariantType.BOOL
import godot.core.VariantType.COLOR
import godot.core.VariantType.LONG
import godot.core.VariantType.NIL
import godot.core.VariantType.OBJECT
import godot.core.VariantType.STRING
import godot.core.VariantType.VECTOR2
import godot.core.Vector2
import godot.core.Vector2i
import godot.core.memory.TransferContext
import godot.signals.Signal1
import godot.signals.signal
import godot.util.VoidPtr
import kotlin.Boolean
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.jvm.JvmOverloads
/**
* [GraphNode] allows to create nodes for a [GraphEdit] graph with customizable content based on its
* child controls. [GraphNode] is derived from [Container] and it is responsible for placing its
* children on screen. This works similar to [VBoxContainer]. Children, in turn, provide [GraphNode]
* with so-called slots, each of which can have a connection port on either side.
* Each [GraphNode] slot is defined by its index and can provide the node with up to two ports: one
* on the left, and one on the right. By convention the left port is also referred to as the **input
* port** and the right port is referred to as the **output port**. Each port can be enabled and
* configured individually, using different type and color. The type is an arbitrary value that you can
* define using your own considerations. The parent [GraphEdit] will receive this information on each
* connect and disconnect request.
* Slots can be configured in the Inspector dock once you add at least one child [Control]. The
* properties are grouped by each slot's index in the "Slot" section.
* **Note:** While GraphNode is set up using slots and slot indices, connections are made between
* the ports which are enabled. Because of that [GraphEdit] uses the port's index and not the slot's
* index. You can use [getInputPortSlot] and [getOutputPortSlot] to get the slot index from the port
* index.
*/
@GodotBaseType
public open class GraphNode : GraphElement() {
/**
* Emitted when any GraphNode's slot is updated.
*/
public val slotUpdated: Signal1<Long> by signal("slotIndex")
/**
* The text displayed in the GraphNode's title bar.
*/
public var title: String
get() {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getTitlePtr, STRING)
return (TransferContext.readReturnValue(STRING, false) as String)
}
set(`value`) {
TransferContext.writeArguments(STRING to value)
TransferContext.callMethod(rawPtr, MethodBindings.setTitlePtr, NIL)
}
public override fun new(scriptIndex: Int): Boolean {
callConstructor(ENGINECLASS_GRAPHNODE, scriptIndex)
return true
}
public open fun _drawPort(
slotIndex: Int,
position: Vector2i,
left: Boolean,
color: Color,
): Unit {
}
/**
* Returns the [HBoxContainer] used for the title bar, only containing a [Label] for displaying
* the title by default. This can be used to add custom controls to the title bar such as option or
* close buttons.
*/
public fun getTitlebarHbox(): HBoxContainer? {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getTitlebarHboxPtr, OBJECT)
return (TransferContext.readReturnValue(OBJECT, true) as HBoxContainer?)
}
/**
* Sets properties of the slot with the given [slotIndex].
* If [enableLeftPort]/[enableRightPort] is `true`, a port will appear and the slot will be able
* to be connected from this side.
* With [typeLeft]/[typeRight] an arbitrary type can be assigned to each port. Two ports can be
* connected if they share the same type, or if the connection between their types is allowed in the
* parent [GraphEdit] (see [GraphEdit.addValidConnectionType]). Keep in mind that the [GraphEdit] has
* the final say in accepting the connection. Type compatibility simply allows the [signal
* GraphEdit.connection_request] signal to be emitted.
* Ports can be further customized using [colorLeft]/[colorRight] and
* [customIconLeft]/[customIconRight]. The color parameter adds a tint to the icon. The custom icon
* can be used to override the default port dot.
* Additionally, [drawStylebox] can be used to enable or disable drawing of the background
* stylebox for each slot. See [theme_item slot].
* Individual properties can also be set using one of the `set_slot_*` methods.
* **Note:** This method only sets properties of the slot. To create the slot itself, add a
* [Control]-derived child to the GraphNode.
*/
@JvmOverloads
public fun setSlot(
slotIndex: Int,
enableLeftPort: Boolean,
typeLeft: Int,
colorLeft: Color,
enableRightPort: Boolean,
typeRight: Int,
colorRight: Color,
customIconLeft: Texture2D? = null,
customIconRight: Texture2D? = null,
drawStylebox: Boolean = true,
): Unit {
TransferContext.writeArguments(LONG to slotIndex.toLong(), BOOL to enableLeftPort, LONG to typeLeft.toLong(), COLOR to colorLeft, BOOL to enableRightPort, LONG to typeRight.toLong(), COLOR to colorRight, OBJECT to customIconLeft, OBJECT to customIconRight, BOOL to drawStylebox)
TransferContext.callMethod(rawPtr, MethodBindings.setSlotPtr, NIL)
}
/**
* Disables the slot with the given [slotIndex]. This will remove the corresponding input and
* output port from the GraphNode.
*/
public fun clearSlot(slotIndex: Int): Unit {
TransferContext.writeArguments(LONG to slotIndex.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.clearSlotPtr, NIL)
}
/**
* Disables all slots of the GraphNode. This will remove all input/output ports from the
* GraphNode.
*/
public fun clearAllSlots(): Unit {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.clearAllSlotsPtr, NIL)
}
/**
* Returns `true` if left (input) side of the slot with the given [slotIndex] is enabled.
*/
public fun isSlotEnabledLeft(slotIndex: Int): Boolean {
TransferContext.writeArguments(LONG to slotIndex.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.isSlotEnabledLeftPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
/**
* Toggles the left (input) side of the slot with the given [slotIndex]. If [enable] is `true`, a
* port will appear on the left side and the slot will be able to be connected from this side.
*/
public fun setSlotEnabledLeft(slotIndex: Int, enable: Boolean): Unit {
TransferContext.writeArguments(LONG to slotIndex.toLong(), BOOL to enable)
TransferContext.callMethod(rawPtr, MethodBindings.setSlotEnabledLeftPtr, NIL)
}
/**
* Sets the left (input) type of the slot with the given [slotIndex] to [type]. If the value is
* negative, all connections will be disallowed to be created via user inputs.
*/
public fun setSlotTypeLeft(slotIndex: Int, type: Int): Unit {
TransferContext.writeArguments(LONG to slotIndex.toLong(), LONG to type.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.setSlotTypeLeftPtr, NIL)
}
/**
* Returns the left (input) type of the slot with the given [slotIndex].
*/
public fun getSlotTypeLeft(slotIndex: Int): Int {
TransferContext.writeArguments(LONG to slotIndex.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getSlotTypeLeftPtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
/**
* Sets the [Color] of the left (input) side of the slot with the given [slotIndex] to [color].
*/
public fun setSlotColorLeft(slotIndex: Int, color: Color): Unit {
TransferContext.writeArguments(LONG to slotIndex.toLong(), COLOR to color)
TransferContext.callMethod(rawPtr, MethodBindings.setSlotColorLeftPtr, NIL)
}
/**
* Returns the left (input) [Color] of the slot with the given [slotIndex].
*/
public fun getSlotColorLeft(slotIndex: Int): Color {
TransferContext.writeArguments(LONG to slotIndex.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getSlotColorLeftPtr, COLOR)
return (TransferContext.readReturnValue(COLOR, false) as Color)
}
/**
* Returns `true` if right (output) side of the slot with the given [slotIndex] is enabled.
*/
public fun isSlotEnabledRight(slotIndex: Int): Boolean {
TransferContext.writeArguments(LONG to slotIndex.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.isSlotEnabledRightPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
/**
* Toggles the right (output) side of the slot with the given [slotIndex]. If [enable] is `true`,
* a port will appear on the right side and the slot will be able to be connected from this side.
*/
public fun setSlotEnabledRight(slotIndex: Int, enable: Boolean): Unit {
TransferContext.writeArguments(LONG to slotIndex.toLong(), BOOL to enable)
TransferContext.callMethod(rawPtr, MethodBindings.setSlotEnabledRightPtr, NIL)
}
/**
* Sets the right (output) type of the slot with the given [slotIndex] to [type]. If the value is
* negative, all connections will be disallowed to be created via user inputs.
*/
public fun setSlotTypeRight(slotIndex: Int, type: Int): Unit {
TransferContext.writeArguments(LONG to slotIndex.toLong(), LONG to type.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.setSlotTypeRightPtr, NIL)
}
/**
* Returns the right (output) type of the slot with the given [slotIndex].
*/
public fun getSlotTypeRight(slotIndex: Int): Int {
TransferContext.writeArguments(LONG to slotIndex.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getSlotTypeRightPtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
/**
* Sets the [Color] of the right (output) side of the slot with the given [slotIndex] to [color].
*/
public fun setSlotColorRight(slotIndex: Int, color: Color): Unit {
TransferContext.writeArguments(LONG to slotIndex.toLong(), COLOR to color)
TransferContext.callMethod(rawPtr, MethodBindings.setSlotColorRightPtr, NIL)
}
/**
* Returns the right (output) [Color] of the slot with the given [slotIndex].
*/
public fun getSlotColorRight(slotIndex: Int): Color {
TransferContext.writeArguments(LONG to slotIndex.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getSlotColorRightPtr, COLOR)
return (TransferContext.readReturnValue(COLOR, false) as Color)
}
/**
* Returns true if the background [StyleBox] of the slot with the given [slotIndex] is drawn.
*/
public fun isSlotDrawStylebox(slotIndex: Int): Boolean {
TransferContext.writeArguments(LONG to slotIndex.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.isSlotDrawStyleboxPtr, BOOL)
return (TransferContext.readReturnValue(BOOL, false) as Boolean)
}
/**
* Toggles the background [StyleBox] of the slot with the given [slotIndex].
*/
public fun setSlotDrawStylebox(slotIndex: Int, enable: Boolean): Unit {
TransferContext.writeArguments(LONG to slotIndex.toLong(), BOOL to enable)
TransferContext.callMethod(rawPtr, MethodBindings.setSlotDrawStyleboxPtr, NIL)
}
/**
* Returns the number of slots with an enabled input port.
*/
public fun getInputPortCount(): Int {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getInputPortCountPtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
/**
* Returns the position of the input port with the given [portIdx].
*/
public fun getInputPortPosition(portIdx: Int): Vector2 {
TransferContext.writeArguments(LONG to portIdx.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getInputPortPositionPtr, VECTOR2)
return (TransferContext.readReturnValue(VECTOR2, false) as Vector2)
}
/**
* Returns the type of the input port with the given [portIdx].
*/
public fun getInputPortType(portIdx: Int): Int {
TransferContext.writeArguments(LONG to portIdx.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getInputPortTypePtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
/**
* Returns the [Color] of the input port with the given [portIdx].
*/
public fun getInputPortColor(portIdx: Int): Color {
TransferContext.writeArguments(LONG to portIdx.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getInputPortColorPtr, COLOR)
return (TransferContext.readReturnValue(COLOR, false) as Color)
}
/**
* Returns the corresponding slot index of the input port with the given [portIdx].
*/
public fun getInputPortSlot(portIdx: Int): Int {
TransferContext.writeArguments(LONG to portIdx.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getInputPortSlotPtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
/**
* Returns the number of slots with an enabled output port.
*/
public fun getOutputPortCount(): Int {
TransferContext.writeArguments()
TransferContext.callMethod(rawPtr, MethodBindings.getOutputPortCountPtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
/**
* Returns the position of the output port with the given [portIdx].
*/
public fun getOutputPortPosition(portIdx: Int): Vector2 {
TransferContext.writeArguments(LONG to portIdx.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getOutputPortPositionPtr, VECTOR2)
return (TransferContext.readReturnValue(VECTOR2, false) as Vector2)
}
/**
* Returns the type of the output port with the given [portIdx].
*/
public fun getOutputPortType(portIdx: Int): Int {
TransferContext.writeArguments(LONG to portIdx.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getOutputPortTypePtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
/**
* Returns the [Color] of the output port with the given [portIdx].
*/
public fun getOutputPortColor(portIdx: Int): Color {
TransferContext.writeArguments(LONG to portIdx.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getOutputPortColorPtr, COLOR)
return (TransferContext.readReturnValue(COLOR, false) as Color)
}
/**
* Returns the corresponding slot index of the output port with the given [portIdx].
*/
public fun getOutputPortSlot(portIdx: Int): Int {
TransferContext.writeArguments(LONG to portIdx.toLong())
TransferContext.callMethod(rawPtr, MethodBindings.getOutputPortSlotPtr, LONG)
return (TransferContext.readReturnValue(LONG, false) as Long).toInt()
}
public companion object
internal object MethodBindings {
public val _drawPortPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphNode", "_draw_port")
public val setTitlePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphNode", "set_title")
public val getTitlePtr: VoidPtr = TypeManager.getMethodBindPtr("GraphNode", "get_title")
public val getTitlebarHboxPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_titlebar_hbox")
public val setSlotPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphNode", "set_slot")
public val clearSlotPtr: VoidPtr = TypeManager.getMethodBindPtr("GraphNode", "clear_slot")
public val clearAllSlotsPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "clear_all_slots")
public val isSlotEnabledLeftPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "is_slot_enabled_left")
public val setSlotEnabledLeftPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "set_slot_enabled_left")
public val setSlotTypeLeftPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "set_slot_type_left")
public val getSlotTypeLeftPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_slot_type_left")
public val setSlotColorLeftPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "set_slot_color_left")
public val getSlotColorLeftPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_slot_color_left")
public val isSlotEnabledRightPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "is_slot_enabled_right")
public val setSlotEnabledRightPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "set_slot_enabled_right")
public val setSlotTypeRightPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "set_slot_type_right")
public val getSlotTypeRightPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_slot_type_right")
public val setSlotColorRightPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "set_slot_color_right")
public val getSlotColorRightPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_slot_color_right")
public val isSlotDrawStyleboxPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "is_slot_draw_stylebox")
public val setSlotDrawStyleboxPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "set_slot_draw_stylebox")
public val getInputPortCountPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_input_port_count")
public val getInputPortPositionPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_input_port_position")
public val getInputPortTypePtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_input_port_type")
public val getInputPortColorPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_input_port_color")
public val getInputPortSlotPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_input_port_slot")
public val getOutputPortCountPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_output_port_count")
public val getOutputPortPositionPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_output_port_position")
public val getOutputPortTypePtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_output_port_type")
public val getOutputPortColorPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_output_port_color")
public val getOutputPortSlotPtr: VoidPtr =
TypeManager.getMethodBindPtr("GraphNode", "get_output_port_slot")
}
}
| 64 | null | 39 | 580 | fd1af79075e7b918200aba3302496b70c76a2028 | 19,039 | godot-kotlin-jvm | MIT License |
analysis/analysis-api-platform-interface/src/org/jetbrains/kotlin/analysis/api/platform/declarations/KotlinFileBasedDeclarationProvider.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.analysis.low.level.api.fir.project.structure
import org.jetbrains.kotlin.analysis.providers.KotlinDeclarationProvider
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.name.CallableId
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.yieldIfNotNull
internal class FileBasedKotlinDeclarationProvider(private val kotlinFile: KtFile) : KotlinDeclarationProvider() {
private val topLevelDeclarations: Sequence<KtDeclaration>
get() {
return sequence {
for (child in kotlinFile.declarations) {
if (child is KtScript) {
yieldAll(child.declarations)
} else {
yield(child)
}
}
}
}
override fun getClassLikeDeclarationByClassId(classId: ClassId): KtClassLikeDeclaration? {
return getClassLikeDeclarationsByClassId(classId).firstOrNull()
}
override fun getAllClassesByClassId(classId: ClassId): Collection<KtClassOrObject> {
return getClassLikeDeclarationsByClassId(classId).filterIsInstance<KtClassOrObject>().toList()
}
private fun getClassLikeDeclarationsByClassId(classId: ClassId): Sequence<KtClassLikeDeclaration> {
if (classId.isLocal) {
return emptySequence()
}
if (kotlinFile.packageFqName != classId.packageFqName) {
return emptySequence()
}
data class Task(val chunks: List<Name>, val element: KtElement)
return sequence {
val tasks = ArrayDeque<Task>()
val startingChunks = classId.relativeClassName.pathSegments()
for (declaration in topLevelDeclarations) {
tasks.addLast(Task(startingChunks, declaration))
}
tasks += Task(startingChunks, kotlinFile)
while (!tasks.isEmpty()) {
val (chunks, element) = tasks.removeFirst()
assert(chunks.isNotEmpty())
if (element !is KtNamedDeclaration || element.nameAsName != chunks[0]) {
continue
}
if (chunks.size == 1) {
yieldIfNotNull(element as? KtClassLikeDeclaration)
continue
}
if (element is KtDeclarationContainer) {
val newChunks = chunks.subList(1, chunks.size)
for (child in element.declarations) {
tasks.addLast(Task(newChunks, child))
}
}
}
}
}
override fun getAllTypeAliasesByClassId(classId: ClassId): Collection<KtTypeAlias> {
return getClassLikeDeclarationsByClassId(classId).filterIsInstance<KtTypeAlias>().toList()
}
override fun getTopLevelKotlinClassLikeDeclarationNamesInPackage(packageFqName: FqName): Set<Name> {
return getTopLevelDeclarationNames<KtClassLikeDeclaration>(packageFqName)
}
override fun getTopLevelProperties(callableId: CallableId): Collection<KtProperty> {
return getTopLevelCallables(callableId)
}
override fun getTopLevelFunctions(callableId: CallableId): Collection<KtNamedFunction> {
return getTopLevelCallables(callableId)
}
override fun getTopLevelCallableFiles(callableId: CallableId): Collection<KtFile> {
return buildSet {
getTopLevelProperties(callableId).mapTo(this) { it.containingKtFile }
getTopLevelFunctions(callableId).mapTo(this) { it.containingKtFile }
}
}
override fun getTopLevelCallableNamesInPackage(packageFqName: FqName): Set<Name> {
return getTopLevelDeclarationNames<KtCallableDeclaration>(packageFqName)
}
override fun findFilesForFacadeByPackage(packageFqName: FqName): Collection<KtFile> {
if (kotlinFile.packageFqName != packageFqName) {
return emptyList()
}
return listOf(kotlinFile)
}
override fun findFilesForFacade(facadeFqName: FqName): Collection<KtFile> {
if (kotlinFile.javaFileFacadeFqName != facadeFqName) return emptyList()
for (declaration in topLevelDeclarations) {
if (declaration !is KtClassLikeDeclaration) {
return listOf(kotlinFile)
}
}
return emptyList()
}
override fun findInternalFilesForFacade(facadeFqName: FqName): Collection<KtFile> = emptyList()
private inline fun <reified T : KtCallableDeclaration> getTopLevelCallables(callableId: CallableId): Collection<T> {
require(callableId.classId == null)
return getTopLevelDeclarations(callableId.packageName, callableId.callableName)
}
private inline fun <reified T : KtNamedDeclaration> getTopLevelDeclarations(packageFqName: FqName, name: Name): Collection<T> {
if (kotlinFile.packageFqName != packageFqName) {
return emptyList()
}
return buildList {
for (declaration in topLevelDeclarations) {
if (declaration is T && declaration.nameAsName == name) {
add(declaration)
}
}
}
}
private inline fun <reified T : KtNamedDeclaration> getTopLevelDeclarationNames(packageFqName: FqName): Set<Name> {
if (kotlinFile.packageFqName != packageFqName) {
return emptySet()
}
return buildSet {
for (declaration in topLevelDeclarations) {
if (declaration is T) {
addIfNotNull(declaration.nameAsName)
}
}
}
}
} | 182 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 6,082 | kotlin | Apache License 2.0 |
app/src/main/java/org/imaginativeworld/simplemvvm/ui/screens/awesometodos/splash/TodoSplashViewModel.kt | ImaginativeShohag | 225,951,395 | false | {"Kotlin": 483782, "Java": 1056} | /*
* Copyright 2023 Md. <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.
*
* ------------------------------------------------------------------------
*
* Project: Simple MVVM
* Developed by: @ImaginativeShohag
*
* Md. <NAME>
* <EMAIL>
*
* Source: https://github.com/ImaginativeShohag/Simple-MVVM
*/
package org.imaginativeworld.simplemvvm.ui.screens.awesometodos.splash
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.launch
import org.imaginativeworld.simplemvvm.utils.SharedPref
@HiltViewModel
class TodoSplashViewModel @Inject constructor(
private val sharedPref: SharedPref
) : ViewModel() {
private val _eventShowMessage: MutableLiveData<String?> by lazy {
MutableLiveData<String?>()
}
val eventShowMessage: LiveData<String?>
get() = _eventShowMessage
// ----------------------------------------------------------------
private val _eventShowLoading: MutableLiveData<Boolean?> by lazy {
MutableLiveData<Boolean?>()
}
val eventShowLoading: LiveData<Boolean?>
get() = _eventShowLoading
// ----------------------------------------------------------------
private val _eventAuthSuccess: MutableLiveData<Boolean?> by lazy {
MutableLiveData<Boolean?>(null)
}
val eventAuthSuccess: LiveData<Boolean?>
get() = _eventAuthSuccess
// ----------------------------------------------------------------
fun checkAuthentication() = viewModelScope.launch {
val existingUser = sharedPref.getUser()
if (existingUser == null) {
_eventAuthSuccess.postValue(false)
} else {
_eventAuthSuccess.postValue(true)
}
}
}
| 0 | Kotlin | 12 | 65 | 5ddbfcf932de943faf6a47654adbd6a018a1f991 | 2,413 | Simple-MVVM | Apache License 2.0 |
markdown/src/test/kotlin/com/appmattus/markdown/rules/NoSpaceInCodeRuleTest.kt | appmattus | 172,489,287 | false | {"Kotlin": 248958, "XSLT": 7533} | package com.appmattus.markdown.rules
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.gherkin.Feature
object NoSpaceInCodeRuleTest : Spek({
Feature("NoSpaceInCodeRule") {
FileRuleScenario { NoSpaceInCodeRule() }
}
})
| 9 | Kotlin | 3 | 16 | 18e5bee66b7f38d1df18484e2f8f23a1f9190cf6 | 259 | markdown-lint | Apache License 2.0 |
markdown/src/test/kotlin/com/appmattus/markdown/rules/NoSpaceInCodeRuleTest.kt | appmattus | 172,489,287 | false | {"Kotlin": 248958, "XSLT": 7533} | package com.appmattus.markdown.rules
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.gherkin.Feature
object NoSpaceInCodeRuleTest : Spek({
Feature("NoSpaceInCodeRule") {
FileRuleScenario { NoSpaceInCodeRule() }
}
})
| 9 | Kotlin | 3 | 16 | 18e5bee66b7f38d1df18484e2f8f23a1f9190cf6 | 259 | markdown-lint | Apache License 2.0 |
dashboard/src/commonMain/kotlin/com/opencritic/dashboard/ui/DashboardPosterGameListItem.kt | MAX-POLKOVNIK | 797,563,657 | false | {"Kotlin": 502940, "Swift": 141399} | package com.opencritic.dashboard.ui
import com.opencritic.dashboard.domain.PosterGame
import com.opencritic.games.GameRankModel
import com.opencritic.games.Tier
import com.opencritic.mvvm.ListItem
data class DashboardPosterGameListItem(
val game: PosterGame,
private val onClick: (DashboardPosterGameListItem) -> Unit,
) : ListItem<Long> {
override val id: Long
get() = game.id
val nameText: String
get() = game.name
val rank: GameRankModel? =
GameRankModel(game.rank)
val posterUrl: String
get() = game.posterUrl
val isPlayedChecked: Boolean
get() = false
val isWantToPlayChecked: Boolean
get() = false
fun click() =
onClick(this)
} | 0 | Kotlin | 0 | 1 | d9b9f89101ab1a94c05e03cb2a45e332270c81b2 | 733 | OpenCritic | Apache License 2.0 |
src/test/java/dev/blachut/svelte/lang/parsing/html/SvelteDirectiveParserTest.kt | tomblachut | 184,821,501 | false | null | package dev.blachut.svelte.lang.parsing.html
import com.intellij.openapi.util.TextRange
import dev.blachut.svelte.lang.directives.SvelteDirectiveTypes
import dev.blachut.svelte.lang.directives.SvelteDirectiveUtil.Directive
import dev.blachut.svelte.lang.directives.SvelteDirectiveUtil.DirectiveSegment
import junit.framework.TestCase
import org.junit.Assert
class SvelteDirectiveParserTest : TestCase() {
fun testNonDirectiveClass() {
val result = SvelteDirectiveParser.parse("class")
Assert.assertEquals(result, null)
}
fun testOn() {
Assert.assertEquals(
SvelteDirectiveParser.parse("on:click|once|capture"),
Directive(
SvelteDirectiveTypes.ON,
listOf(DirectiveSegment("click", TextRange(3, 8))),
listOf(DirectiveSegment("once", TextRange(9, 13)), DirectiveSegment("capture", TextRange(14, 21)))
)
)
}
fun testClass() {
Assert.assertEquals(
SvelteDirectiveParser.parse("class:foo"),
Directive(
SvelteDirectiveTypes.CLASS,
listOf(DirectiveSegment("foo", TextRange(6, 9))),
listOf()
)
)
}
fun testUse() {
Assert.assertEquals(
SvelteDirectiveParser.parse("use:foo.bar"),
Directive(
SvelteDirectiveTypes.USE,
listOf(DirectiveSegment("foo", TextRange(4, 7)), DirectiveSegment("bar", TextRange(8, 11))),
listOf()
)
)
}
}
| 59 | null | 38 | 482 | 793f21924edd2436b2c980ad1958785e000a65ac | 1,396 | svelte-intellij | MIT License |
src/main/kotlin/ai/welltested/fluttergpt/utilities/configManager/secretKeyConfig.kt | Welltested-AI | 630,833,057 | false | null | package ai.welltested.fluttergpt.utilities.configManager
import com.intellij.openapi.components.*
@State(name = "SecretKeyConfig", storages = [Storage("secretKeyConfig.xml")])
@Service
class SecretKeyConfig : PersistentStateComponent<SecretKeyConfig.State> {
data class State(var secretKey: String = "")
private var myState = State()
override fun getState(): State {
return myState
}
override fun loadState(state: State) {
myState = state
}
var secretKey: String
get() = myState.secretKey
set(value) {
myState.secretKey = value
}
companion object {
fun getInstance(): SecretKeyConfig {
return service()
}
}
} | 3 | Kotlin | 2 | 2 | 98133dec3985aeda9998ba1fa0e63b94858a43c2 | 732 | fluttergpt-intellij | Apache License 2.0 |
composeApp/src/commonMain/kotlin/com/rwmobi/kunigami/domain/usecase/product/GetTariffUseCase.kt | ryanw-mobile | 794,752,204 | false | {"Kotlin": 1112930, "Ruby": 2466, "Swift": 693} | /*
* Copyright (c) 2024. <NAME>
* https://github.com/ryanw-mobile
* Sponsored by RW MobiMedia UK Limited
*
*/
package com.rwmobi.kunigami.domain.usecase.product
import com.rwmobi.kunigami.domain.model.product.Tariff
import com.rwmobi.kunigami.domain.repository.OctopusApiRepository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class GetTariffUseCase(
private val octopusApiRepository: OctopusApiRepository,
private val dispatcher: CoroutineDispatcher = Dispatchers.Default,
) {
suspend operator fun invoke(tariffCode: String): Result<Tariff> {
return withContext(dispatcher) {
octopusApiRepository.getTariff(tariffCode = tariffCode)
}
}
}
| 20 | Kotlin | 10 | 98 | e1e73f5b44baaef5ab87fd10db21775d442a3172 | 768 | OctoMeter | Apache License 2.0 |
matrix/src/main/kotlin/Matrix.kt | 3mtee | 98,672,009 | false | null | class Matrix(matrixAsString: String) {
private val matrix: List<List<Int>> = matrixAsString.split("\n")
.map { it.trim().split(Regex("\\s+")).map(String::toInt) }
fun column(colNr: Int): List<Int> = matrix.map { it[colNr - 1] }
fun row(rowNr: Int): List<Int> = matrix[rowNr - 1]
}
| 0 | Kotlin | 0 | 0 | 815d0e41e6f88a47681b8cc6eaec3858e59e0975 | 303 | exercism-kotlin | Apache License 2.0 |
kotlinpoet-metadata-specs/src/main/kotlin/com/squareup/kotlinpoet/metadata/specs/JvmFieldModifier.kt | LloydFinch | 224,367,360 | false | null | package com.squareup.kotlinpoet.metadata.specs
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.metadata.KotlinPoetMetadataPreview
/** Modifiers that are annotations in Kotlin but modifier keywords in bytecode. */
@KotlinPoetMetadataPreview
public enum class JvmFieldModifier : JvmModifier {
STATIC {
override fun annotationSpec(): AnnotationSpec = AnnotationSpec.builder(
JvmStatic::class.asClassName()).build()
},
TRANSIENT {
override fun annotationSpec(): AnnotationSpec = AnnotationSpec.builder(
Transient::class.asClassName()).build()
},
VOLATILE {
override fun annotationSpec(): AnnotationSpec = AnnotationSpec.builder(
Volatile::class.asClassName()).build()
};
}
| 0 | null | 0 | 2 | c73c349b32d1de0d5b5233fa61a40bd15d4a51e1 | 791 | kotlinpoet | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.