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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
marcel-compilation/marcel-semantic/marcel-semantic-core/src/main/kotlin/com/tambapps/marcel/semantic/ast/expression/InstanceOfNode.kt | tambapps | 587,877,674 | false | {"Maven POM": 26, "Text": 1, "Ignore List": 11, "Markdown": 87, "Kotlin": 465, "Gradle Kotlin DSL": 5, "INI": 4, "Java Properties": 4, "Shell": 5, "Batchfile": 2, "Proguard": 8, "XML": 83, "Java": 226, "YAML": 1, "JavaScript": 1, "TOML": 1, "Gradle": 5, "JFlex": 1} | package com.tambapps.marcel.semantic.ast.expression
import com.tambapps.marcel.lexer.LexToken
import com.tambapps.marcel.parser.cst.CstNode
import com.tambapps.marcel.semantic.type.JavaType
class InstanceOfNode(
val instanceType: JavaType,
val expressionNode: ExpressionNode,
tokenStart: LexToken,
tokenEnd: LexToken
) : AbstractExpressionNode(JavaType.boolean, tokenStart, tokenEnd) {
constructor(
instanceType: JavaType,
expressionNode: ExpressionNode,
node: CstNode
) : this(instanceType, expressionNode, node.tokenStart, node.tokenEnd)
override fun <T> accept(visitor: ExpressionNodeVisitor<T>) =
visitor.visit(this)
} | 0 | Java | 0 | 7 | 83bf3562f8bb6b43fe5d6f2e13c9ed5ad3300bce | 656 | marcel | Apache License 2.0 |
cc/ccp/app/src/main/java/com/example/ccp/util/RetrofitClient.kt | chess0716 | 753,962,691 | false | {"XML": 514, "Batchfile": 31, "Markdown": 21, "Text": 74, "Java": 1349, "HTML": 242, "Java Properties": 66, "Shell": 33, "Maven POM": 65, "Ignore List": 68, "INI": 160, "Java Server Pages": 240, "JAR Manifest": 23, "JSON": 114, "JavaScript": 1031, "CSS": 229, "YAML": 15, "JSON with Comments": 24, "robots.txt": 34, "SCSS": 696, "SQL": 1, "Python": 264, "TSX": 10, "SVG": 46, "Rich Text Format": 1, "Gradle Kotlin DSL": 6, "Proguard": 2, "Kotlin": 94} | package com.example.ccp.util
import com.example.ccp.service.ApiService
import com.example.ccp.service.CommentService
import com.example.ccp.service.IngrService
import com.example.ccp.service.MyPageService
import com.example.ccp.service.UserService
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
private const val BASE_URL = "http://10.100.103.73:8005/"
private val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
private val okHttpClient: OkHttpClient = OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build()
private val retrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
private val userServiceRetrofit: Retrofit by lazy {
Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient.newBuilder().addInterceptor(loggingInterceptor).build())
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val apiService: ApiService by lazy {
retrofit.create(ApiService::class.java)
}
val ingrService: IngrService by lazy {
retrofit.create(IngrService::class.java)
}
val userService: UserService by lazy {
userServiceRetrofit.create(UserService::class.java)
}
val myPageService: MyPageService by lazy {
retrofit.create(MyPageService::class.java)
}
val commentService: CommentService by lazy {
retrofit.create(CommentService::class.java)
}
}
| 0 | Java | 0 | 0 | 9297a095a5113a4acc499897de4468055bdab6a9 | 1,791 | Spring | Creative Commons Attribution 3.0 Unported |
app/src/main/java/com/hazz/aipick/ui/activity/CoinDescBuyOrSellActivity.kt | q513718201 | 232,772,377 | false | {"Java": 997236, "Kotlin": 609033} | package com.hazz.aipick.ui.activity
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.support.v4.app.Fragment
import android.view.View
import com.hazz.aipick.R
import com.hazz.aipick.base.BaseActivity
import com.hazz.aipick.ui.adapter.FragmentAdapter
import com.hazz.aipick.ui.fragment.AboutCoinFragment
import com.hazz.aipick.ui.fragment.OnOrderFragment
import com.hazz.aipick.ui.fragment.OnSellFragment
import com.hazz.aipick.utils.ToastUtils
import kotlinx.android.synthetic.main.activity_coin_desc_buy.*
import net.lucode.hackware.magicindicator.ViewPagerHelper
import net.lucode.hackware.magicindicator.buildins.UIUtil
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.ClipPagerTitleView
class CoinDescBuyOrSellActivity : BaseActivity() {
override fun layoutId(): Int = R.layout.activity_coin_desc_buy
override fun initData() {
}
private var name = ""
private var coinName = ""
private var nameKine = ""
@SuppressLint("SetTextI18n", "ResourceType")
override fun initView() {
coinName = intent.getStringExtra("name")
val split = coinName.split(".")
nameKine = split[0] + "." + split[1] + "."
name = split[1].substring(0, split[1].length - 4).toUpperCase()
tv_title.text = "$name/USDT"
chart.setSymbol(nameKine)
market_info.bindView(coinName)
iv_back.setOnClickListener { finish() }
initBottom()
}
private var mTitles: Array<String>? = null
private var fragments: MutableList<Fragment> = ArrayList()
private fun initBottom() {
mTitles = resources.getStringArray(R.array.titles_sell_tab)
fragments.add(OnOrderFragment.getInstance(coinName))
fragments.add(OnSellFragment.getInstance(coinName))
fragments.add(AboutCoinFragment.getInstance(coinName))
view_pager.adapter = FragmentAdapter(supportFragmentManager, fragments, mTitles)
ViewPagerHelper.bind(tab_layout, view_pager)
val commonNavigator = CommonNavigator(this)
commonNavigator.isAdjustMode = true
commonNavigator.adapter = object : CommonNavigatorAdapter() {
override fun getCount(): Int {
return (mTitles as Array<String>).size
}
override fun getTitleView(context: Context, index: Int): IPagerTitleView {
val clipPagerTitleView = ClipPagerTitleView(context)
clipPagerTitleView.text = (mTitles as Array<String>)[index]
clipPagerTitleView.textSize = UIUtil.dip2px(context, 14.0).toFloat()
clipPagerTitleView.textColor = Color.parseColor("#a5b1c8")
clipPagerTitleView.clipColor = resources.getColor(R.color.text_color_highlight)
clipPagerTitleView.setOnClickListener { view_pager.currentItem = index }
return clipPagerTitleView
}
override fun getIndicator(context: Context): IPagerIndicator {
val linePagerIndicator = LinePagerIndicator(context)
linePagerIndicator.mode = LinePagerIndicator.MODE_WRAP_CONTENT
linePagerIndicator.setColors(resources.getColor(R.color.text_color_highlight))
return linePagerIndicator
}
}
tab_layout.navigator = commonNavigator
}
override fun start() {
}
fun onBuy(view: View) {
ToastUtils.showToast(this, "正在开发,暂未开放")
// CoinBuyAndSellActivity.start(this, coinName, 0)
}
fun onSell(view: View) {
ToastUtils.showToast(this, "正在开发,暂未开放")
// CoinBuyAndSellActivity.start(this, coinName, 1)
}
}
| 1 | null | 1 | 1 | a9ca66fb384edc7cc53dd239f216ecdde07c09f6 | 4,166 | Aipick | Apache License 2.0 |
app/src/main/java/com/example/myapplication/FirstFragment.kt | stephanenicolas | 283,885,381 | false | {"Kotlin": 8140} | package com.example.myapplication
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.navigation.fragment.findNavController
/**
* A simple [Fragment] subclass as the default destination in the navigation.
*/
class FirstFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_first, container, false)
}
override fun onViewCreated(
view: View,
savedInstanceState: Bundle?
) {
super.onViewCreated(view, savedInstanceState)
val textView = view.findViewById<TextView>(R.id.textview_first)
val button = view.findViewById<Button>(R.id.button_first)
textView.setText(R.string.first_fragment_label)
button.setOnClickListener {
findNavController().navigate(R.id.action_FirstFragment_to_SecondFragment)
}
}
} | 0 | Kotlin | 0 | 3 | 064db56d54e48ba1d3cb4c74e7996d01e10f6522 | 1,120 | Dependency-Resources-Linearization | Apache License 2.0 |
main/src/main/java/com/proxer/easydo/main/ui/component/Task.kt | binkos | 405,064,940 | false | {"Kotlin": 41409} | package com.proxer.easydo.main.ui.component
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import com.proxer.easydo.main.R
import com.proxer.easydo.main.ui.model.TaskModel
@Composable
fun Task(model: TaskModel, onTaskClickListener: (taskModel: TaskModel) -> Unit) {
Row(
modifier = Modifier
.padding(horizontal = 8.dp)
.clip(RoundedCornerShape(8.dp))
.background(MaterialTheme.colors.primary)
.padding(horizontal = 8.dp)
.height(48.dp)
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically
) {
CompletionIndicator(isCompleted = model.isCompleted, color = Color(model.color)) {
onTaskClickListener(model)
}
Spacer(modifier = Modifier.width(12.dp))
Text(
text = model.name,
textDecoration = if (model.isCompleted) TextDecoration.LineThrough else null,
color = Color.White
)
}
}
@Composable
fun CompletionIndicator(
isCompleted: Boolean,
color: Color,
indicatorClickListener: () -> Unit
) {
Box(
modifier = Modifier
.clip(CircleShape)
.clickable { indicatorClickListener() }
.size(24.dp),
contentAlignment = Alignment.Center
) {
Canvas(modifier = Modifier.size(24.dp)) {
drawCircle(
SolidColor(color),
style = Stroke(4f)
)
if (isCompleted) {
drawOval(color)
}
}
// TODO rewrite to canvas
if (isCompleted) {
Icon(
modifier = Modifier.size(12.dp),
painter = painterResource(id = R.drawable.ic_check_vote),
contentDescription = null,
tint = Color.White
)
}
}
} | 0 | Kotlin | 0 | 0 | 2508089e15254123f470cd23a98c91b3509a10bc | 2,642 | easy-do | Apache License 2.0 |
libraries/stdlib/common/src/kotlin/SequencesH.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2018 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 kotlin.sequences
internal expect class ConstrainedOnceSequence<T> : Sequence<T> {
constructor(sequence: Sequence<T>)
override fun iterator(): Iterator<T>
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 384 | kotlin | Apache License 2.0 |
src/main/kotlin/com/hrappv/ui/feature/department/DefaultDepartmentComponent.kt | m37moud | 601,815,217 | false | null | package com.hrappv.ui.feature.department
import androidx.compose.runtime.Composable
import com.arkivanov.decompose.ComponentContext
import com.arkivanov.decompose.ExperimentalDecomposeApi
import com.arkivanov.decompose.extensions.compose.jetbrains.stack.Children
import com.arkivanov.decompose.extensions.compose.jetbrains.stack.animation.*
import com.arkivanov.decompose.extensions.compose.jetbrains.subscribeAsState
import com.arkivanov.decompose.router.stack.*
import com.arkivanov.decompose.value.Value
import com.arkivanov.essenty.parcelable.Parcelable
import com.arkivanov.essenty.parcelable.Parcelize
import com.hrappv.di.AppComponent
import com.hrappv.di.DaggerAppComponent
import com.hrappv.ui.feature.department.add_department.AddDepartmentComponent
import com.hrappv.ui.feature.department.show_departments.DepartmentComponent
import com.hrappv.ui.navigation.Component
class DefaultDepartmentComponent(
appComponent: AppComponent,
private val componentContext: ComponentContext,
private val onBackPress: () -> Unit
) : Component, ComponentContext by componentContext {
// init {
// appComponent.inject(this)
// }
private val appComponent: AppComponent = DaggerAppComponent
.create()
private val departmentNavigation = StackNavigation<DepartmentConfig>()
private val departmentStack = childStack(
source = departmentNavigation,
initialConfiguration = DepartmentConfig.Department,
handleBackButton = true,
key = "departmentStack",
childFactory = ::createScreenComponent,
)
private fun createScreenComponent(config: DepartmentConfig, componentContext: ComponentContext): Component {
return when (config) {
is DepartmentConfig.Department -> DepartmentComponent(
appComponent = appComponent,
componentContext = componentContext,
onAddDepartment = ::startAddDepartmentScreen,
onBackPress = ::onBackPress
)
is DepartmentConfig.AddDepartment -> AddDepartmentComponent(
appComponent = appComponent,
componentContext = componentContext,
onBackPress = ::onBackPress
)
}
}
@OptIn(ExperimentalDecomposeApi::class)
@Composable
override fun render() {
val childStack: Value<ChildStack<*, Component>> = departmentStack
val child = childStack.subscribeAsState()
val activeComponent= child.value.active.instance
println(activeComponent.toString())
Children(
stack = departmentStack,
// animation = stackAnimation(), //fade() + scale()
animation = stackAnimation { _, _, direction ->
if (direction.isFront) {
slide() + fade()
} else {
scale(frontFactor = 1F, backFactor = 0.7F) + fade()
}
},
) {
it.instance.render()
}
}
private fun startAddDepartmentScreen() {
// router.replaceCurrent(Config.Home)
if (departmentStack.value.active.configuration !is DepartmentConfig.AddDepartment) {
departmentNavigation.push(DepartmentConfig.AddDepartment)
}
}
private fun onBackPress() {
// navigation.replaceCurrent(Config.Department)
if (departmentStack.value.active.configuration !is DepartmentConfig.Department) {
departmentNavigation.pop()
}
// router.replaceCurrent(Config.Main)
}
@Parcelize
private sealed class DepartmentConfig(
// val index: Int,
// val isBackEnabled: Boolean,
) : Parcelable {
object Department : DepartmentConfig()
object AddDepartment : DepartmentConfig()
}
}
| 0 | Kotlin | 0 | 0 | 37e0e8268348cfdceb3e5d0c726c7f4a88635615 | 3,828 | HRSystem | Apache License 2.0 |
domain/src/main/java/org/michaelbel/domain/MoviesRepository.kt | Takeshi-24 | 304,005,827 | true | {"Kotlin": 308219} | package org.michaelbel.domain
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.michaelbel.data.local.dao.MoviesDao
import org.michaelbel.data.local.model.MovieLocal
import org.michaelbel.data.remote.Api
import org.michaelbel.data.remote.model.*
import org.michaelbel.data.remote.model.base.Result
import retrofit2.Response
class MoviesRepository(private val api: Api, private val dao: MoviesDao) {
//region Remote
suspend fun movies(list: String, apiKey: String, language: String, page: Int): Response<Result<Movie>> {
return api.movies(list, apiKey, language, page).await()
}
suspend fun moviesById(movieId: Long, list: String, apiKey: String, language: String, page: Int): Response<Result<Movie>> {
return api.moviesById(movieId, list, apiKey, language, page).await()
}
suspend fun moviesByKeyword(keywordId: Long, apiKey: String, language: String, adult: Boolean, page: Int): Response<Result<Movie>> {
return api.moviesByKeyword(keywordId, apiKey, language, adult, page).await()
}
suspend fun moviesSearch(apiKey: String, language: String, query: String, page: Int, adult: Boolean): Response<Result<Movie>> {
return api.searchMovies(apiKey, language, query, page, adult, "").await()
}
suspend fun moviesWatchlist(accountId: Long, apiKey: String, sessionId: String, language: String, sort: String, page: Int): Response<Result<Movie>> {
return api.moviesWatchlist(accountId, apiKey, sessionId, language, sort, page).await()
}
suspend fun moviesFavorite(accountId: Long, apiKey: String, sessionId: String, language: String, sort: String, page: Int): Response<Result<Movie>> {
return api.moviesFavorite(accountId, apiKey, sessionId, language, sort, page).await()
}
suspend fun movie(movieId: Long, apiKey: String, language: String, addToResponse: String): Response<Movie> {
return api.movie(movieId, apiKey, language, addToResponse).await()
}
suspend fun markFavorite(contentType: String, accountId: Long, apiKey: String, sessionId: String, mediaId: Long, favorite: Boolean): Response<Mark> {
return api.markAsFavorite(contentType, accountId, apiKey, sessionId, Fave(Movie.MOVIE, mediaId, favorite)).await()
}
suspend fun addWatchlist(contentType: String, accountId: Long, sessionId: String, apiKey: String, mediaId: Long, watchlist: Boolean): Response<Mark> {
return api.addToWatchlist(contentType, accountId, apiKey, sessionId, Watch(Movie.MOVIE, mediaId, watchlist)).await()
}
suspend fun accountStates(movieId: Long, apiKey: String, sessionId: String): Response<AccountStates> {
return api.accountStates(movieId, apiKey, sessionId, "").await()
}
//endregion
// region Local
suspend fun addAll(items: List<Movie>) {
val movies = ArrayList<MovieLocal>()
items.forEach {
val movie = MovieLocal(id = it.id.toLong(), title = it.title)
movies.add(movie)
}
CoroutineScope(Dispatchers.IO).launch {
try {
val result = dao.insert(movies)
withContext(Dispatchers.Main) {
Log.e("1488", "Вставка произошла успешно!")
}
} catch (e: Exception) {
Log.e("1488", "Exception: $e")
}
}
dao.insert(movies)
}
//endregion
} | 0 | null | 0 | 0 | d46976dee3c1f1b2513f421fbdb630a24a533f5c | 3,535 | Moviemade | Apache License 2.0 |
cmm/src/main/java/com/benli/cmm/viewmodel/ViewModel.kt | beilly | 98,971,871 | false | null | package com.benli.cmm.viewmodel
/**
* Created by shibenli on 2017/8/2.
*/
interface ViewModel {
fun destroy()
} | 0 | Kotlin | 0 | 1 | 74ad306c941d49a22012d67aa6c05309a81c0452 | 118 | KotlinWeather | Apache License 2.0 |
base/base-find/src/main/java/qsos/base/find/view/adapter/TweetCommentAdapter.kt | hslooooooool | 226,810,480 | false | null | package qsos.base.find.view.adapter
import android.view.View
import android.widget.Toast
import qsos.base.find.R
import qsos.base.find.view.holder.TweetItemCommentViewHolder
import qsos.lib.base.base.adapter.BaseAdapter
import qsos.lib.base.base.holder.BaseHolder
import vip.qsos.lib_data.data._do.chat.WeChatCommentBean
/**
* @author : 华清松
* 推特列表之评论列表容器
*/
class TweetCommentAdapter(
list: ArrayList<WeChatCommentBean>
) : BaseAdapter<WeChatCommentBean>(list) {
override fun getItemViewType(position: Int): Int {
return R.layout.find_item_tweet_comment
}
override fun getHolder(view: View, viewType: Int): BaseHolder<WeChatCommentBean> {
return TweetItemCommentViewHolder(view, this)
}
override fun getLayoutId(viewType: Int): Int {
return viewType
}
override fun onItemClick(view: View, position: Int, obj: Any?) {
}
override fun onItemLongClick(view: View, position: Int, obj: Any?) {
when (view.id) {
R.id.item_tweet_comment_content_tv -> {
Toast.makeText(view.context, "菜单$obj", Toast.LENGTH_SHORT).show()
}
}
}
} | 0 | Kotlin | 0 | 0 | a1e1a342821db975a193c5f9b8d5829d6ceafdd9 | 1,156 | wechat-demo | Apache License 2.0 |
jetpack/src/main/java/io/github/caoshen/androidadvance/jetpack/compose/dialog/TodoAlertDialog.kt | caoshen | 290,115,293 | false | {"Kotlin": 259354, "Java": 87268, "C++": 8150, "Groovy": 7542, "C": 4543, "CMake": 1798, "AIDL": 872, "Makefile": 693, "Shell": 658} | package io.github.caoshen.androidadvance.jetpack.compose.dialog
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import io.github.caoshen.androidadvance.jetpack.R
@Composable
fun TodoAlertDialog(
title: String,
msg: String,
isShowDialog: Boolean,
onNoClicked: () -> Unit,
onYesClicked: () -> Unit
) {
if (isShowDialog) {
AlertDialog(
title = {
Text(
text = title,
fontSize = MaterialTheme.typography.h5.fontSize,
fontWeight = FontWeight.Bold
)
},
text = {
Text(
text = msg,
fontSize = MaterialTheme.typography.subtitle1.fontSize,
fontWeight = FontWeight.Normal
)
},
confirmButton = {
Button(
onClick = {
onYesClicked()
onNoClicked()
}
) {
Text(text = stringResource(id = R.string.yes))
}
},
dismissButton = {
OutlinedButton(onClick = { onNoClicked() }) {
Text(
text = stringResource(id = R.string.no)
)
}
},
onDismissRequest = {
onNoClicked()
}
)
}
} | 0 | Kotlin | 0 | 2 | ffbab9c08d2446b24d45282489f218580eb7ecfa | 1,591 | AndroidAdvance | MIT License |
app/src/commonMain/kotlin/utils/math.kt | luca992 | 716,489,959 | false | {"Kotlin": 46440, "HTML": 359, "CSS": 108} | package utils
import com.ionspin.kotlin.bignum.decimal.BigDecimal
import kotlin.math.pow
fun normalizeDenom(amount: BigDecimal, decimals: UInt): BigDecimal {
return amount.divide(BigDecimal.fromDouble(10.0.pow(decimals.toInt())))
} | 0 | Kotlin | 0 | 1 | ac2c3b226f059f250190bff932891b4e0667fbcb | 238 | sienna-lend-liquidator | MIT License |
demo-projects/arrow-books-library/src/main/kotlin/org/jesperancinha/arrow/books/Coroutines.kt | jesperancinha | 565,555,551 | false | {"Kotlin": 120934, "Makefile": 21000, "Java": 7568, "Scala": 3899, "Shell": 3824, "Fortran": 3072, "Common Lisp": 2510, "COBOL": 2254, "Clojure": 2232, "Haskell": 1370, "Scheme": 870, "Go": 709, "Dockerfile": 700, "Standard ML": 644, "Erlang": 522, "C": 438} | package org.jesperancinha.arrow.books
import arrow.core.merge
import arrow.fx.coroutines.parMap
import arrow.fx.coroutines.parZip
import arrow.fx.coroutines.raceN
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import java.util.*
class Coroutines {
companion object {
@JvmStatic
fun main(args: Array<String> = emptyArray()) = runBlocking {
printSeparator("Coroutines Test 1 - parZip")
println(getClient(1000))
printSeparator("Coroutines Test 2 - parMap")
println(getAssociateNames(1000))
printSeparator("Coroutines Test 2 - raceN")
println(fetchLetter())
printSeparator("Coroutines Test 2 - raceN - Both Fail")
println(fetchLetterFail())
}
suspend fun getClient(id: Long): Book =
parZip(
{ getName(id) },
{ getTelephoneNumber(id) }
) { name, telephoneNumber -> Book(name, telephoneNumber) }
fun getName(id: Long) = "client($id)-${UUID.randomUUID()}"
fun getTelephoneNumber(id: Long) =
(1..5).map { (Random().nextLong(10) + id).toString().last() }.joinToString("").toLong()
suspend fun getAssociateNames(id: Long): List<String> =
getAssociates(id).parMap { getName(it) }
private fun getAssociates(id: Long): List<Long> {
return (1..5).map { Random().nextLong() + id }
}
suspend fun fetchLetter() =
raceN(
{ getA() },
{ getB() }
).merge()
suspend fun fetchLetterFail() = runCatching {
raceN(
{
getA()
throw RuntimeException("Major Fail A")
},
{
getB()
throw RuntimeException("Major Fail B")
},
).merge()
}
suspend fun getA() = delay(Random().nextLong(100)).run { "A" }
suspend fun getB() = delay(Random().nextLong(100)).run { "B" }
}
} | 0 | Kotlin | 0 | 0 | 12776bf0cfb06eb07b3e9d455550256d6dcc7b6e | 2,098 | asnsei-the-right-waf | Apache License 2.0 |
kotlin-browser/src/main/generated/canvas/CanvasImageData.kt | stefanthaler | 440,580,782 | true | {"Kotlin": 8815376, "JavaScript": 528} | // Automatically generated - do not modify!
package canvas
typealias CanvasImageData = org.w3c.dom.CanvasImageData
| 0 | Kotlin | 0 | 0 | fc27a2b5d98423c8db24f8a28d1c3a95dc682b0a | 117 | kotlin-wrappers | Apache License 2.0 |
data/RF00461/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF00461"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
2 to 3
35 to 36
}
value = "#dea4e1"
}
color {
location {
6 to 8
31 to 33
}
value = "#11b6a0"
}
color {
location {
10 to 12
27 to 29
}
value = "#238455"
}
color {
location {
13 to 15
22 to 24
}
value = "#1cdb26"
}
color {
location {
48 to 49
314 to 315
}
value = "#9395bf"
}
color {
location {
51 to 52
311 to 312
}
value = "#276224"
}
color {
location {
55 to 56
308 to 309
}
value = "#1522dc"
}
color {
location {
58 to 59
300 to 301
}
value = "#51feb5"
}
color {
location {
62 to 65
291 to 294
}
value = "#4e1ada"
}
color {
location {
70 to 75
278 to 283
}
value = "#b8c4cb"
}
color {
location {
76 to 77
275 to 276
}
value = "#60f757"
}
color {
location {
79 to 82
271 to 274
}
value = "#f5b1e3"
}
color {
location {
91 to 96
262 to 267
}
value = "#19fa49"
}
color {
location {
101 to 102
249 to 250
}
value = "#f5f7a1"
}
color {
location {
103 to 108
242 to 247
}
value = "#79f2f6"
}
color {
location {
111 to 113
238 to 240
}
value = "#602f52"
}
color {
location {
116 to 118
163 to 165
}
value = "#dfacd9"
}
color {
location {
120 to 122
160 to 162
}
value = "#300a32"
}
color {
location {
123 to 125
156 to 158
}
value = "#40cc5e"
}
color {
location {
126 to 129
151 to 154
}
value = "#837bf7"
}
color {
location {
130 to 131
148 to 149
}
value = "#ff111d"
}
color {
location {
133 to 136
142 to 145
}
value = "#044e70"
}
color {
location {
167 to 169
235 to 237
}
value = "#d973fc"
}
color {
location {
173 to 178
229 to 234
}
value = "#5af2fb"
}
color {
location {
181 to 186
217 to 222
}
value = "#ca07d8"
}
color {
location {
187 to 189
213 to 215
}
value = "#9c3c81"
}
color {
location {
191 to 192
209 to 210
}
value = "#da3bc5"
}
color {
location {
193 to 195
205 to 207
}
value = "#a67f9f"
}
color {
location {
4 to 5
34 to 34
}
value = "#1a5c26"
}
color {
location {
9 to 9
30 to 30
}
value = "#aa2f5a"
}
color {
location {
13 to 12
25 to 26
}
value = "#a14eec"
}
color {
location {
16 to 21
}
value = "#c50e03"
}
color {
location {
50 to 50
313 to 313
}
value = "#f6d699"
}
color {
location {
53 to 54
310 to 310
}
value = "#e97bed"
}
color {
location {
57 to 57
302 to 307
}
value = "#a48af7"
}
color {
location {
60 to 61
295 to 299
}
value = "#386730"
}
color {
location {
66 to 69
284 to 290
}
value = "#a85268"
}
color {
location {
76 to 75
277 to 277
}
value = "#b15006"
}
color {
location {
78 to 78
275 to 274
}
value = "#deffa8"
}
color {
location {
83 to 90
268 to 270
}
value = "#a03b01"
}
color {
location {
97 to 100
251 to 261
}
value = "#43457d"
}
color {
location {
103 to 102
248 to 248
}
value = "#9ae7a6"
}
color {
location {
109 to 110
241 to 241
}
value = "#6440ff"
}
color {
location {
114 to 115
166 to 166
238 to 237
}
value = "#bc7273"
}
color {
location {
119 to 119
163 to 162
}
value = "#d55a0b"
}
color {
location {
123 to 122
159 to 159
}
value = "#6dd028"
}
color {
location {
126 to 125
155 to 155
}
value = "#e4b5f6"
}
color {
location {
130 to 129
150 to 150
}
value = "#2edaeb"
}
color {
location {
132 to 132
146 to 147
}
value = "#068c7e"
}
color {
location {
137 to 141
}
value = "#487cfd"
}
color {
location {
170 to 172
235 to 234
}
value = "#4663eb"
}
color {
location {
179 to 180
223 to 228
}
value = "#e3f633"
}
color {
location {
187 to 186
216 to 216
}
value = "#068f90"
}
color {
location {
190 to 190
211 to 212
}
value = "#c1e55b"
}
color {
location {
193 to 192
208 to 208
}
value = "#84d24a"
}
color {
location {
196 to 204
}
value = "#08d2e9"
}
color {
location {
1 to 1
}
value = "#4191cd"
}
color {
location {
37 to 47
}
value = "#1e9a0f"
}
color {
location {
316 to 316
}
value = "#54e09d"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 8,856 | Rfam-for-RNArtist | MIT License |
authenticator/src/main/java/com/amplifyframework/ui/authenticator/ui/SignInConfirmTotpCode.kt | aws-amplify | 490,439,616 | false | {"Kotlin": 506954, "Java": 41586, "C++": 26045, "CMake": 1057} | package com.amplifyframework.ui.authenticator.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import com.amplifyframework.ui.authenticator.R
import com.amplifyframework.ui.authenticator.SignInConfirmTotpCodeState
import com.amplifyframework.ui.authenticator.enums.AuthenticatorStep
import kotlinx.coroutines.launch
@Composable
fun SignInConfirmTotpCode(
state: SignInConfirmTotpCodeState,
modifier: Modifier = Modifier,
headerContent: @Composable (state: SignInConfirmTotpCodeState) -> Unit = {
AuthenticatorTitle(stringResource(R.string.amplify_ui_authenticator_title_signin_confirm_totp))
},
footerContent: @Composable (state: SignInConfirmTotpCodeState) -> Unit = {
SignInConfirmTotpCodeFooter(state = it)
}
) {
val scope = rememberCoroutineScope()
Column(
modifier = modifier
.fillMaxWidth()
.padding(horizontal = 16.dp)
) {
headerContent(state)
Text(
modifier = Modifier.padding(bottom = 16.dp),
text = stringResource(R.string.amplify_ui_authenticator_enter_totp_code)
)
AuthenticatorForm(
state = state.form
)
AuthenticatorButton(
modifier = modifier.testTag(TestTags.SignInConfirmButton),
onClick = { scope.launch { state.confirmSignIn() } },
loading = !state.form.enabled
)
footerContent(state)
}
}
@Composable
fun SignInConfirmTotpCodeFooter(
state: SignInConfirmTotpCodeState,
modifier: Modifier = Modifier
) = BackToSignInFooter(
modifier = modifier,
onClickBackToSignIn = { state.moveTo(AuthenticatorStep.SignIn) }
)
| 4 | Kotlin | 4 | 9 | eb3979b6b58fdc94f9f3b61043310a8233abb21b | 2,079 | amplify-ui-android | Apache License 2.0 |
app/src/main/java/com/istu/schedule/ui/page/onboarding/OnBoardingPage.kt | imysko | 498,018,609 | false | null | package com.istu.schedule.ui.page.onboarding
import android.util.Log
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.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Surface
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.istu.schedule.R
import com.istu.schedule.data.preference.OnBoardingState
import com.istu.schedule.ui.components.base.button.FilledButton
import com.istu.schedule.ui.components.base.button.OutlineButton
import com.istu.schedule.ui.theme.GrayDisabled
import com.istu.schedule.ui.theme.ScheduleISTUTheme
import com.istu.schedule.util.NavDestinations
import com.istu.schedule.util.collectAsStateValue
@Composable
fun OnBoardingPage(
navController: NavHostController,
viewModel: OnBoardingViewModel = hiltViewModel()
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
val onBoardingUiState = viewModel.onBoardingUiState.collectAsStateValue()
Log.i("SILog", "onboarding page")
Surface(
color = MaterialTheme.colorScheme.background,
content = {
Column(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 15.dp),
verticalArrangement = Arrangement.SpaceBetween
) {
Row() {
when (onBoardingUiState.pageNumber) {
1 -> {
OnBoardingContent(
painterResource = painterResource(id = R.drawable.look_schedule),
title = stringResource(id = R.string.look_schedule),
description = stringResource(
id = R.string.look_schedule_description
)
)
}
2 -> {
OnBoardingContent(
painterResource = painterResource(id = R.drawable.choose_project),
title = stringResource(id = R.string.choose_project),
description = stringResource(
id = R.string.choose_project_description
)
)
}
3 -> {
OnBoardingContent(
painterResource = painterResource(id = R.drawable.adjust_to_you),
title = stringResource(id = R.string.adjust_to_you),
description = stringResource(
id = R.string.adjust_to_you_description
)
)
}
4 -> {
OnBoardingContent(
painterResource = painterResource(
id = R.drawable.login_to_personal_account
),
title = stringResource(id = R.string.login_to_personal_account),
description = stringResource(
id = R.string.login_to_personal_account_description
)
)
}
}
}
Row(
modifier = Modifier.padding(bottom = 40.dp)
) {
Column(
verticalArrangement = Arrangement.spacedBy(25.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
horizontalArrangement = Arrangement.spacedBy(14.dp)
) {
for (i in 1..4) {
Box(
modifier = Modifier
.size(8.dp)
.clip(CircleShape)
.background(
if (onBoardingUiState.pageNumber == i) {
MaterialTheme.colorScheme.primary
} else {
GrayDisabled
}
)
)
}
}
Column(
verticalArrangement = Arrangement.spacedBy(8.dp)
) {
if (onBoardingUiState.isShowNextButton) {
FilledButton(
modifier = Modifier
.fillMaxWidth()
.height(52.dp),
text = stringResource(id = R.string.next_step),
onClick = { viewModel.onNextButtonClick() }
)
}
if (onBoardingUiState.isShowSkipSetupScheduleButton) {
OutlineButton(
modifier = Modifier
.fillMaxWidth()
.height(52.dp),
text = stringResource(id = R.string.skip_setting),
onClick = { viewModel.onSetupScheduleButtonClick() }
)
}
if (onBoardingUiState.isShowSetupScheduleButton) {
FilledButton(
modifier = Modifier
.fillMaxWidth()
.height(52.dp),
text = stringResource(id = R.string.setup_schedule),
onClick = {
viewModel.onSetupScheduleButtonClick()
navController.navigate(NavDestinations.BINDING_PAGE)
}
)
}
if (onBoardingUiState.isShowSkipAuthorizationButton) {
OutlineButton(
modifier = Modifier
.fillMaxWidth()
.height(52.dp),
text = stringResource(id = R.string.skip),
onClick = {
OnBoardingState.isNotFirstLaunch.put(context, scope)
navController.navigate(NavDestinations.MAIN_PAGE)
}
)
}
if (onBoardingUiState.isShowAuthorizationButton) {
FilledButton(
modifier = Modifier
.fillMaxWidth()
.height(52.dp),
text = stringResource(id = R.string.login_campus),
onClick = {
OnBoardingState.isNotFirstLaunch.put(context, scope)
viewModel.onAuthorizationButtonClick()
navController.navigate(NavDestinations.PROJFAIR_LOGIN_PAGE)
}
)
}
if (onBoardingUiState.canNavigateToMainPage) {
FilledButton(
modifier = Modifier
.fillMaxWidth()
.height(52.dp),
text = stringResource(id = R.string.next_step),
onClick = { navController.navigate(NavDestinations.MAIN_PAGE) }
)
}
}
}
}
}
}
)
}
@Composable
@Preview(showBackground = true, locale = "ru")
fun OnBoardingPagePreview() {
ScheduleISTUTheme {
OnBoardingPage(navController = rememberNavController())
}
}
| 0 | Kotlin | 0 | 1 | 3dd025585d9e738468117146bcf881209030fde7 | 9,966 | Schedule-ISTU | MIT License |
app/src/main/java/com/ali/filmrent/dataClass/Customer.kt | Alibalvardi | 740,135,480 | false | {"Kotlin": 200312} | package com.ali.filmrent.dataClass
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "customer")
data class Customer(
@PrimaryKey(autoGenerate = true)
val customer_id: Int? = null,
val firstname: String,
val lastname: String,
val phoneNumber: String,
val email: String,
val username: String,
val password: String,
val wallet : Int
)
| 0 | Kotlin | 0 | 0 | e335ae184e3776a068d96f266da5bab0a2bc212f | 401 | FilmRent | MIT License |
test/resources/uses_self_file_name.kts | holgerbrandl | 53,889,290 | false | null | #!/usr/bin/env kscript
println("Usage: ${System.getenv("KSCRIPT_FILE")} [-ae] [--foo] file+") | 34 | Kotlin | 113 | 1,751 | dc827753adf707cf31cd220716e85139cae2d9cd | 93 | kscript | MIT License |
app/src/test/java/com/mmdev/kudago/app/TestExtensions.kt | muramrr | 259,294,007 | 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.
*/
package com.mmdev.kudago.app
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import java.io.File
import java.net.HttpURLConnection
/**
* This is the documentation block about the class
*/
fun MockWebServer.mockHttpResponse(body: String, responseCode: Int = HttpURLConnection.HTTP_OK) =
this.enqueue(MockResponse()
.setResponseCode(responseCode)
.setBody(body)
)
fun readJson(fileName: String) = File("src/test/java/com/mmdev/kudago/app/res/$fileName").readText() | 0 | Kotlin | 0 | 4 | a41341a5c08e4a49dcd98ec56d3fec7fcb5954d6 | 1,136 | Kudago-Application | Apache License 2.0 |
app/src/test/java/com/mmdev/kudago/app/TestExtensions.kt | muramrr | 259,294,007 | 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.
*/
package com.mmdev.kudago.app
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import java.io.File
import java.net.HttpURLConnection
/**
* This is the documentation block about the class
*/
fun MockWebServer.mockHttpResponse(body: String, responseCode: Int = HttpURLConnection.HTTP_OK) =
this.enqueue(MockResponse()
.setResponseCode(responseCode)
.setBody(body)
)
fun readJson(fileName: String) = File("src/test/java/com/mmdev/kudago/app/res/$fileName").readText() | 0 | Kotlin | 0 | 4 | a41341a5c08e4a49dcd98ec56d3fec7fcb5954d6 | 1,136 | Kudago-Application | Apache License 2.0 |
app/src/test/java/fr/nihilus/music/ui/AlphaIndexerSpecification.kt | ismailghedamsi | 322,889,723 | true | {"Kotlin": 987508, "Prolog": 57} | /*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.nihilus.music.ui
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.google.common.collect.BoundType
import com.google.common.collect.Range
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import com.google.common.truth.TruthJUnit.assume
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Suite
import org.robolectric.RobolectricTestRunner
@RunWith(Suite::class)
@Suite.SuiteClasses(
WithNoItem::class,
WithOneItemPerSection::class,
WithSameFirstLetter::class,
WithNonLetterItems::class,
WithDiacriticsItems::class,
WithLeadingCommonEnglishPrefixes::class,
WithUnexpectedItems::class,
WithLotsOfItemsPerSection::class,
WithLotsOfItemsPerSectionAndSpecialChars::class
)
class AlphaIndexerSpecification
@RunWith(AndroidJUnit4::class)
class WithNoItem {
private lateinit var indexer: AlphaSectionIndexer
@Before
fun whenInitialized() {
indexer = AlphaSectionIndexer()
}
@Test
fun itShouldHaveNoSections() {
assertThat(indexer.sections).isEmpty()
}
@Test
fun itShouldAlwaysReturnSectionZero() {
assertThat(indexer.getSectionForPosition(0)).isEqualTo(0)
assertThat(indexer.getSectionForPosition(2)).isEqualTo(0)
assertThat(indexer.getSectionForPosition(5)).isEqualTo(0)
}
@Test(expected = IndexOutOfBoundsException::class)
fun itShouldFailWhenRequestingAnyPositionForSection() {
indexer.getPositionForSection(0)
}
}
@RunWith(RobolectricTestRunner::class)
class WithOneItemPerSection : ItemBasedIndexerScenario() {
override val items = listOf(
"Another One Bites the Dust",
"Black Betty",
"Come As You Are",
"Get Lucky",
"Hysteria",
"Supermassive Black Hole"
)
@Test
fun itShouldHaveOneSectionPerItem() {
assertThat(indexer.sections).asList().containsExactly("A", "B", "C", "G", "H", "S").inOrder()
}
@Test
fun itShouldMapPositionToCorrespondingSection() {
assume().that(indexer.sections).asList().containsExactly("A", "B", "C", "G", "H", "S").inOrder()
// [0] "Another One Bites the Dust" -> Section [0] "A"
assertItemInSection(0, 0)
// [1] "Black Betty" -> Section [1] "B"
assertItemInSection(1, 1)
// [2] "Come As You Are" -> Section [2] "C"
assertItemInSection(2, 2)
// [3] "Get Lucky" -> Section [3] "G"
assertItemInSection(3, 3)
// [4] "Hysteria" -> Section [4] "H"
assertItemInSection(4, 4)
// [5] "Supermassive Black Hole" -> Section [5] "S"
assertItemInSection(5, 5)
}
@Test
fun itShouldReturnSectionForPosition() {
assume().that(indexer.sections).asList().containsExactly("A", "B", "C", "G", "H", "S").inOrder()
assertSectionStartsAtPosition(0, 0)
assertSectionStartsAtPosition(1, 1)
assertSectionStartsAtPosition(2, 2)
assertSectionStartsAtPosition(3, 3)
assertSectionStartsAtPosition(4, 4)
assertSectionStartsAtPosition(5, 5)
}
}
@RunWith(RobolectricTestRunner::class)
class WithSameFirstLetter : ItemBasedIndexerScenario() {
override val items = listOf(
"Another One Bites the Dust",
"Back in Black",
"Black Betty",
"Beat It",
"Come As You Are",
"Hell's Bells",
"Hysteria",
"Something Human",
"Supermassive Black Hole"
)
@Test
fun itShouldNotHaveDuplicateSections() {
assertThat(indexer.sections).asList().containsExactly("A", "B", "C", "H", "S").inOrder()
}
@Test
fun itShouldGroupItemsStartingWithSameLetterUnderSameSection() {
assume().that(indexer.sections).asList().containsExactly("A", "B", "C", "H", "S").inOrder()
// [0] "Another One Bites the Dust" -> Section [0] "A"
assertItemInSection(0, 0)
// [1] "Back in Black" -> Section [1] "B"
assertItemInSection(1, 1)
// [2] "Black Betty" -> Section [1] "B"
assertItemInSection(2, 1)
// [3] "Beat It" -> Section [1] "B"
assertItemInSection(3, 1)
// [4] "Come As You Are" -> Section [2] "C"
assertItemInSection(4, 2)
// [5] "Hell's Bells" -> Section [3] "H"
assertItemInSection(5, 3)
// [6] "Hysteria" -> Section [3] "H"
assertItemInSection(6, 3)
// [7] "Something Human" -> Section [4] "S"
assertItemInSection(5, 3)
// [8] "Supermassive Black Hole" -> Section [4] "S"
assertItemInSection(5, 3)
}
@Test
fun itShouldReturnPositionOfFirstItemOfSection() {
assume().that(indexer.sections).asList().containsExactly("A", "B", "C", "H", "S").inOrder()
// Section [0] "A" starts at [0] "Another One Bites the Dust"
assertSectionStartsAtPosition(0, 0)
// Section [1] "B" starts at [1] "Back in Black"
assertSectionStartsAtPosition(1, 1)
// Section [2] "C" starts at [4] "Come As You Are"
assertSectionStartsAtPosition(2, 4)
// Section [3] "H" starts at [5] "Hells Bells"
assertSectionStartsAtPosition(3, 5)
// Section [4] "S" starts at [7] "Something Human"
assertSectionStartsAtPosition(4, 7)
}
}
@RunWith(RobolectricTestRunner::class)
class WithNonLetterItems : ItemBasedIndexerScenario() {
override val items = listOf(
"[F]",
"10 Years Today",
"Another One Bites The Dust",
"Get Lucky"
)
@Test
fun itShouldHaveLeadingSharpSection() {
assertThat(indexer.sections).isNotEmpty()
assertThat(indexer.sections.first()).isEqualTo("#")
}
@Test
fun itShouldAlsoHaveLetterSectionsForOtherItems() {
assertThat(indexer.sections).asList().containsExactly("#", "A", "G").inOrder()
}
@Test
fun itShouldPutNonLetterItemsInSharpSection() {
// [0] "[F]" -> Section [0] "#"
assertItemInSection(0, 0)
// [1] "10 Years Today" -> [0] "#"
assertItemInSection(1, 0)
}
@Test
fun itsSharpSectionShouldStartAtFirstItem() {
assertSectionStartsAtPosition(0, 0)
}
}
@RunWith(AndroidJUnit4::class)
class WithDiacriticsItems : ItemBasedIndexerScenario() {
override val items = listOf(
"<NAME>",
"Ça (c'est vraiment toi)",
"Californication",
"<NAME>"
)
@Test
fun itShouldIgnoreDiacriticsInSectionNames() {
assertThat(indexer.sections).asList().containsExactly("A", "C", "E").inOrder()
}
@Test
fun itShouldPutDiacriticItemsInNonDiacriticSections() {
assume().that(indexer.sections).asList().containsExactly("A", "C", "E").inOrder()
assertItemInSection(0, 0)
assertItemInSection(1, 1)
assertItemInSection(2, 1)
assertItemInSection(3, 2)
}
@Test
fun itsSectionsMayStartByDiacriticItem() {
assume().that(indexer.sections).asList().containsExactly("A", "C", "E").inOrder()
assertSectionStartsAtPosition(0, 0)
assertSectionStartsAtPosition(1, 1)
assertSectionStartsAtPosition(2, 3)
}
}
@RunWith(AndroidJUnit4::class)
class WithLeadingCommonEnglishPrefixes : ItemBasedIndexerScenario() {
override val items = listOf(
"The 2nd Law: Isolated System",
"A Little Peace Of Heaven",
"The Sky Is A Neighborhood",
"Supermassive Black Hole",
"An Unexpected Journey"
)
@Test
fun itShouldCreateSectionFomUnprefixedItems() {
assertThat(indexer.sections).asList().containsExactly("#", "L", "S", "U")
}
@Test
fun itShouldPutPrefixedItemsInUnprefixedSections() {
assume().that(indexer.sections).asList().containsExactly("#", "L", "S", "U")
assertItemInSection(0, 0)
assertItemInSection(1, 1)
assertItemInSection(2, 2)
assertItemInSection(3, 2)
assertItemInSection(4, 3)
}
@Test
fun itsSectionsMayStartByPrefixedItem() {
assume().that(indexer.sections).asList().containsExactly("#", "L", "S", "U")
assertSectionStartsAtPosition(0, 0)
assertSectionStartsAtPosition(1, 1)
assertSectionStartsAtPosition(2, 2)
assertSectionStartsAtPosition(3, 4)
}
}
@RunWith(AndroidJUnit4::class)
class WithUnexpectedItems : ItemBasedIndexerScenario() {
override val items = listOf(
" \nHello World!",
"This",
"is",
"unsorted",
""
)
@Test
fun itShouldHaveCorrectAndSortedSections() {
assertThat(indexer.sections).asList().containsExactly("#", "H", "I", "T", "U").inOrder()
}
@Test
fun itShouldIgnoreLeadingWhitespaceCharacters() {
assume().that(indexer.sections).asList().containsExactly("#", "H", "I", "T", "U").inOrder()
// [0] "Hello World" with spaces -> Section [1] "H"
assertItemInSection(0, 1)
}
@Test
fun itShouldPutEmptyStringsInSharpSection() {
assume().that(indexer.sections).asList().containsExactly("#", "H", "I", "T", "U").inOrder()
// [4] "" -> Section [0] "#"
assertItemInSection(4, 0)
}
@Test
fun itShouldPutItemsInCorrectSections() {
assume().that(indexer.sections).asList().containsExactly("#", "H", "I", "T", "U").inOrder()
// [0] "Hello World" -> Section [1] "H"
assertItemInSection(0, 1)
// [1] "This" -> Section [3] "T"
assertItemInSection(1, 3)
// [2] "is" -> Section [2] "I"
assertItemInSection(2, 2)
// [3] "unsorted" -> Section [4] "U"
assertItemInSection(3, 4)
// [4] "" -> Section [0] "#"
assertItemInSection(4, 0)
}
@Test
fun itsSectionsShouldStartAtExistingPositions() {
val itemIndices = Range.range(0, BoundType.CLOSED, items.size, BoundType.OPEN)
for (sectionPosition in indexer.sections.indices) {
assertThat(indexer.getPositionForSection(sectionPosition)).isIn(itemIndices)
}
}
}
@RunWith(AndroidJUnit4::class)
class WithLotsOfItemsPerSection : ItemBasedIndexerScenario() {
override val items = listOf(
"<NAME>",
"Say Goodnight",
"Scream",
"Scream Aim Fire",
"Sean",
"See The Light",
"Session",
"Supermassive Black Hole",
"Supremacy",
"Survival",
"Symphony Of Destruction",
"T-Shirt",
"Teenagers",
"These Days",
"Through Glass",
"Throwdown",
"Thunderstruck",
"Time Is Running Out",
"T.N.T",
"Tribute"
)
@Test
fun itShouldCreateSubsectionsWhenTenOrMoreItemsPerSection() {
assertThat(indexer.sections).asList().containsExactly("SA", "SC", "SE", "SU", "SY", "T").inOrder()
}
@Test
fun itMapsItemsToCorrectSubsection() {
assume().that(indexer.sections).asList().containsExactly("SA", "SC", "SE", "SU", "SY", "T").inOrder()
assertItemInSection(0, 0)
assertItemInSection(1, 0)
assertItemInSection(2, 1)
assertItemInSection(3, 1)
assertItemInSection(4, 2)
assertItemInSection(5, 2)
assertItemInSection(6, 2)
assertItemInSection(7, 3)
assertItemInSection(8, 3)
assertItemInSection(9, 3)
assertItemInSection(10, 4)
}
@Test
fun itShouldReturnPositionOfFirstItemOfSubsection() {
assume().that(indexer.sections).asList().containsExactly("SA", "SC", "SE", "SU", "SY", "T").inOrder()
assertSectionStartsAtPosition(0, 0)
assertSectionStartsAtPosition(1, 2)
assertSectionStartsAtPosition(2, 4)
assertSectionStartsAtPosition(3, 7)
assertSectionStartsAtPosition(4, 10)
}
}
@RunWith(AndroidJUnit4::class)
class WithLotsOfItemsPerSectionAndSpecialChars : ItemBasedIndexerScenario() {
override val items = listOf(
"I Only Lie When I Love You",
"Ich Tu Dir Weh",
"Ich Will",
"If You Have Ghosts",
"If you Want Blood",
"I'm a Lady",
"I'm Going to Hello For This",
"Immortalized",
"In Loving Memory",
"Indestructible",
"Inside the Fire"
)
@Test
fun itShouldIgnoreSpecialCharsWhenCreatingSubsections() {
assertThat(indexer.sections).asList().containsExactly("I", "IC", "IF", "IM", "IN")
}
@Test
fun itMapsToCorrectSubsection() {
assume().that(indexer.sections).asList().containsExactly("I", "IC", "IF", "IM", "IN")
assertItemInSection(0, 0)
assertItemInSection(1, 1)
assertItemInSection(2, 1)
assertItemInSection(3, 2)
assertItemInSection(4, 2)
assertItemInSection(5, 3)
assertItemInSection(6, 3)
assertItemInSection(7, 3)
assertItemInSection(8, 4)
assertItemInSection(9, 4)
assertItemInSection(10, 4)
}
@Test
fun itShouldReturnPositionOfFirstItemOfSubsection() {
assume().that(indexer.sections).asList().containsExactly("I", "IC", "IF", "IM", "IN")
assertSectionStartsAtPosition(0, 0)
assertSectionStartsAtPosition(1, 1)
assertSectionStartsAtPosition(2, 3)
assertSectionStartsAtPosition(3, 5)
assertSectionStartsAtPosition(4, 8)
}
}
/**
* Describes a testing scenario where given items are loaded into the indexer.
*/
abstract class ItemBasedIndexerScenario {
/** The indexer under test, initialized with items. */
protected lateinit var indexer: AlphaSectionIndexer
/** The list of items that should be added into the [indexer]. */
protected abstract val items: List<String>
/**
* Initializes the indexer with the item provided by [items].
*/
@Before
fun setUp() {
indexer = AlphaSectionIndexer()
indexer.update(items.asSequence())
}
/**
* Assert that the indexer under test returns the [expectedItemPosition] for the given [sectionIndex].
* This is a helper function to test [AlphaSectionIndexer.getPositionForSection],
* printing a cleaner error message when the assertion fails.
*/
protected fun assertSectionStartsAtPosition(sectionIndex: Int, expectedItemPosition: Int) {
val actualItemPosition = indexer.getPositionForSection(sectionIndex)
assertWithMessage(
"Section '%s' should start at item [%s] '%s', but started at item [%s] '%s'",
indexer.sections[sectionIndex],
expectedItemPosition, items[expectedItemPosition],
actualItemPosition, items.getOrNull(actualItemPosition) ?: "<out of bound item>"
).that(actualItemPosition).isEqualTo(expectedItemPosition)
}
/**
* Assert that the item at [itemPosition] is sorted in the section at [expectedSectionIndex].
* This is a helper function to test [AlphaSectionIndexer.getSectionForPosition],
* printing a cleaner error message when the assertion fails.
*/
protected fun assertItemInSection(itemPosition: Int, expectedSectionIndex: Int) {
val sections = indexer.sections
val actualSectionIndex = indexer.getSectionForPosition(itemPosition)
assertWithMessage(
"Item [%s] '%s' should be in section '%s', but was in '%s'",
itemPosition,
items[itemPosition],
sections[expectedSectionIndex],
sections.getOrNull(actualSectionIndex) ?: "<out of bound section>"
).that(actualSectionIndex).isEqualTo(expectedSectionIndex)
}
}
| 0 | null | 0 | 0 | 6ae2682be14bb1914ec1ffd3ba07db8b3f1f81c3 | 16,205 | android-odeon | Apache License 2.0 |
app/src/main/java/com/xzwzz/writecharacter/MainActivity.kt | MyMrXu | 207,531,300 | false | null | package com.xzwzz.writecharacter
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.xzwzz.writecharacter.util.FontStrokeUtil
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private var autoDraw = false;
private var showMedian = false;
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
btn_character.setOnClickListener {
search(et_character.text.toString())
}
btn_auto.setOnClickListener {
autoDraw = !autoDraw
mChineseCharacterView.setAutoDraw(autoDraw)
mChineseCharacterView.redraw(false)
btn_auto.text = "自动绘制$autoDraw"
}
btn_median.setOnClickListener {
showMedian = !showMedian
mChineseCharacterView.setShowMedian(showMedian)
mChineseCharacterView.redraw(false)
btn_median.text = "显示中线$showMedian"
}
btn_auto.text = "自动绘制$autoDraw"
btn_median.text = "显示中线$showMedian"
}
private fun search(text: String) {
if (text.length > 1) {
Toast.makeText(this, "只能查询单个字", Toast.LENGTH_SHORT).show()
return
}
val bean = FontStrokeUtil.getInstance().query(text)
mChineseCharacterView.setStrokeInfo(bean.getStrokes()).setMedianPaths(bean.getMedians())
mChineseCharacterView.redraw(true)
}
}
| 1 | null | 15 | 55 | d503aeaf5cb317540af8c98ecbe67f73e3d9e46f | 1,546 | ChineseCharacterView | MIT License |
GaiaXAndroidDemo/app/src/main/kotlin/com/alibaba/gaiax/demo/StyleTemplateActivity.kt | alibaba | 456,772,654 | false | {"C": 3164040, "Kotlin": 1542817, "Rust": 1390378, "Objective-C": 919399, "Java": 650249, "JavaScript": 260489, "TypeScript": 229724, "C++": 223843, "CSS": 154159, "HTML": 113541, "MDX": 86833, "Objective-C++": 60116, "Swift": 25131, "Shell": 12787, "Makefile": 12210, "Ruby": 6268, "CMake": 4674, "Batchfile": 3816, "SCSS": 837} | package com.alibaba.gaiax.demo
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatButton
import androidx.appcompat.widget.LinearLayoutCompat
import com.alibaba.fastjson.JSONObject
import com.alibaba.gaiax.GXTemplateEngine
import com.alibaba.gaiax.utils.GXScreenUtils
class StyleTemplateActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_style_template)
renderTemplate1(this)
renderTemplate2(this)
renderTemplate3(this)
renderTemplate4(this)
}
override fun onDestroy() {
super.onDestroy()
GXTemplateEngine.instance.destroyView(findViewById<LinearLayoutCompat>(R.id.template_1))
}
private var count: Int = 0
private fun renderTemplate1(activity: StyleTemplateActivity) {
var view: View? = null
var templateData: GXTemplateEngine.GXTemplateData? = null
findViewById<AppCompatButton>(R.id.rebind1).setOnClickListener {
if (view != null && templateData != null) {
count++
templateData = createData()
GXTemplateEngine.instance.bindData(view!!, templateData!!)
}
}
// 初始化
GXTemplateEngine.instance.init(activity)
// 模板参数
val params = GXTemplateEngine.GXTemplateItem(
activity, "assets_data_source/templates", "gx-style-backdrop-filter"
)
// 模板绘制尺寸
val size = GXTemplateEngine.GXMeasureSize(GXScreenUtils.getScreenWidthPx(this), null)
// 模板数据
templateData = createData()
// 创建模板View
view = GXTemplateEngine.instance.createView(params, size)!!
// 绑定数据
GXTemplateEngine.instance.bindData(view, templateData!!)
// 插入模板View
findViewById<LinearLayoutCompat>(R.id.template_1).addView(view, 0)
}
private fun createData() = GXTemplateEngine.GXTemplateData(JSONObject().apply {
this["blur_text"] = "我是文本我是文本我是文本我是文本我是文本"
if (count % 2 == 0) {
this["img"] =
"https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fup.enterdesk.com%2Fphoto%2F2011-10-14%2Fenterdesk.com-2E8A38D0891116035E78DD713EED9637.jpg&refer=http%3A%2F%2Fup.enterdesk.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1666781857&t=595349c20a2e34ceddbd48b130339fbf"
} else {
this["img"] =
"https://gw.alicdn.com/imgextra/i1/O1CN01KbLBlr1SmrmfDeShB_!!6000000002290-2-tps-1500-756.png"
}
})
private fun renderTemplate2(activity: StyleTemplateActivity) {
var view: View? = null
var templateData: GXTemplateEngine.GXTemplateData? = null
findViewById<AppCompatButton>(R.id.rebind2).setOnClickListener {
if (view != null && templateData != null) {
count++
templateData = createData()
GXTemplateEngine.instance.bindData(view!!, templateData!!)
}
}
// 初始化
GXTemplateEngine.instance.init(activity)
// 模板参数
val params = GXTemplateEngine.GXTemplateItem(
activity, "assets_data_source/templates", "gx-style-animation-prop"
)
// 模板绘制尺寸
val size = GXTemplateEngine.GXMeasureSize(GXScreenUtils.getScreenWidthPx(this), null)
// 模板数据
templateData = GXTemplateEngine.GXTemplateData(JSONObject())
// 创建模板View
view = GXTemplateEngine.instance.createView(params, size)!!
// 绑定数据
GXTemplateEngine.instance.bindData(view, templateData!!)
// 插入模板View
findViewById<LinearLayoutCompat>(R.id.template_2).addView(view, 0)
}
private fun renderTemplate3(activity: StyleTemplateActivity) {
var view: View? = null
var templateData: GXTemplateEngine.GXTemplateData? = null
// 初始化
GXTemplateEngine.instance.init(activity)
// 模板参数
val params = GXTemplateEngine.GXTemplateItem(
activity, "assets_data_source/templates", "gx-style-animation-lottie-remote"
)
// 模板绘制尺寸
val size = GXTemplateEngine.GXMeasureSize(GXScreenUtils.getScreenWidthPx(this), null)
// 模板数据
templateData = GXTemplateEngine.GXTemplateData(JSONObject())
// 创建模板View
view = GXTemplateEngine.instance.createView(params, size)!!
// 绑定数据
GXTemplateEngine.instance.bindData(view, templateData)
// 插入模板View
findViewById<LinearLayoutCompat>(R.id.template_3).addView(view, 0)
}
private fun renderTemplate4(activity: StyleTemplateActivity) {
var view: View? = null
var templateData: GXTemplateEngine.GXTemplateData? = null
// 初始化
GXTemplateEngine.instance.init(activity)
// 模板参数
val params = GXTemplateEngine.GXTemplateItem(
activity, "assets_data_source/templates", "gx-style-animation-lottie-local"
)
// 模板绘制尺寸
val size = GXTemplateEngine.GXMeasureSize(GXScreenUtils.getScreenWidthPx(this), null)
// 模板数据
templateData = GXTemplateEngine.GXTemplateData(JSONObject())
// 创建模板View
view = GXTemplateEngine.instance.createView(params, size)!!
// 绑定数据
GXTemplateEngine.instance.bindData(view, templateData)
// 插入模板View
findViewById<LinearLayoutCompat>(R.id.template_4).addView(view, 0)
}
}
| 27 | C | 118 | 950 | 125d0cd701adb58ec7ae5e719d3939cd2c5aee5b | 5,580 | GaiaX | Apache License 2.0 |
v2-model/src/commonMain/kotlin/com/bselzer/gw2/v2/model/pvp/amulet/PvpAmulet.kt | Woody230 | 388,820,096 | false | {"Kotlin": 750899} | package com.bselzer.gw2.v2.model.pvp.amulet
import com.bselzer.gw2.v2.model.enumeration.wrapper.AttributeName
import com.bselzer.gw2.v2.model.wrapper.ImageLink
import com.bselzer.ktx.value.identifier.Identifiable
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class PvpAmulet(
@SerialName("id")
override val id: PvpAmuletId = PvpAmuletId(),
@SerialName("name")
val name: String = "",
@SerialName("icon")
val iconLink: ImageLink = ImageLink(),
/**
* The name of the attribute mapped to the amount it is increased by.
*/
@SerialName("attributes")
val attributes: Map<AttributeName, Int> = emptyMap()
) : Identifiable<PvpAmuletId, Int> | 2 | Kotlin | 0 | 2 | 32f1fd4fc4252dbe886b6fc0f4310cf34ac2ef27 | 737 | GW2Wrapper | Apache License 2.0 |
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/small/FastForwardSmall.kt | SchweizerischeBundesbahnen | 853,290,161 | false | {"Kotlin": 6728512} | package ch.sbb.compose_mds.sbbicons.small
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import ch.sbb.compose_mds.sbbicons.SmallGroup
public val SmallGroup.FastForwardSmall: ImageVector
get() {
if (_fastForwardSmall != null) {
return _fastForwardSmall!!
}
_fastForwardSmall = Builder(name = "FastForwardSmall", defaultWidth = 24.0.dp, defaultHeight
= 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveToRelative(4.0f, 4.522f)
lineToRelative(0.793f, 0.573f)
lineToRelative(4.5f, 3.25f)
lineToRelative(0.707f, 0.51f)
verticalLineTo(4.522f)
lineToRelative(0.793f, 0.573f)
lineToRelative(4.5f, 3.25f)
lineToRelative(4.5f, 3.25f)
lineToRelative(0.561f, 0.405f)
lineToRelative(-0.561f, 0.405f)
lineToRelative(-4.5f, 3.25f)
lineToRelative(-4.5f, 3.25f)
lineToRelative(-0.793f, 0.573f)
verticalLineToRelative(-4.334f)
lineToRelative(-0.707f, 0.511f)
lineToRelative(-4.5f, 3.25f)
lineToRelative(-0.793f, 0.573f)
verticalLineTo(4.522f)
moveToRelative(1.0f, 1.956f)
verticalLineToRelative(11.044f)
lineToRelative(3.707f, -2.677f)
lineToRelative(1.5f, -1.084f)
lineToRelative(0.793f, -0.573f)
verticalLineToRelative(4.334f)
lineToRelative(3.707f, -2.677f)
lineTo(18.646f, 12.0f)
lineToRelative(-3.939f, -2.845f)
lineTo(11.0f, 6.478f)
verticalLineToRelative(4.333f)
lineToRelative(-0.793f, -0.573f)
lineToRelative(-1.5f, -1.083f)
close()
}
}
.build()
return _fastForwardSmall!!
}
private var _fastForwardSmall: ImageVector? = null
| 0 | Kotlin | 0 | 1 | 090a66a40e1e5a44d4da6209659287a68cae835d | 2,712 | mds-android-compose | MIT License |
sdkpushexpress/src/main/java/com/pushexpress/sdk/retrofit/RetrofitBuilder.kt | pushexpress | 600,907,986 | false | null | package com.pushexpress.sdk.retrofit
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.security.KeyStore
import java.util.*
import java.util.concurrent.TimeUnit
import javax.net.ssl.*
internal class RetrofitBuilder(commonUrl: String) {
private var retrofit: Retrofit
var sdkService: ApiService
private set
init {
retrofit = Retrofit.Builder()
.client(getUnsafeOkHttpClient())
.baseUrl(commonUrl)
.addConverterFactory(GsonConverterFactory.create())
.build()
sdkService = retrofit.create(ApiService::class.java)
}
private fun getUnsafeOkHttpClient(): OkHttpClient {
val trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(null as KeyStore?)
val trustManagers = trustManagerFactory.trustManagers
check(!(trustManagers.size != 1 || trustManagers[0] !is X509TrustManager)) {
"Unexpected default trust managers:" + Arrays.toString(
trustManagers
)
}
val trustManager = trustManagers[0] as X509TrustManager
val sslContext = SSLContext.getInstance("TLSv1.2")
sslContext.init(null, arrayOf<TrustManager>(trustManager), java.security.SecureRandom())
val sslSocketFactory = sslContext.socketFactory
return OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.retryOnConnectionFailure(true)
.followRedirects(true)
.followSslRedirects(true)
.hostnameVerifier { hostname, session -> true }
.sslSocketFactory(sslSocketFactory, trustManager).build()
}
} | 0 | Kotlin | 0 | 3 | 69ec0acc519cf805447e76745a7e3f868aedd173 | 1,885 | pushexpress-android-sdk | Apache License 2.0 |
ui/src/androidMain/kotlin/kiwi/orbit/compose/ui/controls/LinearIndeterminateProgressIndicator.kt | kiwicom | 289,355,053 | false | {"Kotlin": 908772, "Shell": 1833, "CSS": 443} | package kiwi.orbit.compose.ui.controls
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.unit.dp
import kiwi.orbit.compose.ui.OrbitTheme
import kiwi.orbit.compose.ui.controls.internal.OrbitPreviews
import kiwi.orbit.compose.ui.controls.internal.Preview
/**
* Linear indeterminate progress indicator.
*
* Renders indeterminate progress indicator maximum available width.
* To change the height or width, pass [modifier] with custom sizing.
*/
@Composable
public fun LinearIndeterminateProgressIndicator(
modifier: Modifier = Modifier,
color: Color = OrbitTheme.colors.primary.strong,
backgroundColor: Color = OrbitTheme.colors.surface.normal,
) {
androidx.compose.material3.LinearProgressIndicator(
modifier = modifier.fillMaxWidth(),
color = color,
trackColor = backgroundColor,
strokeCap = StrokeCap.Round,
)
}
@OrbitPreviews
@Composable
internal fun LinearIndeterminateProgressIndicatorPreview() {
Preview {
Column(
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier.padding(8.dp),
) {
LinearIndeterminateProgressIndicator()
LinearIndeterminateProgressIndicator(
color = OrbitTheme.colors.success.normal,
backgroundColor = OrbitTheme.colors.surface.subtle,
)
LinearIndeterminateProgressIndicator(
modifier = Modifier.height(6.dp),
color = OrbitTheme.colors.primary.normal,
backgroundColor = OrbitTheme.colors.primary.subtle,
)
}
}
}
| 19 | Kotlin | 17 | 97 | 6d4026eef9fa059388c50cd9e9760d593c3ad6ac | 2,012 | orbit-compose | MIT License |
app/src/main/java/openfoodfacts/github/scrachx/openfood/features/compare/ProductCompareAdapter.kt | oona988 | 333,890,968 | false | null | /*
* Copyright 2016-2020 Open Food Facts
*
* 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 openfoodfacts.github.scrachx.openfood.features.compare
import android.Manifest.permission
import android.app.Activity
import android.content.pm.PackageManager
import android.os.Build
import android.text.SpannableStringBuilder
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.text.bold
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.afollestad.materialdialogs.MaterialDialog
import com.squareup.picasso.Picasso
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.rxkotlin.toObservable
import io.reactivex.schedulers.Schedulers
import openfoodfacts.github.scrachx.openfood.AppFlavors
import openfoodfacts.github.scrachx.openfood.AppFlavors.OPF
import openfoodfacts.github.scrachx.openfood.AppFlavors.isFlavors
import openfoodfacts.github.scrachx.openfood.R
import openfoodfacts.github.scrachx.openfood.databinding.ProductComparisonListItemBinding
import openfoodfacts.github.scrachx.openfood.features.FullScreenActivityOpener
import openfoodfacts.github.scrachx.openfood.features.shared.adapters.NutrientLevelListAdapter
import openfoodfacts.github.scrachx.openfood.images.ProductImage
import openfoodfacts.github.scrachx.openfood.models.*
import openfoodfacts.github.scrachx.openfood.network.OpenFoodAPIClient
import openfoodfacts.github.scrachx.openfood.repositories.ProductRepository
import openfoodfacts.github.scrachx.openfood.utils.*
import pl.aprilapps.easyphotopicker.EasyImage
import java.io.File
class ProductCompareAdapter(
private val productsToCompare: List<Product>,
internal val activity: Activity,
private val client: OpenFoodAPIClient,
private val productRepository: ProductRepository,
private val picasso: Picasso
) : RecyclerView.Adapter<ProductComparisonViewHolder>() {
private val addProductButton = activity.findViewById<Button>(R.id.product_comparison_button)
private val disp = CompositeDisposable()
private val viewHolders = mutableListOf<ProductComparisonViewHolder>()
private var onPhotoReturnPosition: Int? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductComparisonViewHolder {
val binding = ProductComparisonListItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
val viewHolder = ProductComparisonViewHolder(binding)
viewHolders.add(viewHolder)
return viewHolder
}
override fun onBindViewHolder(holder: ProductComparisonViewHolder, position: Int) {
if (productsToCompare.isEmpty()) {
holder.binding.productComparisonListItemLayout.visibility = View.GONE
return
}
// Support synchronous scrolling
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
holder.binding.productComparisonListItemLayout.setOnScrollChangeListener { _, scrollX, scrollY, _, _ ->
viewHolders.forEach { it.binding.productComparisonListItemLayout.scrollTo(scrollX, scrollY) }
}
}
val product = productsToCompare[position]
// Set the visibility of UI components
holder.binding.productComparisonName.visibility = View.VISIBLE
holder.binding.productComparisonQuantity.visibility = View.VISIBLE
holder.binding.productComparisonBrand.visibility = View.VISIBLE
// if the flavor is OpenProductsFacts hide the additives card
if (isFlavors(OPF)) {
holder.binding.productComparisonAdditive.visibility = View.GONE
}
// Modify the text on the button for adding products
addProductButton?.setText(R.string.add_another_product)
// Image
val imageUrl = product.getImageUrl(LocaleHelper.getLanguage(activity))
holder.binding.productComparisonImage.setOnClickListener {
if (imageUrl != null) {
FullScreenActivityOpener.openForUrl(
activity,
client,
product,
ProductImageField.FRONT,
imageUrl,
holder.binding.productComparisonImage
)
} else {
// take a picture
if (ContextCompat.checkSelfPermission(activity, permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, arrayOf(permission.CAMERA), MY_PERMISSIONS_REQUEST_CAMERA)
} else {
onPhotoReturnPosition = position
if (isHardwareCameraInstalled(activity)) {
EasyImage.openCamera(activity, 0)
} else {
EasyImage.openGallery(activity, 0, false)
}
}
}
}
if (!imageUrl.isNullOrBlank()) {
holder.binding.productComparisonLabel.visibility = View.INVISIBLE
if (!activity.isLowBatteryMode()) {
picasso.load(imageUrl).into(holder.binding.productComparisonImage)
} else {
holder.binding.productComparisonImage.visibility = View.GONE
}
}
// Name
if (!product.productName.isNullOrBlank()) {
holder.binding.productComparisonName.text = product.productName
} else {
holder.binding.productComparisonName.visibility = View.INVISIBLE
}
// Quantity
if (!product.quantity.isNullOrBlank()) {
holder.binding.productComparisonQuantity.text = SpannableStringBuilder()
.bold { append(activity.getString(R.string.compare_quantity)) }
.append(" ")
.append(product.quantity)
} else {
holder.binding.productComparisonQuantity.visibility = View.INVISIBLE
}
// Brands
val brands = product.brands
if (!brands.isNullOrBlank()) {
holder.binding.productComparisonBrand.text = SpannableStringBuilder()
.bold { append(activity.getString(R.string.compare_brands)) }
.append(" ")
.append(brands.split(",").joinToString(", ") { it.trim() })
} else {
//TODO: product brand placeholder goes here
}
// Open Food Facts specific
if (isFlavors(AppFlavors.OFF)) {
// NutriScore
holder.binding.productComparisonImageGrade.setImageResource(product.getNutriScoreResource())
// Nova group
holder.binding.productComparisonNovaGroup.setImageResource(product.getNovaGroupResource())
// Environment impact
holder.binding.productComparisonCo2Icon.setImageResource(product.getEcoscoreResource())
// Nutriments
holder.binding.productComparisonTextNutrientTxt.text = activity.getString(R.string.txtNutrientLevel100g)
holder.binding.productComparisonListNutrientLevels.visibility = View.VISIBLE
holder.binding.productComparisonListNutrientLevels.layoutManager = LinearLayoutManager(activity)
holder.binding.productComparisonListNutrientLevels.adapter = NutrientLevelListAdapter(activity, loadLevelItems(product))
} else {
holder.binding.productComparisonScoresLayout.visibility = View.GONE
holder.binding.productComparisonNutrientCv.visibility = View.GONE
}
// Additives
if (product.additivesTags.isNotEmpty()) loadAdditives(product, holder.binding.productComparisonAdditiveText)
// Full product button
holder.binding.fullProductButton.setOnClickListener {
val barcode = product.code
if (Utils.isNetworkConnected(activity)) {
Utils.hideKeyboard(activity)
client.openProduct(barcode, activity)
} else {
MaterialDialog.Builder(activity).apply {
title(R.string.device_offline_dialog_title)
content(R.string.connectivity_check)
positiveText(R.string.txt_try_again)
negativeText(R.string.dismiss)
onPositive { _, _ ->
if (Utils.isNetworkConnected(activity)) {
client.openProduct(barcode, activity)
} else {
Toast.makeText(activity, R.string.device_offline_dialog_title, Toast.LENGTH_SHORT).show()
}
}
}.show()
}
}
}
private fun loadAdditives(product: Product, view: TextView) {
if (product.additivesTags.isEmpty()) return
product.additivesTags.toObservable()
.flatMapSingle { tag ->
productRepository.getAdditiveByTagAndLanguageCode(tag, LocaleHelper.getLanguage(activity))
.flatMap { categoryName ->
if (categoryName.isNull) {
productRepository.getAdditiveByTagAndDefaultLanguageCode(tag)
} else {
Single.just(categoryName)
}
}
}
.filter { it.isNotNull }
.toList()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnError { Log.e(ProductCompareAdapter::class.simpleName, "loadAdditives", it) }
.subscribe { additives ->
if (additives.isNotEmpty()) {
view.text = SpannableStringBuilder()
.bold { append(activity.getString(R.string.compare_additives)) }
.append(" \n")
.append(additives.joinToString("\n"))
setMaxCardHeight()
}
}.addTo(disp)
}
override fun getItemCount() = productsToCompare.count()
private fun loadLevelItems(product: Product): List<NutrientLevelItem> {
val levelItems = mutableListOf<NutrientLevelItem>()
val nutriments = product.nutriments
val nutrientLevels = product.nutrientLevels
var fat: NutrimentLevel? = null
var saturatedFat: NutrimentLevel? = null
var sugars: NutrimentLevel? = null
var salt: NutrimentLevel? = null
if (nutrientLevels != null) {
fat = nutrientLevels.fat
saturatedFat = nutrientLevels.saturatedFat
sugars = nutrientLevels.sugars
salt = nutrientLevels.salt
}
if (fat != null || salt != null || saturatedFat != null || sugars != null) {
val fatNutriment = nutriments[Nutriments.FAT]
if (fat != null && fatNutriment != null) {
val fatNutrimentLevel = fat.getLocalize(activity)
levelItems += NutrientLevelItem(
activity.getString(R.string.compare_fat),
fatNutriment.displayStringFor100g,
fatNutrimentLevel,
fat.getImgRes()
)
}
val saturatedFatNutriment = nutriments[Nutriments.SATURATED_FAT]
if (saturatedFat != null && saturatedFatNutriment != null) {
val saturatedFatLocalize = saturatedFat.getLocalize(activity)
levelItems += NutrientLevelItem(
activity.getString(R.string.compare_saturated_fat),
saturatedFatNutriment.displayStringFor100g,
saturatedFatLocalize,
saturatedFat.getImgRes()
)
}
val sugarsNutriment = nutriments[Nutriments.SUGARS]
if (sugars != null && sugarsNutriment != null) {
val sugarsLocalize = sugars.getLocalize(activity)
levelItems += NutrientLevelItem(
activity.getString(R.string.compare_sugars),
sugarsNutriment.displayStringFor100g,
sugarsLocalize,
sugars.getImgRes()
)
}
val saltNutriment = nutriments[Nutriments.SALT]
if (salt != null && saltNutriment != null) {
val saltLocalize = salt.getLocalize(activity)
levelItems += NutrientLevelItem(
activity.getString(R.string.compare_salt),
saltNutriment.displayStringFor100g,
saltLocalize,
salt.getImgRes()
)
}
}
return levelItems
}
fun setImageOnPhotoReturn(file: File) {
val product = productsToCompare[onPhotoReturnPosition!!]
val image = ProductImage(
product.code,
ProductImageField.FRONT,
file,
LocaleHelper.getLanguage(activity)
).apply { filePath = file.absolutePath }
client.postImg(image).subscribe().addTo(disp)
product.imageUrl = file.absolutePath
onPhotoReturnPosition = null
notifyDataSetChanged()
}
private fun setMaxCardHeight() {
//getting all the heights of CardViews
val productDetailsHeight = arrayListOf<Int>()
val productNutrientsHeight = arrayListOf<Int>()
val productAdditivesHeight = arrayListOf<Int>()
viewHolders.forEach {
productDetailsHeight += it.binding.productComparisonDetailsCv.height
productNutrientsHeight += it.binding.productComparisonNutrientCv.height
productAdditivesHeight += it.binding.productComparisonAdditiveText.height
}
//setting all the heights to be the maximum
viewHolders.forEach {
it.binding.productComparisonDetailsCv.minimumHeight = productDetailsHeight.maxOrNull()!!
it.binding.productComparisonNutrientCv.minimumHeight = productNutrientsHeight.maxOrNull()!!
it.binding.productComparisonAdditiveText.height = dpsToPixel(productAdditivesHeight.maxOrNull()!!)
}
}
/**
* helper method
*/
private fun dpsToPixel(dps: Int) = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
dps + 100f,
activity.resources.displayMetrics
).toInt()
}
class ProductComparisonViewHolder(
val binding: ProductComparisonListItemBinding
) : RecyclerView.ViewHolder(binding.root) {
init {
binding.fullProductButton.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_fullscreen_blue_18dp, 0, 0, 0)
}
}
| 22 | null | 1 | 1 | 62f2a91bc4d0af6c40849af99649685627854b64 | 15,859 | openfoodfacts-androidapp | Apache License 2.0 |
app/src/main/java/fr/jorisfavier/youshallnotpass/model/QRCodeAnalyzer.kt | jorisfavier | 259,359,448 | false | {"Kotlin": 296450, "Java": 744} | package fr.jorisfavier.youshallnotpass.model
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.ImageProxy
import com.google.mlkit.vision.barcode.BarcodeScannerOptions
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.barcode.common.Barcode
import com.google.mlkit.vision.common.InputImage
import timber.log.Timber
class QRCodeAnalyzer(private val onSuccessListener: (code: String?) -> Unit) :
ImageAnalysis.Analyzer {
override fun analyze(imageProxy: ImageProxy) {
val mediaImage = imageProxy.image
if (mediaImage != null) {
val image = InputImage.fromMediaImage(mediaImage, imageProxy.imageInfo.rotationDegrees)
val options =
BarcodeScannerOptions.Builder().setBarcodeFormats(Barcode.FORMAT_QR_CODE).build()
val scanner = BarcodeScanning.getClient(options)
scanner.process(image)
.addOnSuccessListener { barcodes ->
val code = barcodes.firstOrNull() ?: return@addOnSuccessListener
onSuccessListener(code.displayValue)
Timber.d("Success finding code - ${code.displayValue}")
}
.addOnCompleteListener { imageProxy.close() }
}
}
}
| 0 | Kotlin | 0 | 0 | a583cd9c3d44a234969c088b28b7b4eae37feaff | 1,296 | YouShallNotPass-android | MIT License |
android/app/src/main/java/com/example/clarity/sdk/Requests.kt | ad-world | 645,911,581 | false | null | package com.example.clarity.sdk
import okhttp3.MultipartBody
import retrofit2.http.Multipart
import retrofit2.http.Part
data class LoginRequest(val username: String, val password: String)
data class CreateUserEntity(val user: User)
data class User(val username: String, val email: String, val password: String, val firstname: String, val lastname: String, val phone_number: String)
data class JoinClassroomEntity(val privateCode: String, val userID: String)
data class CreateClassroomEntity(val name: String, val teacher: Integer)
data class CreateCardSetEntity(val creator_id: Int, val title: String, val type: String)
data class GetDataForSetRequest(val set_id: Int)
data class CreateCardEntity(val phrase: String, val title: String, val setId: Int? = null)
data class AddCardToSetRequest(val card_id: Int, val set_id: Int)
data class DeleteCardFromSetRequest(val card_id: Int, val set_id: Int)
data class GetCardsInSetRequest(val set_id: Int)
data class GetProgressForSetRequest(val set_id: Int)
data class UpdateProgressForSetRequest(val set_id: Int, val progress: Int)
/*
val fileToUpload = new File("path/to/file.txt");
val requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), fileToUpload);
use requestBody for audio in CreateClassroomAttemptEntity and CreateAttemptEntity
*/
data class CreateClassroomAttemptEntity(val task_id: Int, val user_id: Int, val card_id: Int, val audio: MultipartBody.Part)
// audio is Int for now, will change once we figure out what it needs to be
data class CreateAttemptEntity(val set_id: Int, val user_id: Int, val card_id: Int, val audio: MultipartBody.Part)
// audio is Int for now, will change once we figure out what it needs to be
data class GetUserAverageAttemptsRequest(val user_id: Int)
data class PhraseSearchEntity(val phrase: String)
data class GetAttemptsForSetEntity(val user: Int, val set: Int)
| 0 | Kotlin | 0 | 1 | 3f00d85daa49b8abc68c00043868c92e7956dff5 | 1,878 | clarity | MIT License |
presentation/history/src/main/java/com/depromeet/threedays/history/model/FrequentHabitUI.kt | depromeet12th | 548,194,728 | false | null | package com.depromeet.threedays.history.model
import com.depromeet.threedays.domain.entity.record.FrequentHabit
data class FrequentHabitUI(
val achievementCount: Int,
val color: String,
val createAt: String,
val dayOfWeeks: List<String>,
val id: Int,
val imojiPath: String,
val memberId: Int,
val title: String
)
fun FrequentHabit.toPresentationModel(): FrequentHabitUI {
return FrequentHabitUI(
achievementCount = this.achievementCount,
color = this.color,
createAt = this.createAt,
dayOfWeeks = this.dayOfWeeks,
id = this.id,
imojiPath = this.imojiPath,
memberId = this.memberId,
title = this.title,
)
}
| 0 | Kotlin | 1 | 15 | 1cc08fcf2b038924ab0fe5feaaff548974f40f4d | 713 | three-days-android | MIT License |
src/commonMain/kotlin/de/jensklingenberg/kt_dart_builder/main/Allocator.kt | Foso | 171,142,071 | false | null | package de.jensklingenberg.kt_dart_builder.main
import de.jensklingenberg.kt_dart_builder.main.specs.Directive
import de.jensklingenberg.kt_dart_builder.main.specs.Reference
open class Allocator {
private val _imports = mutableListOf<String>()
companion object {
val none = de.jensklingenberg.kt_dart_builder.main.NullAllocator()
fun simplePrefixing(): de.jensklingenberg.kt_dart_builder.main.PrefixedAllocator {
return de.jensklingenberg.kt_dart_builder.main.PrefixedAllocator()
}
}
open val allocate: (Reference) -> String
get() = { ref ->
allocate(ref)
}
open fun allocate(ref: Reference): String {
if (ref.url.isNotEmpty() ) {
_imports.add(ref.url)
}
return ref.symbol
}
//fun allocate(ref: Reference): String
open val imports: List<Directive>
get() = _imports.map { u -> Directive.import(u)}
}
class NullAllocator() : de.jensklingenberg.kt_dart_builder.main.Allocator() {
override val allocate: (Reference) -> String
get() = {
it.symbol
}
override val imports: List<Directive> = listOf()
}
class PrefixedAllocator() : de.jensklingenberg.kt_dart_builder.main.Allocator() {
val imports_ = mutableMapOf<String, Int>()
val _doNotPrefix = listOf("dart:core")
var _keys = 1
override val imports: List<Directive>
get() = imports_.keys.map { u -> Directive.import(u, _as = "_i${imports_[u]}") }
override val allocate: (Reference) -> String
get() = { ref ->
allocate(ref)
}
override fun allocate(ref: Reference): String {
val symbol = ref.symbol
if (ref.url.isEmpty() || _doNotPrefix.contains(ref.url)) {
return symbol
}
return "_i${imports_.getOrPut(ref.url, { _nextKey() })}.$symbol"
}
fun _nextKey(): Int = _keys++
}
| 0 | Kotlin | 0 | 1 | beca489288dce4fa8d7c4f1bf536d5bad9591d06 | 1,937 | kt_dart_builder | Apache License 2.0 |
common/src/main/java/com/hh/common/network/ApiResponse.kt | yellowhai | 469,705,102 | false | {"Kotlin": 326860} | package com.hh.common.network
data class ApiResponse<T>(val errorCode: Int = -100,val errorMsg: String = "", val data: T? = null) : BaseResponse<T>() {
override fun isSuccess() = errorCode == 200
override fun getResponseCode() = errorCode
override fun getResponseData() = data
override fun getResponseMsg() = errorMsg
} | 0 | Kotlin | 1 | 8 | 1463c4d222cd0bf36fd8deeccf295b4f68d479a5 | 341 | PlayAndroid | Apache License 2.0 |
sdk/src/main/java/com/paymaya/sdk/android/vault/internal/helpers/AutoFormatTextWatcher.kt | PayMaya | 252,646,327 | false | null | /*
* Copyright (c) 2020 PayMaya Philippines, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.paymaya.sdk.android.vault.internal.helpers
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
internal class AutoFormatTextWatcher(
private val editText: EditText,
private val formatter: Formatter
) : TextWatcher {
private var enabledTextWatcher = true
private var backspaceOnSeparator = false
private var deletedSeparatorPosition: Int? = null
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
if (enabledTextWatcher) {
backspaceOnSeparator = count == 1 && after == 0 && s[start] == formatter.separator
deletedSeparatorPosition = if (backspaceOnSeparator) start else null
}
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
// no-op
}
override fun afterTextChanged(s: Editable) {
if (!enabledTextWatcher) {
return
}
enabledTextWatcher = false
var text = s.toString()
val cursorPosition: Int
if (backspaceOnSeparator) {
text = removeCharBeforeSeparator(text)
cursorPosition = editText.selectionEnd - 1
} else {
cursorPosition = editText.selectionEnd
}
val cursorPositionNoSeparators = cursorPosition - countSeparatorsBeforePosition(text, cursorPosition)
val textNoSeparators = removeSeparators(text)
val (newText, newSeparatorsBeforeCursorCount) =
formatter.format(textNoSeparators, cursorPositionNoSeparators)
editText.setText(newText)
// Trim new cursor position in case a longer text was pasted into the edit text (filter does not prevent it)
val newCursorPosition = (cursorPositionNoSeparators + newSeparatorsBeforeCursorCount)
.coerceAtMost(formatter.lengthWithSeparators)
editText.setSelection(newCursorPosition)
enabledTextWatcher = true
}
private fun removeCharBeforeSeparator(text: String): String {
val charToBeDeletedPosition = requireNotNull(deletedSeparatorPosition) - 1
return text.removeRange(charToBeDeletedPosition..charToBeDeletedPosition)
}
private fun countSeparatorsBeforePosition(text: String, cursorPosition: Int): Int =
text.substring(0, cursorPosition)
.count { char -> char == formatter.separator }
private fun removeSeparators(text: String): String =
text.replace(oldValue = "${formatter.separator}", newValue = "")
}
| 2 | Kotlin | 6 | 9 | 9697f7a31407c937caa04ad49adab52944e5954d | 3,656 | PayMaya-Android-SDK-v2 | MIT License |
src/main/aoc2019/Day16.kt | nibarius | 154,152,607 | false | {"Kotlin": 919743} | package aoc2019
import kotlin.math.abs
class Day16(input: String) {
val parsedInput = input.chunked(1).map { it.toInt() }
private fun patternLookup(currentDigit: Int, index: Int): Int {
// digit 0: length 4, digit 1: length 8, ...
val patternLength = 4 * (currentDigit + 1)
// First time the pattern is applied it's shifted by one step
val positionInPattern = (index + 1) % patternLength
// The pattern have four different sections, divide by current digit to
// get a 0-3 indicating in which section the index is
// Sections: 0, 1, 0, -1
return when(positionInPattern / (currentDigit + 1)) {
1 -> 1
3 -> -1
else -> 0
}
}
private fun runPhases(list: List<Int>): String {
val ret = list.toIntArray()
repeat(100) {
for (currentElement in ret.indices) {
var theSum = 0
// As learned in part two (see below) all digits before currentElement is 0, so those can be skipped.
for (i in currentElement until ret.size) {
theSum += ret[i] * patternLookup(currentElement, i)
}
ret[currentElement] = abs(theSum) % 10
}
}
return ret.take(8).joinToString("")
}
fun solvePart1(): String {
return runPhases(parsedInput)
}
private fun valueStartingAt(offset: Int, list: List<Int>): String {
/*
for line 0, you have 0 zeros at the start of phase
for line 1, you have 1 zero at the start
for line offset, you have offset zeros at the start
==> values of digits only depends on digits after the current digit
offset > input.size / 2 ==> first offset zeros, then rest is ones
==> for any digit, add it's current value with the new value of the digit to the right
all together means, start from last digit work backwards to the offset digit
*/
val digits = list.subList(offset, list.size).toIntArray()
repeat(100) {
var prev = 0
for (i in digits.size - 1 downTo 0) {
digits[i] = (digits[i] + prev) % 10
prev = digits[i]
}
}
return digits.take(8).joinToString("")
}
fun solvePart2(): String {
val realInput = mutableListOf<Int>()
repeat(10_000) {
realInput.addAll(parsedInput)
}
val messageOffset = parsedInput.subList(0, 7).joinToString(("")).toInt()
return valueStartingAt(messageOffset, realInput)
}
}
| 0 | Kotlin | 0 | 6 | 1800cf7487879313e0902d8f8da7e668a8ce1737 | 2,634 | aoc | MIT License |
finished/src/main/java/com/example/android/wearable/composeforwearos/MainActivity.kt | android | 421,594,951 | false | {"Kotlin": 30554} | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.wearable.composeforwearos
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.wear.compose.foundation.lazy.ScalingLazyColumn
import androidx.wear.compose.material.Scaffold
import com.example.android.wearable.composeforwearos.theme.WearAppTheme
import com.google.android.horologist.annotations.ExperimentalHorologistApi
import com.google.android.horologist.compose.layout.AppScaffold
import com.google.android.horologist.compose.layout.ScalingLazyColumn
import com.google.android.horologist.compose.layout.ScalingLazyColumnDefaults
import com.google.android.horologist.compose.layout.ScalingLazyColumnDefaults.ItemType
import com.google.android.horologist.compose.layout.ScreenScaffold
import com.google.android.horologist.compose.layout.rememberResponsiveColumnState
/**
* This code lab is meant to help existing Compose developers get up to speed quickly on
* Compose for Wear OS.
*
* The code lab walks through a majority of the simple composables for Wear OS (both similar to
* existing mobile composables and new composables).
*
* It also covers more advanced composables like [ScalingLazyColumn] (Wear OS's version of
* [LazyColumn]) and the Wear OS version of [Scaffold].The codelab explains the advantage of using
* Horologist [ScalingLazyColumn] and Horologist [AppScaffold] and [ScreenScaffold] to simplify
* code development to align with Wear OS UX guidance.
*
* Check out [this link](https://android-developers.googleblog.com/2021/10/compose-for-wear-os-now-in-developer.html)
* for more information on Compose for Wear OS.
*/
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
WearApp()
}
}
}
@OptIn(ExperimentalHorologistApi::class)
@Composable
fun WearApp() {
WearAppTheme {
/* *************************** Part 4: Wear OS Scaffold *************************** */
// TODO (Start): Create a AppScaffold (Wear Version)
/*
* [Horologist] AppScaffold adds a TimeText by default that can be override by the
* ScreenScaffold. It ensures that TimeText animates correctly when navigating between
* screens.
* */
AppScaffold {
// TODO: Swap to ScalingLazyColumnState
/*
* Specifying the types of items that appear at the start and end of the list ensures that the
* appropriate padding is used.
*/
val listState = rememberResponsiveColumnState(
contentPadding = ScalingLazyColumnDefaults.padding(
first = ItemType.SingleButton,
last = ItemType.Chip,
),
)
// Modifiers used by our Wear composables.
val contentModifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)
val iconModifier = Modifier.size(24.dp).wrapContentSize(align = Alignment.Center)
/* *************************** Part 4: Wear OS Scaffold *************************** */
// TODO (Start): Create a ScreenScaffold (Wear Version)
/*
* [Horologist] ScreenScaffold is used in conjunction with AppScaffold and adds a
* position indicator to the list by default.
* */
ScreenScaffold(
scrollState = listState,
) {
/* *************************** Part 3: ScalingLazyColumn *************************** */
// TODO: Swap a ScalingLazyColumn (Wear's version of LazyColumn)
/*
* [Horologist] ScalingLazyColumn applies padding for elements in the list to
* make sure no elements are clipped on different screen sizes.
* */
ScalingLazyColumn(
columnState = listState,
) {
/* ******************* Part 1: Simple composables ******************* */
item { ButtonExample(contentModifier, iconModifier) }
item { TextExample(contentModifier) }
item { CardExample(contentModifier, iconModifier) }
/* ********************* Part 2: Wear unique composables ********************* */
item { ChipExample(contentModifier, iconModifier) }
item { ToggleChipExample(contentModifier) }
}
// TODO (End): Create a ScreenScaffold (Wear Version)
}
// TODO (End): Create a AppScaffold (Wear Version)
}
}
}
| 0 | Kotlin | 15 | 19 | 5091b20d2328cc752df32a75a726e3e11af9f74c | 5,749 | codelab-compose-for-wear-os | Apache License 2.0 |
app/src/test/java/dev/pimentel/marvelapp/CommonMocks.kt | bfpimentel | 225,730,080 | false | null | package dev.pimentel.marvelapp
import dev.pimentel.marvelapp.business.model.repository.CharacterResponse.ThumbnailResponse.Companion.LANDSCAPE_IMAGE_VARIANT
import dev.pimentel.marvelapp.business.model.repository.CharacterResponse.ThumbnailResponse.Companion.STANDARD_IMAGE_VARIANT
import dev.pimentel.marvelapp.business.model.view.Character
import dev.pimentel.marvelapp.business.model.view.Character.*
/**
* @author <NAME> on 05/12/2019
*/
object CommonMocks {
val CHARACTERS = listOf(
createCharacterMock("Spider Man"),
createCharacterMock("Iron Man"),
createCharacterMock("Ant Man")
)
private fun createCharacterMock(characterName: String) =
Character(
1,
characterName,
"$characterName description",
"http://img.com/$characterName$STANDARD_IMAGE_VARIANT.jpg",
"http://img.com/$characterName$LANDSCAPE_IMAGE_VARIANT.jpg",
3,
listOf(
Comic("Comic $characterName 1"),
Comic("Comic $characterName 2"),
Comic("Comic $characterName 3")
),
3,
listOf(
Series("Series $characterName 1"),
Series("Series $characterName 2"),
Series("Series $characterName 3")
),
3,
listOf(
Story("Story $characterName 1"),
Story("Story $characterName 2"),
Story("Story $characterName 3")
)
)
} | 0 | Kotlin | 0 | 0 | 8990a7f098e15ad35b4cf743b79be6424b5ff2c4 | 1,540 | marvel-app | MIT License |
HA01_CLI/src/test/kotlin/ru/spbau/smirnov/cli/FillFiles.kt | smirnov-i-SPbAU | 234,049,436 | false | null | package ru.spbau.smirnov.cli
import java.io.File
val resourcesDir = "src" + File.separator + "test" + File.separator + "resources" + File.separator
fun fillFiles() {
fillAnotherFile()
fillExample()
fillJustAFileWithSomeContent()
}
private fun fillAnotherFile() {
val filename = "${resourcesDir}AnotherFile.txt"
val printWriter = File(filename).printWriter()
printWriter.println(
"Some" + System.lineSeparator() +
"Other awesome" + System.lineSeparator() +
"Content"
)
printWriter.close()
}
private fun fillExample() {
val filename = "${resourcesDir}example.txt"
val printWriter = File(filename).printWriter()
printWriter.println("Some example text")
printWriter.close()
}
private fun fillJustAFileWithSomeContent() {
val filename = "${resourcesDir}JustAFileWithSomeContent.txt"
val printWriter = File(filename).printWriter()
printWriter.println(
"some" + System.lineSeparator() +
"content" + System.lineSeparator() +
"is" + System.lineSeparator() +
"here" + System.lineSeparator() +
"42"
)
printWriter.close()
} | 1 | Kotlin | 2 | 0 | 2c61eb4c1ed0275a3e7ed5f121d0dbe0c45f054e | 1,157 | SoftwareDesign | MIT License |
visionai-shared/src/main/java/com/bendenen/visionai/visionai/shared/utils/ImageUtils.kt | BenDenen | 174,499,157 | false | null | package com.bendenen.visionai.visionai.shared.utils
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Matrix
import android.graphics.Paint
import android.media.ThumbnailUtils
import android.util.Log
import java.nio.ByteBuffer
fun getTransformationMatrix(
srcWidth: Int,
srcHeight: Int,
dstWidth: Int,
dstHeight: Int,
applyRotation: Int,
maintainAspectRatio: Boolean
): Matrix {
val matrix = Matrix()
if (applyRotation != 0) {
// Translate so center of image is at origin.
matrix.postTranslate(-srcWidth / 2.0f, -srcHeight / 2.0f)
// Rotate around origin.
matrix.postRotate(applyRotation.toFloat())
}
// Account for the already applied rotation, if any, and then determine how
// much scaling is needed for each axis.
val transpose = (Math.abs(applyRotation) + 90) % 180 == 0
val inWidth = if (transpose) srcHeight else srcWidth
val inHeight = if (transpose) srcWidth else srcHeight
// Apply scaling if necessary.
if (inWidth != dstWidth || inHeight != dstHeight) {
val scaleFactorX = dstWidth / inWidth.toFloat()
val scaleFactorY = dstHeight / inHeight.toFloat()
if (maintainAspectRatio) {
// Scale by minimum factor so that dst is filled completely while
// maintaining the aspect ratio. Some image may fall off the edge.
val scaleFactor = Math.max(scaleFactorX, scaleFactorY)
matrix.postScale(scaleFactor, scaleFactor)
} else {
// Scale exactly to fill dst from src.
matrix.postScale(scaleFactorX, scaleFactorY)
}
}
if (applyRotation != 0) {
// Translate back from origin centered reference to destination frame.
matrix.postTranslate(dstWidth / 2.0f, dstHeight / 2.0f)
}
return matrix
}
fun getSquaredBitmap(bitmap: Bitmap): Bitmap {
val dimension = bitmap.width.coerceAtMost(bitmap.height)
return ThumbnailUtils.extractThumbnail(bitmap, dimension, dimension)
}
fun Bitmap.toNormalizedFloatArray(): FloatArray {
val intValues = IntArray(this.width * this.height)
this.getPixels(intValues, 0, this.width, 0, 0, this.width, this.height)
val channelNum = 3
val rgbFloatArray = FloatArray(this.width * this.height * channelNum)
for ((index, pixel) in intValues.withIndex()) {
rgbFloatArray[index * channelNum + 0] = Color.red(pixel).toFloat() / 255
rgbFloatArray[index * channelNum + 1] = Color.green(pixel).toFloat() / 255
rgbFloatArray[index * channelNum + 2] = Color.blue(pixel).toFloat() / 255
}
return rgbFloatArray
}
fun Bitmap.toByteArray(): ByteArray {
val intValues = IntArray(this.width * this.height)
this.getPixels(intValues, 0, this.width, 0, 0, this.width, this.height)
val channelNum = 4
val byteArray = ByteArray(this.width * this.height * channelNum)
for ((index, pixel) in intValues.withIndex()) {
byteArray[index * channelNum + 0] = Color.alpha(pixel).toByte()
byteArray[index * channelNum + 1] = Color.red(pixel).toByte()
byteArray[index * channelNum + 2] = Color.green(pixel).toByte()
byteArray[index * channelNum + 3] = Color.blue(pixel).toByte()
}
return byteArray
}
fun Bitmap.toThreeChannelByteArray(): ByteArray {
val intValues = IntArray(this.width * this.height)
this.getPixels(intValues, 0, this.width, 0, 0, this.width, this.height)
val channelNum = 3
val byteArray = ByteArray(this.width * this.height * channelNum)
for ((index, pixel) in intValues.withIndex()) {
byteArray[index * channelNum + 0] = Color.red(pixel).toByte()
byteArray[index * channelNum + 1] = Color.green(pixel).toByte()
byteArray[index * channelNum + 2] = Color.blue(pixel).toByte()
}
return byteArray
}
fun Bitmap.toNormalizedFloatByteBuffer(
buffer: ByteBuffer,
inputSize: Int,
mean: Float
) {
val intValues = IntArray(this.width * this.height)
this.getPixels(intValues, 0, this.width, 0, 0, this.width, this.height)
buffer.rewind()
for (i in 0 until inputSize) {
for (j in 0 until inputSize) {
val pixelValue = intValues[i * inputSize + j]
buffer.putFloat(((pixelValue shr 16 and 0xFF) / mean))
buffer.putFloat(((pixelValue shr 8 and 0xFF) / mean))
buffer.putFloat(((pixelValue and 0xFF) / mean))
}
}
}
@Synchronized fun ByteArray.toNormalizedFloatByteBuffer(
buffer: ByteBuffer,
mean: Float
) {
buffer.rewind()
this.forEach {
buffer.putFloat(((2 * it.toPositiveInt()) / mean) - 1)
}
}
fun ByteArray.toBitmap(
width: Int,
height: Int
): Bitmap {
val pixelValues = IntArray(width * height)
var intIndex = 0
val channelNum = 4
for ((index, pixel) in pixelValues.withIndex()) {
val a = this[index * channelNum + 0].toPositiveInt()
val r = this[index * channelNum + 1].toPositiveInt()
val g = this[index * channelNum + 2].toPositiveInt()
val b = this[index * channelNum + 3].toPositiveInt()
pixelValues[intIndex++] = Color.argb(a, r, g, b)
}
return Bitmap.createBitmap(pixelValues, width, height, Bitmap.Config.ARGB_8888)
}
fun Byte.toPositiveInt() = toInt() and 0xFF
/**
*
* @param bmp input bitmap
* @param contrast 0..10 1 is default
* @param brightness -255..255 0 is default
* @return new bitmap
*/
fun changeBitmapContrastBrightness(bmp: Bitmap, contrast: Float, brightness: Float): Bitmap {
val cm = ColorMatrix(
floatArrayOf(
contrast,
0f,
0f,
0f,
brightness,
0f,
contrast,
0f,
0f,
brightness,
0f,
0f,
contrast,
0f,
brightness,
0f,
0f,
0f,
1f,
0f
)
)
val ret = Bitmap.createBitmap(bmp.width, bmp.height, bmp.config)
val canvas = Canvas(ret)
val paint = Paint()
paint.colorFilter = ColorMatrixColorFilter(cm)
canvas.drawBitmap(bmp, Matrix(), paint)
return ret
} | 15 | null | 1 | 3 | 750856e60523b93516f16e2181dd4001c024b0f4 | 6,350 | VisionAi | Apache License 2.0 |
app/src/main/java/com/coinninja/coinkeeper/util/uri/parameter/BitcoinParameter.kt | coinninjadev | 175,276,289 | false | null | package com.coinninja.coinkeeper.util.uri.parameter
import javax.annotation.Nonnull
enum class BitcoinParameter {
AMOUNT, BIP70, MEMO, REQUIRED_FEE;
val parameterKey: String
get() = when (this) {
AMOUNT -> "amount"
BIP70 -> "request"
MEMO -> "memo"
REQUIRED_FEE -> "required_fee"
}
companion object {
fun from(@Nonnull param: String?): BitcoinParameter? {
when (param) {
"amount" -> return AMOUNT
"r" -> return BIP70
"request" -> return BIP70
"memo" -> return MEMO
"required_fee" -> return REQUIRED_FEE
}
return null
}
}
} | 2 | null | 0 | 6 | d67d7c0b9cad27db94470231073c5d6cdda83cd0 | 738 | dropbit-android | MIT License |
player/src/androidMain/kotlin/de/julianostarek/motif/player/Spotify.kt | jlnstrk | 550,456,917 | false | null | package de.julianostarek.motif.player
import de.julianostarek.motif.player.spotify.ImageDimension
import de.julianostarek.motif.player.spotify.SpotifyRemote
public actual class SpotifyPlatformControls actual constructor(public val backing: SpotifyRemote) : PlatformControls {
override suspend fun trackImage(track: PlayerTrack, size: Int): AndroidTrackImage? {
if (track !is SpotifyPlayerTrack) return null
// TODO: Use upper bound < size
return backing.imagesApi.getImage(track.backing, ImageDimension.LARGE)
.let(AndroidTrackImage::Bitmap)
}
} | 0 | Kotlin | 0 | 1 | bd4376470c8f4281a1e8fd4641ea5339f66425ad | 591 | motif | Apache License 2.0 |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/FaceSunglassesAlt.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.FaceSunglassesAlt: ImageVector
get() {
if (_faceSunglassesAlt != null) {
return _faceSunglassesAlt!!
}
_faceSunglassesAlt = Builder(name = "FaceSunglassesAlt", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(12.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f)
reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(12.0f, 3.0f)
curveToRelative(3.113f, 0.0f, 5.862f, 1.59f, 7.478f, 4.0f)
horizontalLineToRelative(-3.831f)
curveToRelative(-0.98f, 0.0f, -1.913f, 0.367f, -2.653f, 1.0f)
horizontalLineToRelative(-1.988f)
curveToRelative(-0.74f, -0.633f, -1.673f, -1.0f, -2.653f, -1.0f)
horizontalLineToRelative(-3.831f)
curveToRelative(1.617f, -2.41f, 4.365f, -4.0f, 7.478f, -4.0f)
close()
moveTo(12.0f, 21.0f)
curveToRelative(-4.86f, 0.0f, -8.823f, -3.875f, -8.985f, -8.697f)
curveToRelative(0.598f, 0.435f, 1.325f, 0.697f, 2.109f, 0.697f)
horizontalLineToRelative(2.115f)
curveToRelative(1.387f, 0.0f, 2.615f, -0.798f, 3.214f, -2.0f)
horizontalLineToRelative(3.094f)
curveToRelative(0.599f, 1.202f, 1.827f, 2.0f, 3.214f, 2.0f)
horizontalLineToRelative(2.115f)
curveToRelative(0.784f, 0.0f, 1.511f, -0.262f, 2.109f, -0.697f)
curveToRelative(-0.162f, 4.822f, -4.125f, 8.697f, -8.985f, 8.697f)
close()
moveTo(17.234f, 14.394f)
curveToRelative(0.611f, 0.559f, 0.653f, 1.508f, 0.094f, 2.119f)
curveToRelative(-2.276f, 2.487f, -4.856f, 2.487f, -5.828f, 2.487f)
curveToRelative(-0.829f, 0.0f, -1.5f, -0.672f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.671f, -1.5f, 1.5f, -1.5f)
curveToRelative(0.78f, 0.0f, 2.231f, 0.0f, 3.615f, -1.513f)
curveToRelative(0.558f, -0.61f, 1.507f, -0.653f, 2.119f, -0.094f)
close()
}
}
.build()
return _faceSunglassesAlt!!
}
private var _faceSunglassesAlt: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,346 | icons | MIT License |
src/main/kotlin/hygge/plugin/generator/core/domain/po/MysqlTableInfo.kt | soupedog | 807,185,350 | false | {"Kotlin": 43378} | package hygge.plugin.generator.core.domain.po
class MysqlTablesInfo {
/**
* 表所在库
*/
var tableCatalog: String? = null
var tableSchema: String? = null
var tableName: String? = null
var tableType: String? = null
var engine: String? = null
var version: Int? = null
var rowFormat: String? = null
var tableRows: Long? = null
var avgRowLength: Long? = null
var dataLength: Long? = null
var maxDataLength: Long? = null
var indexLength: Long? = null
var dataFree: Long? = null
var autoIncrement: Long? = null
var createTime: String? = null
var updateTime: String? = null
var checkTime: String? = null
var tableCollation: String? = null
var checksum: String? = null
var createOptions: String? = null
var tableComment: String? = null
} | 0 | Kotlin | 0 | 0 | ec563a0de22e350ca75a57cfe4f664a7a1b27598 | 823 | hygge-code-generator | Apache License 2.0 |
lib/src/main/kotlin/com/lemonappdev/konsist/core/provider/KoInitBlockProviderCore.kt | LemonAppDev | 621,181,534 | false | {"Kotlin": 2941189, "Python": 25669} | package com.lemonappdev.konsist.core.provider
import com.lemonappdev.konsist.api.declaration.KoInitBlockDeclaration
import com.lemonappdev.konsist.api.provider.KoInitBlockProvider
import com.lemonappdev.konsist.core.declaration.KoInitBlockDeclarationCore
import org.jetbrains.kotlin.psi.KtClassOrObject
internal interface KoInitBlockProviderCore :
KoInitBlockProvider,
KoContainingDeclarationProviderCore,
KoBaseProviderCore {
val ktClassOrObject: KtClassOrObject
override val initBlocks: List<KoInitBlockDeclaration>
get() {
val anonymousInitializers = ktClassOrObject
.body
?.anonymousInitializers
return if (anonymousInitializers?.isEmpty() == true) {
emptyList()
} else {
anonymousInitializers
?.map { init -> KoInitBlockDeclarationCore.getInstance(init, this) }
?: emptyList()
}
}
override val numInitBlocks: Int
get() = initBlocks.size
@Deprecated("Will be removed in v1.0.0", replaceWith = ReplaceWith("hasInitBlocks()"))
override val hasInitBlocks: Boolean
get() = initBlocks.isNotEmpty()
override fun countInitBlocks(predicate: (KoInitBlockDeclaration) -> Boolean): Int =
initBlocks.count { predicate(it) }
override fun hasInitBlocks(): Boolean = initBlocks.isNotEmpty()
override fun hasInitBlock(predicate: (KoInitBlockDeclaration) -> Boolean): Boolean = initBlocks.any(predicate)
override fun hasAllInitBlocks(predicate: (KoInitBlockDeclaration) -> Boolean): Boolean = initBlocks.all(predicate)
}
| 16 | Kotlin | 19 | 768 | 22f45504ab1c88fca8314bd86f91af7dd8a3672b | 1,658 | konsist | Apache License 2.0 |
app/src/main/java/com/example/doseloop/viewmodel/DeviceStatusViewModel.kt | Metropolia-ZeroUI | 601,762,572 | false | null | package com.example.doseloop.viewmodel
import android.util.Log
import androidx.navigation.findNavController
import com.example.doseloop.R
import com.example.doseloop.comms.impl.Message
import com.example.doseloop.util.*
/**
* ViewModel for the DeviceStatusFragment and the related popup windows.
*/
class DeviceStatusViewModel: AbstractViewModel() {
fun saveDeviceNumber(phoneNumber: String) {
saveToPrefs(DEVICE_PHONE_NUMBER, phoneNumber)
}
fun saveDeviceLockedState(deviceLocked: Boolean) {
try {
msgService.sendMessage(if (deviceLocked) Message.LOCK_DEVICE else Message.UNLOCK_DEVICE)
saveToPrefs(DEVICE_LOCKED_STATE, deviceLocked)
Log.d("MESSAGE_SEND", "Message OK")
} catch(e: Exception) {
Log.d("MESSAGE_SEND", "Send failed: $e")
}
}
fun onPopupConfirmUserNumber(msg: Message, payload: String, prefKey: String) {
try {
msgService.sendMessage(msg)
saveToPrefs(prefKey, payload)
Log.d("MESSAGE_SEND", "Message OK")
} catch(e: Exception) {
Log.d("MESSAGE_SEND", "Send failed: $e")
}
}
fun getLockedState() = getFromPrefs(DEVICE_LOCKED_STATE, false)
fun getChanges(editTextNumber: String, deviceLocked: Boolean, deviceEditTextNumber: String): String {
var s = ""
if (getFromPrefs(DEVICE_LOCKED_STATE, false) != deviceLocked) {
s += if (deviceLocked) "Älydosetin lukitus päällä\n"
else "Älydosetin lukitus pois\n"
}
if (getFromPrefs(DEVICE_USER_NUMBER, "") != editTextNumber) {
s += "Älydosetin käyttäjän numero muokattu\n"
}
if (getFromPrefs(DEVICE_PHONE_NUMBER, "") != deviceEditTextNumber) {
s += "Älydosetin numero muokattu"
}
return s
}
} | 4 | Kotlin | 0 | 0 | bcf01b61ab273350b8b59a8fc2c1633bd62257a7 | 1,853 | DoseLoop | MIT License |
src/river/exertion/sac/swe/Swe.kt | exertionriver | 742,813,983 | false | {"Kotlin": 441812} | package river.exertion.sac.swe
import swisseph.SwissEph
import java.nio.file.Paths
object Swe {
val sw = SwissEph("assetExt/plugin/ephe")
} | 0 | Kotlin | 0 | 0 | f19f85a9695a59ed9e35f6bdcb17d89cf98da878 | 147 | sac-kcop | MIT License |
asset-converter/src/main/kotlin/de/roamingthings/ktepaper/assetconverter/image/view/ImageConversionView.kt | roamingthings | 114,105,702 | false | null | package de.roamingthings.ktepaper.assetconverter.image.view
import de.roamingthings.ktepaper.assetconverter.ImageConverter
import de.roamingthings.ktepaper.assetconverter.view.Styles
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleStringProperty
import javafx.embed.swing.SwingFXUtils.toFXImage
import javafx.geometry.Pos.CENTER
import javafx.geometry.Pos.CENTER_LEFT
import javafx.scene.control.TextField
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.layout.Priority.ALWAYS
import javafx.stage.FileChooser
import tornadofx.*
import java.io.File
//private const val displayWidth = 176.0
//private const val displayHeight = 264.0
private const val displayWidth = 128.0
private const val displayHeight = 250.0
class ImageConversionView : View() {
private val imageConverter: ImageConverter by di()
private lateinit var sourceImagePathField: TextField
private lateinit var originalImageView: ImageView
private lateinit var convertedImageView: ImageView
private lateinit var targetWidthField: TextField
private lateinit var targetHeightField: TextField
private val originalImagePath = SimpleStringProperty()
private val imageSource = SimpleStringProperty()
private val targetWidth = SimpleIntegerProperty(displayWidth.toInt())
private val targetHeight = SimpleIntegerProperty(displayHeight.toInt())
override val root = vbox(10) {
useMaxSize = true
text("Convert Image") {
padding = insets(6.0)
useMaxWidth = true
}
hbox(10) {
label("Source Image") {
alignment = CENTER
useMaxHeight = true
}
sourceImagePathField = textfield {
hgrow = ALWAYS
useMaxWidth = true
bind(originalImagePath)
originalImagePath.addListener({ observable, oldValue, newValue ->
loadImage(newValue)
})
}
button("...") {
action {
val filters = arrayOf(FileChooser.ExtensionFilter("Image files", "*.bmp", "*.jpg", "*.png", "*.gif"))
val chosenFiles = chooseFile("Select some text files", filters)
if (chosenFiles.isNotEmpty()) {
val newImageFile = chosenFiles[0].absolutePath
originalImagePath.set(newImageFile)
}
}
}
}
hbox(10) {
label("Target width") {
alignment = CENTER
useMaxHeight = true
}
targetWidthField = textfield {
bind(targetWidth)
targetWidth.addListener({ observable, oldValue, newValue ->
updateTargetDimension(newValue.toInt(), targetHeight.value)
loadImage(originalImagePath.value)
})
}
label("px") {
alignment = CENTER_LEFT
useMaxHeight = true
}
label("height") {
alignment = CENTER
useMaxHeight = true
}
targetHeightField = textfield {
bind(targetHeight)
targetHeight.addListener({ observable, oldValue, newValue ->
updateTargetDimension(targetWidth.value, newValue.toInt())
loadImage(originalImagePath.value)
})
}
label("px") {
alignment = CENTER_LEFT
hgrow = ALWAYS
useMaxWidth = true
useMaxHeight = true
}
}
hbox(10) {
vbox {
originalImageView = imageview {
addClass(Styles.previewImage)
prefWidth = targetWidth.value.toDouble()
prefHeight = targetHeight.value.toDouble()
fitWidth = targetWidth.value.toDouble()
fitHeight = targetHeight.value.toDouble()
}
label("Original Image") {
useMaxWidth = true
alignment = CENTER
}
}
label(">>") {
hgrow = ALWAYS
alignment = CENTER
useMaxSize = true
}
vbox {
convertedImageView = imageview {
addClass(Styles.previewImage)
prefWidth = targetWidth.value.toDouble()
prefHeight = targetHeight.value.toDouble()
fitWidth = targetWidth.value.toDouble()
fitHeight = targetHeight.value.toDouble()
}
text("Monochrome Image") {
useMaxWidth = true
alignment = CENTER
}
}
}
textarea {
prefWidth = 600.0
prefHeight = 400.0
useMaxSize = true
vgrow = ALWAYS
hgrow = ALWAYS
bind(imageSource)
}
hbox {
useMaxWidth = true
hgrow = ALWAYS
vbox {
useMaxWidth = true
hgrow = ALWAYS
}
button("Copy to clipboard") {
action {
clipboard.setContent {
putString(imageSource.value)
}
}
}
}
}
private fun updateTargetDimension(width: Int, height: Int) {
convertedImageView.resize(width.toDouble(), height.toDouble())
convertedImageView.prefHeight(height.toDouble())
convertedImageView.prefWidth(width.toDouble())
convertedImageView.fitHeight = height.toDouble()
convertedImageView.fitWidth = width.toDouble()
}
private fun loadImage(imagePath: String) {
val imageFile = File(imagePath)
if (imageFile.exists()) {
val image = Image(imageFile.inputStream())
originalImageView.image = image
val bitmap = imageConverter.convertToBitmap(image, targetWidth.value, targetHeight.value)
convertedImageView.image = toFXImage(bitmap, null)
imageSource.set(imageConverter.createSourceForImage(bitmap))
}
}
override fun onDock() {
if (originalImagePath.isEmpty.value) {
val welcomeResource = javaClass.getResource("/welcome.bmp")?.file
if (welcomeResource != null) {
originalImagePath.set(welcomeResource)
}
}
}
}
| 0 | Kotlin | 0 | 6 | bb24eb43ef85406a1e8bf0ed7d53428a8c11867b | 6,727 | ktepaper | Apache License 2.0 |
asset-converter/src/main/kotlin/de/roamingthings/ktepaper/assetconverter/image/view/ImageConversionView.kt | roamingthings | 114,105,702 | false | null | package de.roamingthings.ktepaper.assetconverter.image.view
import de.roamingthings.ktepaper.assetconverter.ImageConverter
import de.roamingthings.ktepaper.assetconverter.view.Styles
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleStringProperty
import javafx.embed.swing.SwingFXUtils.toFXImage
import javafx.geometry.Pos.CENTER
import javafx.geometry.Pos.CENTER_LEFT
import javafx.scene.control.TextField
import javafx.scene.image.Image
import javafx.scene.image.ImageView
import javafx.scene.layout.Priority.ALWAYS
import javafx.stage.FileChooser
import tornadofx.*
import java.io.File
//private const val displayWidth = 176.0
//private const val displayHeight = 264.0
private const val displayWidth = 128.0
private const val displayHeight = 250.0
class ImageConversionView : View() {
private val imageConverter: ImageConverter by di()
private lateinit var sourceImagePathField: TextField
private lateinit var originalImageView: ImageView
private lateinit var convertedImageView: ImageView
private lateinit var targetWidthField: TextField
private lateinit var targetHeightField: TextField
private val originalImagePath = SimpleStringProperty()
private val imageSource = SimpleStringProperty()
private val targetWidth = SimpleIntegerProperty(displayWidth.toInt())
private val targetHeight = SimpleIntegerProperty(displayHeight.toInt())
override val root = vbox(10) {
useMaxSize = true
text("Convert Image") {
padding = insets(6.0)
useMaxWidth = true
}
hbox(10) {
label("Source Image") {
alignment = CENTER
useMaxHeight = true
}
sourceImagePathField = textfield {
hgrow = ALWAYS
useMaxWidth = true
bind(originalImagePath)
originalImagePath.addListener({ observable, oldValue, newValue ->
loadImage(newValue)
})
}
button("...") {
action {
val filters = arrayOf(FileChooser.ExtensionFilter("Image files", "*.bmp", "*.jpg", "*.png", "*.gif"))
val chosenFiles = chooseFile("Select some text files", filters)
if (chosenFiles.isNotEmpty()) {
val newImageFile = chosenFiles[0].absolutePath
originalImagePath.set(newImageFile)
}
}
}
}
hbox(10) {
label("Target width") {
alignment = CENTER
useMaxHeight = true
}
targetWidthField = textfield {
bind(targetWidth)
targetWidth.addListener({ observable, oldValue, newValue ->
updateTargetDimension(newValue.toInt(), targetHeight.value)
loadImage(originalImagePath.value)
})
}
label("px") {
alignment = CENTER_LEFT
useMaxHeight = true
}
label("height") {
alignment = CENTER
useMaxHeight = true
}
targetHeightField = textfield {
bind(targetHeight)
targetHeight.addListener({ observable, oldValue, newValue ->
updateTargetDimension(targetWidth.value, newValue.toInt())
loadImage(originalImagePath.value)
})
}
label("px") {
alignment = CENTER_LEFT
hgrow = ALWAYS
useMaxWidth = true
useMaxHeight = true
}
}
hbox(10) {
vbox {
originalImageView = imageview {
addClass(Styles.previewImage)
prefWidth = targetWidth.value.toDouble()
prefHeight = targetHeight.value.toDouble()
fitWidth = targetWidth.value.toDouble()
fitHeight = targetHeight.value.toDouble()
}
label("Original Image") {
useMaxWidth = true
alignment = CENTER
}
}
label(">>") {
hgrow = ALWAYS
alignment = CENTER
useMaxSize = true
}
vbox {
convertedImageView = imageview {
addClass(Styles.previewImage)
prefWidth = targetWidth.value.toDouble()
prefHeight = targetHeight.value.toDouble()
fitWidth = targetWidth.value.toDouble()
fitHeight = targetHeight.value.toDouble()
}
text("Monochrome Image") {
useMaxWidth = true
alignment = CENTER
}
}
}
textarea {
prefWidth = 600.0
prefHeight = 400.0
useMaxSize = true
vgrow = ALWAYS
hgrow = ALWAYS
bind(imageSource)
}
hbox {
useMaxWidth = true
hgrow = ALWAYS
vbox {
useMaxWidth = true
hgrow = ALWAYS
}
button("Copy to clipboard") {
action {
clipboard.setContent {
putString(imageSource.value)
}
}
}
}
}
private fun updateTargetDimension(width: Int, height: Int) {
convertedImageView.resize(width.toDouble(), height.toDouble())
convertedImageView.prefHeight(height.toDouble())
convertedImageView.prefWidth(width.toDouble())
convertedImageView.fitHeight = height.toDouble()
convertedImageView.fitWidth = width.toDouble()
}
private fun loadImage(imagePath: String) {
val imageFile = File(imagePath)
if (imageFile.exists()) {
val image = Image(imageFile.inputStream())
originalImageView.image = image
val bitmap = imageConverter.convertToBitmap(image, targetWidth.value, targetHeight.value)
convertedImageView.image = toFXImage(bitmap, null)
imageSource.set(imageConverter.createSourceForImage(bitmap))
}
}
override fun onDock() {
if (originalImagePath.isEmpty.value) {
val welcomeResource = javaClass.getResource("/welcome.bmp")?.file
if (welcomeResource != null) {
originalImagePath.set(welcomeResource)
}
}
}
}
| 0 | Kotlin | 0 | 6 | bb24eb43ef85406a1e8bf0ed7d53428a8c11867b | 6,727 | ktepaper | Apache License 2.0 |
app/src/main/java/com/vitorpamplona/amethyst/ui/components/RichTextViewer.kt | vitorpamplona | 587,850,619 | false | null | package com.vitorpamplona.amethyst.ui.components
import android.util.Patterns
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextDirection
import androidx.navigation.NavController
import com.google.accompanist.flowlayout.FlowRow
import com.vitorpamplona.amethyst.lnurl.LnInvoiceUtil
import com.vitorpamplona.amethyst.model.LocalCache
import com.vitorpamplona.amethyst.model.toByteArray
import com.vitorpamplona.amethyst.model.toNote
import com.vitorpamplona.amethyst.service.Nip19
import com.vitorpamplona.amethyst.ui.note.toShortenHex
import nostr.postr.toNpub
import java.net.MalformedURLException
import java.net.URISyntaxException
import java.net.URL
import java.util.regex.Pattern
val imageExtension = Pattern.compile("(.*/)*.+\\.(png|jpg|gif|bmp|jpeg|webp|svg)$")
val videoExtension = Pattern.compile("(.*/)*.+\\.(mp4|avi|wmv|mpg|amv|webm)$")
val noProtocolUrlValidator = Pattern.compile("^[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&//=]*)$")
val tagIndex = Pattern.compile(".*\\#\\[([0-9]+)\\].*")
val mentionsPattern: Pattern = Pattern.compile("@([A-Za-z0-9_-]+)")
val hashTagsPattern: Pattern = Pattern.compile("#([A-Za-z0-9_-]+)")
val urlPattern: Pattern = Patterns.WEB_URL
fun isValidURL(url: String?): Boolean {
return try {
URL(url).toURI()
true
} catch (e: MalformedURLException) {
false
} catch (e: URISyntaxException) {
false
}
}
@Composable
fun RichTextViewer(
content: String,
canPreview: Boolean,
tags: List<List<String>>?,
navController: NavController
) {
Column(
Modifier
.fillMaxWidth()
.animateContentSize()) {
// FlowRow doesn't work well with paragraphs. So we need to split them
content.split('\n').forEach { paragraph ->
FlowRow() {
paragraph.split(' ').forEach { word: String ->
if (canPreview) {
// Explicit URL
val lnInvoice = LnInvoiceUtil.findInvoice(word)
if (lnInvoice != null) {
InvoicePreview(lnInvoice)
} else if (isValidURL(word)) {
val removedParamsFromUrl = word.split("?")[0].toLowerCase()
if (imageExtension.matcher(removedParamsFromUrl).matches()) {
ZoomableImageView(word)
} else if (videoExtension.matcher(removedParamsFromUrl).matches()) {
VideoView(word)
} else {
UrlPreview(word, word)
}
} else if (Patterns.EMAIL_ADDRESS.matcher(word).matches()) {
ClickableEmail(word)
} else if (Patterns.PHONE.matcher(word).matches() && word.length > 6) {
ClickablePhone(word)
} else if (noProtocolUrlValidator.matcher(word).matches()) {
UrlPreview("https://$word", word)
} else if (tagIndex.matcher(word).matches() && tags != null) {
TagLink(word, tags, navController)
} else if (isBechLink(word)) {
BechLink(word, navController)
} else {
Text(
text = "$word ",
style = LocalTextStyle.current.copy(textDirection = TextDirection.Content),
)
}
} else {
if (isValidURL(word)) {
ClickableUrl("$word ", word)
} else if (Patterns.EMAIL_ADDRESS.matcher(word).matches()) {
ClickableEmail(word)
} else if (Patterns.PHONE.matcher(word).matches() && word.length > 6) {
ClickablePhone(word)
} else if (noProtocolUrlValidator.matcher(word).matches()) {
ClickableUrl(word, "https://$word")
} else if (tagIndex.matcher(word).matches() && tags != null) {
TagLink(word, tags, navController)
} else if (isBechLink(word)) {
BechLink(word, navController)
} else {
Text(
text = "$word ",
style = LocalTextStyle.current.copy(textDirection = TextDirection.Content),
)
}
}
}
}
}
}
}
fun isBechLink(word: String): Boolean {
return word.startsWith("nostr:", true)
|| word.startsWith("npub1", true)
|| word.startsWith("note1", true)
|| word.startsWith("nprofile1", true)
|| word.startsWith("nevent1", true)
|| word.startsWith("@npub1", true)
|| word.startsWith("@note1", true)
|| word.startsWith("@nprofile1", true)
|| word.startsWith("@nevent1", true)
}
@Composable
fun BechLink(word: String, navController: NavController) {
val uri = if (word.startsWith("nostr", true)) {
word
} else if (word.startsWith("@")) {
word.replaceFirst("@", "nostr:")
} else {
"nostr:${word}"
}
val nip19Route = try {
Nip19().uriToRoute(uri)
} catch (e: Exception) {
null
}
if (nip19Route == null) {
Text(text = "$word ")
} else {
ClickableRoute(nip19Route, navController)
}
}
@Composable
fun TagLink(word: String, tags: List<List<String>>, navController: NavController) {
val matcher = tagIndex.matcher(word)
val index = try {
matcher.find()
matcher.group(1).toInt()
} catch (e: Exception) {
println("Couldn't link tag ${word}")
null
}
if (index == null) {
return Text(text = "$word ")
}
if (index >= 0 && index < tags.size) {
if (tags[index][0] == "p") {
val user = LocalCache.users[tags[index][1]]
if (user != null) {
ClickableUserTag(user, navController)
} else {
Text(text = "${tags[index][1].toByteArray().toNpub().toShortenHex()} ")
}
} else if (tags[index][0] == "e") {
val note = LocalCache.notes[tags[index][1]]
if (note != null) {
ClickableNoteTag(note, navController)
} else {
Text(text = "${tags[index][1].toByteArray().toNote().toShortenHex()} ")
}
} else
Text(text = "$word ")
}
}
| 63 | Kotlin | 40 | 442 | 7cb146bb50135afe2ee373dfe67ce8f55972a47b | 6,106 | amethyst | MIT License |
app/src/main/java/com/vitorpamplona/amethyst/ui/components/RichTextViewer.kt | vitorpamplona | 587,850,619 | false | null | package com.vitorpamplona.amethyst.ui.components
import android.util.Patterns
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextDirection
import androidx.navigation.NavController
import com.google.accompanist.flowlayout.FlowRow
import com.vitorpamplona.amethyst.lnurl.LnInvoiceUtil
import com.vitorpamplona.amethyst.model.LocalCache
import com.vitorpamplona.amethyst.model.toByteArray
import com.vitorpamplona.amethyst.model.toNote
import com.vitorpamplona.amethyst.service.Nip19
import com.vitorpamplona.amethyst.ui.note.toShortenHex
import nostr.postr.toNpub
import java.net.MalformedURLException
import java.net.URISyntaxException
import java.net.URL
import java.util.regex.Pattern
val imageExtension = Pattern.compile("(.*/)*.+\\.(png|jpg|gif|bmp|jpeg|webp|svg)$")
val videoExtension = Pattern.compile("(.*/)*.+\\.(mp4|avi|wmv|mpg|amv|webm)$")
val noProtocolUrlValidator = Pattern.compile("^[-a-zA-Z0-9@:%._\\+~#=]{1,256}\\.[a-zA-Z0-9()]{1,6}\\b(?:[-a-zA-Z0-9()@:%_\\+.~#?&//=]*)$")
val tagIndex = Pattern.compile(".*\\#\\[([0-9]+)\\].*")
val mentionsPattern: Pattern = Pattern.compile("@([A-Za-z0-9_-]+)")
val hashTagsPattern: Pattern = Pattern.compile("#([A-Za-z0-9_-]+)")
val urlPattern: Pattern = Patterns.WEB_URL
fun isValidURL(url: String?): Boolean {
return try {
URL(url).toURI()
true
} catch (e: MalformedURLException) {
false
} catch (e: URISyntaxException) {
false
}
}
@Composable
fun RichTextViewer(
content: String,
canPreview: Boolean,
tags: List<List<String>>?,
navController: NavController
) {
Column(
Modifier
.fillMaxWidth()
.animateContentSize()) {
// FlowRow doesn't work well with paragraphs. So we need to split them
content.split('\n').forEach { paragraph ->
FlowRow() {
paragraph.split(' ').forEach { word: String ->
if (canPreview) {
// Explicit URL
val lnInvoice = LnInvoiceUtil.findInvoice(word)
if (lnInvoice != null) {
InvoicePreview(lnInvoice)
} else if (isValidURL(word)) {
val removedParamsFromUrl = word.split("?")[0].toLowerCase()
if (imageExtension.matcher(removedParamsFromUrl).matches()) {
ZoomableImageView(word)
} else if (videoExtension.matcher(removedParamsFromUrl).matches()) {
VideoView(word)
} else {
UrlPreview(word, word)
}
} else if (Patterns.EMAIL_ADDRESS.matcher(word).matches()) {
ClickableEmail(word)
} else if (Patterns.PHONE.matcher(word).matches() && word.length > 6) {
ClickablePhone(word)
} else if (noProtocolUrlValidator.matcher(word).matches()) {
UrlPreview("https://$word", word)
} else if (tagIndex.matcher(word).matches() && tags != null) {
TagLink(word, tags, navController)
} else if (isBechLink(word)) {
BechLink(word, navController)
} else {
Text(
text = "$word ",
style = LocalTextStyle.current.copy(textDirection = TextDirection.Content),
)
}
} else {
if (isValidURL(word)) {
ClickableUrl("$word ", word)
} else if (Patterns.EMAIL_ADDRESS.matcher(word).matches()) {
ClickableEmail(word)
} else if (Patterns.PHONE.matcher(word).matches() && word.length > 6) {
ClickablePhone(word)
} else if (noProtocolUrlValidator.matcher(word).matches()) {
ClickableUrl(word, "https://$word")
} else if (tagIndex.matcher(word).matches() && tags != null) {
TagLink(word, tags, navController)
} else if (isBechLink(word)) {
BechLink(word, navController)
} else {
Text(
text = "$word ",
style = LocalTextStyle.current.copy(textDirection = TextDirection.Content),
)
}
}
}
}
}
}
}
fun isBechLink(word: String): Boolean {
return word.startsWith("nostr:", true)
|| word.startsWith("npub1", true)
|| word.startsWith("note1", true)
|| word.startsWith("nprofile1", true)
|| word.startsWith("nevent1", true)
|| word.startsWith("@npub1", true)
|| word.startsWith("@note1", true)
|| word.startsWith("@nprofile1", true)
|| word.startsWith("@nevent1", true)
}
@Composable
fun BechLink(word: String, navController: NavController) {
val uri = if (word.startsWith("nostr", true)) {
word
} else if (word.startsWith("@")) {
word.replaceFirst("@", "nostr:")
} else {
"nostr:${word}"
}
val nip19Route = try {
Nip19().uriToRoute(uri)
} catch (e: Exception) {
null
}
if (nip19Route == null) {
Text(text = "$word ")
} else {
ClickableRoute(nip19Route, navController)
}
}
@Composable
fun TagLink(word: String, tags: List<List<String>>, navController: NavController) {
val matcher = tagIndex.matcher(word)
val index = try {
matcher.find()
matcher.group(1).toInt()
} catch (e: Exception) {
println("Couldn't link tag ${word}")
null
}
if (index == null) {
return Text(text = "$word ")
}
if (index >= 0 && index < tags.size) {
if (tags[index][0] == "p") {
val user = LocalCache.users[tags[index][1]]
if (user != null) {
ClickableUserTag(user, navController)
} else {
Text(text = "${tags[index][1].toByteArray().toNpub().toShortenHex()} ")
}
} else if (tags[index][0] == "e") {
val note = LocalCache.notes[tags[index][1]]
if (note != null) {
ClickableNoteTag(note, navController)
} else {
Text(text = "${tags[index][1].toByteArray().toNote().toShortenHex()} ")
}
} else
Text(text = "$word ")
}
}
| 63 | Kotlin | 40 | 442 | 7cb146bb50135afe2ee373dfe67ce8f55972a47b | 6,106 | amethyst | MIT License |
invert-report/src/jsMain/kotlin/com/squareup/invert/common/pages/GradlePluginsReportPage.kt | square | 789,061,154 | false | {"Kotlin": 369133, "JavaScript": 4120, "HTML": 1882, "CSS": 1113, "Shell": 878} | package com.squareup.invert.common.pages
import PagingConstants.MAX_RESULTS
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import com.squareup.invert.common.DependencyGraph
import com.squareup.invert.common.InvertReportPage
import com.squareup.invert.common.ReportDataRepo
import com.squareup.invert.common.charts.ChartJsChartComposable
import com.squareup.invert.common.charts.ChartsJs
import com.squareup.invert.common.navigation.NavPage
import com.squareup.invert.common.navigation.NavRouteRepo
import com.squareup.invert.common.navigation.routes.BaseNavRoute
import com.squareup.invert.models.GradlePluginId
import ui.BootstrapClickableList
import ui.BootstrapColumn
import ui.BootstrapLoadingSpinner
import ui.BootstrapRow
import ui.BootstrapSearchBox
import ui.TitleRow
import kotlin.reflect.KClass
data class GradlePluginsNavRoute(
val query: String?,
) : BaseNavRoute(GradlePluginsReportPage.navPage) {
override fun toSearchParams(): Map<String, String> = toParamsWithOnlyPageId(this)
.also { params ->
query?.let {
params[QUERY_PARAM] = query
}
}
companion object {
private const val QUERY_PARAM = "query"
fun parser(params: Map<String, String?>): ArtifactsNavRoute {
return ArtifactsNavRoute(
query = params[QUERY_PARAM]
)
}
}
}
object GradlePluginsReportPage : InvertReportPage<GradlePluginsNavRoute> {
override val navPage: NavPage = NavPage(
pageId = "plugins",
displayName = "Gradle Plugins",
navIconSlug = "plugin",
navRouteParser = { GradlePluginsNavRoute.parser(it) }
)
override val navRouteKClass: KClass<GradlePluginsNavRoute> = GradlePluginsNavRoute::class
override val composableContent: @Composable (GradlePluginsNavRoute) -> Unit = { navRoute ->
PluginsComposable(navRoute)
}
}
@Composable
fun PluginsComposable(
navRoute: GradlePluginsNavRoute,
reportDataRepo: ReportDataRepo = DependencyGraph.reportDataRepo,
navRouteRepo: NavRouteRepo = DependencyGraph.navRouteRepo,
) {
val allPluginIds: List<GradlePluginId>? by reportDataRepo.allPluginIds.collectAsState(null)
val pluginIdToModulesMap by reportDataRepo.pluginIdToAllModulesMap.collectAsState(mapOf())
if (allPluginIds == null || pluginIdToModulesMap == null) {
BootstrapLoadingSpinner()
return
}
val pluginIdToCount = allPluginIds!!
.associateWith { pluginIdToModulesMap!!.getValue(it).size }
.entries
.sortedByDescending { it.value }
val count = allPluginIds!!.size
TitleRow("Applied Plugins ($count Total)")
BootstrapSearchBox(
navRoute.query ?: "",
"Search For Artifact..."
) {
navRouteRepo.updateNavRoute(
ArtifactsNavRoute(it)
)
}
BootstrapRow {
BootstrapColumn(6) {
BootstrapClickableList("Plugins", allPluginIds!!, MAX_RESULTS) { gradlePluginId ->
navRouteRepo.updateNavRoute(PluginDetailNavRoute(gradlePluginId))
}
}
BootstrapColumn(6) {
ChartJsChartComposable(
type = "bar",
data = ChartsJs.ChartJsData(
labels = pluginIdToCount.map { it.key },
datasets = listOf(
ChartsJs.ChartJsDataset(
label = "Plugin",
data = pluginIdToCount.map { it.value }
)
)
),
onClick = { label, value ->
navRouteRepo.updateNavRoute(
PluginDetailNavRoute(
pluginId = label,
)
)
}
)
}
}
}
| 4 | Kotlin | 0 | 82 | 31b1859a5b9b49553068a4da6ada5de2fe9d82ac | 3,951 | invert | Apache License 2.0 |
ChainSupport/src/main/java/com/creativedrewy/nativ/chainsupport/network/ApiRequestClient.kt | creativedrewy | 384,370,844 | false | null | package com.creativedrewy.nativ.chainsupport.network
import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
sealed class ResponseStatus
class Error(
val exception: Exception
) : ResponseStatus()
class Success(
val response: Response
) : ResponseStatus()
class ApiRequestClient(
private val okHttpClient: OkHttpClient = OkHttpClient()
) {
suspend fun apiRequest(request: Request): ResponseStatus {
return suspendCoroutine { cont ->
val call = okHttpClient.newCall(request)
call.enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
cont.resume(Error(e))
}
override fun onResponse(call: Call, response: Response) {
cont.resume(Success(response))
}
})
}
}
}
| 0 | Kotlin | 3 | 9 | 25bd21fd8eeb097db3db0d5c557e1253ac5e849c | 1,031 | NATIV | Apache License 2.0 |
app/src/main/java/ru/rznnike/eyehealthmanager/app/presentation/settings/testing/TestingSettingsView.kt | RznNike | 207,148,781 | false | {"Kotlin": 539909} | package ru.rznnike.eyehealthmanager.app.presentation.settings.testing
import moxy.viewstate.strategy.alias.AddToEndSingle
import ru.rznnike.eyehealthmanager.app.global.presentation.NavigationMvpView
interface TestingSettingsView : NavigationMvpView {
@AddToEndSingle
fun populateData(
armsLength: Int,
dpmm: Float,
replaceBeginningWithMorning: Boolean,
enableAutoDayPart: Boolean,
timeToDayBeginning: Long,
timeToDayMiddle: Long,
timeToDayEnd: Long
)
}
| 0 | Kotlin | 0 | 0 | 6f319237d56f99a836fe3481efd32908e28c3d56 | 523 | EyeHealthManager | MIT License |
app/src/main/java/io/github/tonnyl/mango/ui/settings/license/LicensesPresenter.kt | SelvaGaneshM | 101,606,103 | true | {"Kotlin": 256284, "HTML": 27144} | package io.github.tonnyl.mango.ui.settings.license
/**
* Created by lizhaotailang on 2017/7/21.
*
* Listens to user action from the ui [io.github.tonnyl.mango.ui.settings.license.LicensesFragment],
* retrieves the data and update the ui as required.
*/
class LicensesPresenter(view: LicensesContract.View) : LicensesContract.Presenter {
private val mView = view
init {
mView.setPresenter(this)
}
override fun subscribe() {
}
override fun unsubscribe() {
}
} | 0 | Kotlin | 1 | 0 | 2c6de8532424dcaa814445a66830e4b9f24d0495 | 507 | Mango | MIT License |
app/src/main/java/zemoa/pantrycompanion/domain/pantry/business/operations/arguments/AddItemArg.kt | zemoa | 809,462,301 | false | {"Kotlin": 13526} | package zemoa.pantrycompanion.domain.pantry.business.operations.arguments
data class AddItemArg(val name: String, val quantity: Int = 1)
| 0 | Kotlin | 0 | 0 | ad7fdaf09edfceae5e933833d74fa91460cdc921 | 138 | pantry-companion-app | Apache License 2.0 |
app/src/main/kotlin/ch/empa/openbisio/propertyassignment/PropertyAssignmentDTO.kt | empa-scientific-it | 618,383,912 | false | null | /*
* Copyright 2023 Simone Baffelli
*
* 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 ch.empa.openbisio.propertyassignment
import ch.empa.openbisio.interfaces.DTO
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class PropertyAssignmentDTO(
val section: String?,
val mandatory: Boolean,
@SerialName("property_type") val propertyTypeCode: String
) : DTO
| 0 | Kotlin | 0 | 0 | 39396bb489fa91e8e65f83206e806b67fcd3ac65 | 950 | instanceio | Apache License 2.0 |
src/main/kotlin/fr/minemobs/Application.kt | AntiMCreator | 376,626,425 | false | null | package fr.minemobs
import fr.minemobs.plugins.configureRouting
import io.ktor.application.*
import io.ktor.features.*
import io.ktor.serialization.*
import io.ktor.server.engine.*
import io.ktor.server.netty.*
fun main() {
embeddedServer(Netty, port = 8001) {
configureRouting()
install(ContentNegotiation) {
json()
}
}.start(wait = true)
}
| 0 | Kotlin | 0 | 0 | e0f9abb04a743bbaf25bb1f7bd3bc750c39c6cd5 | 388 | AntiMCreator-API | MIT License |
vendorNAVX/src/main/kotlin/org/ghrobotics/lib/util/NavXExtensions.kt | pietroglyph | 200,567,234 | true | {"Kotlin": 289769} | import com.kauailabs.navx.frc.AHRS
import org.ghrobotics.lib.mathematics.twodim.geometry.Rotation2d
import org.ghrobotics.lib.utils.Source
fun AHRS.asSource(): Source<Rotation2d> = { Rotation2d.fromDegrees(-fusedHeading.toDouble()) } | 0 | Kotlin | 0 | 0 | ba1f7b5d80c5de9763c227bc94ecde13957610a7 | 234 | FalconLibrary | MIT License |
src/main/kotlin/org/saigon/striker/config/WebConfig.kt | kupcimat | 146,526,527 | false | null | package org.saigon.striker.config
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Import
import org.springframework.web.reactive.config.WebFluxConfigurer
@Configuration
@Import(SecurityConfig::class)
class WebConfig : WebFluxConfigurer
| 6 | Kotlin | 0 | 0 | fb29449914968d7d0b88180377d6d259becc35c5 | 296 | striker | MIT License |
app/src/main/java/com/kotlin/sacalabici/framework/views/activities/activities/ModifyActivityActivity.kt | Saca-la-Bici | 849,110,267 | false | {"Kotlin": 595596} | package com.kotlin.sacalabici.framework.views.activities.activities
import android.app.Activity
import android.net.Uri
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.kotlin.sacalabici.R
import com.kotlin.sacalabici.data.network.model.ActivityData
import com.kotlin.sacalabici.data.network.model.ActivityInfo
import com.kotlin.sacalabici.databinding.ActivityAddactivityBinding
import com.kotlin.sacalabici.framework.viewmodel.ActivitiesViewModel
import com.kotlin.sacalabici.framework.viewmodel.MapViewModel
import com.kotlin.sacalabici.framework.views.fragments.ModifyActivityInfoFragment
import com.kotlin.sacalabici.framework.views.fragments.ModifyActivityRouteFragment
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class ModifyActivityActivity: AppCompatActivity(),
ModifyActivityInfoFragment.OnNextInteractionListener,
ModifyActivityRouteFragment.OnRutaConfirmListener
{
private lateinit var binding: ActivityAddactivityBinding
private lateinit var viewModel: ActivitiesViewModel
private lateinit var viewModelRoute: MapViewModel
private var isAddActivityRouteFragmentVisible = false
// Variables del intent
private lateinit var id: String
private lateinit var title: String
private lateinit var date: String
private lateinit var hour: String
private lateinit var ubi: String
private lateinit var desc: String
private lateinit var hourDur: String
private lateinit var typeAct: String
private var peopleEnrolled: Int = 0
private var state: Boolean = true
private var foro: String? = null
private var register: ArrayList<String>? = null
private var idRoute: String? = null
private var selectedImageUri: Uri? = null
private var originalImageUrl: String? = null
private lateinit var rodadaInformation: ActivityData
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_addactivity)
initializeBinding()
viewModel = ViewModelProvider(this).get(ActivitiesViewModel::class.java)
viewModelRoute = ViewModelProvider(this).get(MapViewModel::class.java)
// Guarda la información pasada en intent
id = intent.getStringExtra("id").toString()
title = intent.getStringExtra("title").toString()
date = intent.getStringExtra("date").toString()
hour = intent.getStringExtra("hour").toString()
ubi = intent.getStringExtra("ubi").toString()
desc = intent.getStringExtra("desc").toString()
hourDur = intent.getStringExtra("hourDur").toString()
originalImageUrl = intent.getStringExtra("url")
typeAct = intent.getStringExtra("typeAct").toString()
peopleEnrolled = intent.getIntExtra("peopleEnrolled", 0)
state = intent.getBooleanExtra("state", true)
foro = intent.getStringExtra("foro")
register = intent.getStringArrayListExtra("register")
idRoute = intent.getStringExtra("idRoute")
// Observa los cambios en los LiveData del ViewModel
observeViewModel()
if (savedInstanceState == null) {
// Crea una instancia del fragmento
val fragment = ModifyActivityInfoFragment().apply {
arguments = Bundle().apply {
putString("title", title)
putString("date", date)
putString("hour", hour)
putString("ubi", ubi)
putString("desc", desc)
putString("hourDur", hourDur)
putString("url", originalImageUrl)
putString("typeAct", typeAct)
}
}
// Agrega el fragmento al contenedor de la vista de la Activity
supportFragmentManager.beginTransaction()
.replace(R.id.fragmentAddActivity, fragment)
.commit()
}
}
private fun initializeBinding(){
binding = ActivityAddactivityBinding.inflate(layoutInflater)
setContentView(binding.root)
}
/*
* Función llamada desde ModifyActivityInfoFragment
* Recibe la información general del formulario en el primer fragmento
* */
override fun receiveInformation(
title: String,
date: String,
hour: String,
minutes: String,
hourDur: String,
minutesDur: String,
ubi: String,
description: String,
imageUri: Uri?
) {
// Almacenamiento de datos escritos
val info = ActivityInfo(title, date, hour, minutes, hourDur, minutesDur, ubi, description)
viewModel.activityInfo.value = info
val inputDateFormat = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
val parsedDate: Date = inputDateFormat.parse(date) ?: throw IllegalArgumentException("Fecha inválida")
val outputDateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
val formattedDate = outputDateFormat.format(parsedDate)
val hourAct = "$hour:$minutes"
val duration = "$hourDur horas $minutesDur minutos"
if (typeAct == "Rodada") {
val rodadaInfo = ActivityData(id, title, formattedDate, hourAct, ubi, description,
duration, imageUri, "Rodada", peopleEnrolled, state, foro, register, idRoute)
rodadaInformation = rodadaInfo
} else if (typeAct == "Taller") {
val taller = ActivityData(id, title, formattedDate, hourAct, ubi, description,
duration, imageUri, "Taller", peopleEnrolled, state, foro, register, idRoute)
viewModel.patchActivityTaller(taller, this@ModifyActivityActivity) { result ->
result.fold(
onSuccess = {
showToast("Taller modificado exitosamente")
val sharedPreferences = getSharedPreferences("activity_prefs", MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putBoolean("activity_updated", true)
editor.apply()
setResult(Activity.RESULT_OK)
finish()
},
onFailure = { error ->
showToast("Error al modificar el taller")
}
)
}
} else if (typeAct == "Evento") {
val evento = ActivityData(id, title, formattedDate, hourAct, ubi, description,
duration, imageUri, "Evento", peopleEnrolled, state, foro, register, idRoute)
viewModel.patchActivityEvento(evento, this@ModifyActivityActivity) { result ->
result.fold(
onSuccess = {
showToast("Evento modificado exitosamente")
val sharedPreferences = getSharedPreferences("activity_prefs", MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putBoolean("activity_updated", true)
editor.apply()
setResult(Activity.RESULT_OK)
finish()
},
onFailure = { error ->
showToast("Error al modificar el evento")
}
)
}
}
}
/*
* Función que llama la lista de rutas desde el viewModel
* */
private fun toggleRutasList() {
val fragmentManager = supportFragmentManager
val modifyActivityFragment = fragmentManager.findFragmentById(R.id.fragmentAddActivity)
if (isAddActivityRouteFragmentVisible) {
// Si el fragmento ya está visible, lo eliminamos
if (modifyActivityFragment != null) {
fragmentManager.beginTransaction()
.remove(modifyActivityFragment)
.addToBackStack(null)
.commit()
}
isAddActivityRouteFragmentVisible = false
} else {
// Si el fragmento no está visible, lo añadimos
viewModelRoute.getRouteList() // Esto activará la observación y añadirá el fragmento
isAddActivityRouteFragmentVisible = true
}
}
/*
* Función llamada desde ModifyActivityInfoFragment
* Termina la actividad
*
*/
override fun onCloseClicked() {
setResult(Activity.RESULT_OK)
finish()
}
/*
* Función llamada desde ModifyActivityInfoFragment
* Si es rodada, cambia al siguiente fragmento para elegir una ruta
* */
override fun onNextClicked(type: String) {
if (type == "Rodada") {
toggleRutasList()
}
}
/*
* Función que observa los cambios en los LiveData del ViewModel
* */
private fun observeViewModel() {
// Observa los LiveData del ViewModel
viewModelRoute.routeObjectLiveData.observe(this, Observer { rutasList ->
rutasList?.let {
// Si la lista de rutas se ha obtenido, crea el fragmento RutasFragment con el ID de la ruta
val routeFragment = ModifyActivityRouteFragment.newInstance(it, idRoute)
supportFragmentManager.beginTransaction()
.replace(R.id.fragmentAddActivity, routeFragment)
.addToBackStack(null)
.commit()
} ?: run {
showToast("Error al obtener la lista de rutas.")
}
})
viewModelRoute.toastMessageLiveData.observe(this, Observer { message ->
showToast(message)
})
}
/*
* Función llamada desde ModifyActivityRouteFragment
* Recibe la ruta seleccionada por el usuario
* */
override fun onRutaConfirmed(rutaID: String) {
rodadaInformation.idRouteBase = rutaID
viewModel.patchActivityRodada(rodadaInformation, this@ModifyActivityActivity) { result ->
result.fold(
onSuccess = {
showToast("Rodada modificada exitosamente")
val sharedPreferences = getSharedPreferences("activity_prefs", MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putBoolean("activity_updated", true)
editor.apply()
setResult(Activity.RESULT_OK)
finish()
},
onFailure = { error ->
showToast("Error al modificar la rodada")
}
)
}
}
private fun showToast(message: String) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
}
} | 1 | Kotlin | 1 | 1 | b8a06baa119ffb0d355d1ae7fe7e607bb8f1c52c | 10,916 | app-android | MIT License |
app/src/main/java/com/hwilliamgo/fuzzy_video_drill/scene/screenprojection/CodecLiveH265.kt | HWilliamgo | 344,464,529 | false | null | package com.hwilliamgo.fuzzy_video_drill.scene.screenprojection
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.MediaCodec
import android.media.MediaCodecInfo
import android.media.MediaFormat
import android.media.projection.MediaProjection
import com.blankj.utilcode.util.LogUtils
import com.hwilliamgo.fuzzy_video_drill.socket.ISocket
import java.nio.ByteBuffer
import kotlin.concurrent.thread
/**
* date: 2021/3/4
* author: HWilliamgo
* description:
*/
class CodecLiveH265(
private val socketPush: ISocket,
private val mediaProjection: MediaProjection
) {
companion object {
const val NAL_I = 19
const val NAL_VPS = 32
}
private var mediaCodec: MediaCodec? = null
private var virtualDisplay: VirtualDisplay? = null
private val width = 720
private val height = 1280
private var vps_sps_pps_buffer: ByteArray? = null
@Volatile
private var isRunning = false
// <editor-fold defaultstate="collapsed" desc="API">
fun startLive() {
//create format
val format = MediaFormat.createVideoFormat(MediaFormat.MIMETYPE_VIDEO_HEVC, width, height)
format.apply {
setInteger(
MediaFormat.KEY_COLOR_FORMAT,
MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface
)
setInteger(MediaFormat.KEY_BIT_RATE, width * height)
setInteger(MediaFormat.KEY_FRAME_RATE, 20)
setInteger(MediaFormat.KEY_I_FRAME_INTERVAL, 1)
}
//create codec
mediaCodec = MediaCodec.createEncoderByType("video/hevc")
mediaCodec?.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
//get input surface
val surface = mediaCodec?.createInputSurface()
//create screen projection display, and set input surface of codec to it.
virtualDisplay = mediaProjection.createVirtualDisplay(
"-display",
width,
height,
1,
DisplayManager.VIRTUAL_DISPLAY_FLAG_PUBLIC,
surface,
null,
null
)
isRunning = true
thread {
val codec = mediaCodec ?: return@thread
codec.start()
val bufferInfo = MediaCodec.BufferInfo()
while (isRunning) {
try {
val outputBufferId = codec.dequeueOutputBuffer(bufferInfo, 10000)
if (outputBufferId >= 0) {
val byteBuffer = codec.getOutputBuffer(outputBufferId)!!
dealFrame(byteBuffer, bufferInfo)
codec.releaseOutputBuffer(outputBufferId, false);
}
} catch (e: Exception) {
e.printStackTrace()
break
}
}
}
}
fun stopLive() {
isRunning = false
}
// </editor-fold>
private fun dealFrame(bb: ByteBuffer, bufferInfo: MediaCodec.BufferInfo) {
//如果是00 00 00 01,那么是偏移到第4个元素来取出nalu type。
//如果是00 00 01, 那么是偏移到第3个元素来取出nalu type。
val offset: Int = if (bb.get(2).toInt() == 0x01) {
3
} else {
4
}
val type = (bb.get(offset).toInt() and 0x7E) ushr 1
LogUtils.d("nalueType=$type")
when (type) {
NAL_VPS -> {
vps_sps_pps_buffer = ByteArray(bufferInfo.size)
bb.get(vps_sps_pps_buffer)
}
NAL_I -> {
val bytes = ByteArray(bufferInfo.size)
bb.get(bytes)
val vpsSpsPpsBufferTmp = vps_sps_pps_buffer!!
val newBuf: ByteArray
newBuf = ByteArray(vpsSpsPpsBufferTmp.size + bytes.size)
System.arraycopy(vpsSpsPpsBufferTmp, 0, newBuf, 0, vpsSpsPpsBufferTmp.size)
System.arraycopy(bytes, 0, newBuf, vpsSpsPpsBufferTmp.size, bytes.size)
socketPush.sendData(newBuf)
}
else -> {
val bytes = ByteArray(bufferInfo.size)
bb.get(bytes)
socketPush.sendData(bytes)
}
}
}
} | 4 | Kotlin | 0 | 0 | 210df31642510088cea6e621d0cc6dfd22964156 | 4,256 | fuzzy-video-drill | MIT License |
android/DartsScorecard/domain/src/main/java/nl/entreco/domain/beta/vote/SubmitVoteResponse.kt | Entreco | 110,022,468 | false | null | package nl.entreco.domain.beta.vote
/**
* Created by entreco on 07/02/2018.
*/
class SubmitVoteResponse (val ok: Boolean) | 4 | null | 1 | 1 | a031a0eeadd0aa21cd587b5008364a16f890b264 | 124 | Darts-Scorecard | Apache License 2.0 |
Core/src/main/kotlin/com/asanasoft/util/Utils.kt | asanasoft | 729,726,651 | false | {"Kotlin": 55106} | package com.asanasoft.util
import com.asanasoft.graphdb.GraphEntity
import kotlinx.serialization.json.*
data class Result<out T>(
val value : T? = null,
val cause : Throwable? = null,
val isSuccess : Boolean = (value != null),
val isFailure : Boolean = (cause != null),
val message : String = ""
)
fun noop() = Unit
fun noop(someValue : Any?) = Unit
val pass : Unit = Unit
val mapSerializer = GenericMapSerializer()
fun jsonObjectToMap(json : JsonElement, map : MutableMap<String, Any?>) {
val jsonObject = json as JsonObject
for (key in jsonObject.keys) {
var jsonElement = jsonObject[key]
when (jsonElement) {
is JsonPrimitive -> map.put(key, jsonElement.content)
is JsonObject -> map.put(key, GraphEntity(jsonElement))
is JsonArray -> {
val list = mutableListOf<GraphEntity>()
for (elem in jsonElement.iterator()) {
list.add(GraphEntity(elem as JsonObject))
}
map.put(key, list)
}
null -> TODO()
}
}
}
fun stringToJsonElement(jsonString : String) : JsonElement {
Json.parseToJsonElement(jsonString).let {
return when (it) {
is JsonPrimitive -> it
is JsonObject -> it
is JsonArray -> it
else -> JsonPrimitive("")
}
}
}
fun jsonElementToString(json : JsonElement) : String {
return when (json) {
is JsonPrimitive -> json.content
is JsonObject -> json.toString()
is JsonArray -> json.toString()
else -> ""
}
}
fun jsonElementToMap(json : JsonElement) : Map<String, Any?> {
val map = mutableMapOf<String, Any?>()
jsonObjectToMap(json, map)
return map
}
fun mapToJsonElement(map : Map<String, Any?>) : JsonElement {
return Json.encodeToJsonElement(mapSerializer, map)
}
fun mapToJsonElement(map : Map<String, String>, key : String) : JsonElement {
return Json.encodeToJsonElement(mapSerializer, mapOf(key to map))
}
| 0 | Kotlin | 0 | 0 | fc0995c94a9be5cc174e2b7e2d2f51ce37188984 | 2,079 | graphdb-document | MIT License |
core/ui/src/main/java/com/niyaj/ui/utils/AnalyticsExtensions.kt | skniyajali | 644,752,474 | false | {"Kotlin": 5045629, "Shell": 16584, "Ruby": 1461, "Java": 232} | /*
* Copyright 2024 <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.niyaj.ui.utils
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import com.niyaj.core.analytics.AnalyticsEvent
import com.niyaj.core.analytics.AnalyticsEvent.Param
import com.niyaj.core.analytics.AnalyticsEvent.ParamKeys
import com.niyaj.core.analytics.AnalyticsEvent.Types
import com.niyaj.core.analytics.AnalyticsHelper
import com.niyaj.core.analytics.LocalAnalyticsHelper
/**
* Classes and functions associated with analytics events for the UI.
*/
fun AnalyticsHelper.logScreenView(screenName: String) {
logEvent(
AnalyticsEvent(
type = Types.SCREEN_VIEW,
extras = listOf(
Param(ParamKeys.SCREEN_NAME, screenName),
),
),
)
}
/**
* A side-effect which records a screen view event.
*/
@Composable
fun TrackScreenViewEvent(
screenName: String,
analyticsHelper: AnalyticsHelper = LocalAnalyticsHelper.current,
) = DisposableEffect(Unit) {
analyticsHelper.logScreenView(screenName)
onDispose {}
}
| 42 | Kotlin | 0 | 1 | 49485fe344b9345cd0cce0e0961742226dbd8ea1 | 1,644 | PoposRoom | Apache License 2.0 |
src/main/kotlin/burrows/apps/example/gif/presentation/BaseSchedulerProvider.kt | waterpoweredmonkey | 118,532,876 | true | {"Kotlin": 73221, "HTML": 3528} | package burrows.apps.example.gif.presentation
import io.reactivex.Scheduler
/**
* @author [<NAME>](mailto:<EMAIL>)
*/
interface BaseSchedulerProvider {
fun io(): Scheduler
fun ui(): Scheduler
}
| 0 | Kotlin | 0 | 0 | b68754cf80382552ee88e411fab151a44ea06e72 | 202 | android-gif-example | Apache License 2.0 |
app/src/main/java/name/lmj0011/courierlocker/helpers/AppDataImportExportHelper.kt | lmj0011 | 213,748,690 | false | null | package name.lmj0011.courierlocker.helpers
import com.github.salomonbrys.kotson.jsonArray
import com.github.salomonbrys.kotson.jsonObject
import com.github.salomonbrys.kotson.toJsonArray
import com.google.gson.JsonObject
import name.lmj0011.courierlocker.database.*
object AppDataImportExportHelper {
fun appModelsToJson(
trips: List<Trip>,
apartments: List<Apartment>,
gatecodes: List<GateCode>,
customers: List<Customer>,
gigLabels: List<GigLabel>
): JsonObject {
return jsonObject(
"trips" to jsonArray(
trips.map {
jsonObject(
"id" to it.id,
"timestamp" to it.timestamp,
"pickupAddress" to it.pickupAddress,
"pickupAddressLatitude" to it.pickupAddressLatitude,
"pickupAddressLongitude" to it.pickupAddressLongitude,
"dropOffAddress" to it.dropOffAddress,
"dropOffAddressLatitude" to it.dropOffAddressLatitude,
"dropOffAddressLongitude" to it.dropOffAddressLongitude,
"distance" to it.distance,
"payAmount" to it.payAmount,
"gigName" to it.gigName,
"stops" to jsonArray(
it.stops.map {stop ->
jsonObject(
"address" to stop.address,
"latitude" to stop.latitude,
"longitude" to stop.longitude
)
}
),
"notes" to it.notes
)
}
),
"apartments" to jsonArray(
apartments.map {
jsonObject(
"id" to it.id,
"gateCodeId" to it.gateCodeId,
"name" to it.name,
"address" to it.address,
"latitude" to it.latitude,
"longitude" to it.longitude,
"aboveGroundFloorCount" to it.aboveGroundFloorCount,
"belowGroundFloorCount" to it.belowGroundFloorCount,
"floorOneAsBlueprint" to it.floorOneAsBlueprint,
"buildings" to jsonArray(
it.buildings.map {bldg ->
jsonObject(
"number" to bldg.number,
"latitude" to bldg.latitude,
"longitude" to bldg.longitude,
"hasWaypoint" to bldg.hasWaypoint,
"waypointLatitude" to bldg.waypointLatitude,
"waypointLongitude" to bldg.waypointLongitude
)
}
),
"buildingUnits" to jsonArray(
it.buildingUnits.map { bldgUnit ->
jsonObject(
"number" to bldgUnit.number,
"floorNumber" to bldgUnit.floorNumber,
"latitude" to bldgUnit.latitude,
"longitude" to bldgUnit.longitude,
"hasWaypoint" to bldgUnit.hasWaypoint,
"waypointLatitude" to bldgUnit.waypointLatitude,
"waypointLongitude" to bldgUnit.waypointLongitude
)
}
)
)
}
),
"gatecodes" to jsonArray(
gatecodes.map {
jsonObject(
"id" to it.id,
"address" to it.address,
"latitude" to it.latitude,
"longitude" to it.longitude,
"codes" to it.codes.toJsonArray() // can't call this on a non-primitive object :(
)
}
),
"customers" to jsonArray(
customers.map {
jsonObject(
"id" to it.id,
"name" to it.name,
"address" to it.address,
"addressLatitude" to it.addressLatitude,
"addressLongitude" to it.addressLongitude,
"impression" to it.impression,
"note" to it.note
)
}
),
"gigLabels" to jsonArray(
gigLabels.map {
jsonObject(
"id" to it.id,
"name" to it.name,
"order" to it.order,
"visible" to it.visible
)
}
)
)
}
} | 0 | Kotlin | 3 | 2 | 930974f6dba1a6ab516d6c4f95813ba0c6668570 | 5,293 | courier-locker | Apache License 2.0 |
wear/src/main/java/io/homeassistant/companion/android/onboarding/phoneinstall/PhoneInstallView.kt | home-assistant | 179,008,173 | false | {"Kotlin": 2427322, "Ruby": 3180} | package io.homeassistant.companion.android.onboarding.phoneinstall
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.ButtonDefaults
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import io.homeassistant.companion.android.R
import io.homeassistant.companion.android.views.ThemeLazyColumn
import io.homeassistant.companion.android.common.R as commonR
@Composable
fun PhoneInstallView(
onInstall: () -> Unit,
onRefresh: () -> Unit,
onAdvanced: () -> Unit
) {
ThemeLazyColumn {
item {
Image(
painter = painterResource(R.drawable.app_icon),
contentDescription = null,
modifier = Modifier.size(48.dp)
)
}
item {
Text(
text = stringResource(commonR.string.install_phone_to_continue),
style = MaterialTheme.typography.title3,
textAlign = TextAlign.Center,
modifier = Modifier.fillMaxWidth().padding(vertical = 16.dp)
)
}
item {
Button(
onClick = onInstall,
modifier = Modifier.fillMaxWidth()
) {
Text(stringResource(commonR.string.install))
}
}
item {
Button(
onClick = onRefresh,
modifier = Modifier.fillMaxWidth(),
colors = ButtonDefaults.secondaryButtonColors()
) {
Text(stringResource(commonR.string.refresh))
}
}
item {
Button(
onClick = onAdvanced,
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp),
colors = ButtonDefaults.secondaryButtonColors()
) {
Text(stringResource(commonR.string.advanced))
}
}
}
}
@Preview(device = Devices.WEAR_OS_LARGE_ROUND)
@Composable
fun PhoneInstallViewPreview() {
PhoneInstallView(
onInstall = { },
onRefresh = { },
onAdvanced = { }
)
}
| 146 | Kotlin | 524 | 1,766 | b290d568efc8c56a68607cb5997c0424c01b2222 | 2,726 | android | Apache License 2.0 |
privacysandbox/tools/tools-apigenerator/src/test/test-data/callbacks/output/com/sdkwithcallbacks/SdkServiceClientProxy.kt | androidx | 256,589,781 | false | null | package com.sdkwithcallbacks
public class SdkServiceClientProxy(
public val remote: ISdkService,
) : SdkService {
public override fun registerCallback(callback: SdkCallback): Unit {
remote.registerCallback(SdkCallbackStubDelegate(callback))
}
}
| 16 | Kotlin | 787 | 4,563 | 2c8f7ee9eb6bd033a33c2cf8e22b21dd953accac | 266 | androidx | Apache License 2.0 |
plugins/full-line/local/src/org/jetbrains/completion/full/line/local/generation/model/HiddenStateCachingModelWrapper.kt | xGreat | 182,651,778 | false | null | package org.jetbrains.completion.full.line.local.generation.model
import io.kinference.model.ExecutionContext
class HiddenStateCachingModelWrapper(
private val delegate: ModelWrapper, private val cache: HiddenStateCache
) : ModelWrapper by delegate {
override fun initLastLogProbs(inputIds: Array<IntArray>, execContext: ExecutionContext): ModelOutput {
val cacheQueryResult = cache.query(inputIds[0])
val modelOutput = getModelOutput(inputIds[0], cacheQueryResult, execContext)
if (cacheQueryResult.cacheOutdated) {
cache.cache(inputIds[0], modelOutput)
}
return modelOutput
}
private fun getModelOutput(
inputIds: IntArray, cacheQueryResult: HiddenStateCache.QueryResult, execContext: ExecutionContext
): ModelOutput {
val (newInputIds, pastStates, modelOutput) = cacheQueryResult
return when {
modelOutput != null -> modelOutput
pastStates != null -> delegate.getLogProbs(arrayOf(newInputIds), pastStates, execContext).lastLogProbs()
else -> delegate.initLastLogProbs(arrayOf(inputIds), execContext)
}
}
}
| 1 | null | 1 | 1 | fb5f23167ce9cc53bfa3ee054b445cf4d8f1ce98 | 1,085 | intellij-community | Apache License 2.0 |
mui-icons-kotlin/src/jsMain/kotlin/mui/icons/material/PushPinRounded.kt | karakum-team | 387,062,541 | false | {"Kotlin": 3060426, "TypeScript": 2249, "HTML": 724, "CSS": 86} | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/PushPinRounded")
package mui.icons.material
@JsName("default")
external val PushPinRounded: SvgIconComponent
| 0 | Kotlin | 5 | 35 | 83952a79ffff62f5409461a2928102d0ff95d86b | 192 | mui-kotlin | Apache License 2.0 |
src/Day13Alt.kt | GarrettShorr | 571,769,671 | false | null | import com.beust.klaxon.Klaxon
import kotlin.reflect.typeOf
fun main() {
fun isCorrect(leftList: MutableList<Any>?, rightList: MutableList<Any>?): Boolean? {
println("$leftList vs. $rightList")
if(leftList == null && rightList == null) {
return null
}
if(leftList?.isEmpty() == true && !rightList?.isEmpty()!!) {
return true
}
if(rightList?.isEmpty() == true && !leftList?.isEmpty()!!) {
return false
}
var left = leftList?.get(0)
var right = rightList?.get(0)
//both list
if(left is List<*> && right is List<*>) {
if(left.isEmpty() && !right.isEmpty()) {
return true
} else if(!left.isEmpty() && right.isEmpty()) {
return false
} else {
return isCorrect(left as MutableList<Any>?, right as MutableList<Any>?)
}
}
// both string
if(left is Int && right is Int) {
if(left == right) {
leftList?.removeAt(0)
rightList?.removeAt(0)
return isCorrect(leftList, rightList)
} else {
return left < right
}
}
// 1 of each
if(left is String && right is List<*>) {
left = listOf(left)
leftList?.set(0, left)
return isCorrect(leftList, rightList)
}
// 1 empty
return false
}
fun part1(input: List<String>): Int {
val parser = Klaxon()
var instructions = mutableListOf<List<Any>>()
for(line in input) {
if(line != "") {
instructions.add(parser.parseArray<List<Any>>(line)!!)
}
}
instructions = instructions.windowed(2).toMutableList()
// println(instructions.joinToString("\n"))
var count = 0
var indexTotal = 0
for(i in instructions.indices step 2) {
println("original pair: ${instructions[i]} ")
if(isCorrect(instructions[i][0] as MutableList<Any>, instructions[i][1] as MutableList<Any>) == true) {
count++
indexTotal += i
println("pair: ${instructions[i]} is correct. count: $count i: $i")
}
}
return indexTotal
}
fun part2(input: List<String>): Int {
return 0
}
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day13_test")
println(part1(testInput))
// println(part2(testInput))
val input = readInput("Day13")
// output(part1(input))
// output(part2(input))
}
| 0 | Kotlin | 0 | 0 | 391336623968f210a19797b44d027b05f31484b5 | 2,715 | AdventOfCode2022 | Apache License 2.0 |
mysql-async/src/main/java/com/github/jasync/sql/db/mysql/binary/encoder/ShortEncoder.kt | mirromutth | 176,066,212 | true | {"Kotlin": 679473, "Java": 15957, "Shell": 3740} | package com.github.jasync.sql.db.mysql.binary.encoder
import com.github.jasync.sql.db.mysql.column.ColumnTypes
import io.netty.buffer.ByteBuf
object ShortEncoder : BinaryEncoder {
override fun encode(value: Any, buffer: ByteBuf) {
buffer.writeShort((value as Short).toInt())
}
override fun encodesTo(): Int = ColumnTypes.FIELD_TYPE_SHORT
}
| 0 | Kotlin | 0 | 2 | 76854b2df7ba39c4843d8c372343403721c4c8b7 | 363 | jasync-sql | Apache License 2.0 |
app/src/main/java/teka/android/chamaaapp/data/remote/services/ChamaaAccountRetrofitService.kt | samAricha | 759,726,734 | false | {"Kotlin": 368851} | package teka.android.chamaaapp.data.remote.services
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.POST
import teka.android.chamaaapp.data.models.MemberRequest
import teka.android.chamaaapp.data.remote.dtos.ApiResponseHandler
import teka.android.chamaaapp.data.remote.dtos.ChamaAccountDTO
import teka.android.chamaaapp.data.room_remote_sync.models.FetchMembersResponse
import teka.android.chamaaapp.data.room_remote_sync.models.UploadDataResponse
interface ChamaaAccountRetrofitService {
@GET("api/chamaa_accounts")
suspend fun getChamaaAccounts():ApiResponseHandler<List<ChamaAccountDTO>>
@POST("api/chamaa_accounts")
suspend fun backupChamaaAccounts(@Body chamaAccountDTO: ChamaAccountDTO): ApiResponseHandler<ChamaAccountDTO>
}
| 0 | Kotlin | 0 | 1 | 72c9892e0bec64f082d0c237da58be9cc6822194 | 781 | ChamaYetu | The Unlicense |
app/src/main/java/com/example/tasks/viewmodel/TaskFormViewModel.kt | josias-soares | 300,976,150 | false | null | package com.example.tasks.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.tasks.service.listener.APIListener
import com.example.tasks.service.listener.ValidationListener
import com.example.tasks.service.model.PriorityModel
import com.example.tasks.service.model.TaskModel
import com.example.tasks.service.repository.PriorityRepository
import com.example.tasks.service.repository.TaskRepository
class TaskFormViewModel(application: Application) : AndroidViewModel(application) {
private val mPriorityRepository = PriorityRepository(application)
private val mTaskRepository = TaskRepository(application)
private val mPriorities = MutableLiveData<List<PriorityModel>>()
var priorities: LiveData<List<PriorityModel>> = mPriorities
private val mTaskCreated = MutableLiveData<ValidationListener>()
var taskCreated: LiveData<ValidationListener> = mTaskCreated
private val mTask = MutableLiveData<TaskModel>()
var task: LiveData<TaskModel> = mTask
fun listPriorities() {
mPriorities.value = mPriorityRepository.list()
}
fun save(task: TaskModel) {
if (task.id == 0) {
mTaskRepository.create(task, object : APIListener<Boolean> {
override fun onSuccess(model: Boolean) {
mTaskCreated.value = ValidationListener()
}
override fun onFailure(failure: String) {
mTaskCreated.value = ValidationListener(failure)
}
})
} else {
mTaskRepository.update(task, object : APIListener<Boolean> {
override fun onSuccess(model: Boolean) {
mTaskCreated.value = ValidationListener()
}
override fun onFailure(failure: String) {
mTaskCreated.value = ValidationListener(failure)
}
})
}
}
fun load(id: Int) {
mTaskRepository.load(id, object : APIListener<TaskModel> {
override fun onSuccess(model: TaskModel) {
mTask.value = model
}
override fun onFailure(failure: String) {
mTask.value = null
}
})
}
} | 0 | Kotlin | 0 | 1 | 6388e87998f20a8e8a622d1e44f0db2387004dbd | 2,358 | mvvm_task | Apache License 2.0 |
jwk/client/src/main/kotlin/net/razvan/http4kconnect/jwk/client/Jwk.kt | razvn | 332,550,485 | false | null | package net.razvan.http4kconnect.jwk.client
import dev.forkhandles.result4k.Result
import net.razvan.http4kconnect.jwk.client.action.JwkAction
import org.http4k.connect.RemoteFailure
interface Jwk {
operator fun <R : Any> invoke(action: JwkAction<R>): Result<R, RemoteFailure>
companion object
}
| 0 | Kotlin | 0 | 1 | 4327d225dbc7ad26042ea1ad199ba7442b30e9c8 | 307 | http4k-connect-jwk | Apache License 2.0 |
src/org/jetbrains/r/visualization/ui/DumbAwareActionAdapter.kt | JetBrains | 214,212,060 | false | {"Kotlin": 2850628, "Java": 814635, "R": 36890, "CSS": 23692, "Lex": 14307, "HTML": 10063, "Rez": 245, "Rebol": 64} | package org.jetbrains.r.visualization.ui
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
abstract class DumbAwareActionAdapter : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
// Nothing to do here
}
} | 2 | Kotlin | 12 | 62 | 7953e644bfb78f3573ebec4e156aed2a985f457c | 292 | Rplugin | Apache License 2.0 |
animatedFabMenu.kt | rajaumair7890 | 691,658,004 | false | {"Kotlin": 4166} | package com.codingwithumair.app.vidcompose
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material3.ElevatedCard
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AnimatedFabMenu(){
var isFabExpanded by remember {
mutableStateOf(false)
}
val fabTransition = updateTransition(targetState = isFabExpanded, label = "")
val expandFabHorizontally by fabTransition.animateDp(
transitionSpec = { tween(200, 50, LinearEasing) }, label = "",
targetValueByState = {isExpanded ->
if (isExpanded) 155.dp else 80.dp
}
)
val shrinkFabVertically by fabTransition.animateDp(
transitionSpec = { tween(200, 50, LinearEasing) }, label = "",
targetValueByState = {isExpanded ->
if (isExpanded) 60.dp else 80.dp
}
)
val menuHeight by fabTransition.animateDp(
transitionSpec = { tween(150, 100, LinearEasing) }, label = "",
targetValueByState = {isExpanded ->
if (isExpanded) 200.dp else 0.dp
}
)
Scaffold(
floatingActionButton = {
ElevatedCard(
modifier = Modifier.padding(4.dp),
shape = RoundedCornerShape(20.dp)
) {
AnimatedVisibility(
visible = isFabExpanded,
enter = fadeIn(tween(700, 200, LinearEasing)),
exit = fadeOut(tween(500, 0, LinearEasing)),
){
Column(
modifier = Modifier
.height(menuHeight)
){
(1..4).forEach {
Row(
modifier = Modifier
.width(expandFabHorizontally),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Icon(
Icons.Default.Menu,
contentDescription = null,
modifier = Modifier.padding(12.dp)
)
Spacer(modifier = Modifier.weight(1f))
Text(text = "item $it", modifier = Modifier.padding(end = 12.dp))
}
}
}
}
FloatingActionButton(
onClick = { isFabExpanded = !isFabExpanded },
modifier = Modifier
.width(expandFabHorizontally)
.height(shrinkFabVertically)
) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
){
Icon(Icons.Default.Menu, contentDescription = null, modifier = Modifier.padding(12.dp))
AnimatedVisibility(
visible = isFabExpanded,
enter = fadeIn(tween(300, 100, LinearEasing)),
exit = fadeOut(tween(150, 50, LinearEasing))
) {
Text(text = "Expanded Menu", modifier = Modifier.padding(end = 12.dp))
}
}
}
}
}
){ paddingValues ->
LazyColumn(Modifier.padding(paddingValues)){
items(20){
Text(text = "item $it")
}
}
}
}
| 0 | Kotlin | 0 | 6 | e1ab4b32b0e0ee84db68c88e0514bc1abe5185ec | 4,035 | AnimatedFABMenu | Apache License 2.0 |
src/test/kotlin/com/ne_rabotaem/ApplicationTest.kt | spbu-math-cs | 698,936,932 | false | {"Kotlin": 35658, "HTML": 16846, "JavaScript": 12279, "Handlebars": 2519, "CSS": 912} | package com.ne_rabotaem
import com.ne_rabotaem.database.event.Event
import com.ne_rabotaem.database.grade.Demo_grade
import com.ne_rabotaem.database.team.Team
import com.ne_rabotaem.database.token.Token
import com.ne_rabotaem.database.user.User
import com.ne_rabotaem.database.user.UserDTO
import com.ne_rabotaem.database.user.rank
import com.ne_rabotaem.features.demo.configureDemoRouting
import com.ne_rabotaem.features.home.configureAboutRouting
import com.ne_rabotaem.features.home.configureHomeRouting
import com.ne_rabotaem.features.login.LoginReceiveRemote
import com.ne_rabotaem.features.login.LoginResponseRemote
import com.ne_rabotaem.features.login.configureLoginRouting
import com.ne_rabotaem.features.register.configureRegisterRouting
import com.ne_rabotaem.plugins.*
import io.ktor.client.call.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.server.testing.*
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.transactions.transaction
import kotlin.test.*
class ApplicationTest {
val numberOfTestUsers = 10L
val loginToToken = HashMap<String, String>()
val loginToUser = HashMap<String, UserDTO>()
private fun connectToTestDB() {
Database.connect(
"jdbc:postgresql://localhost:5432/DEV_ne_rabotaem",
driver = "org.postgresql.Driver",
user = "postgres",
password = "<PASSWORD>",
)
}
private fun ApplicationTestBuilder.setApplication() {
application {
connectToTestDB()
configureSerialization()
configureRouting()
configureHomeRouting()
configureLoginRouting()
configureRegisterRouting()
configureDemoRouting()
configureAboutRouting()
}
}
private fun getRandomString(length: Int): String {
val allowedChars = (Char.MIN_VALUE..Char.MAX_VALUE)
return (1..length)
.map { allowedChars.random() }
.joinToString("")
}
@BeforeTest
fun generateTestData() {
while (loginToUser.size < numberOfTestUsers) {
var login = getRandomString((1..User.login_max_length).random())
while (login in loginToUser.keys) {
login = getRandomString((1..User.login_max_length).random())
}
val first_name = getRandomString((1..User.first_name_max_length).random())
val last_name = getRandomString((1..User.last_name_max_length).random())
val father_name = getRandomString((1..User.father_name_max_length).random())
val password = getRandomString((1..User.password_max_length).random())
val rank_ = rank.values().random()
val user = UserDTO(first_name, last_name, father_name, login, password, rank_)
loginToUser[login] = user
}
}
@AfterTest
fun clean() {
loginToToken.clear()
loginToUser.clear()
connectToTestDB()
User.run {
transaction {
deleteAll()
}
}
Token.run {
transaction {
deleteAll()
}
}
Team.run {
transaction {
deleteAll()
}
}
Demo_grade.run {
transaction {
deleteAll()
}
}
Event.run {
transaction {
deleteAll()
}
}
}
@Test
fun basicRegistrationAndLoginTest() = testApplication {
setApplication()
// check if registration is correct
for (user in loginToUser.values) {
val response = client.post("/register") {
contentType(ContentType.Application.Json)
setBody(Json.encodeToString(user))
}
assertEquals(HttpStatusCode.OK, response.status)
}
var numberOfQueries: Long = 0
User.run {
transaction {
numberOfQueries = selectAll().count()
}
}
assertEquals(numberOfTestUsers, numberOfQueries)
// check if double registration is NOT allowed
for (user in loginToUser.values) {
val response = client.post("/register") {
contentType(ContentType.Application.Json)
setBody(Json.encodeToString(user))
}
assertEquals(HttpStatusCode.Conflict, response.status)
}
User.run {
transaction {
numberOfQueries = selectAll().count()
}
}
assertEquals(numberOfTestUsers, numberOfQueries)
// check if login handles correctly
for (user in loginToUser.values) {
val response = client.post("/login") {
contentType(ContentType.Application.Json)
setBody(Json.encodeToString(LoginReceiveRemote(user.login, user.password)))
}
assertEquals(HttpStatusCode.OK, response.status)
var tokenFromDB = ""
Token.run {
transaction {
tokenFromDB = select { login eq user.login }.single()[token]
}
}
val tokenFromResponse = Json.decodeFromString<LoginResponseRemote>(response.body()).token
assertEquals(tokenFromResponse, tokenFromDB)
loginToToken[user.login] = tokenFromDB
}
Token.run {
transaction {
numberOfQueries = selectAll().count()
}
}
assertEquals(numberOfTestUsers, numberOfQueries)
// check if double login is allowed
for (user in loginToUser.values) {
val response = client.post("/login") {
contentType(ContentType.Application.Json)
setBody(Json.encodeToString(LoginReceiveRemote(user.login, user.password)))
}
assertEquals(HttpStatusCode.OK, response.status)
var tokenFromDB = ""
Token.run {
transaction {
tokenFromDB = select { login eq user.login }.last()[token]
}
}
val tokenFromResponse = Json.decodeFromString<LoginResponseRemote>(response.body()).token
assertEquals(tokenFromResponse, tokenFromDB)
}
Token.run {
transaction {
numberOfQueries = selectAll().count()
}
}
assertEquals(2*numberOfTestUsers, numberOfQueries)
// check if login with wrong password is NOT allowed
if (loginToUser.isNotEmpty()) {
val login = loginToUser.keys.first()
var wrongPassword = getRandomString((1..User.password_max_length).random())
while (wrongPassword == loginToUser[login]!!.password) {
wrongPassword = getRandomString((1..User.password_max_length).random())
}
val response = client.post("/login") {
contentType(ContentType.Application.Json)
setBody(Json.encodeToString(LoginReceiveRemote(login, wrongPassword)))
}
assertEquals(HttpStatusCode.BadRequest, response.status)
}
}
@Test
fun nonExistingLoginTest() = testApplication {
setApplication()
var login = getRandomString((1..User.login_max_length).random())
while (login in loginToUser.keys) {
login = getRandomString((1..User.login_max_length).random())
}
val password = getRandomString((1..User.password_max_length).random())
val response = client.post("/login") {
contentType(ContentType.Application.Json)
setBody(Json.encodeToString(LoginReceiveRemote(login, password)))
}
assertEquals(HttpStatusCode.Conflict, response.status)
}
@Test
fun emptyLoginInRegisterTest() {
TODO()
}
@Test
fun emptyFirstNameInRegisterTest() {
TODO()
}
@Test
fun emptyLastNameInRegisterTest() {
TODO()
}
@Test
fun emptyPasswordInRegisterTest() {
TODO()
}
}
| 0 | Kotlin | 0 | 1 | dc0410be3ec12966ed73219b17a00fad618e439b | 8,260 | 360 | Apache License 2.0 |
kmp-nativecoroutines-compiler/src/main/kotlin/com/rickclephas/kmp/nativecoroutines/compiler/utils/CoroutinesFqNames.kt | rickclephas | 374,341,212 | false | {"Kotlin": 259150, "Swift": 44712, "Java": 7760, "Ruby": 2852} | package com.rickclephas.kmp.nativecoroutines.compiler.utils
import org.jetbrains.kotlin.name.FqName
internal object CoroutinesFqNames {
val coroutineScope: FqName = FqName("kotlinx.coroutines.CoroutineScope")
val flow: FqName = FqName("kotlinx.coroutines.flow.Flow")
val stateFlow: FqName = FqName("kotlinx.coroutines.flow.StateFlow")
}
| 14 | Kotlin | 31 | 996 | bca9b8c5eef3c771876376973f86993c9ab93e46 | 351 | KMP-NativeCoroutines | MIT License |
vietnamdateconverter/src/main/java/com/albertkhang/vietnamdateconverter/utils/CanChiDate.kt | albertkhang | 249,316,652 | false | null | package com.albertkhang.vietnamdateconverter.utils
class CanChiDate {
private var _canChiDay: String = "Tân Hợi"
var canChiDay: String = _canChiDay
get() {
return _canChiDay
}
private set
private var _canChiMonth: String = "Bính Thân"
var canChiMonth: String = _canChiMonth
get() {
return _canChiMonth
}
private set
private var _canChiYear: String = "Kỷ Mão"
var canChiYear: String = _canChiYear
get() {
return _canChiYear
}
private set
internal constructor(day: String, month: String, year: String) {
_canChiDay = day
_canChiMonth = month
_canChiYear = year
}
override fun toString(): String {
return "LunarDate[day=$_canChiDay, month=$_canChiMonth, year=$_canChiYear]"
}
} | 1 | Kotlin | 0 | 0 | c67f7f4f0ff050c0b31e8dd9cff682f0aae29a8e | 859 | VietnamDateConverter | Apache License 2.0 |
easy/src/main/java/com/mazaiting/easy/utils/rx/BaseObserver.kt | mazaiting | 223,694,088 | false | null | package com.mazaiting.easy.utils.rx
import androidx.annotation.NonNull
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
/**
* 自定义通知
* @author mazaiting
* @date 2018/2/5
*/
abstract class BaseObserver<T> : Observer<T> {
/**
* 请求成功
* @param t 数据
*/
protected abstract fun onSuccess(t: T)
/**
* 请求失败
* @param e 异常信息
*/
protected abstract fun onFailed(e: Throwable)
override fun onNext(@NonNull t: T) {
onSuccess(t)
}
override fun onError(@NonNull e: Throwable) {
onFailed(e)
}
override fun onSubscribe(@NonNull d: Disposable) {
}
override fun onComplete() {
}
}
| 0 | Kotlin | 0 | 0 | 5ddb80ee3590dc23a84a7fc5d02a0d83b3b9765b | 690 | EasyAndroid | Apache License 2.0 |
paystack/src/main/java/co/paystack/android/AuthType.kt | PaystackHQ | 43,757,476 | false | null | package co.paystack.android
object AuthType {
const val PIN = "pin"
const val OTP = "otp"
const val THREE_DS = "3DS"
const val PHONE = "phone"
const val ADDRESS_VERIFICATION = "avs"
} | 8 | null | 102 | 127 | 25a23359c0f1a86c603763b90cbd6df2a1e7bb70 | 204 | paystack-android | Apache License 2.0 |
Katydid-CSS-JVM/src/test/kotlin/jvm/katydid/css/styles/builders/ListStylePropertyTests.kt | martin-nordberg | 131,987,610 | false | null | //
// (C) Copyright 2018-2019 <NAME>
// Apache 2.0 License
//
package jvm.katydid.css.styles.builders
import o.katydid.css.colors.blue
import o.katydid.css.styles.KatydidStyle
import o.katydid.css.styles.builders.listStyle
import o.katydid.css.styles.builders.listStyleImage
import o.katydid.css.styles.builders.listStylePosition
import o.katydid.css.styles.builders.listStyleType
import o.katydid.css.styles.makeStyle
import o.katydid.css.types.EImage
import o.katydid.css.types.EListStylePosition
import o.katydid.css.types.EListStyleType
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
//---------------------------------------------------------------------------------------------------------------------
@Suppress("RemoveRedundantBackticks")
class ListStylePropertyTests {
private fun checkStyle(
expectedCss: String,
build: KatydidStyle.() -> Unit
) {
assertEquals(expectedCss, makeStyle(build).toString())
}
@Test
fun `Nested list style properties convert to correct CSS`() {
checkStyle("list-style-image: none;") { listStyle { image(EImage.none) } }
checkStyle("list-style-image: url(\"http://myimage.jpg\");") {
listStyle { image(EImage.url("http://myimage.jpg")) }
}
checkStyle("list-style-image: image(\"http://myimage.jpg\", blue);") {
listStyle { image(EImage.image("http://myimage.jpg", color = blue)) }
}
checkStyle("list-style-position: inside;") { listStyle { position(EListStylePosition.inside) } }
checkStyle("list-style-type: armenian;") { listStyle { type(EListStyleType.armenian) } }
}
@Test
fun `List style properties convert to correct CSS`() {
checkStyle("list-style-image: none;") { listStyleImage(EImage.none) }
checkStyle("list-style-image: url(\"http://myimage.jpg\");") {
listStyleImage(EImage.url("http://myimage.jpg"))
}
checkStyle("list-style-image: image(\"http://myimage.jpg\", blue);") {
listStyleImage(EImage.image("http://myimage.jpg", color = blue))
}
checkStyle("list-style-position: inside;") { listStylePosition(EListStylePosition.inside) }
checkStyle("list-style-position: outside;") { listStylePosition(EListStylePosition.outside) }
checkStyle("list-style-type: armenian;") { listStyleType(EListStyleType.armenian) }
checkStyle("list-style-type: circle;") { listStyleType(EListStyleType.circle) }
checkStyle("list-style-type: decimal;") { listStyleType(EListStyleType.decimal) }
checkStyle("list-style-type: decimal-leading-zero;") { listStyleType(EListStyleType.decimalLeadingZero) }
checkStyle("list-style-type: disc;") { listStyleType(EListStyleType.disc) }
checkStyle("list-style-type: georgian;") { listStyleType(EListStyleType.georgian) }
checkStyle("list-style-type: lower-greek;") { listStyleType(EListStyleType.lowerGreek) }
checkStyle("list-style-type: lower-latin;") { listStyleType(EListStyleType.lowerLatin) }
checkStyle("list-style-type: lower-roman;") { listStyleType(EListStyleType.lowerRoman) }
checkStyle("list-style-type: square;") { listStyleType(EListStyleType.square) }
checkStyle("list-style-type: upper-latin;") { listStyleType(EListStyleType.upperLatin) }
checkStyle("list-style-type: upper-roman;") { listStyleType(EListStyleType.upperRoman) }
checkStyle("list-style-type: lower-latin;") { listStyleType(EListStyleType.lowerAlpha) }
checkStyle("list-style-type: upper-latin;") { listStyleType(EListStyleType.upperAlpha) }
checkStyle("list-style: square;") { listStyle(EListStyleType.square) }
checkStyle("list-style: square outside;") { listStyle(EListStyleType.square, EListStylePosition.outside) }
checkStyle("list-style: square outside url(\"images/image.jpg\");") { listStyle(EListStyleType.square, EListStylePosition.outside, "images/image.jpg") }
}
}
//---------------------------------------------------------------------------------------------------------------------
| 1 | Kotlin | 1 | 6 | 8fcb99b2d96a003ff3168aef101eaa610e268bff | 4,140 | Katydid | Apache License 2.0 |
app/src/test/kotlin/com/quittle/a11yally/crashlytics/ExtensionsTest.kt | quittle | 135,217,260 | false | null | package com.quittle.a11yally.crashlytics
import com.quittle.a11yally.FirebaseRule
import org.junit.Rule
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class ExtensionsTest {
@get:Rule
var firebaseRule = FirebaseRule()
@Test
fun testCrashlytics() {
val crashlyticsInstance = crashlytics
assertNotNull(crashlyticsInstance)
}
@Test
fun testRecordException() {
// Ensures no exceptions but cannot actually validate the calls do what they are supposed to
crashlytics.recordException("message")
crashlytics.recordException("message", RuntimeException("nested"))
}
}
| 48 | Kotlin | 4 | 22 | b277dda83087b12774198ec8372914278088da3a | 781 | a11y-ally | Apache License 2.0 |
Projects/Samples/05 - Enum with Function.kts | an-jorge | 170,856,534 | false | null | enum class Direction {
NORTH, SOUTH, EAST, WEST
}
fun africaMgs() {
println("We have the power to chance the world")
}
fun toGo (gps: Direction) {
when (gps) {
Direction.NORTH -> println("In North the Things go Well")
Direction.SOUTH -> africaMgs()
Direction.EAST -> println("We can try")
Direction.WEST -> println("Noel is not HERE Oh oh oh")
}
}
toGo(Direction.SOUTH) | 1 | Kotlin | 1 | 1 | b3a217b44719c737b5925cecfbdfb6348532d741 | 420 | Learning-Kotlin | MIT License |
monetisation/ads/src/main/kotlin/dev/teogor/ceres/monetisation/ads/AdsControlUtil.kt | teogor | 555,090,893 | false | {"Kotlin": 1324729} | /*
* Copyright 2023 teogor (<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 dev.teogor.ceres.monetisation.ads
@RequiresOptIn(message = "Ads Control is experimental. The API may be changed in the future.")
@Retention(AnnotationRetention.BINARY)
annotation class ExperimentalAdsControlApi
| 2 | Kotlin | 4 | 62 | 48576bbf21c28c200d18167d0178125c2d5c239a | 821 | ceres | Apache License 2.0 |
intellij-plugin/educational-core/src/com/jetbrains/edu/learning/yaml/format/CourseChangeApplier.kt | JetBrains | 43,696,115 | false | null | package com.jetbrains.edu.learning.yaml.format
import com.intellij.openapi.project.Project
import com.jetbrains.edu.learning.courseFormat.Course
import com.jetbrains.edu.learning.courseFormat.CourseraCourse
import com.jetbrains.edu.learning.courseFormat.codeforces.CodeforcesCourse
class CourseChangeApplier(project: Project) : ItemContainerChangeApplier<Course>(project) {
override fun applyChanges(existingItem: Course, deserializedItem: Course) {
super.applyChanges(existingItem, deserializedItem)
existingItem.name = deserializedItem.name
existingItem.description = deserializedItem.description
existingItem.languageCode = deserializedItem.languageCode
existingItem.environment = deserializedItem.environment
existingItem.solutionsHidden = deserializedItem.solutionsHidden
existingItem.vendor = deserializedItem.vendor
existingItem.feedbackLink = deserializedItem.feedbackLink
existingItem.isMarketplacePrivate = deserializedItem.isMarketplacePrivate
existingItem.languageId = deserializedItem.languageId
existingItem.languageVersion = deserializedItem.languageVersion
if (deserializedItem is CourseraCourse && existingItem is CourseraCourse) {
existingItem.submitManually = deserializedItem.submitManually
}
if (deserializedItem is CodeforcesCourse && existingItem is CodeforcesCourse) {
existingItem.endDateTime = deserializedItem.endDateTime
existingItem.programTypeId = deserializedItem.programTypeId
}
}
}
| 7 | null | 49 | 150 | 9cec6c97d896f4485e76cf9a2a95f8a8dd21c982 | 1,499 | educational-plugin | Apache License 2.0 |
compose/ui/ui-graphics/src/androidInstrumentedTest/kotlin/androidx/compose/ui/graphics/RectHelperTest.kt | androidx | 256,589,781 | false | {"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019} | /*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.graphics
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.unit.IntRect
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
@SmallTest
@RunWith(AndroidJUnit4::class)
class RectHelperTest {
@Suppress("DEPRECATION")
@Test
fun rectToAndroidRectTruncates() {
assertEquals(android.graphics.Rect(2, 3, 4, 5), Rect(2f, 3.1f, 4.5f, 5.99f).toAndroidRect())
}
@Test
fun rectToAndroidRectFConverts() {
assertEquals(
android.graphics.RectF(2f, 3.1f, 4.5f, 5.99f),
Rect(2f, 3.1f, 4.5f, 5.99f).toAndroidRectF()
)
}
@Test
fun androidRectToRectConverts() {
assertEquals(
Rect(2f, 3f, 4f, 5f),
android.graphics.Rect(2, 3, 4, 5).toComposeRect(),
)
}
@Test
fun intRectToAndroidRectConverts() {
assertEquals(
android.graphics.Rect(2, 3, 4, 5),
IntRect(2, 3, 4, 5).toAndroidRect(),
)
}
@Test
fun androidRectToIntRectConverts() {
assertEquals(
IntRect(2, 3, 4, 5),
android.graphics.Rect(2, 3, 4, 5).toComposeIntRect(),
)
}
@Test
fun androidRectFToRectConverts() {
assertEquals(
Rect(2.1f, 3.2f, 4.3f, 5.4f),
android.graphics.RectF(2.1f, 3.2f, 4.3f, 5.4f).toComposeRect(),
)
}
}
| 29 | Kotlin | 1011 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 2,142 | androidx | Apache License 2.0 |
sample/src/androidTest/java/com/daimler/mbloggerkit/sample/MainActivityTest.kt | ots-dev | 243,309,499 | false | null | package com.daimler.mbdeeplinkkit.sample
import android.content.Intent
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.espresso.matcher.ViewMatchers.withText
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import com.daimler.mbdeeplinkkit.sample.main.MainActivity
import org.hamcrest.Matchers.not
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@Rule
@JvmField
val mainActivityTestRule: ActivityTestRule<MainActivity> = ActivityTestRule(
MainActivity::class.java,
true,
true
)
/** Tests whether the MainActivity's TextView is non-empty after a click on the button. */
@Test
fun testTextView() {
mainActivityTestRule.launchActivity(Intent())
onView(withId(R.id.main_button)).perform(click())
onView(withId(R.id.main_text)).check(matches(not(withText(""))))
}
}
| 0 | Kotlin | 0 | 0 | d2dbc1a47643a23d7cd264a519668a291c0d0f0e | 1,363 | MBSDK-LoggerKit-Android | MIT License |
mediator_old/src/main/kotlin/no/nav/dagpenger/behandling/db/HardkodedVurderingRepository.kt | navikt | 571,475,339 | false | {"Kotlin": 199091, "Mustache": 4238, "HTML": 687, "Dockerfile": 77} | package no.nav.dagpenger.behandling.db
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import no.nav.dagpenger.behandling.InntektPeriode
import no.nav.dagpenger.behandling.MinsteInntektVurdering
import no.nav.dagpenger.behandling.db.PacketMapper.beregningsdato
import no.nav.dagpenger.behandling.db.PacketMapper.beregningsregel
import no.nav.dagpenger.behandling.db.PacketMapper.inntektPerioder
import no.nav.dagpenger.behandling.db.PacketMapper.inntektsId
import no.nav.dagpenger.behandling.db.PacketMapper.oppFyllerMinsteInntekt
import no.nav.dagpenger.behandling.db.PacketMapper.regelIdentifikator
import no.nav.dagpenger.behandling.db.PacketMapper.subsumsjonsId
import java.time.LocalDate
import java.time.YearMonth
import java.util.UUID
internal val objectMapper =
jacksonObjectMapper()
.registerModule(JavaTimeModule())
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
internal class HardkodedVurderingRepository : VurderingRepository {
private val resourceRetriever = object {}.javaClass
private val vurderinger =
mutableListOf<MinsteInntektVurdering>().also {
it.populate()
}
private fun MutableList<MinsteInntektVurdering>.populate() {
val jsonNode = objectMapper.readTree(resourceRetriever.getResource("/LEL_eksempel.json")?.readText()!!)
this.add(
MinsteInntektVurdering(
virkningsdato = jsonNode.beregningsdato(),
vilkaarOppfylt = jsonNode.oppFyllerMinsteInntekt(),
inntektsId = jsonNode.inntektsId(),
inntektPerioder = jsonNode.inntektPerioder(),
subsumsjonsId = jsonNode.subsumsjonsId(),
regelIdentifikator = jsonNode.regelIdentifikator(),
beregningsregel = jsonNode.beregningsregel(),
),
)
}
override fun hentMinsteInntektVurdering(oppgaveId: UUID): MinsteInntektVurdering {
return vurderinger.first()
}
override fun lagreMinsteInntektVurdering(
oppgaveId: UUID,
vurdering: MinsteInntektVurdering,
) {
TODO("Not yet implemented")
}
}
internal object PacketMapper {
fun JsonNode.subsumsjonsId(): String = this["minsteinntektResultat"]["subsumsjonsId"].asText()
fun JsonNode.regelIdentifikator(): String = this["minsteinntektResultat"]["regelIdentifikator"].asText()
fun JsonNode.beregningsregel(): String = this["minsteinntektResultat"]["beregningsregel"].asText()
fun JsonNode.beregningsdato(): LocalDate =
this["beregningsDato"].asText().let {
LocalDate.parse(it)
}
fun JsonNode.oppFyllerMinsteInntekt() = this["minsteinntektResultat"]["oppfyllerMinsteinntekt"].asBooleanStrict()
fun JsonNode.inntektsId(): String = this["inntektV1"]["inntektsId"].asText()
private fun JsonNode.asYearMonth(): YearMonth = YearMonth.parse(this.asText())
fun JsonNode.inntektPerioder(): List<InntektPeriode> {
return this["minsteinntektInntektsPerioder"].map { node ->
InntektPeriode(
førsteMåned = node["inntektsPeriode"]["førsteMåned"].asYearMonth(),
sisteMåned = node["inntektsPeriode"]["sisteMåned"].asYearMonth(),
inntekt = node["inntekt"].asDouble(),
)
}
}
private fun JsonNode.asBooleanStrict(): Boolean = asText().toBooleanStrict()
}
| 1 | Kotlin | 0 | 0 | ada9fc0e965dde27c358c036a78814b3d8071afd | 3,704 | dp-behandling | MIT License |
config/src/main/kotlin/org/wcl/mfn/config/ui/mvc/ViewConfig.kt | warnettconsultingltd | 809,363,042 | false | {"Kotlin": 57760, "HTML": 6681, "CSS": 4145} | package org.wcl.mfn.config.ui.mvc
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.PropertySource
@Configuration
@PropertySource("classpath:ui/mvc/view.properties")
open class ViewConfig {
@Value("\${view.home}")
private val homeView: String? = null
@Value("\${view.tools.contract-calculator}")
private val contractCalculatorView: String? = null
fun homeView(): String? {
return homeView
}
fun contractCalculatorView(): String? {
return contractCalculatorView
}
}
| 0 | Kotlin | 0 | 0 | 736f94fe30c021bd8579d09646e92b46265c8884 | 632 | wcl-mfn-manager | Apache License 2.0 |
XClipper.Android/modules/core-auto-delete/src/main/java/com/kpstv/xclipper/ui/sheet/AutoDeleteBottomSheet.kt | KaustubhPatange | 253,389,289 | false | {"Kotlin": 759193, "C#": 620517, "JavaScript": 536661, "SCSS": 203703, "Java": 121328, "HTML": 31009, "CSS": 7591, "Inno Setup": 4894, "Batchfile": 2239, "PowerShell": 1915, "Ruby": 1112} | package com.kpstv.xclipper.ui.sheet
import android.content.res.ColorStateList
import android.os.Bundle
import android.view.View
import androidx.core.text.HtmlCompat
import androidx.lifecycle.lifecycleScope
import androidx.transition.Fade
import androidx.transition.TransitionManager
import com.google.android.material.chip.Chip
import com.kpstv.xclipper.auto_delete.R
import com.kpstv.xclipper.auto_delete.databinding.BottomSheetAutoDeleteBinding
import com.kpstv.xclipper.data.model.ClipTag
import com.kpstv.xclipper.extensions.collapse
import com.kpstv.xclipper.extensions.collectIn
import com.kpstv.xclipper.extensions.drawableFrom
import com.kpstv.xclipper.extensions.elements.CustomRoundedBottomSheetFragment
import com.kpstv.xclipper.extensions.getColorAttr
import com.kpstv.xclipper.extensions.show
import com.kpstv.xclipper.extensions.small
import com.kpstv.xclipper.extensions.viewBinding
import com.kpstv.xclipper.ui.helpers.AppSettings
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
internal class AutoDeleteBottomSheet : CustomRoundedBottomSheetFragment(R.layout.bottom_sheet_auto_delete) {
@Inject
lateinit var appSettings: AppSettings
private val binding by viewBinding(BottomSheetAutoDeleteBinding::bind)
private var autoDeleteDayNumberFlow = MutableStateFlow<Int>(1)
private val autoDeleteSetting by lazy { appSettings.getAutoDeleteSetting() }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.swEnable.isChecked = appSettings.canAutoDeleteClips()
binding.swEnable.setOnCheckedChangeListener { _, _ ->
updateConfigLayout()
}
binding.cbDeleteRemote.isChecked = autoDeleteSetting.shouldDeleteRemoteClip
binding.cbDeletePinned.isChecked = autoDeleteSetting.shouldDeletePinnedClip
binding.npDays.value = autoDeleteSetting.dayNumber
binding.npDays.setOnValueChangedListener { _, _, value ->
updateAutoDeleteNumber(value)
}
updateConfigLayout()
setupTagExcludeChipGroup()
observeAutoDeleteNumberFlow()
binding.btnClose.setOnClickListener { dismiss() }
binding.btnSave.setOnClickListener {
saveOptions()
dismiss()
}
}
private fun saveOptions() {
val excludeTags = binding.cgDeleteTags.checkedChipIds.map {
binding.cgDeleteTags.findViewById<Chip>(it).text.toString()
}.toSet()
val updatedSettings = autoDeleteSetting.copy(
shouldDeleteRemoteClip = binding.cbDeleteRemote.isChecked,
shouldDeletePinnedClip = binding.cbDeletePinned.isChecked,
dayNumber = autoDeleteDayNumberFlow.value,
excludeTags = excludeTags
)
appSettings.setAutoDeleteSetting(updatedSettings)
appSettings.setAutoDeleteClips(binding.swEnable.isChecked)
}
private fun updateAutoDeleteNumber(value: Int) {
viewLifecycleOwner.lifecycleScope.launch {
autoDeleteDayNumberFlow.emit(value)
}
}
private fun setupTagExcludeChipGroup() {
val excludeTags = autoDeleteSetting.excludeTags
val foregroundColor =
ColorStateList.valueOf(requireContext().getColorAttr(R.attr.colorForeground))
ClipTag.values().forEach {
binding.cgDeleteTags.addView(
Chip(requireContext()).apply {
id = it.small().hashCode()
checkedIcon = drawableFrom(R.drawable.ic_check_white_24dp)
text = it.small()
chipBackgroundColor = foregroundColor
isCheckable = true
isChecked = excludeTags.contains(it.small())
}
)
}
}
private fun observeAutoDeleteNumberFlow() {
fun update(value: Int) {
binding.tvSummary.text = getString(R.string.ad_sheet_summary, value)
binding.tvInfo.text = HtmlCompat.fromHtml(
getString(R.string.ad_sheet_info, value),
HtmlCompat.FROM_HTML_MODE_COMPACT
)
}
update(autoDeleteDayNumberFlow.value)
// so that we don't make getString calls every millisecond
autoDeleteDayNumberFlow.debounce(300L)
.distinctUntilChanged()
.collectIn(viewLifecycleOwner) { update(it) }
}
private fun updateConfigLayout() {
val isChecked = binding.swEnable.isChecked
if (isChecked) {
TransitionManager.beginDelayedTransition(binding.root, Fade())
binding.mainLayout.show()
} else {
binding.mainLayout.collapse()
}
}
} | 7 | Kotlin | 24 | 165 | 61d20867344f5bb2d3353ecd6a89e4e76021349b | 4,958 | XClipper | Apache License 2.0 |
core/domain/src/test/java/com/hisui/kanna/core/domain/usecase/GetQuoteStreamUseCaseTest.kt | okumusashi | 570,818,154 | false | {"Kotlin": 369717, "Shell": 1387} | /*
* Copyright 2023 Lynn Sakashita
*
* 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.hisui.kanna.core.domain.usecase
import com.google.common.truth.Truth.assertThat
import com.hisui.kanna.core.Result
import com.hisui.kanna.core.domain.error.QuoteError
import com.hisui.kanna.core.model.QuoteForm
import com.hisui.kanna.core.testing.data.defaultBook
import com.hisui.kanna.core.testing.repository.TestQuoteRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
@OptIn(ExperimentalCoroutinesApi::class)
class GetQuoteStreamUseCaseTest {
private val repository = TestQuoteRepository()
private val useCase = GetQuoteStreamUseCase(repository = repository)
@Nested
@DisplayName("GIVEN - arbitrary id")
inner class Given {
private val id = 1L
@Test
fun `WHEN - repository#getStream returns null, THEN - it shuold return NotFound`() {
runTest {
val quotes = repository.getAllStream().first()
assertThat(quotes).isEmpty()
}
runTest {
val expected = QuoteError.NotFound
val result = useCase(id = id).first() as Result.Error
assertThat(result.error).isEqualTo(expected)
}
}
@Test
fun `WHEN - repository#getStream returns a quote, THEN - it should success with the data`() {
val book = defaultBook.copy(id = id)
repository.addBook(book = book)
val quote = QuoteForm(
page = 1,
quote = "quote",
thought = "thought",
bookId = book.id
)
runTest {
// This is the first item so the id should be 1L
repository.save(quote)
val result = useCase(id = id).first() as Result.Success
assertThat(result.data.quote).isEqualTo(quote.quote)
}
}
}
}
| 16 | Kotlin | 0 | 1 | 131f9ea7bcf6dac58aeb1d9337a12e69a7c53147 | 2,662 | kanna | Apache License 2.0 |
compiler/testData/diagnostics/tests/declarationChecks/sealedOnMembers.fir.kt | android | 263,405,600 | true | null | interface A {
sealed fun foo()
sealed var bar: Unit
}
interface B {
abstract fun foo()
abstract var bar: Unit
}
interface C : A, B
abstract class D(sealed var x: Int) {
abstract var y: Unit
sealed set
}
abstract class E : D(42)
| 0 | Kotlin | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 260 | kotlin | Apache License 2.0 |
app/src/main/java/com/fajaradisetyawan/movieku/di/AppModule.kt | FajarAdiSetyawan | 578,452,658 | false | {"Kotlin": 822443} | /*
* Created by <NAME> on 13/1/2023 - 10:17:42
* <EMAIL>
* Copyright (c) 2023.
*/
package com.fajaradisetyawan.movieku.di
import android.content.Context
import androidx.room.Room
import com.fajaradisetyawan.movieku.data.local.FavoriteDatabase
import com.fajaradisetyawan.movieku.data.local.WatchListDatabase
import com.fajaradisetyawan.movieku.data.remote.endpoint.*
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Provides
@Singleton
fun provideRetrofit(): Retrofit =
Retrofit.Builder()
.baseUrl(MovieApi.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
@Provides
@Singleton
fun provideTrendingApi(retrofit: Retrofit): TrendingApi =
retrofit.create(TrendingApi::class.java)
@Provides
@Singleton
fun provideMovieApi(retrofit: Retrofit): MovieApi =
retrofit.create(MovieApi::class.java)
@Provides
@Singleton
fun provideTvShowApi(retrofit: Retrofit): TvShowApi =
retrofit.create(TvShowApi::class.java)
@Provides
@Singleton
fun provideSearchApi(retrofit: Retrofit): SearchApi =
retrofit.create(SearchApi::class.java)
@Provides
@Singleton
fun providePersonApi(retrofit: Retrofit): PeopleApi =
retrofit.create(PeopleApi::class.java)
@Singleton
@Provides
fun provideFavDatabase(
@ApplicationContext app: Context
) = Room.databaseBuilder(
app,
FavoriteDatabase::class.java,
"movie_db"
).build()
@Singleton
@Provides
fun provideFavMovieDao(db: FavoriteDatabase) = db.favoriteMovieDao()
@Singleton
@Provides
fun provideFavTvDao(db: FavoriteDatabase) = db.favoriteTvShowDao()
@Singleton
@Provides
fun provideFavPeopleDao(db: FavoriteDatabase) = db.favoritePeopleDao()
@Singleton
@Provides
fun provideWatchListDb(
@ApplicationContext app: Context
) = Room.databaseBuilder(
app,
WatchListDatabase::class.java,
"watch_db"
).build()
@Singleton
@Provides
fun provideWatchListMovieDao(db: WatchListDatabase) = db.watchListMovieDao()
@Singleton
@Provides
fun provideWatchListTvDao(db: WatchListDatabase) = db.watchListTvDao()
} | 0 | Kotlin | 0 | 3 | 53b7b5fa48fb09daf1b363b3445f98a88cec6055 | 2,580 | MovieKu | MIT License |
app/src/main/kotlin/compiler/lowlevel/allocation/GraphColoring.kt | brzeczyk-compiler | 545,707,939 | false | {"Kotlin": 1167879, "C": 4004, "Shell": 3242, "Vim Script": 2238} | package compiler.lowlevel.allocation
import compiler.intermediate.Register
import compiler.lowlevel.dataflow.Liveness
// GraphColoring colors registers and manages spills
// It uses some heuristics to decrease number of copies
// HashSets/HashMaps are used in various places to ensure that some operations run in O(1)
class GraphColoring private constructor(
private val graph: Map<RegisterGraph.Node, Set<RegisterGraph.Node>>,
private val preColoredRegisters: HashSet<Register>,
private val allAvailableColors: HashSet<Register>
) {
companion object {
fun color( // main algorithm
livenessGraphs: Liveness.LivenessGraphs,
selfColoredRegisters: List<Register>,
availableColors: List<Register>
): PartialAllocation.AllocationResult {
val stack = RegisterGraph.process(livenessGraphs, selfColoredRegisters, availableColors)
val (coalescedInterferenceGraph, coalescedCopyGraph) = livenessGraphs.toCoalesced(stack)
with(GraphColoring(coalescedInterferenceGraph, selfColoredRegisters.toHashSet(), availableColors.toHashSet())) {
for (register in stack.reversed()) {
val bestForColored: Register? by lazy(LazyThreadSafetyMode.NONE) {
findBestFitForColoredCopyGraphNeighbours(register, coalescedCopyGraph)
}
val bestForUncolored: Register? by lazy(LazyThreadSafetyMode.NONE) {
findBestFitForUncoloredCopyGraphNeighbours(register, coalescedCopyGraph)
}
when {
register.isColored() -> {}
register.availableColors().isEmpty() -> {
register.spill()
}
bestForColored != null -> {
register.assignColor(bestForColored!!)
}
bestForUncolored != null -> {
register.assignColor(bestForUncolored!!)
}
else -> {
register.assignColor(register.availableColors().first())
}
}
}
return createAllocationResult()
}
}
// ----------- helper function ----------------
private fun Liveness.LivenessGraphs.toCoalesced(nodes: Collection<RegisterGraph.Node>): Pair<Map<RegisterGraph.Node, Set<RegisterGraph.Node>>, Map<RegisterGraph.Node, Set<RegisterGraph.Node>>> =
Pair(HashMap<RegisterGraph.Node, HashSet<RegisterGraph.Node>>(), HashMap<RegisterGraph.Node, HashSet<RegisterGraph.Node>>()).also { (interferenceNodeGraph, copyNodeGraph) ->
val regToNode = nodes.flatMap { node -> node.registers.associateWith { node }.toList() }.toMap().let { HashMap(it) }
fun Register.toNode() = regToNode[this]!!
fun HashMap<RegisterGraph.Node, HashSet<RegisterGraph.Node>>.addEdge(left: RegisterGraph.Node, right: RegisterGraph.Node) {
putIfAbsent(left, hashSetOf())
putIfAbsent(right, hashSetOf())
this[left]!!.add(right)
}
fun build(initialMap: Map<Register, Set<Register>>, targetMap: HashMap<RegisterGraph.Node, HashSet<RegisterGraph.Node>>) {
initialMap.flatMap { (reg, neigh) -> neigh.map { reg to it }.toList() }
.map { it.first.toNode() to it.second.toNode() }
.forEach { targetMap.addEdge(it.first, it.second) }
regToNode.values.forEach { targetMap.putIfAbsent(it, hashSetOf()) }
}
build(interferenceGraph, interferenceNodeGraph)
build(copyGraph, copyNodeGraph)
copyNodeGraph.forEach { (node, set) ->
set.removeAll(interferenceNodeGraph[node]!!)
}
nodes.forEach {
interferenceNodeGraph.putIfAbsent(it, hashSetOf())
}
}.let { Pair(it.first, it.second.withDefault { hashSetOf() }) }
}
// ------------- coloring data --------------------
private val allocationMap = HashMap<RegisterGraph.Node, Register>()
private val availableColorsMap = HashMap<RegisterGraph.Node, HashSet<Register>>()
private val spilledRegisters = mutableListOf<RegisterGraph.Node>()
init {
graph.keys.forEach { node ->
(node.registers intersect preColoredRegisters).firstOrNull()?.let { node.assignColor(it) }
}
}
// ------------ main functionalities -------------
private fun RegisterGraph.Node.isColored() = allocationMap.contains(this)
private fun RegisterGraph.Node.color() = allocationMap[this]
private fun RegisterGraph.Node.availableColors() = availableColorsMap.getOrPut(this) { allAvailableColors.toHashSet() }
private fun RegisterGraph.Node.assignColor(color: Register) {
allocationMap[this] = color
graph[this]!!.forEach { availableColorsMap.getOrPut(it) { allAvailableColors.toHashSet() }.remove(color) }
}
private fun RegisterGraph.Node.spill() = spilledRegisters.add(this)
// ------------ coloring heuristics -------------
private fun findBestFitForColoredCopyGraphNeighbours(
register: RegisterGraph.Node,
copyGraphWithoutInterferences: Map<RegisterGraph.Node, Set<RegisterGraph.Node>>
): Register? {
val availableColorsOfCopyGraphNeighbours =
copyGraphWithoutInterferences.getValue(register).filter { it.color() in register.availableColors() }.map { it.color()!! }
return availableColorsOfCopyGraphNeighbours.groupingBy { it }.eachCount().maxByOrNull { it.value }?.key
}
private fun findBestFitForUncoloredCopyGraphNeighbours(
register: RegisterGraph.Node,
copyGraphWithoutInterferences: Map<RegisterGraph.Node, Set<RegisterGraph.Node>>
): Register? {
val uncoloredCopyGraphNeighbours = copyGraphWithoutInterferences.getValue(register).filter { !it.isColored() }
val commonAvailableColors = uncoloredCopyGraphNeighbours.map { it.availableColors() intersect register.availableColors() }
return commonAvailableColors.flatten().groupingBy { it }.eachCount().maxByOrNull { it.value }?.key
}
// ----------- create result ------------------
private fun createAllocationResult(): PartialAllocation.AllocationResult = PartialAllocation.AllocationResult(
allocationMap.flatMap { (node, reg) -> node.registers.associateWith { reg }.toList() }.toMap(),
spilledRegisters.flatMap { it.registers }
)
}
| 7 | Kotlin | 0 | 2 | 5917f4f9d0c13c2c87d02246da8ef8394499d33c | 6,794 | brzeczyk | MIT License |
app/src/main/java/com/example/wishlist/MainActivity.kt | Reckhammer | 536,378,650 | false | {"Kotlin": 4489} | package com.example.wishlist
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
lateinit var wishList : MutableList<Wish>
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val wishRV = findViewById<RecyclerView>( R.id.wishRV )
wishList = mutableListOf()
val adapter = WishAdapter( wishList )
wishRV.adapter = adapter
wishRV.layoutManager = LinearLayoutManager( this )
findViewById<Button>( R.id.submitBtn ).setOnClickListener {
val nameInput = findViewById<EditText>( R.id.itemNameInput )
val priceInput = findViewById<EditText>( R.id.priceInput )
val linkInput = findViewById<EditText>( R.id.linkInput )
if ( !isFieldsEmpty() )
{
var priceStr = priceInput.getText().toString()
var wishItem = Wish( nameInput.text.toString(), priceStr.toFloat(), linkInput.text.toString() )
nameInput.text.clear()
priceInput.text.clear()
linkInput.text.clear()
wishList.add( wishItem )
adapter.notifyDataSetChanged()
}
else
{
Toast.makeText( this, "Fields MUST be filled", Toast.LENGTH_SHORT ).show()
}
}
}
fun isFieldsEmpty() : Boolean
{
val nameEmpty = findViewById<EditText>( R.id.itemNameInput ).text.isEmpty()
val priceEmpty = findViewById<EditText>( R.id.priceInput ).text.isEmpty()
val linkEmpty = findViewById<EditText>( R.id.linkInput ).text.isEmpty()
return nameEmpty || priceEmpty || linkEmpty
}
} | 1 | Kotlin | 0 | 0 | 9960197be32144df95ad2a39be90408dd54d1b0c | 2,006 | Wishlist | Apache License 2.0 |
NavigationAdvancedSample/app/src/main/java/com/example/android/navigationadvancedsample/MainFragment.kt | JarvisGG | 199,967,798 | true | {"Kotlin": 563474, "Java": 261635, "Shell": 2979, "RenderScript": 2642} | /*
* Copyright 2019, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.navigationadvancedsample
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.navigation.NavController
import androidx.navigation.Navigation
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupActionBarWithNavController
import com.example.android.navigationadvancedsample.sheet.navigator.BottomSheetFragmentNavigator
import com.google.android.material.bottomnavigation.BottomNavigationView
import kotlinx.android.synthetic.main.fragment_main.*
/**
* An activity that inflates a layout that has a [BottomNavigationView].
*/
class MainFragment : Fragment() {
private var currentNavController: LiveData<NavController>? = null
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_main, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (savedInstanceState == null) {
setupBottomNavigationBar(view)
}
setUpDrawerToggle()
val drawerNavController = findNavController()
NavigationUI.setupWithNavController(navView, drawerNavController)
}
private fun setUpDrawerToggle() {
val mDrawerToggle = object : ActionBarDrawerToggle(
requireActivity(), navDrawer, null,
R.string.open, R.string.close
) {
}
navDrawer.addDrawerListener(mDrawerToggle)
mDrawerToggle.syncState()
}
override fun onViewStateRestored(savedInstanceState: Bundle?) {
super.onViewStateRestored(savedInstanceState)
setupBottomNavigationBar(view!!)
}
/**
* Called on first creation and when restoring state.
*/
private fun setupBottomNavigationBar(view: View) {
val bottomNavigation = view.findViewById<BottomNavigationView>(R.id.bottomNavigation)
val navGraphIds = listOf(R.navigation.home, R.navigation.list, R.navigation.form)
val controller = bottomNavigation.setupWithNavController(
navGraphIds = navGraphIds,
fragmentManager = childFragmentManager,
containerId = R.id.navHostContainer,
intent = requireActivity().intent
)
// Whenever the selected controller changes, setup the action bar.
controller.observe(this, Observer { navController ->
// setupActionBarWithNavController(navController)
})
currentNavController = controller
}
}
| 0 | Kotlin | 0 | 0 | d3e5a7a55dc9740951fb19b2f15ef8cbb4b13912 | 3,621 | android-architecture-components | Apache License 2.0 |
app/src/test/java/com/ranga/todo/domain/GetTodoItemsUseCaseImplTestEntity.kt | rtippisetty | 857,640,891 | false | {"Kotlin": 45642} | package com.ranga.todo.domain
import com.ranga.todo.api.GetTodoItemsUseCase
import com.ranga.todo.api.model.Todo
import io.mockk.coEvery
import io.mockk.mockk
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.toList
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Test
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.assertThrows
class GetTodoItemsUseCaseImplTestEntity {
private lateinit var getTodoItemsUseCase: GetTodoItemsUseCase
private val todoRepository: TodoRepository = mockk(relaxed = true)
@Before
fun setUp() {
getTodoItemsUseCase = GetTodoItemsUseCaseImpl(todoRepository)
}
@Test
fun `Given todoRepository returns Todo list, When items invoked Then it should returns the same list`() =
runTest {
// Given
val expectedTodos = listOf(Todo("1", "Task 1", false), Todo("2","Task 2", false))
coEvery { todoRepository.getItems() } returns flowOf(expectedTodos)
// When
val result = getTodoItemsUseCase.items().toList()
// Then
assertEquals(expectedTodos, result.first())
}
@Test
fun `Given todoRepository fails When items invoked Then it should throw exception`() = runTest {
coEvery { todoRepository.getItems() } throws Exception("Database error")
assertThrows<Exception> {
getTodoItemsUseCase.items()
}
}
} | 0 | Kotlin | 0 | 0 | 131c2ebfa184e19d2596f9a6a7418022d87f11ca | 1,493 | Todo | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.