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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
presentation/src/commonMain/kotlin/ireader/presentation/ui/component/components/ShowLoading.kt | kazemcodes | 540,829,865 | true | {"Kotlin": 2179459} | package ireader.presentation.ui.component.components
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
@Composable
fun ShowLoading(modifier: Modifier = Modifier, size: Dp = 44.dp) {
Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
CircularProgressIndicator(Modifier.align(Alignment.Center).size(size))
}
}
| 0 | Kotlin | 0 | 6 | b6b2414fa002cec2aa0d199871fcfb4c2e190a8f | 696 | IReader | Apache License 2.0 |
src/main/kotlin/math/Sample.kt | perun-network | 824,164,250 | false | {"Kotlin": 155715} | package perun_network.ecdsa_threshold.math
import java.io.InputStream
import java.math.BigInteger
// Security parameter definition
const val SecParam = 256
const val L = 1 * SecParam // = 256
const val LPrime = 5 * SecParam // = 1280
const val Epsilon = 2 * SecParam // = 512
const val LPlusEpsilon = L + Epsilon // = 768
const val LPrimePlusEpsilon = LPrime + Epsilon // 1792
const val BitsIntModN = 8 * SecParam // = 2048
const val BitsBlumPrime = 4 * SecParam // = 1024
const val BitsPaillier = 2 * BitsBlumPrime // = 2048
/**
* Generates a random integer with the given number of bits, potentially negated.
*
* @param inputStream The input stream to read random bytes from.
* @param bits The number of bits for the random integer.
* @return A randomly generated BigInteger, which may be negative.
*/
fun sampleNeg(inputStream: InputStream, bits: Int): BigInteger {
val buf = ByteArray(bits / 8 + 1)
mustReadBits(inputStream, buf)
val neg = buf[0].toInt() and 1
val out = BigInteger(1, buf.copyOfRange(1, buf.size))
return if (neg == 1) -out else out
}
/**
* Samples a random integer L in the range ±2^l.
*
* @return A randomly generated BigInteger within the specified range.
*/
fun sampleL() : BigInteger = sampleNeg(random, L)
/**
* Samples a random integer in the range ±2^l'.
*
* @return A randomly generated BigInteger within the specified range.
*/
fun sampleLPrime(): BigInteger = sampleNeg(random,LPrime)
/**
* Samples a random integer in the range ±2^(l+ε).
*
* @return A randomly generated BigInteger within the specified range.
*/
fun sampleLEps(): BigInteger = sampleNeg(random, LPlusEpsilon)
/**
* Samples a random integer in the range ±2^(l'+ε).
*
* @return A randomly generated BigInteger within the specified range.
*/
fun sampleLPrimeEps(): BigInteger = sampleNeg(random, LPrimePlusEpsilon)
/**
* Samples a random integer in the range ±2^l•N, where N is the size of a Paillier modulus.
*
* @return A randomly generated BigInteger within the specified range.
*/
fun sampleLN(): BigInteger = sampleNeg(random, L + BitsIntModN)
/**
* Samples a random integer in the range ±2^(l+ε)•N.
*
* @return A randomly generated BigInteger within the specified range.
*/
fun sampleLEpsN(): BigInteger = sampleNeg(random, LPlusEpsilon + BitsIntModN)
| 0 | Kotlin | 0 | 0 | de39fe1d9c86f68ae4b6fa4b40f6e3e481f61796 | 2,342 | atala-prism-threshold | Apache License 2.0 |
app/src/main/java/com/computer/inu/sqkakaotalk/get/GetSearchFriendInfoResponse.kt | jung2929 | 178,861,046 | false | null | package com.computer.inu.sqkakaotalk.get
import com.computer.inu.sqkakaotalk.Data.SearchFriendData
data class GetSearchFriendInfoResponse (
val result : SearchFriendData,
val code : Int,
val message : String
) | 0 | Kotlin | 1 | 0 | 8ae2c8bd8f693694be275eb884ca1cf726acfe83 | 223 | kakaotalk_mock_android_mudol | MIT License |
app/src/main/java/ir/hossein/wikipedia/activity/MainActivity.kt | hosseinsoltaninejad | 531,351,640 | false | null | package ir.hossein.wikipedia.activity
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import cn.pedant.SweetAlert.SweetAlertDialog
import com.google.android.material.snackbar.Snackbar
import ir.hossein.wikipedia.R
import ir.hossein.wikipedia.databinding.ActivityMainBinding
import ir.hossein.wikipedia.fragments.FragmentExplore
import ir.hossein.wikipedia.fragments.FragmentPhotographer
import ir.hossein.wikipedia.fragments.FragmentProfile
import ir.hossein.wikipedia.fragments.FragmentTrend
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar( binding.toolbarMain )
// Drawer Layout
val actionBarDrawerToggle = ActionBarDrawerToggle(
this ,
binding.drawerLayoutMain ,
binding.toolbarMain ,
R.string.openDrawer,
R.string.closeDrawer
)
binding.drawerLayoutMain.addDrawerListener( actionBarDrawerToggle )
actionBarDrawerToggle.syncState()
binding.navagationViewMain.setNavigationItemSelectedListener {
when( it.itemId ){
R.id.menu_writer -> {
val dialog = SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
dialog.titleText = "Alert!"
dialog.confirmText = "Confirm"
dialog.cancelText = "Cancel"
dialog.contentText = "Wanna be a Writer?"
dialog.setCancelClickListener {
dialog.dismiss()
}
dialog.setConfirmClickListener {
dialog.dismiss()
Toast.makeText(this, "you can be a writer just work :)", Toast.LENGTH_SHORT)
.show()
}
dialog.show()
// close drawer =>
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
}
R.id.menu_photograph -> {
// load fragment =>
val transaction = supportFragmentManager.beginTransaction()
transaction.add(R.id.frame_main_container, FragmentPhotographer() )
transaction.addToBackStack(null)
transaction.commit()
// check menu item =>
binding.navagationViewMain.menu.getItem(1).isChecked = true
// close drawer =>
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
// binding.navagationViewMain.menu.getItem(1).isCheckable = true
// binding.navagationViewMain.setCheckedItem( R.id.menu_photograph )
}
R.id.menu_video_maker -> {
// create a snackbar =>
Snackbar
.make( binding.root , "You can Create Video!" , Snackbar.LENGTH_LONG )
.setAction( "Retry" ) {
}
.setActionTextColor( ContextCompat.getColor( this , R.color.white) )
.setBackgroundTint( ContextCompat.getColor( this , R.color.blue) )
.show()
// close drawer =>
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
}
R.id.menu_translator -> {
// open an activity =>
val intent = Intent( this , MainActivity2::class.java )
startActivity( intent )
// close drawer =>
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
}
// ------------------------------------
R.id.menu_open_wikipedia -> {
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
openWebsite("https://www.wikipedia.org/")
}
R.id.menu_open_wikimedia -> {
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
openWebsite("https://www.wikimedia.org/")
}
}
true
}
// Bottom Navigation View
firstRun()
binding.bottomNavigationMain.setOnItemSelectedListener {
when ( it.itemId ){
R.id.menu_explore -> {
replaceFragment( FragmentExplore() )
}
R.id.menu_trend -> {
replaceFragment( FragmentTrend() )
}
R.id.menu_profile -> {
replaceFragment( FragmentProfile() )
}
}
// check menu item =>
binding.navagationViewMain.menu.getItem(1).isChecked = false
true
}
binding.bottomNavigationMain.setOnItemReselectedListener { }
}
private fun openWebsite(url: String) {
val intent = Intent( Intent.ACTION_VIEW , Uri.parse( url ) )
startActivity( intent )
}
private fun replaceFragment (fragment : Fragment ) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.frame_main_container, fragment )
transaction.commit()
}
private fun firstRun () {
replaceFragment( FragmentExplore() )
binding.bottomNavigationMain.selectedItemId = R.id.menu_explore
}
override fun onBackPressed() {
super.onBackPressed()
// check menu item off =>
binding.navagationViewMain.menu.getItem(1).isChecked = false
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate( R.menu.menu_main , menu )
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when ( item.itemId ){
R.id.menu_exit -> {
finish()
}
}
return true
}
} | 0 | Kotlin | 0 | 0 | bda16a446eed23d2049d285a9e705b02c5012882 | 6,609 | Wikipedia | MIT License |
app/src/main/java/ir/hossein/wikipedia/activity/MainActivity.kt | hosseinsoltaninejad | 531,351,640 | false | null | package ir.hossein.wikipedia.activity
import android.content.Intent
import android.net.Uri
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.ActionBarDrawerToggle
import androidx.core.content.ContextCompat
import androidx.core.view.GravityCompat
import androidx.fragment.app.Fragment
import cn.pedant.SweetAlert.SweetAlertDialog
import com.google.android.material.snackbar.Snackbar
import ir.hossein.wikipedia.R
import ir.hossein.wikipedia.databinding.ActivityMainBinding
import ir.hossein.wikipedia.fragments.FragmentExplore
import ir.hossein.wikipedia.fragments.FragmentPhotographer
import ir.hossein.wikipedia.fragments.FragmentProfile
import ir.hossein.wikipedia.fragments.FragmentTrend
class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar( binding.toolbarMain )
// Drawer Layout
val actionBarDrawerToggle = ActionBarDrawerToggle(
this ,
binding.drawerLayoutMain ,
binding.toolbarMain ,
R.string.openDrawer,
R.string.closeDrawer
)
binding.drawerLayoutMain.addDrawerListener( actionBarDrawerToggle )
actionBarDrawerToggle.syncState()
binding.navagationViewMain.setNavigationItemSelectedListener {
when( it.itemId ){
R.id.menu_writer -> {
val dialog = SweetAlertDialog(this, SweetAlertDialog.SUCCESS_TYPE)
dialog.titleText = "Alert!"
dialog.confirmText = "Confirm"
dialog.cancelText = "Cancel"
dialog.contentText = "Wanna be a Writer?"
dialog.setCancelClickListener {
dialog.dismiss()
}
dialog.setConfirmClickListener {
dialog.dismiss()
Toast.makeText(this, "you can be a writer just work :)", Toast.LENGTH_SHORT)
.show()
}
dialog.show()
// close drawer =>
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
}
R.id.menu_photograph -> {
// load fragment =>
val transaction = supportFragmentManager.beginTransaction()
transaction.add(R.id.frame_main_container, FragmentPhotographer() )
transaction.addToBackStack(null)
transaction.commit()
// check menu item =>
binding.navagationViewMain.menu.getItem(1).isChecked = true
// close drawer =>
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
// binding.navagationViewMain.menu.getItem(1).isCheckable = true
// binding.navagationViewMain.setCheckedItem( R.id.menu_photograph )
}
R.id.menu_video_maker -> {
// create a snackbar =>
Snackbar
.make( binding.root , "You can Create Video!" , Snackbar.LENGTH_LONG )
.setAction( "Retry" ) {
}
.setActionTextColor( ContextCompat.getColor( this , R.color.white) )
.setBackgroundTint( ContextCompat.getColor( this , R.color.blue) )
.show()
// close drawer =>
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
}
R.id.menu_translator -> {
// open an activity =>
val intent = Intent( this , MainActivity2::class.java )
startActivity( intent )
// close drawer =>
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
}
// ------------------------------------
R.id.menu_open_wikipedia -> {
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
openWebsite("https://www.wikipedia.org/")
}
R.id.menu_open_wikimedia -> {
binding.drawerLayoutMain.closeDrawer( GravityCompat.START )
openWebsite("https://www.wikimedia.org/")
}
}
true
}
// Bottom Navigation View
firstRun()
binding.bottomNavigationMain.setOnItemSelectedListener {
when ( it.itemId ){
R.id.menu_explore -> {
replaceFragment( FragmentExplore() )
}
R.id.menu_trend -> {
replaceFragment( FragmentTrend() )
}
R.id.menu_profile -> {
replaceFragment( FragmentProfile() )
}
}
// check menu item =>
binding.navagationViewMain.menu.getItem(1).isChecked = false
true
}
binding.bottomNavigationMain.setOnItemReselectedListener { }
}
private fun openWebsite(url: String) {
val intent = Intent( Intent.ACTION_VIEW , Uri.parse( url ) )
startActivity( intent )
}
private fun replaceFragment (fragment : Fragment ) {
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.frame_main_container, fragment )
transaction.commit()
}
private fun firstRun () {
replaceFragment( FragmentExplore() )
binding.bottomNavigationMain.selectedItemId = R.id.menu_explore
}
override fun onBackPressed() {
super.onBackPressed()
// check menu item off =>
binding.navagationViewMain.menu.getItem(1).isChecked = false
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate( R.menu.menu_main , menu )
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when ( item.itemId ){
R.id.menu_exit -> {
finish()
}
}
return true
}
} | 0 | Kotlin | 0 | 0 | bda16a446eed23d2049d285a9e705b02c5012882 | 6,609 | Wikipedia | MIT License |
data/src/main/java/com/thiennguyen/survey/data/response/SurveyDataResponse.kt | thiennguyen0196 | 482,177,646 | false | {"Kotlin": 148873} | package com.thiennguyen.survey.data.response
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import com.thiennguyen.survey.domain.model.SurveyDataModel
@Keep
data class SurveyDataResponse(
@SerializedName("id")
val id: String? = null,
@SerializedName("type")
val type: String? = null
) {
fun mapToModel(): SurveyDataModel {
return with(this) {
SurveyDataModel(
id = id,
type = type
)
}
}
}
| 6 | Kotlin | 0 | 0 | 25bed7de5aad8abfee37173ac28458d2a60c154d | 523 | survey | Apache License 2.0 |
fontawesome/src/main/java/com/sacrificeghuleh/fontawesome/FontCache.kt | SacrificeGhuleh | 623,855,247 | false | null | package com.sacrificeghuleh.fontawesome
import android.content.Context
import android.graphics.Typeface
import com.sacrificeghuleh.fontawesome.FontCache
import java.lang.Exception
import java.util.*
object FontCache {
const val FA_FONT_REGULAR = "fa-regular-400.ttf"
const val FA_FONT_SOLID = "fa-solid-900.ttf"
const val FA_FONT_BRANDS = "fa-brands-400.ttf"
private val fontCache = Hashtable<String, Typeface?>()
@JvmStatic
operator fun get(context: Context, name: String): Typeface? {
var typeface = fontCache[name]
if (typeface == null) {
typeface = try {
Typeface.createFromAsset(context.assets, name)
} catch (e: Exception) {
return null
}
fontCache[name] = typeface
}
return typeface
}
} | 0 | Kotlin | 0 | 0 | c8feb5267750073dfe25ee253daa169697f1fc08 | 836 | BoulderTwister | MIT License |
aws-runtime/aws-config/common/src/aws/sdk/kotlin/runtime/auth/credentials/StsAssumeRoleCredentialsProvider.kt | awslabs | 121,333,316 | false | null | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
package aws.sdk.kotlin.runtime.auth.credentials
import aws.sdk.kotlin.crt.auth.credentials.build
import aws.sdk.kotlin.runtime.crt.SdkDefaultIO
import aws.sdk.kotlin.crt.auth.credentials.StsAssumeRoleCredentialsProvider as StsAssumeRoleCredentialsProviderCrt
/**
* A provider that gets credentials from the STS assume role credential provider.
*
* @param credentialsProvider The underlying Credentials Provider to use for source credentials
* @param roleArn The target role's ARN
* @param sessionName The name to associate with the session
* @param durationSeconds The number of seconds from authentication that the session is valid for
*/
public class StsAssumeRoleCredentialsProvider public constructor(
credentialsProvider: CredentialsProvider,
roleArn: String,
sessionName: String,
durationSeconds: Int? = null,
) : CrtCredentialsProvider {
override val crtProvider: StsAssumeRoleCredentialsProviderCrt = StsAssumeRoleCredentialsProviderCrt.build {
clientBootstrap = SdkDefaultIO.ClientBootstrap
tlsContext = SdkDefaultIO.TlsContext
this.credentialsProvider = asCrt(credentialsProvider)
this.roleArn = roleArn
this.sessionName = sessionName
this.durationSeconds = durationSeconds
}
}
| 79 | Kotlin | 7 | 98 | 05fb6d3631b02e87034f60e57051c25b7b70351d | 1,387 | aws-sdk-kotlin | Apache License 2.0 |
src/commonMain/kotlin/dev/inmo/saucenaoapi/models/HeaderIndex.kt | InsanusMokrassar | 171,594,922 | false | null | package dev.inmo.saucenaoapi.models
import kotlinx.serialization.Serializable
@Serializable
data class HeaderIndex(
val status: Int? = null,
val id: Int? = null,
val results: Int? = null,
val parent_id: Int? = null
)
| 7 | Kotlin | 0 | 6 | 930523f69a327a5f32c627c95a68a5880a8ed881 | 235 | SauceNaoAPI | Apache License 2.0 |
app/src/main/java/yt/javi/nftweets/domain/service/news/GetLatestNewsService.kt | javiyt | 102,260,623 | false | null | package yt.javi.nftweets.domain.service.news
import yt.javi.nftweets.domain.model.news.Article
import yt.javi.nftweets.domain.model.news.ArticleRepository
import java.net.URL
class GetLatestNewsService(private val repository: ArticleRepository, private val url: URL) {
fun getLatestNews(): List<Article> = repository.getLatestNews(url)
} | 4 | Kotlin | 0 | 5 | ad40b5aa7d725c5e814fdaa692486a1670b129a6 | 344 | nftweets | Apache License 2.0 |
app/src/main/java/com/blocksdecoded/dex/presentation/exchange/model/ExchangeType.kt | Sakshamappinternational | 214,494,204 | true | {"Kotlin": 464312} | package com.blocksdecoded.dex.presentation.exchange.model
enum class ExchangeType {
MARKET,
LIMIT
} | 0 | null | 0 | 0 | d9940d1210e54dc32bb135ef344b1d2e713f84ba | 102 | dex-app-android | MIT License |
app/src/main/java/br/com/si/ufrrj/carta/CartaAdapter.kt | filipeklinger | 224,267,474 | false | null | package br.com.si.ufrrj.carta
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.Adapter
import br.com.si.ufrrj.R
import br.com.si.ufrrj.logica.UserStatus
import br.com.si.ufrrj.logica.VolleySingleton
import com.android.volley.toolbox.NetworkImageView
import kotlinx.android.synthetic.main.carta_single.*
//construtor primario recebe uma lista de singleCard e o contexto em que foi chamado
//implementa a classe abstrata Adapter do tipo ViewHolder
class CartaAdapter(private val context:Context,private val cartaList: ArrayList<singleCard>) : Adapter<CartaAdapter.ViewHolder>() {
var childClickListener: OnChildClickListener? = null
//essa inner class implementa o tipo abstrato ViewHolder para ser utilizado no Adapter
class ViewHolder(itemView: View,childClickListener: OnChildClickListener?) : RecyclerView.ViewHolder(itemView) {
//aqui vamos associar os ids em carta_single com as variaveis da nossa classe
private val titulo: TextView = itemView.findViewById(R.id.titulo_card)
private val inteligencia: TextView = itemView.findViewById(R.id.inteligencia_card)
private val forca: TextView = itemView.findViewById(R.id.forca_card)
private val velocidade: TextView = itemView.findViewById(R.id.velocidade_card)
private val vigor: TextView = itemView.findViewById(R.id.vigor_card)
private val poder: TextView = itemView.findViewById(R.id.poder_card)
private val combate: TextView = itemView.findViewById(R.id.combate_card)
private val card_figure: NetworkImageView = itemView.findViewById(R.id.card_figure)
private val addOrRemoveButton: ImageButton = itemView.findViewById(R.id.add_or_remove_card)
init {
addOrRemoveButton.setOnClickListener {
childClickListener?.onChildClick(it,layoutPosition,adapterPosition,0)
}
}
fun bindView(card: singleCard,context: Context) {
//obtendo a carta da visualizacao atual
titulo.text = card.nome
inteligencia.text = "Inte: ${card.inteligencia}"
forca.text = "Forç: ${card.forca}"
velocidade.text = "Velo: ${card.velocidade}"
vigor.text = "Vigo: ${card.vigor}"
poder.text = "Pode: ${card.poder}"
combate.text = "Comb: ${card.combate}"
//Mostrando a imagem da Carta
card_figure.setDefaultImageResId(R.drawable.image_placeholder)
val imageLoader = VolleySingleton.getInstance(context).getImageLoader()
card_figure.setImageUrl(card.figura,imageLoader)
if(UserStatus.deckAtual.contains(card)){//verificando se o card atual esta contido em deck
addOrRemoveButton.setImageResource(R.drawable.ic_remove_card)
}else{
addOrRemoveButton.setImageResource(R.drawable.ic_add_card)
}
}
}
/**
* @return The total number of items in this adapter.
*/
override fun getItemCount(): Int {
return cartaList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
//inflando o layout criado em carta single dentro do ReciclerView
val view = LayoutInflater.from(context).inflate(R.layout.carta_single, parent, false)
//passando a view e o listenner criado
return ViewHolder(view,childClickListener)
}
/**
* Aqui inserimos as informacoes de singleCard nas variaveis setadas em ViewHolder
* para cada item do ReciclerView
*/
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindView(cartaList[position],context)
}
fun setChildClickListenner(clickListener: OnChildClickListener) {
this.childClickListener = clickListener
}
interface OnChildClickListener {
/**
* Callback method to be invoked when a child in this expandable list has
* been clicked.
*
* @param v The view within the expandable list/ListView that was clicked
* @param groupPosition The group position that contains the child that
* was clicked
* @param childPosition The child position within the group
* @param id The row id of the child that was clicked
* @return True if the click was handled
*/
fun onChildClick(
v: View?,
groupPosition: Int,
childPosition: Int,
id: Long
): Boolean
}
} | 0 | Kotlin | 0 | 1 | 3406a4a69ef2a4e0cb5250ea31480903211c42eb | 4,744 | CardGame | MIT License |
app/src/test/java/com/zwq65/unity/kotlin/Coroutine/2CancellationAndTimeouts.kt | Izzamuzzic | 95,655,850 | false | {"Kotlin": 449365, "Java": 17918} | package com.zwq65.unity.kotlin.Coroutine
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.withContext
import org.junit.Test
/**
* ================================================
* 取消与超时
* <p>
* Created by NIRVANA on 2020/1/14.
* Contact with <[email protected]>
* ================================================
*/
class `2CancellationAndTimeouts` {
/**
* 取消协程的执行
*
* 一个长时间运行的应用程序中,你也许需要对你的后台协程进行细粒度的控制. 比如说,一个用户也许关闭了一个启动了协程的界面,那么现在协程的执行结果已经不再被需要了,
* 这时,它应该是可以被取消的. 该[launch]函数返回了一个可以被用来取消运行中的协程的[Job]:
*/
@Test
fun test1() = runBlocking {
val job = launch {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
}
delay(1300L) // 延迟一段时间
println("main: I'm tired of waiting!")
// job.cancel() // 取消该作业
// job.join() // 等待作业执行结束
//挂起的函数cancelAndJoin()合并了对cancel()以及join()的调用.
job.cancelAndJoin()
println("main: Now I can quit.")
}
/**
* 取消是协作的
*
* 协程的取消是 协作 的.一段协程代码必须协作才能被取消. 所有 [CoroutineScope] 中的挂起函数都是 可被取消的 .
* 它们检查协程的取消, 并在取消时抛出 [CancellationException].
* 然而,如果协程正在执行计算任务,并且没有检查取消的话,那么它是不能被取消的!
*/
@Test
fun test2() = runBlocking {
val startTime = System.currentTimeMillis()
val job = launch(Dispatchers.Default) {
var nextPrintTime = startTime
var i = 0
/**
* 使计算代码可取消
*
* 我们有两种方法来使执行计算的代码可以被取消.第一种方法是定期调用挂起函数来检查取消.对于这种目的 [yield]yield 是一个好的选择.
* 另一种方法是显式的检查取消状态.让我们试试第二种方法.
*/
//检测协程是否被取消 方法二:
while (isActive) { // 可以被取消的计算循环
// 每秒打印消息两次
if (System.currentTimeMillis() >= nextPrintTime) {
println("job: I'm sleeping ${i++} ...")
nextPrintTime += 500L
}
//检测协程是否被取消 方法一:
// yield()
}
}
delay(1300L) // 等待一段时间
println("main: I'm tired of waiting!")
job.cancelAndJoin() // 取消该作业并等待它结束
println("main: Now I can quit.")
}
/**
* 在 finally 中释放资源
*
* 我们通常使用如下的方法处理在被取消时抛出 CancellationException 的可被取消的挂起函数.
* 比如说,try {……} finally {……} 表达式以及 Kotlin 的 use 函数一般在协程被取消的时候执行它们的终结动作:
*/
@Test
fun test3() = runBlocking {
val job = launch {
try {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
} finally {
println("job: I'm running finally")
}
}
delay(1300L) // 延迟一段时间
println("main: I'm tired of waiting!")
job.cancelAndJoin() // 取消该作业并且等待它结束
println("main: Now I can quit.")
}
/**
* 运行不能取消的代码块
*
* 在前一个例子中任何尝试在 finally 块中调用挂起函数的行为都会抛出 [CancellationException],因为这里持续运行的代码是可以被取消的.
* 通常,这并不是一个问题,所有良好的关闭操作(关闭一个文件、取消一个作业、或是关闭任何一种通信通道)通常都是非阻塞的,并且不会调用任何挂起函数.
* 然而,在真实的案例中,当你需要挂起一个不被取消的协程,你可以将相应的代码包装在 withContext(NonCancellable) {……} 中,并使用 [withContext] 函数以及 [NonCancellable] 上下文
*/
@Test
fun test4() = runBlocking {
val job = launch {
try {
repeat(1000) { i ->
println("job: I'm sleeping $i ...")
delay(500L)
}
} finally {
withContext(NonCancellable) {
//// this code will not be cancelled
println("job: I'm running finally")
delay(1000L)
println("job: And I've just delayed for 1 sec because I'm non-cancellable")
}
}
}
delay(1300L) // 延迟一段时间
println("main: I'm tired of waiting!")
job.cancelAndJoin() // 取消该作业并等待它结束
println("main: Now I can quit.")
}
/**
* 超时
*
* 在实践中绝大多数取消一个协程的理由是它有可能超时. 当你手动追踪一个相关 Job 的引用并启动了一个单独的协程在延迟后取消追踪,这里已经准备好使用[withTimeout]函数来做这件事
* [withTimeout]抛出了 [TimeoutCancellationException],它是 [CancellationException] 的子类.
*/
@Test
fun test5() = runBlocking {
try {
withTimeout(1300L) {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
}
} catch (e: Exception) {
withContext(NonCancellable) {
//// this code will not be cancelled
println("job: I'm running finally")
}
}
}
/**
* 由于取消只是一个例外,所有的资源都使用常用的方法来关闭. 如果你需要做一些各类使用超时的特别的额外操作,
* 可以使用类似 [withTimeout] 的 [withTimeoutOrNull] 函数,并把这些会超时的代码包装在 try {...} catch (e: TimeoutCancellationException) {...} 代码块中,
* 而 [withTimeoutOrNull] 通过返回 null 来进行超时操作,从而替代抛出一个异常
*/
@Test
fun test6() = runBlocking {
val result = withTimeoutOrNull(1300L) {
repeat(1000) { i ->
println("I'm sleeping $i ...")
delay(500L)
}
"Done" // 在它运行得到结果之前取消它
}
println("Result is $result")
}
} | 0 | Kotlin | 0 | 0 | 98a9ad7bb298d0b0cfd314825918a683d89bb9e8 | 5,201 | Unity | Apache License 2.0 |
android/testData/projects/unitTesting/app/src/main/java/com/example/app/AppKotlinClass.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | package com.example.app
class AppKotlinClass {
val name get() = javaClass.simpleName
} | 5 | Kotlin | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 91 | android | Apache License 2.0 |
app/src/main/java/io/github/manuelernesto/devfestapp/ui/team/TeamFragment.kt | sajibt | 307,908,047 | true | {"Kotlin": 27987} | package io.github.manuelernesto.devfestapp.ui.team
import androidx.lifecycle.ViewModelProviders
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.github.manuelernesto.devfestapp.R
import io.github.manuelernesto.devfestapp.adapter.GeneralAdapter
import io.github.manuelernesto.devfestapp.util.Dummy
class TeamFragment : Fragment() {
companion object {
fun newInstance() = TeamFragment()
}
private lateinit var viewModel: TeamViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.team_fragment, container, false).apply {
val recyclerView: RecyclerView = findViewById(R.id.rv_team)
val adapter = GeneralAdapter(Dummy.getTeam(), context)
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = adapter
}
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(this).get(TeamViewModel::class.java)
}
}
| 0 | null | 0 | 0 | 140c968214d177d87107a09982f5d058fac6781b | 1,374 | devfest_kotlin | MIT License |
core/utils/src/main/java/com/trodar/utils/extension/NumberExt.kt | trodar | 788,273,590 | false | {"Kotlin": 279609} | package com.trodar.utils.extension
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalDensity
//fun Double.format(scale: Int) = "%.${scale}f".format(this)
fun Int.format(scale: Int = 2) = "%0${scale}d".format(this)
@Composable
fun Int.pxToDp() = with(LocalDensity.current) { [email protected]() } | 0 | Kotlin | 0 | 0 | b172bbcc5decf3e5d161b8024fbf35da4effb226 | 330 | Partner | Apache License 2.0 |
app/src/main/java/com/example/flixstercast/MainActivity.kt | py94NJIT | 877,609,645 | false | {"Kotlin": 6809} | package com.example.flixstercast
import android.content.Intent
import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.flixstercast.databinding.ActivityMainBinding
import com.example.flixstercast.PeopleViewModel
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private val viewModel: PeopleViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
viewModel.popularPeople.observe(this) { people ->
binding.recyclerView.layoutManager = LinearLayoutManager(this)
binding.recyclerView.adapter = PeopleAdapter(people) { person ->
val intent = Intent(this, PersonDetailActivity::class.java)
intent.putExtra("person_key", person) // Pass the entire person object
startActivity(intent)
}
}
}
}
| 0 | Kotlin | 0 | 0 | eb236318280ac89785fac9003350a8737c2a9f09 | 1,144 | FlixsterCast | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/manageoffencesapi/model/external/sdrs/SDRSRequest.kt | ministryofjustice | 460,455,417 | false | {"Kotlin": 340270, "Dockerfile": 1564, "Shell": 1564} | package uk.gov.justice.digital.hmpps.manageoffencesapi.model.external.sdrs
import com.fasterxml.jackson.databind.PropertyNamingStrategies.UpperCamelCaseStrategy
import com.fasterxml.jackson.databind.annotation.JsonNaming
@JsonNaming(UpperCamelCaseStrategy::class)
data class SDRSRequest(
val messageBody: MessageBodyRequest,
val messageHeader: MessageHeader,
)
| 0 | Kotlin | 0 | 0 | 8ab008ba897b65e3c5c7ca770e0114789433bff7 | 367 | hmpps-manage-offences-api | MIT License |
utils/src/main/java/com/zhangteng/utils/StateView.kt | DL-ZhangTeng | 531,906,518 | false | {"Kotlin": 215160, "Java": 302} | package com.zhangteng.utils
import android.content.Context
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
/**
* 请求无数据显示view
*
* @author swing
* @date 2018/1/23
*/
open class StateView : LinearLayout {
private var llState: ConstraintLayout? = null
private var tvState: TextView? = null
private var ivState: ImageView? = null
private var btnState: Button? = null
private var isStateViewShow = false
constructor(context: Context) : super(context) {
initView(context)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
initView(context)
setAttrs(context, attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
initView(context)
setAttrs(context, attrs)
}
private fun setAttrs(context: Context, attrs: AttributeSet?) {
val a = context.obtainStyledAttributes(
attrs,
R.styleable.StateView
)
val indexCount = a.indexCount
for (i in 0 until indexCount) {
when (val attr = a.getIndex(i)) {
R.styleable.StateView_stateText -> {
val str = a.getString(attr)
setStateText(str)
}
R.styleable.StateView_stateImage -> {
val id = a.getResourceId(attr, R.mipmap.icon_default)
setStateImageResource(id)
}
R.styleable.StateView_stateVisibility -> {
val visibility = a.getInt(attr, VISIBLE)
setStateVisibility(visibility)
}
}
}
a.recycle()
}
private fun initView(context: Context) {
LayoutInflater.from(context).inflate(R.layout.layout_no_data_view, this, true)
llState = findViewById(R.id.ll_no_data)
tvState = findViewById(R.id.tv_no_data)
ivState = findViewById(R.id.iv_no_data)
btnState = findViewById(R.id.btn_no_data)
}
open fun setStateVisibility(visibility: Int) {
llState?.visibility = visibility
}
open fun setStateText(stateText: String?) {
tvState?.text = stateText
}
open fun setStateText(resourceId: Int) {
tvState?.setText(resourceId)
}
open fun setStateDrawable(dataDrawable: Drawable?) {
ivState?.setImageDrawable(dataDrawable)
}
open fun setStateImageResource(resourceId: Int) {
ivState?.setImageResource(resourceId)
}
open fun isStateViewShow(): Boolean {
return isStateViewShow
}
open fun setStateViewShow(stateViewShow: Boolean) {
isStateViewShow = stateViewShow
}
open fun setStateAgainText(stateAgainText: String?) {
btnState?.text = stateAgainText
}
open fun setStateAgainVisibility(visibility: Int) {
btnState?.visibility = visibility
}
open fun setAgainRequestListener(againRequestListener: AgainRequestListener?) {
btnState?.setOnClickListener { againRequestListener?.request(it) }
}
interface AgainRequestListener {
fun request(view: View)
}
} | 0 | Kotlin | 0 | 4 | 3880ff287b59347ad3df0a58e08b09ba50c9e3e3 | 3,497 | Utils | The Unlicense |
src/main/kotlin/ru/krindra/vknorthtypes/ads/AdsClipItem.kt | kravandir | 745,597,090 | false | {"Kotlin": 633233} | package ru.krindra.vknorthtypes.ads
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class AdsClipItem (
@SerialName("video_id") val videoId: Long? = null,
@SerialName("preview_url") val previewUrl: String? = null,
@SerialName("link") val link: AdsClipItemLink? = null,
)
| 0 | Kotlin | 0 | 0 | 508d2d1d59c4606a99af60b924c6509cfec6ef6c | 338 | VkNorthTypes | MIT License |
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/codepipeline/TriggerDsl.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 70198112} | @file:Suppress(
"RedundantVisibilityModifier",
"RedundantUnitReturnType",
"RemoveRedundantQualifierName",
"unused",
"UnusedImport",
"ClassName",
"REDUNDANT_PROJECTION",
"DEPRECATION"
)
package io.cloudshiftdev.awscdkdsl.services.codepipeline
import io.cloudshiftdev.awscdkdsl.common.CdkDslMarker
import kotlin.Unit
import software.amazon.awscdk.services.codepipeline.GitConfiguration
import software.amazon.awscdk.services.codepipeline.ProviderType
import software.amazon.awscdk.services.codepipeline.Trigger
/**
* Trigger.
*
* Example:
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.codepipeline.*;
* Action action;
* Trigger trigger = Trigger.Builder.create()
* .providerType(ProviderType.CODE_STAR_SOURCE_CONNECTION)
* // the properties below are optional
* .gitConfiguration(GitConfiguration.builder()
* .sourceAction(action)
* // the properties below are optional
* .pushFilter(List.of(GitPushFilter.builder()
* .tagsExcludes(List.of("tagsExcludes"))
* .tagsIncludes(List.of("tagsIncludes"))
* .build()))
* .build())
* .build();
* ```
*/
@CdkDslMarker
public class TriggerDsl {
private val cdkBuilder: Trigger.Builder = Trigger.Builder.create()
/**
* Provides the filter criteria and the source stage for the repository event that starts the
* pipeline, such as Git tags.
*
* Default: - no configuration.
*
* @param gitConfiguration Provides the filter criteria and the source stage for the repository
* event that starts the pipeline, such as Git tags.
*/
public fun gitConfiguration(gitConfiguration: GitConfigurationDsl.() -> Unit = {}) {
val builder = GitConfigurationDsl()
builder.apply(gitConfiguration)
cdkBuilder.gitConfiguration(builder.build())
}
/**
* Provides the filter criteria and the source stage for the repository event that starts the
* pipeline, such as Git tags.
*
* Default: - no configuration.
*
* @param gitConfiguration Provides the filter criteria and the source stage for the repository
* event that starts the pipeline, such as Git tags.
*/
public fun gitConfiguration(gitConfiguration: GitConfiguration) {
cdkBuilder.gitConfiguration(gitConfiguration)
}
/**
* The source provider for the event, such as connections configured for a repository with Git
* tags, for the specified trigger configuration.
*
* @param providerType The source provider for the event, such as connections configured for a
* repository with Git tags, for the specified trigger configuration.
*/
public fun providerType(providerType: ProviderType) {
cdkBuilder.providerType(providerType)
}
public fun build(): Trigger = cdkBuilder.build()
}
| 0 | Kotlin | 0 | 3 | 256ad92aebe2bcf9a4160089a02c76809dbbedba | 2,931 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/me/ykrank/s1next/view/page/login/LoginDialogFragment.kt | UFR6cRY9xufLKtx2idrc | 853,383,380 | false | {"Kotlin": 1174002, "Java": 356564, "HTML": 20430} | package me.ykrank.s1next.view.page.login
import android.os.Bundle
import io.reactivex.Single
import kotlinx.coroutines.DelicateCoroutinesApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import me.ykrank.s1next.App
import me.ykrank.s1next.data.api.model.wrapper.AccountResultWrapper
import me.ykrank.s1next.data.db.exmodel.RealLoginUser
import me.ykrank.s1next.view.dialog.ProgressDialogFragment
import me.ykrank.s1next.view.event.LoginEvent
/**
* A [ProgressDialogFragment] posts a request to login to server.
*/
class LoginDialogFragment : BaseLoginDialogFragment<AccountResultWrapper>() {
override fun getSourceObservable(): Single<AccountResultWrapper> {
return mS1Service.login(username, password, questionId, answer).map { resultWrapper ->
// the authenticity token is not fresh after login
resultWrapper.data?.apply {
authenticityToken = null
mUserValidator.validate(this)
}
resultWrapper
}
}
override fun parseData(data: AccountResultWrapper): Result {
val result = data.result
return if (result.defaultSuccess) {
Result(true, result.message)
} else {
Result(false, result.message)
}
}
override fun onSuccess(data: AccountResultWrapper, result: Result) {
super.onSuccess(data, result)
// 自动登录黑科技
val username = this.username
val password = <PASSWORD>
if (username != null && password != null) {
saveLoginUser2Db(data)
AppLoginDialogFragment.newInstance(username, password, questionId, answer).show(
parentFragmentManager,
AppLoginDialogFragment.TAG
)
}
mEventBus?.postDefault(LoginEvent())
}
@OptIn(DelicateCoroutinesApi::class)
private fun saveLoginUser2Db(data: AccountResultWrapper) {
GlobalScope.launch(Dispatchers.IO) {
val time = System.currentTimeMillis()
val user = RealLoginUser(
id = null,
uid = data.data?.uid?.toInt() ?: 0,
name = data.data?.username,
password = <PASSWORD>,
questionId = questionId?.toString(),
answer = answer,
loginTime = time,
timestamp = time,
)
App.appComponent.loginUserBiz.saveUser(user)
}
}
companion object {
val TAG = LoginDialogFragment::class.java.simpleName
fun newInstance(
username: String,
password: String,
questionId: Int?,
answer: String?
): LoginDialogFragment {
val fragment = LoginDialogFragment()
val bundle = Bundle()
addBundle(bundle, username, password, questionId, answer)
fragment.arguments = bundle
return fragment
}
}
}
| 0 | Kotlin | 0 | 0 | 7cfc58523207dc5ed5df4525c2e3de087cf9e8b9 | 3,018 | test24 | Apache License 2.0 |
src/main/kotlin/message/RoomInfoSc.kt | CuteReimu | 591,960,504 | false | null | package org.tfcc.bingo.message
class RoomInfoSc(
val rid: String,
val type: Int,
val host: String,
val names: Array<String>?,
val changeCardCount: IntArray?,
val started: Boolean?,
val score: IntArray?,
val winner: Int?,
val watchers: Array<String>?,
val roomConfig: RoomConfig,
)
| 6 | null | 1 | 6 | f485b6a43a3fbe78e2726e92a639df97a72ceee2 | 322 | th-bingo | MIT License |
compiler/testData/diagnostics/tests/DelegationNotTotrait.kt | nyerel | 5,550,338 | true | {"Python": 1, "Markdown": 18, "Kotlin": 2730, "Java": 2183, "HTML": 15, "JavaScript": 47, "CSS": 10, "Java Properties": 4, "INI": 1, "Batchfile": 2, "Makefile": 1} | open class Foo() {
}
class Barrr() : <!DELEGATION_NOT_TO_TRAIT!>Foo<!> by Foo() {}
trait T {}
class Br(t : T) : T by t {}
open enum class EN() {
A
}
class Test2(e : EN) : <!DELEGATION_NOT_TO_TRAIT!>EN<!> by e {}
| 0 | Java | 0 | 0 | c0c2ca0ac2d92bafaa7cb81238b8f6abfbe9731b | 220 | kotlin | Apache License 2.0 |
mobile_app1/module1265/src/main/java/module1265packageKt0/Foo1.kt | uber-common | 294,831,672 | false | null | package module1265packageKt0;
annotation class Foo1Fancy
@Foo1Fancy
class Foo1 {
fun foo0(){
module1265packageKt0.Foo0().foo3()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
} | 6 | Java | 6 | 72 | 9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e | 231 | android-build-eval | Apache License 2.0 |
tongs-plugin-android/src/test/java/com/github/tarcv/tongs/runner/TongsInstrumentationResultParserTest.kt | engeniousio | 262,129,936 | false | null | /*
* Copyright 2020 TarCV
*
* 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.github.tarcv.tongs.runner
import com.android.ddmlib.testrunner.TestIdentifier
import com.android.utils.toSystemLineSeparator
import com.github.tarcv.tongs.api.run.ResultStatus
import com.github.tarcv.tongs.api.run.TestCaseEvent
import com.github.tarcv.tongs.api.run.aTestCaseEvent
import com.github.tarcv.tongs.api.testcases.aTestCase
import com.github.tarcv.tongs.runner.listeners.ResultListener
import com.github.tarcv.tongs.runner.listeners.RunListenerAdapter
import org.junit.Assert.assertEquals
import org.junit.Test
class TongsInstrumentationResultParserTest {
private val testShortClassName = "ResultTest"
private val testMethodName = "failureFromEspresso[failAfter = true]"
private val testCase = TestCaseEvent.aTestCaseEvent(aTestCase(testShortClassName, testMethodName))
private val listener = ResultListener(testCase.toString())
private val parser = TongsInstrumentationResultParser(
"unitTest",
listOf(RunListenerAdapter(testCase.toString(), TestIdentifier(testCase.testClass,testCase.testMethod), listOf(listener)))
)
private val afterMethodException = """java.lang.RuntimeException: Exception from afterMethod
at ${testCase.testClass}.afterMethod($testShortClassName.java:30)
at java.lang.reflect.Method.invoke(Native Method)"""
private val testException = """android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with res-name that is "non_existing_id"
at dalvik.system.VMStack.getThreadStackTrace(Native Method)
at java.lang.Thread.getStackTrace(Thread.java:1566)
at android.support.test.espresso.base.DefaultFailureHandler.getUserFriendlyError(DefaultFailureHandler.java:88)
at android.support.test.espresso.base.DefaultFailureHandler.handle(DefaultFailureHandler.java:51)
at android.support.test.espresso.ViewInteraction.waitForAndHandleInteractionResults(ViewInteraction.java:312)
at android.support.test.espresso.ViewInteraction.check(ViewInteraction.java:297)
at ${testCase.testClass}.failureFromEspresso($testShortClassName.java:42)
at java.lang.reflect.Method.invoke(Native Method)"""
@Test
fun resultListenerReceivesCorrectShellResult() {
val stdLines = """INSTRUMENTATION_STATUS: numtests=1
INSTRUMENTATION_STATUS: stream=
${testCase.testClass}:
INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
INSTRUMENTATION_STATUS: test=$testMethodName
INSTRUMENTATION_STATUS: class=${testCase.testClass}
INSTRUMENTATION_STATUS: current=1
INSTRUMENTATION_STATUS_CODE: 1
INSTRUMENTATION_STATUS: numtests=1
INSTRUMENTATION_STATUS: stream=
Error in $testMethodName(${testCase.testClass}):
$afterMethodException
INSTRUMENTATION_STATUS: id=AndroidJUnitRunner
INSTRUMENTATION_STATUS: test=$testMethodName
INSTRUMENTATION_STATUS: class=${testCase.testClass}
INSTRUMENTATION_STATUS: stack=$afterMethodException
INSTRUMENTATION_STATUS: current=1
INSTRUMENTATION_STATUS_CODE: -2
INSTRUMENTATION_RESULT: stream=
Time: 5.235
There were 2 failures:
1) $testMethodName(${testCase.testClass})
$testException
2) $testMethodName(${testCase.testClass})
$afterMethodException
FAILURES!!!
Tests run: 1, Failures: 2
INSTRUMENTATION_CODE: -1
""".lines().toTypedArray()
parser.processNewLines(stdLines)
parser.done()
val expectedOutput = """
${testCase.testClass}:
Error in $testMethodName(${testCase.testClass}):
$afterMethodException
Time: 5.235
There were 2 failures:
1) $testMethodName(${testCase.testClass})
$testException
2) $testMethodName(${testCase.testClass})
$afterMethodException
FAILURES!!!
Tests run: 1, Failures: 2
"""
val result = listener.result
assertEquals(ResultStatus.FAIL, result.status)
assertEquals(
expectedOutput.trim().toSystemLineSeparator(),
result.output.trim().toSystemLineSeparator()
)
}
} | 1 | null | 2 | 3 | da5ee89d7509f66fe58468eb30e03dd05a1b89c9 | 4,452 | sift-android | Apache License 2.0 |
app-wan/src/main/java/com/wanandroid/ui/first/FirstFragment.kt | AsaLynn | 302,626,261 | false | {"Gradle": 9, "Java Properties": 2, "Shell": 1, "Text": 2, "Ignore List": 5, "Batchfile": 1, "Markdown": 1, "Proguard": 4, "Kotlin": 334, "XML": 209, "Java": 15, "Gradle Kotlin DSL": 1, "INI": 1} | package com.wanandroid.ui.first
import android.os.Bundle
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.Toast
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.navigation.Navigation
import androidx.navigation.fragment.NavHostFragment
import com.wanandroid.App
import com.wanandroid.BrowserActivity
import com.wanandroid.R
import com.wanandroid.adapter.FirstArticleAdapter
import com.wanandroid.base.BaseVMFragment
import com.wanandroid.customui.MyBanner
import com.wanandroid.databinding.FragmentFirstBinding
import com.wanandroid.model.resultbean.Banner
import com.wanandroid.util.GlideImageLoader
import com.wanandroid.util.dp2px
import com.wanandroid.view.CustomLoadMoreView
import com.youth.banner.BannerConfig
import kotlinx.android.synthetic.main.fragment_first.*
import kotlinx.coroutines.ExperimentalCoroutinesApi
import org.koin.androidx.viewmodel.ext.android.viewModel
/**
* MyFirstFragment.
* Created by Donkey
* on 3:18 PM
*/
class FirstFragment() : BaseVMFragment<FragmentFirstBinding>(R.layout.fragment_first) {
private val articleViewModel by viewModel<ArticleViewModel>()
private val firstArticleAdapter by lazy { FirstArticleAdapter() }
private val bannerImages = mutableListOf<String>()
private val bannerTitles = mutableListOf<String>()
private val bannerUrls = mutableListOf<String>()
private val banner by lazy { MyBanner(activity) }
override fun initView() {
binding.run {
viewModel = articleViewModel
adapter= firstArticleAdapter
}
initBanner()
firstArticleAdapter.run {
setOnItemClickListener { _, _, position ->
val bundle = Bundle()
bundle.putString(BrowserActivity.URL,firstArticleAdapter.data[position].link)
bundle.putString(BrowserActivity.TITLE,firstArticleAdapter.data[position].title)
// val bundle =
// bundleOf(BrowserActivity.URL to firstArticleAdapter.data[position].link,
// BrowserActivity.TITLE to firstArticleAdapter.data[position].title
// )
NavHostFragment.findNavController(this@FirstFragment)
.navigate(R.id.browserActivity, bundle)
}
addHeaderView(banner)
setLoadMoreView(CustomLoadMoreView())//添加上拉加载更多布局
setOnLoadMoreListener({ loadMore() }, homeRecycleView) //上拉加载更多
}
}
private fun loadMore() {
articleViewModel.getFirstArticleList(false)
}
@ExperimentalCoroutinesApi
private fun refresh() {
articleViewModel.getFirstArticleList()
articleViewModel.getBannerList()
}
@ExperimentalCoroutinesApi
override fun initData() {
refresh()
}
private fun initBanner() {
banner.run {
layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, banner.dp2px(200))
setImageLoader(GlideImageLoader())
setOnBannerListener { position ->
run {
val bundle = Bundle()
bundle.putString(BrowserActivity.URL,bannerUrls[position])
bundle.putString(BrowserActivity.TITLE,bannerTitles[position])
NavHostFragment.findNavController(this@FirstFragment)
.navigate(R.id.browserActivity, bundle)
}
}
}
}
private fun setBanner(bannerList: List<Banner>) {
for (banner in bannerList) {
bannerImages.add(banner.imagePath)
bannerTitles.add(banner.title)
bannerUrls.add(banner.url)
}
banner.setImages(bannerImages)
.setBannerTitles(bannerTitles)
.setBannerStyle(BannerConfig.NUM_INDICATOR_TITLE)
.setDelayTime(3000)
banner.start()
}
override fun startObserve() {
articleViewModel.mBanners.observe(viewLifecycleOwner, Observer { it ->
it?.let { setBanner(it) }
})
articleViewModel.uiState.observe(viewLifecycleOwner, Observer {
it.successData?.let { list ->
firstArticleAdapter.run {
firstArticleAdapter.setEnableLoadMore(false)
if (it.isRefresh){
replaceData(list.datas)
}else{
addData(list.datas)
}
setEnableLoadMore(true)
loadMoreComplete()
}
}
if (it.showEnd) firstArticleAdapter.loadMoreEnd()
it.showError?.let { message ->
Toast.makeText(App.getContext(),if (message.isBlank()) "网络异常" else message,Toast.LENGTH_SHORT).show()
}
})
}
override fun onStart() {
super.onStart()
banner.startAutoPlay()
}
override fun onStop() {
super.onStop()
banner.stopAutoPlay()
}
} | 1 | null | 1 | 1 | bb42c08a0eeaf5052fe8deef84068fe5c3b2fef6 | 5,099 | jetpackmvvm | Apache License 2.0 |
analysis/analysis-api-fir/src/org/jetbrains/kotlin/analysis/api/fir/references/KtFirCollectionLiteralReference.kt | JetBrains | 3,432,266 | false | {"Kotlin": 78943108, "Java": 6823266, "Swift": 4063298, "C": 2609288, "C++": 1970234, "Objective-C++": 171723, "JavaScript": 138329, "Python": 59488, "Shell": 32312, "TypeScript": 22800, "Objective-C": 22132, "Lex": 21352, "Groovy": 17400, "Batchfile": 11748, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.references
import org.jetbrains.kotlin.analysis.api.KaSession
import org.jetbrains.kotlin.analysis.api.fir.KaFirSession
import org.jetbrains.kotlin.analysis.api.fir.symbols.KaFirArrayOfSymbolProvider.arrayOf
import org.jetbrains.kotlin.analysis.api.fir.symbols.KaFirArrayOfSymbolProvider.arrayOfSymbol
import org.jetbrains.kotlin.analysis.api.fir.symbols.KaFirArrayOfSymbolProvider.arrayTypeToArrayOfCall
import org.jetbrains.kotlin.analysis.api.symbols.KaSymbol
import org.jetbrains.kotlin.analysis.low.level.api.fir.api.getOrBuildFirSafe
import org.jetbrains.kotlin.fir.expressions.FirArrayLiteral
import org.jetbrains.kotlin.fir.types.ConeClassLikeType
import org.jetbrains.kotlin.fir.types.resolvedType
import org.jetbrains.kotlin.psi.KtCollectionLiteralExpression
import org.jetbrains.kotlin.psi.KtImportAlias
class KaFirCollectionLiteralReference(
expression: KtCollectionLiteralExpression
) : KtCollectionLiteralReference(expression), KaFirReference {
override fun KaSession.resolveToSymbols(): Collection<KaSymbol> {
check(this is KaFirSession)
val fir = element.getOrBuildFirSafe<FirArrayLiteral>(firResolveSession) ?: return emptyList()
val type = fir.resolvedType as? ConeClassLikeType ?: return listOfNotNull(arrayOfSymbol(arrayOf))
val call = arrayTypeToArrayOfCall[type.lookupTag.classId] ?: arrayOf
return listOfNotNull(arrayOfSymbol(call))
}
override fun isReferenceToImportAlias(alias: KtImportAlias): Boolean {
return super<KaFirReference>.isReferenceToImportAlias(alias)
}
}
| 180 | Kotlin | 5642 | 48,082 | 2742b94d9f4dbdb1064e65e05682cb2b0badf2fc | 1,811 | kotlin | Apache License 2.0 |
idea/formatter/src/org/jetbrains/kotlin/idea/util/FormatterUtil.kt | cr8tpro | 189,964,139 | true | {"Kotlin": 37481242, "Java": 7489008, "JavaScript": 157778, "HTML": 74773, "Lex": 23159, "TypeScript": 21255, "IDL": 10895, "ANTLR": 9803, "CSS": 8084, "Shell": 7727, "Groovy": 6940, "Batchfile": 5362, "Swift": 2253, "Ruby": 668, "Objective-C": 293, "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 org.jetbrains.kotlin.idea.util
import com.intellij.formatting.ASTBlock
import org.jetbrains.kotlin.idea.core.formatter.KotlinCodeStyleSettings
/*
* ASTBlock is nullable since 182, this extension was introduced to minimize changes between bunches
*/
fun ASTBlock.requireNode() = node ?: error("ASTBlock.getNode() returned null")
/**
* Can be removed with all usages after moving master to 1.3 with new default code style settings.
*/
val isDefaultOfficialCodeStyle by lazy { !KotlinCodeStyleSettings.DEFAULT.CONTINUATION_INDENT_FOR_CHAINED_CALLS } | 0 | Kotlin | 1 | 2 | dca23f871cc22acee9258c3d58b40d71e3693858 | 771 | kotlin | Apache License 2.0 |
app/src/main/java/ir/mirrajabi/kotlet/infrastructure/api/services/SimpleService.kt | mirrajabi | 96,014,417 | false | null | package ir.mirrajabi.kotlet.infrastructure.api.services
import io.reactivex.Observable
import ir.mirrajabi.kotlet.infrastructure.api.models.CommentModel
import ir.mirrajabi.kotlet.infrastructure.api.models.PostModel
import retrofit2.http.GET
import retrofit2.http.Path
interface SimpleService {
@GET("/posts")
fun getPosts() : Observable<ArrayList<PostModel>>
@GET("/posts/{id}")
fun getPost(@Path("id") postId: Int) : Observable<PostModel>
@GET("/posts/{id}/comments")
fun getCommentsForPost(@Path("id") postId: Int) : Observable<ArrayList<CommentModel>>
} | 0 | Kotlin | 4 | 27 | 9645e4a7a2df117d9e1a98fecaeb47913500fa67 | 583 | kotlet | Apache License 2.0 |
android/src/com/android/tools/idea/diagnostics/crash/ExceptionRateLimiter.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.diagnostics.crash
import java.util.ArrayDeque
import java.util.concurrent.TimeUnit
class ExceptionRateLimiter(
private val maxEventsPerPeriod: Int = 10,
private val periodMs: Long = TimeUnit.MINUTES.toMillis(10),
private val allowancePerSignature: Int = 2,
private val timeProvider: () -> Long = { TimeUnit.NANOSECONDS.toMillis(System.nanoTime()) }
) {
data class SignatureStatistics(var count: Int, var deniedSinceLastAllow: Int)
private val signatureStats = HashMap<String, SignatureStatistics>()
private var globalCount = 0
private fun isPowerOfTwo(n: Int) = n and (n - 1) == 0
private val queue = ArrayDeque<Long>(maxEventsPerPeriod)
@Synchronized
fun tryAcquireForSignature(sig: String): Permit {
val stats = signatureStats.getOrPut(sig) { SignatureStatistics(0, 0) }
globalCount++
val count = ++stats.count
val currentTimeMs = timeProvider()
val evictedTimeMs = updateTimeQueue(currentTimeMs)
// Allow first _allowance_ exceptions
if (count <= allowancePerSignature) {
return allow(stats)
}
// Allow reports that is a power of two per signature
if (isPowerOfTwo(count)) {
return allow(stats)
}
// Allow if rate limiter permits: maximum of maxEventsPerPeriod per periodMs
if (evictedTimeMs == null || currentTimeMs - evictedTimeMs > periodMs) {
return allow(stats)
}
return deny(stats)
}
/**
* Added current timestamp to the queue, if queue is full, returns evicted timestamp.
* Otherwise return <code>null</code>
*/
private fun updateTimeQueue(currentTimeMs: Long): Long? {
queue.addLast(currentTimeMs)
if (queue.size <= maxEventsPerPeriod) {
return null
}
return queue.removeFirst()
}
private fun allow(stats: SignatureStatistics): Permit {
val deniedSinceLastAllow = stats.deniedSinceLastAllow
stats.deniedSinceLastAllow = 0
return Permit(PermissionType.ALLOW, deniedSinceLastAllow, globalCount, stats.count)
}
private fun deny(stats: SignatureStatistics): Permit {
val deniedSinceLastAllow = ++stats.deniedSinceLastAllow
return Permit(PermissionType.DENY, deniedSinceLastAllow, globalCount, stats.count)
}
enum class PermissionType {
DENY,
ALLOW
}
data class Permit(val permissionType: PermissionType,
val deniedSinceLastAllow: Int,
val globalExceptionCounter: Int,
val localExceptionCounter: Int)
} | 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 3,116 | android | Apache License 2.0 |
app/src/main/java/com/pixerapps/assignment/data/remote/ApiClient.kt | ashujhaji | 271,519,938 | false | {"Gradle": 3, "Java Properties": 1, "Text": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 21, "XML": 16, "Java": 1} | package com.pixerapps.assignment.data.remote
/*MIT License
Copyright (c) 2020 Ashutosh Jha
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.*/
import android.content.Context
import com.pixerapps.assignment.BuildConfig
import com.pixerapps.assignment.model.TopHeadlineResponse
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
class ApiClient(context: Context) {
private lateinit var apiService: ApiService
init {
val retrofit = initRetrofit(context)
initServices(retrofit)
}
private fun initRetrofit(context: Context): Retrofit {
val interceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
val client = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.retryOnConnectionFailure(true)
.apply {
networkInterceptors().add(Interceptor { chain ->
val original = chain.request()
val request = original.newBuilder()
.method(original.method(), original.body())
.build()
chain.proceed(request)
})
if (BuildConfig.DEBUG)
addInterceptor(interceptor)
addInterceptor(ConnectivityAwareClient(context))
}
return Retrofit.Builder().baseUrl(BuildConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client.build())
.build()
}
private fun initServices(retrofit: Retrofit?) {
if (retrofit != null)
apiService = retrofit.create(ApiService::class.java)
}
suspend fun getTopHeadlines(): Response<TopHeadlineResponse> {
return apiService.getHeadlines("in", BuildConfig.API_KEY)
}
} | 0 | Kotlin | 0 | 2 | 3fe37d72b0eb2042c5f00f85b3a139b78f981119 | 3,181 | Kotlin-MVVM-LiveData-Room | MIT License |
networking/src/main/java/com/artear/networking/util/ConnectionUtil.kt | Artear | 164,454,820 | false | null | /*
* Copyright 2018 Artear S.A.
*
* 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.artear.networking.util
import android.annotation.TargetApi
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities.*
import android.net.NetworkInfo
import android.os.Build.VERSION_CODES.LOLLIPOP
import android.os.Build.VERSION_CODES.M
import android.telephony.TelephonyManager.*
import com.artear.networking.extension.connectivityManager
import com.artear.networking.extension.telephonyManager
import com.artear.tools.android.isLollipop
import com.artear.tools.android.isMarshMallow
import java.util.*
object ConnectionUtil {
/**
* Check if there is any connectivity
*
* @param context
* @return is Device Connected
*/
fun isConnected(context: Context): Boolean {
context.connectivityManager()?.apply {
val activeNetwork = activeNetworkInfo
return activeNetwork != null && activeNetwork.isConnected
}
return false
}
fun connectionType(context: Context): ConnectionType {
context.connectivityManager()?.apply {
return isMarshMallow({
connectionTypeMarshMallow(it, context)
}, {
connectionTypePreviousM(context)
})
}
return ConnectionType.UNKNOWN
}
@TargetApi(M)
private fun connectionTypeMarshMallow(connectivityManager: ConnectivityManager,
context: Context): ConnectionType {
connectivityManager.activeNetwork?.apply {
val nc = connectivityManager.getNetworkCapabilities(this)
val transports = setOf(TRANSPORT_WIFI, TRANSPORT_VPN, TRANSPORT_CELLULAR)
val transport = transports.first { nc.hasTransport(it) }
when (transport) {
TRANSPORT_WIFI, TRANSPORT_VPN -> return ConnectionType.WIFI
TRANSPORT_CELLULAR -> return connectionMobileType(context)
}
}
return ConnectionType.UNKNOWN
}
private fun ConnectivityManager.connectionTypePreviousM(context: Context): ConnectionType {
return isLollipop({ connectionTypeLollipop(context) }, { connectionTypePreviousL(context) })
}
@TargetApi(LOLLIPOP)
private fun ConnectivityManager.connectionTypeLollipop(context: Context): ConnectionType {
var connectionType = ConnectionType.UNKNOWN
val networks = Arrays.asList(*allNetworks)
for (network in networks) {
val networkInfo = getNetworkInfo(network)
val compare = when {
networkInfo.isWifi() -> ConnectionType.WIFI
networkInfo.isMobile() -> connectionMobileType(context)
else -> ConnectionType.UNKNOWN
}
connectionType = compareConnections(connectionType, compare)
}
return connectionType
}
private fun compareConnections(lastConnectionType: ConnectionType,
compared: ConnectionType): ConnectionType =
if (compared.ordinal > lastConnectionType.ordinal) compared else lastConnectionType
/**
* Just in old version for check connection
*/
@Suppress("deprecation")
private fun ConnectivityManager.connectionTypePreviousL(context: Context): ConnectionType {
var networkInfo = getNetworkInfo(ConnectivityManager.TYPE_WIFI)
if (networkInfo.isConnectedOrConnecting)
return ConnectionType.WIFI
else {
networkInfo = getNetworkInfo(ConnectivityManager.TYPE_MOBILE)
if (networkInfo.isConnectedOrConnecting)
return connectionMobileType(context)
}
return ConnectionType.UNKNOWN
}
private fun connectionMobileType(context: Context): ConnectionType {
context.telephonyManager()?.apply {
when (networkType) {
NETWORK_TYPE_GPRS,
NETWORK_TYPE_EDGE,
NETWORK_TYPE_CDMA,
NETWORK_TYPE_1xRTT,
NETWORK_TYPE_IDEN -> {
return ConnectionType._2G
}
NETWORK_TYPE_UMTS,
NETWORK_TYPE_EVDO_0,
NETWORK_TYPE_EVDO_A,
NETWORK_TYPE_HSDPA,
NETWORK_TYPE_HSUPA,
NETWORK_TYPE_HSPA,
NETWORK_TYPE_EVDO_B,
NETWORK_TYPE_EHRPD,
NETWORK_TYPE_HSPAP -> {
return ConnectionType._3G
}
NETWORK_TYPE_LTE -> return ConnectionType._4G
}
}
return ConnectionType.UNKNOWN
}
enum class ConnectionType {
UNKNOWN, _2G, _3G, _4G, WIFI
}
}
/**
* Just in old version for check connection
*/
@Suppress("deprecation")
private fun NetworkInfo.isMobile(): Boolean {
return type == ConnectivityManager.TYPE_MOBILE && isConnectedOrConnecting
}
/**
* Just in old version for check connection
*/
@Suppress("deprecation")
fun NetworkInfo.isWifi(): Boolean {
return type == ConnectivityManager.TYPE_WIFI && isConnectedOrConnecting
} | 1 | null | 1 | 1 | 75a09cfefb1e7025b620f2680860825a5e470312 | 5,704 | app_lib_networking_android | Apache License 2.0 |
paging/rxjava2/src/test/java/androidx/paging/RxPagedListBuilderTest.kt | FYI-Google | 258,765,297 | false | null | /*
* Copyright (C) 2018 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.paging
import io.reactivex.Observable
import io.reactivex.observers.TestObserver
import io.reactivex.schedulers.TestScheduler
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class RxPagedListBuilderTest {
/**
* Creates a data source that will sequentially supply the passed lists
*/
private fun testDataSourceSequence(data: List<List<String>>): DataSource.Factory<Int, String> {
return object : DataSource.Factory<Int, String>() {
var localData = data
override fun create(): DataSource<Int, String> {
val currentList = localData.first()
localData = localData.drop(1)
return ListDataSource<String>(currentList)
}
}
}
@Test
fun basic() {
val factory = testDataSourceSequence(listOf(listOf("a", "b"), listOf("c", "d")))
val scheduler = TestScheduler()
val observable = RxPagedListBuilder(factory, 10)
.setFetchScheduler(scheduler)
.setNotifyScheduler(scheduler)
.buildObservable()
val observer = TestObserver<PagedList<String>>()
observable.subscribe(observer)
// initial state
observer.assertNotComplete()
observer.assertValueCount(0)
// load first item
scheduler.triggerActions()
observer.assertValueCount(1)
assertEquals(listOf("a", "b"), observer.values().first())
// invalidate triggers second load
observer.values().first().dataSource.invalidate()
scheduler.triggerActions()
observer.assertValueCount(2)
assertEquals(listOf("c", "d"), observer.values().last())
}
@Test
fun checkSchedulers() {
val factory = testDataSourceSequence(listOf(listOf("a", "b"), listOf("c", "d")))
val notifyScheduler = TestScheduler()
val fetchScheduler = TestScheduler()
val observable: Observable<PagedList<String>> = RxPagedListBuilder(
factory, 10)
.setFetchScheduler(fetchScheduler)
.setNotifyScheduler(notifyScheduler)
.buildObservable()
val observer = TestObserver<PagedList<String>>()
observable.subscribe(observer)
// notify has nothing to do
notifyScheduler.triggerActions()
observer.assertValueCount(0)
// fetch creates list, but observer doesn't see
fetchScheduler.triggerActions()
observer.assertValueCount(0)
// now notify reveals item
notifyScheduler.triggerActions()
observer.assertValueCount(1)
}
}
| 8 | null | 657 | 6 | b9cd83371e928380610719dfbf97c87c58e80916 | 3,359 | platform_frameworks_support | Apache License 2.0 |
bukkit/rpk-block-log-lib-bukkit/src/main/kotlin/com/rpkit/blocklog/bukkit/block/RPKBlockHistoryProvider.kt | Nyrheim | 269,929,653 | true | {"Gradle": 71, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "INI": 1, "YAML": 103, "Kotlin": 1043, "Java": 291, "HTML": 23, "CSS": 2, "JavaScript": 1} | package com.rpkit.blocklog.bukkit.block
import com.rpkit.core.service.ServiceProvider
import org.bukkit.Material
import org.bukkit.block.Block
import org.bukkit.inventory.ItemStack
interface RPKBlockHistoryProvider: ServiceProvider {
fun getBlockHistory(id: Int): RPKBlockHistory?
fun addBlockHistory(blockHistory: RPKBlockHistory)
fun updateBlockHistory(blockHistory: RPKBlockHistory)
fun removeBlockHistory(blockHistory: RPKBlockHistory)
fun getBlockChange(id: Int): RPKBlockChange?
fun addBlockChange(blockChange: RPKBlockChange)
fun updateBlockChange(blockChange: RPKBlockChange)
fun removeBlockChange(blockChange: RPKBlockChange)
fun getBlockInventoryChange(id: Int): RPKBlockInventoryChange?
fun addBlockInventoryChange(blockInventoryChange: RPKBlockInventoryChange)
fun updateBlockInventoryChange(blockInventoryChange: RPKBlockInventoryChange)
fun removeBlockInventoryChange(blockInventoryChange: RPKBlockInventoryChange)
fun getBlockHistory(block: Block): RPKBlockHistory
fun getBlockTypeAtTime(block: Block, time: Long): Material
fun getBlockInventoryAtTime(block: Block, time: Long): Array<ItemStack>
} | 0 | null | 0 | 0 | f2196a76e0822b2c60e4a551de317ed717bbdc7e | 1,177 | RPKit | Apache License 2.0 |
compiler/testData/diagnostics/tests/subtyping/topLevelAnonymousObjects.kt | AlexeyTsvetkov | 17,321,988 | true | {"Java": 22837096, "Kotlin": 18913890, "JavaScript": 180163, "HTML": 47571, "Protocol Buffer": 46162, "Lex": 18051, "Groovy": 13300, "ANTLR": 9729, "CSS": 9358, "IDL": 6426, "Shell": 4704, "Batchfile": 3703} | private var x = object {}
fun test() {
// No error, because the type of x is normalized to Any
x = object {}
} | 1 | Java | 0 | 2 | 72a84083fbe50d3d12226925b94ed0fe86c9d794 | 119 | kotlin | Apache License 2.0 |
common/src/desktopMain/kotlin/dev/zwander/common/util/FileExporter.kt | zacharee | 641,202,797 | false | {"Kotlin": 370098, "Swift": 11066, "Ruby": 2834, "Objective-C": 1853, "Shell": 566} | package dev.zwander.common.util
import io.github.vinceglb.filekit.core.PlatformFile
import okio.BufferedSink
import okio.buffer
import okio.sink
actual fun PlatformFile.bufferedSink(append: Boolean): BufferedSink? {
return file.sink(append).buffer()
}
| 4 | Kotlin | 7 | 144 | e9a111510b0ae2e9022390047569952df25bff8a | 258 | HINTControl | MIT License |
app/src/main/java/com/abhishek_jaiswal/nutriguide/MainActivity.kt | Abhijais2003 | 793,204,480 | false | {"Kotlin": 19362} | package com.abhishek_jaiswal.nutriguide
import EdamamResponse
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.abhishek_jaiswal.nutriguide.databinding.ActivityMainBinding
import com.google.firebase.auth.FirebaseAuth
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.io.IOException
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val toolbar: androidx.appcompat.widget.Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragmentContainer, NutritionFragment())
.commit()
}
binding.submitBtn.setOnClickListener {
val foodName = binding.editText.text.toString().trim()
if (foodName.isEmpty()) {
Toast.makeText(this, "Please enter a food name", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
// Make API request with Retrofit
val retrofit = Retrofit.Builder()
.baseUrl("https://api.edamam.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val apiService = retrofit.create(EdamamApiService::class.java)
val call = apiService.getNutritionData("89c00de8", "5be60b13561740c65d06e33ac0b4f8c1", foodName)
call.enqueue(object : Callback<EdamamResponse> {
override fun onResponse(call: Call<EdamamResponse>, response: Response<EdamamResponse>) {
if (response.isSuccessful) {
val edamamResponse = response.body()
Log.d("API Response", "Response received: $edamamResponse")
val fragment = supportFragmentManager.findFragmentById(R.id.fragmentContainer)
if (fragment is NutritionFragment && fragment.view != null && edamamResponse != null) {
fragment.displayNutrition(edamamResponse)
}
} else {
// Handle error response
Log.d("API Error", "Response received but not successful. Error code: ${response.code()}, message: ${response.message()}")
Toast.makeText(applicationContext, "Error: ${response.code()}", Toast.LENGTH_SHORT).show()
}
}
override fun onFailure(call: Call<EdamamResponse>, t: Throwable) {
// Handle network error
Log.d("API Failure", "No response received. Failure message: ${t.message}")
if (t is IOException) {
Toast.makeText(applicationContext, "Network error occurred", Toast.LENGTH_SHORT).show()
} else {
Toast.makeText(applicationContext, "An error occurred", Toast.LENGTH_SHORT).show()
}
}
})
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.drawer_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.about-> {
val intent = Intent(this, about::class.java)
startActivity(intent)
true
}
R.id.contact -> {
val intent = Intent(this, contact::class.java)
startActivity(intent)
true
}
R.id.version -> {
val intent = Intent(this, version::class.java)
startActivity(intent)
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| 0 | Kotlin | 0 | 1 | fbd8a9c568058d165f9e9f6e8d7d2a1054d5b4de | 4,366 | NutriGuide-Nutrition-Expert-Android | MIT License |
openai-android/src/main/java/dev/sunnat629/ai_client/apis/messages/MessagesRepositoryImpl.kt | sunnat629 | 778,014,307 | false | {"Kotlin": 96033} | /**
* @author <NAME>
* @date 01.04.24
* Copyright ©2024 Sunnat629.dev. All rights reserved.
*/
package dev.sunnat629.ai_client.apis.messages
import dev.sunnat629.ai_client.models.messages.CreateMessageRequest
import dev.sunnat629.ai_client.models.messages.ListMessageFilesResponse
import dev.sunnat629.ai_client.models.messages.MessageFileDetails
import dev.sunnat629.ai_client.models.messages.MessageResponse
import dev.sunnat629.ai_client.networks.ApiResult
import dev.sunnat629.ai_client.networks.getRequest
import dev.sunnat629.ai_client.networks.postRequest
import io.ktor.client.HttpClient
class MessageRepositoryImpl(private val httpClient: HttpClient) : MessageRepository {
private val baseUrl = "https://api.openai.com/v1/threads"
override suspend fun createMessage(
threadId: String,
request: CreateMessageRequest
): ApiResult<MessageResponse> {
return httpClient.postRequest(
url = "$baseUrl/$threadId/messages",
request = request
)
}
override suspend fun listMessages(threadId: String): ApiResult<List<MessageResponse>> {
return httpClient.getRequest(
url = "$baseUrl/$threadId/messages"
)
}
override suspend fun retrieveMessage(
threadId: String,
messageId: String
): ApiResult<MessageResponse> {
return httpClient.getRequest(
url = "$baseUrl/$threadId/messages/$messageId"
)
}
override suspend fun listMessageFiles(
threadId: String,
messageId: String
): ApiResult<ListMessageFilesResponse> {
TODO("Not yet implemented")
}
override suspend fun retrieveMessageFile(
threadId: String,
messageId: String,
fileId: String
): ApiResult<MessageFileDetails> {
TODO("Not yet implemented")
}
} | 3 | Kotlin | 0 | 1 | 324c454b9fe651cd3c6984815642919e8e29ac06 | 1,858 | openai-android | MIT License |
src/commonMain/kotlin/dev/folomeev/kotgl/matrix/matrices/mutables/Adjoint.kt | folomeev | 487,706,128 | false | null | /** Set of matrix adjoint calculating methods. */
@file:kotlin.jvm.JvmName("MutableMatrices")
@file:kotlin.jvm.JvmMultifileClass
package dev.folomeev.kotgl.matrix.matrices.mutables
import dev.folomeev.kotgl.matrix.FloatMapping16
import dev.folomeev.kotgl.matrix.FloatMapping4
import dev.folomeev.kotgl.matrix.FloatMapping9
import dev.folomeev.kotgl.matrix.matrices.Mat2
import dev.folomeev.kotgl.matrix.matrices.Mat3
import dev.folomeev.kotgl.matrix.matrices.Mat4
/** Adjoint [this] and reduce the result by [reducer]. */
internal fun <T> Mat2.adjoint(reducer: FloatMapping4<T>) =
reducer(m11, -m01, -m10, m00)
/** Adjoint [this] and reduce the result by [reducer]. */
internal fun <T> Mat3.adjoint(reducer: FloatMapping9<T>): T {
return reducer(
m22 * m11 - m12 * m21,
(-m22 * m01 + m02 * m21),
(m12 * m01 - m02 * m11),
-m22 * m10 + m12 * m20,
(m22 * m00 - m02 * m20),
(-m12 * m00 + m02 * m10),
m21 * m10 - m11 * m20,
(-m21 * m00 + m01 * m20),
(m11 * m00 - m01 * m10)
)
}
/** Adjoint [this] and reduce the result by [reducer]. */
internal fun <T> Mat4.adjoint(reducer: FloatMapping16<T>): T {
val a00 = m00 * m11 - m01 * m10
val a01 = m00 * m12 - m02 * m10
val a02 = m00 * m13 - m03 * m10
val a03 = m01 * m12 - m02 * m11
val a04 = m01 * m13 - m03 * m11
val a05 = m02 * m13 - m03 * m12
val a06 = m20 * m31 - m21 * m30
val a07 = m20 * m32 - m22 * m30
val a08 = m20 * m33 - m23 * m30
val a09 = m21 * m32 - m22 * m31
val a10 = m21 * m33 - m23 * m31
val a11 = m22 * m33 - m23 * m32
// Calculate the determinant
return reducer(
(m11 * a11 - m12 * a10 + m13 * a09),
(m02 * a10 - m01 * a11 - m03 * a09),
(m31 * a05 - m32 * a04 + m33 * a03),
(m22 * a04 - m21 * a05 - m23 * a03),
(m12 * a08 - m10 * a11 - m13 * a07),
(m00 * a11 - m02 * a08 + m03 * a07),
(m32 * a02 - m30 * a05 - m33 * a01),
(m20 * a05 - m22 * a02 + m23 * a01),
(m10 * a10 - m11 * a08 + m13 * a06),
(m01 * a08 - m00 * a10 - m03 * a06),
(m30 * a04 - m31 * a02 + m33 * a00),
(m21 * a02 - m20 * a04 - m23 * a00),
(m11 * a07 - m10 * a09 - m12 * a06),
(m00 * a09 - m01 * a07 + m02 * a06),
(m31 * a01 - m30 * a03 - m32 * a00),
(m20 * a03 - m21 * a01 + m22 * a00)
)
}
/** Adjoint [this] and set the result to a new instance of [MutableMat2]. */
fun Mat2.adjoint() = adjoint(::mutableMat2)
/** Adjoint [this] and set the result to a new instance of [MutableMat3]. */
fun Mat3.adjoint() = adjoint(::mutableMat3)
/** Adjoint [this] and set the result to a new instance of [MutableMat4]. */
fun Mat4.adjoint() = adjoint(::mutableMat4)
/** Adjoint [this] and set the result to [out].
* @return [out]. */
fun Mat2.adjointTo(out: MutableMat2) = adjoint(out::set)
/** Adjoint [this] and set the result to [out].
* @return [out]. */
fun Mat3.adjointTo(out: MutableMat3) = adjoint(out::set)
/** Adjoint [this] and set the result to [out].
* @return [out]. */
fun Mat4.adjointTo(out: MutableMat4) = adjoint(out::set)
/** Adjoint [this] and set the result to [this].
* @return [this]. */
fun MutableMat2.adjointSelf() = adjointTo(this)
/** Adjoint [this] and set the result to [this].
* @return [this]. */
fun MutableMat3.adjointSelf() = adjointTo(this)
/** Adjoint [this] and set the result to [this].
* @return [this]. */
fun MutableMat4.adjointSelf() = adjointTo(this) | 0 | Kotlin | 0 | 1 | e4fee9e2647579825c05c1976e15a4469dc9633e | 3,502 | kotgl-matrix | MIT License |
fx-sample/src/main/kotlin/net/aquadc/properties/fx/FxViewModel.kt | b3nnee | 141,005,633 | true | {"Kotlin": 197353, "Java": 1022} | package net.aquadc.properties.fx
import javafx.beans.binding.Bindings
import javafx.beans.binding.StringBinding
import javafx.beans.binding.When
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.SimpleStringProperty
import net.aquadc.properties.sample.logic.User
import java.util.concurrent.Callable
class FxViewModel(
private val userProp: SimpleObjectProperty<User>
) {
val emailProp: SimpleStringProperty
val nameProp: SimpleStringProperty
val surnameProp: SimpleStringProperty
init {
val currentUser = userProp.get()
emailProp = SimpleStringProperty(currentUser.email)
nameProp = SimpleStringProperty(currentUser.name)
surnameProp = SimpleStringProperty(currentUser.surname)
}
val onScreenUserProp =
Bindings.createObjectBinding(Callable<User> {
User(emailProp.value, nameProp.value, surnameProp.value)
}, emailProp, nameProp, surnameProp)
val buttonEnabledProp = !userProp.isEqualTo(onScreenUserProp)
val buttonTextProp: StringBinding = When(buttonEnabledProp).then("Save changes").otherwise("Nothing changed")
fun saveButtonClicked() {
userProp.set(onScreenUserProp.value)
}
}
| 0 | Kotlin | 0 | 0 | 425916a3a318c07f1b80eb80a7a36bc355acd847 | 1,249 | reactive-properties | Apache License 2.0 |
kermit-config/src/commonMain/kotlin/com/gatebuzz/kermit/ext/Kermit.kt | psh | 612,020,219 | false | {"Kotlin": 17144} | package com.gatebuzz.kermit.ext
import co.touchlab.kermit.LogWriter
import co.touchlab.kermit.Logger
import co.touchlab.kermit.Severity
import co.touchlab.kermit.StaticConfig
class Kermit {
companion object {
fun builder() : Builder = LoggerBuilder()
operator fun invoke(block: Builder.() -> Unit): Logger = with(LoggerBuilder()) {
block(this)
build()
}
}
interface Builder {
fun path(path: String): Builder
fun tag(tag: String): Builder
fun minSeverity(severity: Severity): Builder
fun setLogWriters(vararg logWriter: LogWriter): Builder
fun addLogWriter(vararg logWriter: LogWriter): Builder
operator fun LogWriter.plusAssign(logWriter: LogWriter)
operator fun LogWriter.unaryPlus()
fun build(): Logger
}
internal class LoggerBuilder : Builder {
private var path: String? = null
private var tag: String = ""
private var logWriters: MutableList<LogWriter> = mutableListOf()
private var minSeverity: Severity = Severity.Verbose
override fun path(path: String): Builder {
this.path = path
return this
}
override fun tag(tag: String): Builder {
this.tag = tag
return this
}
override fun minSeverity(severity: Severity): Builder {
this.minSeverity = severity
return this
}
override fun setLogWriters(vararg logWriter: LogWriter): Builder {
logWriters = logWriter.toMutableList()
return this
}
override operator fun LogWriter.plusAssign(logWriter: LogWriter) {
logWriters.add(logWriter)
}
override operator fun LogWriter.unaryPlus() {
logWriters.add(this)
}
override fun addLogWriter(vararg logWriter: LogWriter): Builder {
logWriters.addAll(logWriter)
return this
}
override fun build(): Logger {
if (logWriters.isEmpty()) throw Exception("At least one log writer is needed")
return Logger(
StaticConfig(minSeverity, logWriters.toList())
)
}
}
}
| 4 | Kotlin | 0 | 1 | 5ec75f0d161deba07c340a3a2e63f7db22cc253d | 2,249 | KermitExt | Apache License 2.0 |
app/src/main/java/com/beerup/beerapp/StartingFragment.kt | MaciejSurowiec | 640,218,708 | false | null | package com.beerup.beerapp
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.beerup.beerapp.ViewModels.SharedViewModel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
class StartingFragment : Fragment() {
// TODO: Rename and change types of parameters
private var param1: String? = null
private var param2: String? = null
private lateinit var sharedViewModel: SharedViewModel
lateinit var retryButton: Button
lateinit var image: ImageView
lateinit var text: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val sharedPref = activity?.getSharedPreferences("userInfo", AppCompatActivity.MODE_PRIVATE)
val navHostFragment = activity?.supportFragmentManager?.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
if(sharedPref!!.contains("userLogin")) {
val userLogin = sharedPref!!.getString("userLogin", null).toString()
sharedViewModel = ViewModelProvider(requireActivity()).get(SharedViewModel::class.java)
sharedViewModel.userLogin = userLogin
sharedViewModel.getStatistics()
sharedViewModel.getTags()
} else {
val action = StartingFragmentDirections.actionStartingFragmentToUnloggedFragment()
navController.navigate(action)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
(activity as AppCompatActivity).supportActionBar?.hide()
(activity as MainActivity).bottomNavigation?.visibility = View.GONE
return inflater.inflate(R.layout.fragment_starting, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
retryButton = view.findViewById(R.id.retrytagsbutton)
text = view.findViewById(R.id.startingtext)
image = view.findViewById(R.id.startingimage)
retryButton.setOnClickListener{
sharedViewModel._statsDownloaded.postValue(false)
sharedViewModel._tagsDownloaded.postValue(false)
sharedViewModel._tagsError.postValue(false)
sharedViewModel.getStatistics()
sharedViewModel.getTags()
}
sharedViewModel._statsDownloaded.observe(viewLifecycleOwner) {
if(it and sharedViewModel._tagsDownloaded.value!!) {
val navHostFragment =
activity?.supportFragmentManager?.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
val action =
StartingFragmentDirections.actionStartingFragmentToLoggedFragment(sharedViewModel.userLogin)
navController.navigate(action)
}
}
sharedViewModel._tagsDownloaded.observe(viewLifecycleOwner) {
if(it and sharedViewModel._statsDownloaded.value!!) {
val navHostFragment =
activity?.supportFragmentManager?.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
val action =
StartingFragmentDirections.actionStartingFragmentToLoggedFragment(sharedViewModel.userLogin)
navController.navigate(action)
}
}
sharedViewModel._tagsError.observe(viewLifecycleOwner) {
showRetryButton(it)
}
}
fun showRetryButton(show: Boolean) {
if(show) {
retryButton.visibility = View.VISIBLE
text.visibility = View.GONE
image.visibility = View.GONE
} else {
retryButton.visibility = View.GONE
text.visibility = View.VISIBLE
image.visibility = View.VISIBLE
}
}
companion object {
@JvmStatic
fun newInstance(param1: String, param2: String) =
StartingFragment().apply {
arguments = Bundle().apply {
putString(ARG_PARAM1, param1)
putString(ARG_PARAM2, param2)
}
}
}
} | 0 | Kotlin | 0 | 0 | 9ec5131996f95f5ba1ebee9c55ab334e70b61a61 | 4,977 | beerapp-android | MIT License |
feature/metis/conversation/src/main/kotlin/de/tum/informatics/www1/artemis/native_app/feature/metis/conversation/service/MetisModificationFailure.kt | ls1intum | 537,104,541 | false | {"Kotlin": 1958386, "Dockerfile": 1306, "Shell": 1187} | package de.tum.informatics.www1.artemis.native_app.feature.metis
import de.tum.informatics.www1.artemis.native_app.core.data.NetworkResponse
enum class MetisModificationFailure(val messageRes: Int) {
CREATE_REACTION(R.string.metis_modification_failure_dialog_message_create_reaction),
DELETE_REACTION(R.string.metis_modification_failure_dialog_message_delete_reaction),
CREATE_POST(R.string.metis_modification_failure_dialog_message_create_post),
DELETE_POST(R.string.metis_modification_failure_dialog_message_delete_post),
UPDATE_POST(R.string.metis_modification_failure_dialog_message_update_post)
}
sealed class MetisModificationResponse<T> {
data class Failure<T>(val failure: MetisModificationFailure) : MetisModificationResponse<T>()
data class Response<T>(val data: T) : MetisModificationResponse<T>()
}
fun NetworkResponse<*>.asMetisModificationFailure(metisModificationFailure: MetisModificationFailure): MetisModificationFailure? =
bind<MetisModificationFailure?> { null }.or(metisModificationFailure) | 2 | Kotlin | 0 | 6 | dd4b99ab6a143b669d3db20af45dbe533c650bd4 | 1,048 | artemis-android | MIT License |
shared/core/utils/src/main/kotlin/ru/hh/plugins/utils/yaml/YamlUtils.kt | hhru | 159,637,875 | false | {"Kotlin": 476963, "Shell": 3314} | package ru.hh.plugins.utils.yaml
import org.yaml.snakeyaml.LoaderOptions
import org.yaml.snakeyaml.Yaml
import org.yaml.snakeyaml.constructor.CustomClassLoaderConstructor
import java.io.File
import java.io.FileNotFoundException
import java.io.FileReader
object YamlUtils {
inline fun <reified T : YamlConfigModel> tryLoadFromConfigFile(configFilePath: String): Result<T> {
val configFromYaml = loadFromConfigFile<T>(
configFilePath = configFilePath,
onError = {
return Result.failure(it)
}
)?.setConfigFilePath<T>(configFilePath = configFilePath)
return if (configFromYaml != null) {
Result.success(configFromYaml)
} else {
Result.failure(FileNotFoundException("File `$configFilePath` not found"))
}
}
inline fun <reified T> loadFromConfigFile(configFilePath: String, onError: (Throwable) -> Unit): T? {
val configFile = File(configFilePath).takeIf { it.exists() } ?: return null
return try {
val yaml = Yaml(
CustomClassLoaderConstructor(
T::class.java,
T::class.java.classLoader,
LoaderOptions(),
)
)
yaml.load<T>(FileReader(configFile))
} catch (ex: Exception) {
onError.invoke(ex)
null
}
}
fun loadFromConfigFile(filePath: String, onError: (Throwable) -> Unit): LinkedHashMap<String, Any>? {
val configFile = File(filePath).takeIf { it.exists() } ?: return null
return try {
val yaml = Yaml()
return yaml.load(FileReader(configFile))
} catch (ex: Exception) {
onError.invoke(ex)
null
}
}
fun Map<String, Any>.getBooleanOrStringExpression(key: String): String? {
return (this[key] as? Boolean)?.let { "$it" } ?: this[key] as? String
}
}
| 15 | Kotlin | 18 | 156 | 8f4e52c65b45a70268a7693af0261440864abcae | 1,971 | android-multimodule-plugin | MIT License |
server/src/main/kotlin/org/javacs/kt/CompilerClassPath.kt | krgn | 236,720,621 | true | {"Kotlin": 320780, "Python": 13312, "Java": 625, "Dockerfile": 453, "Shell": 328} | package org.javacs.kt
import org.javacs.kt.classpath.defaultClassPathResolver
import java.io.Closeable
import java.nio.file.Path
class CompilerClassPath(private val config: CompilerConfiguration) : Closeable {
private val workspaceRoots = mutableSetOf<Path>()
private val classPath = mutableSetOf<Path>()
private val buildScriptClassPath = mutableSetOf<Path>()
var compiler = Compiler(classPath, buildScriptClassPath)
private set
init {
compiler.updateConfiguration(config)
}
private fun refresh(updateBuildScriptClassPath: Boolean = true) {
// TODO: Fetch class path and build script class path concurrently (and asynchronously)
val resolver = defaultClassPathResolver(workspaceRoots)
var refreshCompiler = false
val newClassPath = resolver.classpathOrEmpty
if (newClassPath != classPath) {
syncClassPath(classPath, newClassPath)
refreshCompiler = true
}
if (updateBuildScriptClassPath) {
val newBuildScriptClassPath = resolver.buildScriptClasspathOrEmpty
if (newBuildScriptClassPath != buildScriptClassPath) {
syncClassPath(buildScriptClassPath, newBuildScriptClassPath)
refreshCompiler = true
}
}
if (refreshCompiler) {
compiler.close()
compiler = Compiler(classPath, buildScriptClassPath)
updateCompilerConfiguration()
}
}
private fun syncClassPath(dest: MutableSet<Path>, new: Set<Path>) {
val added = new - dest
val removed = dest - new
logAdded(added)
logRemoved(removed)
dest.removeAll(removed)
dest.addAll(added)
}
fun updateCompilerConfiguration() {
compiler.updateConfiguration(config)
}
fun addWorkspaceRoot(root: Path) {
LOG.info("Searching for dependencies in workspace root {}", root)
workspaceRoots.add(root)
refresh()
}
fun removeWorkspaceRoot(root: Path) {
LOG.info("Remove dependencies from workspace root {}", root)
workspaceRoots.remove(root)
refresh()
}
fun createdOnDisk(file: Path) {
changedOnDisk(file)
}
fun deletedOnDisk(file: Path) {
changedOnDisk(file)
}
fun changedOnDisk(file: Path) {
val name = file.fileName.toString()
if (name == "pom.xml" || name == "build.gradle" || name == "build.gradle.kts")
refresh(updateBuildScriptClassPath = false)
}
override fun close() {
compiler.close()
}
}
private fun logAdded(sources: Collection<Path>) {
when {
sources.isEmpty() -> return
sources.size > 5 -> LOG.info("Adding {} files to class path", sources.size)
else -> LOG.info("Adding {} to class path", sources)
}
}
private fun logRemoved(sources: Collection<Path>) {
when {
sources.isEmpty() -> return
sources.size > 5 -> LOG.info("Removing {} files from class path", sources.size)
else -> LOG.info("Removing {} from class path", sources)
}
}
| 0 | Kotlin | 0 | 0 | bb5c110f7cc9d24a77add41d2bf763a325572d06 | 3,130 | kotlin-language-server | MIT License |
library/verification-core/src/main/java/com/sinch/verification/core/internal/pattern/PatternHandler.kt | sinch | 353,915,754 | false | null | package com.sinch.verification.core.internal.pattern
import java.util.regex.Pattern
/**
* Common logic for classes using [Pattern] instances created with given regular expression.
*/
abstract class PatternHandler(template: String, patternFactory: PatternFactory) {
internal val pattern: Pattern = patternFactory.create(template)
} | 0 | Kotlin | 1 | 0 | 9ff7e4b0311a0a8609dc5faac91d0e78b4e9afff | 338 | verification-android-sdk | Apache License 2.0 |
domain/src/main/java/com/sfaxdroid/domain/GetLiveWallpapersUseCase.kt | yassinBaccour | 106,160,036 | false | {"Kotlin": 348508, "Java": 3869} | package com.sfaxdroid.domain
import com.sfaxdroid.data.entity.Response
import com.sfaxdroid.data.entity.WallpaperResponse
import com.sfaxdroid.data.repositories.WsRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class GetLiveWallpapersUseCase @Inject constructor(private val wsRepository: WsRepository) :
ResultUseCase<GetLiveWallpapersUseCase.Param, Response<WallpaperResponse>>() {
override suspend fun doWork(params: Param): Response<WallpaperResponse> {
return withContext(Dispatchers.IO) {
wsRepository.getLiveWallpapers(params.file)
}
}
class Param(
val file: String
)
}
| 0 | Kotlin | 0 | 2 | 136ac811fb1495a8ea2800480954121bf092742b | 702 | SfaxDroid_Wallpaper_App | Apache License 2.0 |
features/core/logger/impl/staging_tools/src/main/java/com/ruslan/hlushan/core/logger/impl/di/StagingLogcatLoggerModule.kt | game-x50 | 361,364,864 | false | null | package com.ruslan.hlushan.core.logger.impl.di
import com.ruslan.hlushan.core.logger.api.EmptyLogcatLoggerImpl
import com.ruslan.hlushan.core.logger.api.LogcatLogger
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
object StagingLogcatLoggerModule {
@Provides
@Singleton
fun provideLogcatLogger(): LogcatLogger = EmptyLogcatLoggerImpl
} | 26 | Kotlin | 0 | 0 | 155c9ae3e60bb24141823837b2dddf041f71ff89 | 384 | android_client_app | Apache License 2.0 |
repository/src/main/java/com/redvelvet/repository/source/DataStoreDataSource.kt | RedVelvet-Team | 670,763,637 | false | null | package com.redvelvet.repository.source
interface DataStoreDataSource {
// region user
suspend fun setIsLoggedInByAccount(isLogged: Boolean)
suspend fun getIsLoggedInByAccount(): Boolean
suspend fun setIsLoggedInByGuest(isLogged: Boolean)
suspend fun getIsLoggedInByGuest(): Boolean
suspend fun setIsFirstTimeUsingApp(isFirstTime: Boolean)
suspend fun getIsFirstTimeUsingApp(): Boolean
//endregion
// region auth
suspend fun setUserSessionId(id: String)
fun getUserSessionId(): String?
suspend fun setGuestSession(id: String, expDate: String)
fun getGuestSessionId(): String?
fun getGuestSessionExpDate(): String?
suspend fun setToken(token: String)
suspend fun getToken(): String?
//endregion
} | 5 | Kotlin | 0 | 1 | 2c541e51c7b0dd5697032da65dbef58ce4c3ea87 | 773 | IMovie | Apache License 2.0 |
app/src/main/java/com/kojek/movie_app/ui/tv_shows/TvShowsFragment.kt | najiabdillah | 409,103,585 | false | null | package com.kojek.movie_app.ui.tv_shows
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.kojek.movie_app.data.model.EventObserver
import com.kojek.movie_app.databinding.FragmentTvShowsBinding
import com.kojek.movie_app.ui.BaseFragment
import com.kojek.movie_app.util.extension.showSnackBar
class TvShowsFragment : BaseFragment(false) {
private val viewModel: TvShowsViewModel by viewModels()
private lateinit var viewDataBinding: FragmentTvShowsBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewDataBinding =
FragmentTvShowsBinding.inflate(inflater, container, false)
.apply {
viewmodel = viewModel
lifecycleOwner = [email protected]
}
return viewDataBinding.root
}
override fun setupViewModelObservers() {
viewModel.snackBarText.observe(viewLifecycleOwner, EventObserver { view?.showSnackBar(it) })
viewModel.goToTvShowEvent.observe(
viewLifecycleOwner,
EventObserver { navigateToTvShowDetails(it.id, it.title) })
}
private fun navigateToTvShowDetails(tvShowId: Int, tvShowTitle: String) {
val action = TvShowsFragmentDirections.actionNavigationTvShowsToTVShowDetailsFragment(
tvShowId, tvShowTitle
)
findNavController().navigate(action)
}
} | 0 | Kotlin | 0 | 0 | 5e6b1ca3539f892156940c027c7d90a99e12fae0 | 1,646 | MoviesTes | MIT License |
app/src/main/java/tech/nekonyan/githubapp/util/Utils.kt | nekonynn | 479,783,005 | false | null | package tech.nekonyan.githubapp.util
class Utils {
companion object {
@JvmStatic
fun isNullOrBlank(string: String): Boolean {
return string.isBlank()
}
}
} | 0 | Kotlin | 0 | 0 | 608946233df08965a77f5b221d98d498ff232169 | 200 | GithubApp | Apache License 2.0 |
opendc-compute/opendc-compute-service/src/main/kotlin/org/opendc/compute/service/scheduler/weights/CpuDemandWeigher.kt | Timovanmilligen | 463,493,229 | true | {"Kotlin": 1739390, "JavaScript": 315037, "Shell": 133006, "Python": 120908, "R": 36284, "SCSS": 13210, "Dockerfile": 2314} | package org.opendc.compute.service.scheduler.weights
import org.opendc.compute.api.Server
import org.opendc.compute.service.internal.HostView
/**
* A [HostWeigher] that weighs the hosts based on cpu demand. A negative [multiplier] will favor hosts with a lower cpu demand.
*
*/
public class CpuDemandWeigher(override val multiplier: Double = -1.0) : HostWeigher {
override fun getWeight(host: HostView, server: Server): Double {
return host.provisionedCores * (host.host.model.cpuCapacity/host.host.model.cpuCount)
}
override fun toString(): String = "CpuDemandWeigher[multiplier=$multiplier]"
}
| 0 | Kotlin | 0 | 0 | fe4c5852fe39b04b72da6882bfbee10f01a9897e | 623 | opendc | MIT License |
src/main/kotlin/org/railwaystations/rsapi/core/services/CountryService.kt | RailwayStations | 54,231,798 | false | {"Kotlin": 499047, "HTML": 8259, "Python": 1189, "Dockerfile": 405, "CSS": 126} | package org.railwaystations.rsapi.core.services
import org.railwaystations.rsapi.adapter.db.CountryDao
import org.railwaystations.rsapi.core.model.Country
import org.railwaystations.rsapi.core.ports.ListCountriesUseCase
import org.springframework.stereotype.Service
@Service
class CountryService(private val countryDao: CountryDao) : ListCountriesUseCase {
override fun list(onlyActive: Boolean?): Collection<Country> {
return countryDao.list(onlyActive == null || onlyActive)
}
}
| 5 | Kotlin | 1 | 9 | ad2a4fba9410a441d3c15ea5a2d58c4884f8af36 | 499 | RSAPI | MIT License |
src/main/kotlin/com/sparetimedevs/ami/app/utils/UiThread.kt | sparetimedevs | 731,672,148 | false | {"Kotlin": 225206} | /*
* Copyright (c) 2023 sparetimedevs and respective authors and developers.
*
* 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.sparetimedevs.ami.app.utils
import javax.swing.SwingUtilities
// https://github.com/arkivanov/Decompose/blob/d708782e889771a5753be59134806d128acdcfe4/sample/app-desktop/src/jvmMain/kotlin/com/arkivanov/sample/app/Utils.kt#L5
internal fun <T> runOnUiThread(block: () -> T): T {
if (SwingUtilities.isEventDispatchThread()) {
return block()
}
var error: Throwable? = null
var result: T? = null
SwingUtilities.invokeAndWait {
try {
result = block()
} catch (e: Throwable) {
error = e
}
}
error?.also { throw it }
@Suppress("UNCHECKED_CAST") return result as T
}
| 1 | Kotlin | 0 | 0 | 74e05e13643fadef3986d9ef72cecc625bb88d5b | 1,305 | ami-desktop | Apache License 2.0 |
ids-connector/src/main/kotlin/de/fhg/aisec/ids/dynamictls/AcmeSslContextFactory.kt | Fraunhofer-AISEC | 102,444,259 | false | {"Kotlin": 544298, "TypeScript": 85510, "HTML": 54291, "CSS": 14146, "Shell": 9516, "Python": 7090, "Dockerfile": 3166, "Prolog": 1584, "HCL": 276} | /*-
* ========================LICENSE_START=================================
* ids-connector
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.dynamictls
// import de.fhg.aisec.ids.api.acme.SslContextFactoryReloadable
// import de.fhg.aisec.ids.api.acme.SslContextFactoryReloadableRegistry
// import org.eclipse.jetty.util.ssl.SslContextFactory
// import org.slf4j.LoggerFactory
// import org.springframework.beans.factory.annotation.Autowired
//
// /**
// * This SslContextFactory registers started instances to a service that allows reloading of
// * all active SslContextFactory instances.
// *
// * @author <NAME>
// */
// class AcmeSslContextFactory : SslContextFactory.Server(), SslContextFactoryReloadable {
//
// @Autowired
// private lateinit var reloadableRegistry: SslContextFactoryReloadableRegistry
//
// @Throws(Exception::class)
// override fun doStart() {
// if (LOG.isDebugEnabled) {
// LOG.debug("Starting {}", this)
// }
// reloadableRegistry.registerSslContextFactoryReloadable(this)
// super.doStart()
// }
//
// @Throws(java.lang.Exception::class)
// override fun doStop() {
// if (LOG.isDebugEnabled) {
// LOG.debug("Stopping {}", this)
// }
// reloadableRegistry.removeSslContextFactoryReloadable(this)
// super.doStop()
// }
//
// override fun reload(newKeyStorePath: String) {
// try {
// if (LOG.isInfoEnabled) {
// LOG.info("Reloading {}", this)
// }
// reload { f: SslContextFactory -> f.keyStorePath = newKeyStorePath }
// } catch (e: Exception) {
// LOG.error("Error whilst reloading SslContextFactory: $this", e)
// }
// }
//
// override fun toString(): String {
// return String.format(
// "%s@%x (%s)", this.javaClass.simpleName, this.hashCode(), this.keyStorePath
// )
// }
//
// companion object {
// private val LOG = LoggerFactory.getLogger(AcmeSslContextFactory::class.java)
// }
// }
| 7 | Kotlin | 39 | 43 | 70ec9242444990d3797368f267fe774b2d6920bd | 2,762 | trusted-connector | Apache License 2.0 |
src/main/kotlin/tech/aaregall/lab/functions/weather/service/openmeteo/OpenMeteoClient.kt | ArnauAregall | 648,974,932 | false | null | package tech.aaregall.lab.functions.weather.service.openmeteo
import org.springframework.aot.hint.annotation.RegisterReflectionForBinding
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.http.HttpStatus
import org.springframework.http.HttpStatusCode
import org.springframework.http.client.reactive.ReactorClientHttpConnector
import org.springframework.stereotype.Component
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.ResponseStatus
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.support.WebClientAdapter
import org.springframework.web.service.annotation.GetExchange
import org.springframework.web.service.invoker.HttpServiceProxyFactory
import org.springframework.web.service.invoker.createClient
import reactor.core.publisher.Mono
import reactor.netty.http.client.HttpClient
import java.time.Duration
import java.util.function.Predicate.not
@ConfigurationProperties("app.open-meteo")
data class OpenMeteoProperties (
val baseUrl: String,
val timeout: Duration,
val hourlyParams: List<String>
)
@Component
class OpenMeteoClient(private val openMeteoProperties: OpenMeteoProperties, webClientBuilder: WebClient.Builder) {
private val openMeteoHttpClient: OpenMeteoHttpClient = HttpServiceProxyFactory
.builder(
WebClientAdapter.forClient(
webClientBuilder
.baseUrl(openMeteoProperties.baseUrl)
.clientConnector(ReactorClientHttpConnector(HttpClient.create().responseTimeout(openMeteoProperties.timeout)))
.defaultStatusHandler(not(HttpStatusCode::is2xxSuccessful)) {
Mono.error(OpenMeteoException("Error: OpenMeteo API responded with ${it.statusCode()}"))
}.build()
)
)
.build()
.createClient()
@RegisterReflectionForBinding(classes = [OpenMeteoForecastResponse::class])
fun getForecast(latitude: Float, longitude: Float): Mono<OpenMeteoForecastResponse> =
openMeteoHttpClient.getForecast(latitude, longitude, openMeteoProperties.hourlyParams.joinToString(","))
}
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
private class OpenMeteoException(override val message: String?) : IllegalStateException()
private fun interface OpenMeteoHttpClient {
@GetExchange("/forecast")
fun getForecast(
@RequestParam("latitude") latitude: Float,
@RequestParam("longitude") longitude: Float,
@RequestParam("hourly") hourly: String
): Mono<OpenMeteoForecastResponse>
} | 0 | Kotlin | 0 | 0 | cf926e34cb7aa407d8ec61b59fb262ead7770ea6 | 2,698 | aws-lambda-spring-cloud-function | Apache License 2.0 |
src/main/kotlin/tgmentionsbot/RequestMapper.kt | winogradoff | 306,044,611 | false | {"Kotlin": 87414, "Roff": 409, "Procfile": 103} | package tgmentionsbot
import org.springframework.stereotype.Component
import org.telegram.telegrambots.meta.api.objects.EntityType
import org.telegram.telegrambots.meta.api.objects.Message
import org.telegram.telegrambots.meta.api.objects.MessageEntity
import org.telegram.telegrambots.meta.api.objects.Update
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMember
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMemberAdministrator
import org.telegram.telegrambots.meta.api.objects.chatmember.ChatMemberOwner
@Component
class RequestMapper {
fun isCommandMessage(update: Update): Boolean =
update.message
?.let { getAnyMessageEntities(it) }
?.any { isBotCommand(it) }
?: false
fun isForwardedMessage(update: Update): Boolean =
update.message.forwardFrom != null
fun isPrivateChat(message: Message) =
message.chat.type == CHAT_TYPE_PRIVATE
fun isOwnerOrAdmin(message: Message, members: List<ChatMember>): Boolean {
val fromUserId = requireNotNull(message.from).id
for (member in members) {
when {
member is ChatMemberOwner && member.user.id == fromUserId -> return true
member is ChatMemberAdministrator && member.user.id == fromUserId -> return true
}
}
return false
}
fun parseCommand(message: Message, botName: String): Command? {
val commandText = getAnyMessageEntities(message).single { isBotCommand(it) }.text
return Command.getByKey(commandText.removeSuffix("@$botName"))
}
fun parseGroup(message: Message): GroupName {
val matchResult = parseByRegex(message, BotConstraints.REGEX_CMD_GROUP)
return GroupName(requireNotNull(matchResult.groups["group"]?.value))
}
fun parseGroupWithTail(message: Message): GroupName {
val matchResult = parseByRegex(message, BotConstraints.REGEX_CMD_GROUP_WITH_TAIL)
return GroupName(requireNotNull(matchResult.groups["group"]?.value))
}
fun parseGroupWithAlias(message: Message): Pair<GroupName, GroupName> {
val matchResult: MatchResult = parseByRegex(message, BotConstraints.REGEX_CMD_GROUP_ALIAS)
val groupName = GroupName(requireNotNull(matchResult.groups["group"]?.value))
val aliasName = GroupName(requireNotNull(matchResult.groups["alias"]?.value))
return groupName to aliasName
}
fun parseGroupWithMembers(message: Message): Pair<GroupName, Set<Member>> {
val matchResult: MatchResult = parseByRegex(message, BotConstraints.REGEX_CMD_GROUP_MEMBERS)
val groupName = GroupName(requireNotNull(matchResult.groups["group"]?.value))
val members: Set<Member> = (message.entities ?: emptyList())
.asSequence()
.mapNotNull {
when (it.type) {
EntityType.MENTION -> Member(memberName = MemberName(it.text))
EntityType.TEXTMENTION -> Member(memberName = MemberName(it.text), userId = UserId(it.user.id))
else -> null
}
}
.toSet()
return groupName to members
}
fun parseMembers(message: Message): Set<Member> {
parseByRegex(message, BotConstraints.REGEX_CMD_MEMBERS)
return (message.entities ?: emptyList())
.asSequence()
.mapNotNull {
when (it.type) {
EntityType.MENTION -> Member(memberName = MemberName(it.text))
EntityType.TEXTMENTION -> Member(memberName = MemberName(it.text), userId = UserId(it.user.id))
else -> null
}
}
.toSet()
}
private fun getAnyMessageEntities(message: Message): List<MessageEntity> =
message.entities ?: message.captionEntities ?: emptyList()
private fun isBotCommand(messageEntity: MessageEntity): Boolean =
messageEntity.offset == 0 && messageEntity.type == EntityType.BOTCOMMAND
private fun parseByRegex(message: Message, pattern: Regex): MatchResult {
val input = message.text ?: message.caption
return pattern.matchEntire(input)
?: throw BotParseException("Match error: pattern=[$pattern], input=[$input]")
}
companion object {
private const val CHAT_TYPE_PRIVATE = "private"
}
}
| 1 | Kotlin | 5 | 5 | eb507d27110aa09073362ae5cbbbfc5050c22bd2 | 4,401 | tg-mentions-bot | Apache License 2.0 |
app/src/main/java/io/github/mcasper3/prep/data/database/step/Step.kt | mcasper3 | 90,561,284 | false | null | package io.github.mcasper3.prep.data.database.step
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.ForeignKey
import android.arch.persistence.room.ForeignKey.CASCADE
import android.arch.persistence.room.Index
import android.arch.persistence.room.PrimaryKey
import io.github.mcasper3.prep.data.database.recipe.Recipe
@Entity(
tableName = "steps",
foreignKeys = arrayOf(
ForeignKey(
entity = Recipe::class,
parentColumns = arrayOf("_id"),
childColumns = arrayOf("recipe_id"),
onDelete = CASCADE
)
),
indices = arrayOf(
Index(
value = "recipe_id"
)
)
)
data class Step(
@ColumnInfo(name = "_id")
@PrimaryKey(autoGenerate = true)
val id: Long = 0,
val text: String,
@ColumnInfo(name = "step_number") val stepNumber: Int,
@ColumnInfo(name = "recipe_id") val recipeId: Long
)
| 15 | Kotlin | 0 | 0 | 397ba370ae5e71e245a60a0763cfb33c2b52a132 | 989 | Prep | Apache License 2.0 |
easychecker/src/main/java/com/validator/easychecker/exceptions/InputErrorException.kt | mkhan9047 | 216,574,748 | false | null | package com.validator.easychecker.exceptions
import java.security.MessageDigest
class InputErrorException(var messageText: String) : Exception() {
override val message: String?
get() = messageText
} | 0 | Kotlin | 4 | 9 | 075a3022182acd45f1a1fccd583e2e81951fc9bb | 212 | Easy-Checker | MIT License |
app/src/main/java/unpas/ac/id/mydb/fragment/Add.kt | RidhaAF | 359,389,075 | false | null | package unpas.ac.id.mydb.fragment
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import unpas.ac.id.mydb.R
import unpas.ac.id.mydb.data.Mahasiswa
import unpas.ac.id.mydb.databinding.FragmentAddBinding
import unpas.ac.id.mydb.viewModel.MahasiswaViewModel
class Add : Fragment() {
lateinit var addBinding: FragmentAddBinding
lateinit var mahasiswaViewModel: MahasiswaViewModel
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_add, container, false)
addBinding = FragmentAddBinding.bind(view)
mahasiswaViewModel = ViewModelProvider(this).get(MahasiswaViewModel::class.java)
addBinding.btnAdd.setOnClickListener {
insertData()
}
return view
}
// function insert to database
private fun insertData() {
var nrp: String = addBinding.nrpInput.text.toString()
var nama: String = addBinding.namaInput.text.toString()
if (checkInput(nrp, nama)) {
var mahasiswa = Mahasiswa(0, nrp, nama)
mahasiswaViewModel.addMahasiswa(mahasiswa)
Toast.makeText(requireContext(), "Input saved", Toast.LENGTH_SHORT).show()
findNavController().navigate(R.id.action_add_to_list)
} else {
Toast.makeText(requireContext(), "Input can't empty", Toast.LENGTH_SHORT).show()
}
}
// function check input kosong
private fun checkInput(nrp: String, nama: String): Boolean {
return !nrp.isEmpty() && !nama.isEmpty()
}
} | 0 | Kotlin | 0 | 0 | 0409530bd41bcb0225e5cef070598c7035b15f2f | 1,918 | MyDB | MIT License |
src/test/kotlin/com/github/zlbovolini/keymanager/removechavepix/RemoveChavePixControllerTest.kt | zlbovolini | 407,256,310 | true | {"Kotlin": 34653} | package com.github.zlbovolini.keymanager.removechavepix
import com.github.zlbovolini.keymanager.comum.GrpcClientFactory
import com.github.zlbovolini.keymanager.grpc.RemoveChavePixServiceGrpc
import com.google.protobuf.Empty
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.micronaut.context.annotation.Factory
import io.micronaut.context.annotation.Replaces
import io.micronaut.http.HttpRequest
import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.HttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.http.client.exceptions.HttpClientResponseException
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import jakarta.inject.Singleton
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.mockito.ArgumentMatchers.any
import org.mockito.BDDMockito.given
import org.mockito.Mockito
import java.util.*
@MicronautTest
internal class RemoveChavePixControllerTest(
@Client("/")
private val httpClient: HttpClient,
private val grpcClient: RemoveChavePixServiceGrpc.RemoveChavePixServiceBlockingStub
) {
@BeforeEach
fun setUp() {
Mockito.reset(grpcClient)
}
@Test
fun `deve remover chave pix registrada`() {
val clienteId = UUID.randomUUID().toString()
val pixId = UUID.randomUUID().toString()
val request = HttpRequest.DELETE<Any>("/api/clientes/$clienteId/pix/$pixId")
given(grpcClient.remove(any())).willReturn(Empty.newBuilder().build())
val response = httpClient.toBlocking().exchange(request, HttpResponse::class.java)
assertNotNull(response)
assertEquals(HttpStatus.NO_CONTENT, response.status)
}
@Test
fun `deve retornar 404 quando chave nao existe`() {
val clienteId = UUID.randomUUID().toString()
val pixId = UUID.randomUUID().toString()
val request = HttpRequest.DELETE<Any>("/api/clientes/$clienteId/pix/$pixId")
given(grpcClient.remove(any())).willThrow(Status.NOT_FOUND.asRuntimeException())
val error = assertThrows<HttpClientResponseException> {
httpClient.toBlocking().exchange(request, HttpResponse::class.java)
}
assertNotNull(error)
assertEquals(HttpStatus.NOT_FOUND, error.status)
}
@Factory
@Replaces(factory = GrpcClientFactory::class)
class StubFactory {
@Singleton
fun removeGrpc() = Mockito.mock(RemoveChavePixServiceGrpc.RemoveChavePixServiceBlockingStub::class.java)
}
} | 0 | Kotlin | 1 | 0 | f65b3fc61e82b15ae1edb5bce1ed1b9f4ad8e8e2 | 2,662 | orange-talents-07-template-pix-keymanager-rest | Apache License 2.0 |
src/main/kotlin/apollointhehouse/speedyPaths/SpeedyPaths.kt | Apollointhehouse | 629,825,720 | false | null | package apollointhehouse.speedyPaths
import org.slf4j.Logger
import org.slf4j.LoggerFactory
val MODID: String = "speedy-paths"
val LOGGER: Logger = LoggerFactory.getLogger(MODID)
@Suppress("unused")
fun init() {
LOGGER.info("SpeedyPaths initialized.")
}
| 0 | Kotlin | 0 | 0 | 494f01fcd10761458e32daa028955b7325fe743a | 261 | SpeedyPaths | Creative Commons Zero v1.0 Universal |
compiler/testData/codegen/box/defaultArguments/reflection/privateConstructor.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} | // TARGET_BACKEND: JVM_IR
// FULL_JDK
package test
class Foo private constructor(val a: Int = 1) {}
fun box(): String {
try {
Class.forName("test.Foo").getDeclaredConstructor()
return "Fail"
} catch (e: NoSuchMethodException) {
return "OK"
}
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 283 | kotlin | Apache License 2.0 |
app/src/main/java/com/cwlarson/deviceid/settings/PreferenceManager.kt | dev9kopb | 487,510,860 | true | {"Kotlin": 191406} | package com.cwlarson.deviceid.settings
import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.content.edit
import androidx.preference.PreferenceManager
import com.cwlarson.deviceid.BuildConfig
import com.cwlarson.deviceid.R
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import org.json.JSONArray
import timber.log.Timber
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
open class PreferenceManager @Inject constructor(@ApplicationContext private val context: Context,
private val preferences: SharedPreferences) {
open fun setDefaultValues() {
try {
PreferenceManager.setDefaultValues(context, R.xml.pref_general, false)
if (BuildConfig.DEBUG && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
PreferenceManager.setDefaultValues(context, R.xml.pref_testing_app_update, true)
} catch (e: Throwable) {
Timber.e("Unable to set default preferences")
}
}
open fun setDarkTheme(newValue: Any? = null) {
AppCompatDelegate.setDefaultNightMode(
when (newValue
?: preferences.getString(context.getString(R.string.pref_daynight_mode_key),
context.getString(R.string.pref_night_mode_system))) {
context.getString(R.string.pref_night_mode_off) -> AppCompatDelegate.MODE_NIGHT_NO
context.getString(R.string.pref_night_mode_on) -> AppCompatDelegate.MODE_NIGHT_YES
else -> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q)
AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM else AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY
})
}
open var hideUnavailable: Boolean
get() = preferences.getBoolean(context.getString(R.string.pref_hide_unavailable_key), false)
set(value) = preferences.edit {
putBoolean(context.getString(R.string
.pref_hide_unavailable_key), value)
}
@ExperimentalCoroutinesApi
open fun observeHideUnavailable() =
preferences.observeKey(context.getString(R.string.pref_hide_unavailable_key),
default = false, onlyChanges = true)
open var autoRefreshRate: Int
get() = preferences.getInt(context.getString(R.string.pref_auto_refresh_rate_key), 0)
set(value) = preferences.edit {
putInt(context.getString(R.string
.pref_auto_refresh_rate_key), value)
}
@ExperimentalCoroutinesApi
open fun observerAutoRefreshRate() =
preferences.observeKey(context.getString(R.string.pref_auto_refresh_rate_key),
default = 0, onlyChanges = true)
private var searchHistoryData: String?
get() = preferences.getString(context.getString(R.string.pref_search_history_data_key), "[]")
set(value) = if (value == null)
preferences.edit { remove(context.getString(R.string.pref_search_history_data_key)) }
else preferences.edit {
putString(context.getString(R.string
.pref_search_history_data_key), value)
}
open fun saveSearchHistoryItem(item: String?) {
if (searchHistory && item?.isNotBlank() == true) {
searchHistoryData = JSONArray(getSearchHistoryItems().toMutableList().run {
// Remove item in the list if already in history
removeAll { s -> s == item }
// Prepend item to top of list and remove older ones if more than 10 items
(listOf(item).plus(this)).take(10)
}).toString()
}
}
private fun JSONArray.toList(): List<String> = List(length(), this::getString)
open fun getSearchHistoryItems(items: String? = searchHistoryData) =
JSONArray(items).toList()
@ExperimentalCoroutinesApi
open fun observeSearchHistoryData() =
preferences.observeKey(context.getString(R.string.pref_search_history_data_key), "[]").map {
getSearchHistoryItems(it)
}
open var searchHistory: Boolean
get() = preferences.getBoolean(context.getString(R.string.pref_search_history_key), false)
set(value) {
if (!value) searchHistoryData = null
preferences.edit { putBoolean(context.getString(R.string.pref_search_history_key), value) }
}
open var useFakeUpdateManager: Boolean
get() = preferences.getBoolean(context.getString(R.string.pref_use_fake_update_manager_key), false)
set(value) = preferences.edit(commit = true) {
putBoolean(context.getString(R.string
.pref_use_fake_update_manager_key), value)
}
@ExperimentalCoroutinesApi
open fun observeUseFakeUpdateManager() =
preferences.observeKey(context.getString(R.string.pref_use_fake_update_manager_key),
default = false, onlyChanges = true)
}
@ExperimentalCoroutinesApi
private inline fun <reified T> SharedPreferences.observeKey(key: String, default: T,
onlyChanges: Boolean = false,
dispatcher: CoroutineContext = Dispatchers.Default): Flow<T> {
val flow: Flow<T> = callbackFlow {
if (!onlyChanges) trySend(getItem(key, default))
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, k ->
if (key == k) trySend(getItem(key, default))
}
registerOnSharedPreferenceChangeListener(listener)
awaitClose { unregisterOnSharedPreferenceChangeListener(listener) }
}
return flow.flowOn(dispatcher)
}
private inline fun <reified T> SharedPreferences.getItem(key: String, default: T): T {
@Suppress("UNCHECKED_CAST")
return when (default) {
is String -> getString(key, default) as T
is Int -> getInt(key, default) as T
is Long -> getLong(key, default) as T
is Boolean -> getBoolean(key, default) as T
is Float -> getFloat(key, default) as T
is Set<*> -> getStringSet(key, default as Set<String>) as T
is MutableSet<*> -> getStringSet(key, default as MutableSet<String>) as T
else -> throw IllegalArgumentException("generic type not handle ${T::class.java.name}")
}
} | 0 | null | 0 | 0 | b55bdf340bf447a1dcb7842cb8a146720c9571b9 | 6,817 | deviceid | MIT License |
feature/main/src/main/java/co/orange/main/main/home/HomeAdapter.kt | Orange-Co | 806,038,557 | false | {"Kotlin": 430580, "HTML": 2625} | package co.orange.main.main.home
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import co.orange.core.R
import co.orange.core.util.ItemDiffCallback
import co.orange.domain.entity.response.ProductModel
import co.orange.main.databinding.ItemHomeBannerBinding
import co.orange.main.databinding.ItemHomeProductBinding
class HomeAdapter(
private val bannerClick: (String) -> (Unit),
private val productClick: (String, Int) -> (Unit),
private val likeClick: (String, Boolean, Int) -> (Unit),
) : ListAdapter<ProductModel, RecyclerView.ViewHolder>(diffUtil) {
private var itemList = mutableListOf<ProductModel>()
private var bannerItem: String? = null
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int,
): RecyclerView.ViewHolder {
val inflater by lazy { LayoutInflater.from(parent.context) }
return when (viewType) {
VIEW_TYPE_BANNER ->
HomeBannerViewHolder(
ItemHomeBannerBinding.inflate(inflater, parent, false),
bannerClick,
)
VIEW_TYPE_PRODUCT ->
HomeProductViewHolder(
ItemHomeProductBinding.inflate(inflater, parent, false),
productClick,
likeClick,
)
else -> throw ClassCastException(
parent.context.getString(
R.string.view_type_error_msg,
viewType,
),
)
}
}
override fun onBindViewHolder(
holder: RecyclerView.ViewHolder,
position: Int,
) {
when (holder) {
is HomeBannerViewHolder -> {
bannerItem?.let { holder.onBind(it) }
}
is HomeProductViewHolder -> {
val itemPosition = position - HEADER_COUNT
holder.onBind(itemList[itemPosition], itemPosition)
}
}
val layoutParams = holder.itemView.layoutParams as RecyclerView.LayoutParams
layoutParams.bottomMargin = if (position == currentList.size) 24 else 0
holder.itemView.layoutParams = layoutParams
}
override fun getItemCount() = itemList.size + HEADER_COUNT
override fun getItemViewType(position: Int) =
when (position) {
0 -> VIEW_TYPE_BANNER
else -> VIEW_TYPE_PRODUCT
}
fun addBannerItem(bannerUrl: String) {
this.bannerItem = bannerUrl
notifyDataSetChanged()
}
fun addItemList(newItems: List<ProductModel>) {
this.itemList.addAll(newItems)
notifyDataSetChanged()
}
fun plusItemLike(position: Int) {
itemList[position].apply {
isInterested = true
interestCount += 1
}
notifyItemChanged(position + HEADER_COUNT)
}
fun minusItemLike(position: Int) {
itemList[position].apply {
isInterested = false
interestCount -= 1
}
notifyItemChanged(position + HEADER_COUNT)
}
companion object {
private val diffUtil =
ItemDiffCallback<ProductModel>(
onItemsTheSame = { old, new -> old.productId == new.productId },
onContentsTheSame = { old, new -> old == new },
)
const val HEADER_COUNT = 1
const val VIEW_TYPE_BANNER = 0
const val VIEW_TYPE_PRODUCT = 1
}
}
| 0 | Kotlin | 1 | 2 | b1f2b0b3025c5e27a07ad4e0406db5c1ffa777c7 | 3,573 | DDANZI_Android | MIT License |
app/src/main/java/com/app/lotlin/kotlinapp/data/SearchRepository.kt | VolodymyrFedyshy | 136,487,340 | false | {"Kotlin": 7606} | package com.app.lotlin.kotlinapp.data
import com.app.lotlin.kotlinapp.Result
class SearchRepository(val apiService: GithubApiService) {
fun searchUsers(location: String, language: String): io.reactivex.Observable<Result> {
return apiService.search(query = "location:$location language:$language")
}
} | 0 | Kotlin | 0 | 1 | 6d5725ac0c54d5453497fa2275e88a144b534388 | 321 | KotlinApp | Apache License 2.0 |
composeApp/src/commonMain/kotlin/utils/Constants.kt | aritra-tech | 800,504,454 | false | {"Kotlin": 72377, "Swift": 594} | package utils
object Constants {
const val BASE_URL = "https://pro-api.coinmarketcap.com/v1/"
const val REQUEST_TIME_OUT: Long = 10000
} | 0 | Kotlin | 0 | 2 | 31cfb4ab556873d7d512f3b22f2f324fef0be8bd | 145 | Coinify | MIT License |
springboot/resttest/src/main/kotlin/com/example/demo/ExampleDTO.kt | CrowdSalat | 667,082,566 | false | {"Kotlin": 4515, "Shell": 442, "HTML": 12} | package com.example.demo
// jakarta.* instead of javax since Spring Boot 3
import jakarta.validation.constraints.Min
import jakarta.validation.constraints.Max
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Size
data class ExampleDTO(
// Why is field: needed: https://kotlinlang.org/docs/annotations.html#annotation-use-site-targets
@field:NotBlank(message = "Name is required")
@field:Size(min = 2, message = "Name must have at least 2 characters")
val name: String,
@field:Min(value = 0, message = "Age must be at least 0")
@field:Max(value = 99, message = "Age must be below 100")
val age: Int
) | 0 | Kotlin | 0 | 0 | 814be546d9e7be81d562263cb17f4589fb8612db | 666 | boilerplate | MIT License |
app/src/main/java/com/example/deportesdalda/ReservationActivity.kt | FerCobo | 519,836,349 | false | {"Kotlin": 80944} | package com.example.deportesdalda
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Toast
import com.example.deportesdalda.databinding.ActivityReservationBinding
import com.google.android.gms.tasks.OnSuccessListener
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.QuerySnapshot
import com.google.firebase.firestore.SetOptions
class ReservationActivity : AppCompatActivity() {
private lateinit var binding: ActivityReservationBinding
private val db = FirebaseFirestore.getInstance()
private lateinit var databaseReference: DatabaseReference
private lateinit var database: FirebaseDatabase
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityReservationBinding.inflate(layoutInflater)
setContentView(binding.root)
MyToolbar().show(this, "Reservas")
initialise()
table()
}
private fun initialise(){
database = FirebaseDatabase.getInstance()
databaseReference = database.reference.child("reservations")
}
fun add(view: View) {
if (!TextUtils.isEmpty(binding.nameTxt.text.toString()) && !TextUtils.isEmpty(binding.phoneTxt.text.toString())
&& !TextUtils.isEmpty(binding.dateTxt.text.toString())) {
if (binding.phoneTxt.text.toString().length < 9 || binding.phoneTxt.text.toString().length > 9) {
Toast.makeText(this, "El teléfono introducido no es válido", Toast.LENGTH_SHORT).show()
} else {
db.collection("reservations")
.document(binding.phoneTxt.text.toString())
.get()
.addOnSuccessListener { document ->
if (document.exists()) {
db.collection("reservations")
.document(binding.phoneTxt.text.toString())
.set(
hashMapOf(
"name" to binding.nameTxt.text.toString(),
"date" to binding.dateTxt.text.toString()
), SetOptions.merge()
)
} else {
db.collection("reservations")
.document(binding.phoneTxt.text.toString())
.set(
hashMapOf(
"name" to binding.nameTxt.text.toString(),
"phone" to binding.phoneTxt.text.toString(),
"date" to binding.dateTxt.text.toString()
)
)
.addOnSuccessListener {
binding.nameTxt.setText("")
binding.phoneTxt.setText("")
binding.dateTxt.setText("")
Toast.makeText(this, "Reserva registrada", Toast.LENGTH_SHORT).show()
}
}
}
}
} else{
Toast.makeText(this, "Debes rellenar todos los campos", Toast.LENGTH_SHORT).show()
}
}
fun delete(view: View) {
if (TextUtils.isEmpty(binding.phoneTxt.text.toString())) {
Toast.makeText(this, "Debes introducir un teléfono", Toast.LENGTH_SHORT).show()
} else {
db.collection("reservations")
.document(binding.phoneTxt.text.toString())
.get()
.addOnSuccessListener { document ->
if (!document.exists()) {
Toast.makeText(this, "No existe una reserva asociada a ese teléfono", Toast.LENGTH_SHORT).show()
} else {
val alertDialog = AlertDialog.Builder(this)
alertDialog.apply {
setTitle("Eliminar reserva")
setMessage("¿Estás seguro/a de que deseas eliminar esta reserva?")
setPositiveButton(
"Sí",
DialogInterface.OnClickListener { dialog, id -> yes() })
setNegativeButton("No", null)
}.create().show()
}
}
}
}
private fun yes() {
db.collection("reservations").document(binding.phoneTxt.text.toString())
.delete()
.addOnSuccessListener {
binding.phoneTxt.setText("")
Toast.makeText(this, "Reserva eliminada", Toast.LENGTH_SHORT).show()
}
}
private fun table(){
db.collection("reservations").get()
.addOnSuccessListener(OnSuccessListener<QuerySnapshot> { queryDocumentSnapshots ->
var data1 = ""
var data2 = ""
var data3 = ""
for (documentSnapshot in queryDocumentSnapshots) {
val users: Users = documentSnapshot.toObject(Users::class.java)
users.setName(documentSnapshot.getString("name"))
val name: String? = users.getName()
users.setPhone(documentSnapshot.id)
val phone: String? = users.getPhone()
users.setDate(documentSnapshot.getString("date"))
val date: String? = users.getDate()
data1 += "$name\n"
data2 += "$phone\n"
data3 += "$date\n"
}
binding.txtName.text = data1
binding.txtPhone.text = data2
binding.txtDate.text = data3
})
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.nav_menu6, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.nav_back -> {
finish()
true
}
R.id.nav_refresh -> {
finish()
startActivity(Intent(this, ReservationActivity::class.java))
true
}
else -> super.onOptionsItemSelected(item)
}
}
} | 0 | Kotlin | 0 | 0 | e849ce50dfd5026607105dbcc665ef238004f072 | 6,922 | AppDalda | MIT License |
app/src/main/java/com/kucingapes/datagempa/adapter/GempaAdapter.kt | utsmannn | 152,791,939 | false | {"Kotlin": 13246} | /*
* GempaAdapter.kt on DataGempa
* Developed by <NAME> on 10/12/18 4:54 PM
* Last modified 10/12/18 4:52 PM
* Copyright (c) 2018 kucingapes
*/
package com.kucingapes.datagempa.adapter
import android.annotation.SuppressLint
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.gms.maps.*
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
import com.kucingapes.datagempa.ItemClick
import com.kucingapes.datagempa.R
import com.kucingapes.datagempa.model.DataGempa
import kotlinx.android.synthetic.main.item_gempa.view.*
import java.text.SimpleDateFormat
import java.util.*
class GempaAdapter(var dataList: ArrayList<DataGempa.Gempa>,
var itemClick: ItemClick) : RecyclerView.Adapter<GempaAdapter.Holder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): Holder {
val view = LayoutInflater.from(p0.context).inflate(R.layout.item_gempa, p0, false)
return Holder(view)
}
override fun getItemCount(): Int {
return dataList.size
}
@SuppressLint("SetTextI18n", "SimpleDateFormat")
override fun onBindViewHolder(p0: Holder, p1: Int) {
val dataGempa = dataList[p1]
//07/10/2018-14:39:27 WIB
var patternDate = ""
var patternFormat = ""
when {
dataGempa.tanggal!!.contains("WIB") -> {
patternDate = "dd/MM/yyyy-HH:mm:ss 'WIB'"
patternFormat = "EEE dd MMM yyyy / HH:mm:ss 'WIB'"
}
dataGempa.tanggal!!.contains("WIT") -> {
patternDate = "dd/MM/yyyy-HH:mm:ss 'WIT'"
patternFormat = "EEE dd MMM yyyy / HH:mm:ss 'WIT'"
}
dataGempa.tanggal!!.contains("WITA") -> {
patternDate = "dd/MM/yyyy-HH:mm:ss 'WITA'"
patternFormat = "EEE dd MMM yyyy / HH:mm:ss 'WITA'"
}
}
val parseDateFormat = SimpleDateFormat(patternDate)
val dateFormat = SimpleDateFormat(patternFormat, Locale("id"))
val date = parseDateFormat.parse(dataGempa.tanggal)
p0.itemView.tanggal.text = dateFormat.format(date)
p0.itemView.posisi.text = "Koordinat ${dataGempa.posisi}"
p0.itemView.magnitude.text = "M ${dataGempa.magnitude}"
p0.itemView.kedalaman.text = "Kedalaman ${dataGempa.kedalaman}"
p0.itemView.keterangan.text = dataGempa.keterangan
/*p0.itemView.dirasakan.text = dataGempa.dirasakan*/
p0.setLocation(dataGempa)
p0.itemView.setOnClickListener {
itemClick.OnItemClickRecycler(dataGempa)
}
}
class Holder(itemView: View) : RecyclerView.ViewHolder(itemView), OnMapReadyCallback {
private var mapView: MapView = itemView.findViewById(R.id.map_item)
var gMap: GoogleMap? = null
lateinit var mapData: DataGempa.Gempa
init {
mapView.onCreate(null)
mapView.getMapAsync(this)
}
override fun onMapReady(p0: GoogleMap?) {
MapsInitializer.initialize(itemView.context)
gMap = p0!!
gMap!!.uiSettings.isMapToolbarEnabled = false
updateLocation()
}
fun setLocation(mapLoc: DataGempa.Gempa) {
mapData = mapLoc
if (gMap != null) {
updateLocation()
}
}
private fun updateLocation() {
gMap!!.clear()
val stringLatlng = mapData.point?.coordinates?.split(",")
val lat = stringLatlng?.get(0)?.toDouble()
val lng = stringLatlng?.get(1)?.toDouble()
val marker = LatLng(lat!!, lng!!)
gMap!!.addMarker(MarkerOptions().position(marker).flat(true))
gMap!!.moveCamera(CameraUpdateFactory.newLatLngZoom(marker, 5f))
}
}
} | 0 | Kotlin | 1 | 0 | 762b33bdfbd35c88f22ba09e1518fa86d8397086 | 3,946 | DataGempa | MIT License |
core/src/main/kotlin/com/mineinabyss/emojy/EmojyListener.kt | MineInAbyss | 545,724,197 | false | {"Kotlin": 86449} | package com.mineinabyss.emojy
import com.mineinabyss.emojy.nms.EmojyNMSHandlers
import com.mineinabyss.idofront.textcomponents.serialize
import io.papermc.paper.event.player.AsyncChatDecorateEvent
import net.kyori.adventure.text.Component
import net.kyori.adventure.text.TextReplacementConfig
import net.kyori.adventure.translation.GlobalTranslator
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority
import org.bukkit.event.Listener
import org.bukkit.event.player.PlayerJoinEvent
import java.util.*
@Suppress("UnstableApiUsage")
class EmojyListener : Listener {
@EventHandler
fun PlayerJoinEvent.injectPlayer() {
EmojyNMSHandlers.getHandler()?.inject(player)
}
// Replace with result not original message to avoid borking other chat formatting
@EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true)
fun AsyncChatDecorateEvent.onPlayerChat() {
result(result().replaceEmoteIds(player()))
}
}
//TODO Tags like rainbow and gradient, which split the text into multiple children, will break replacement below
// Find out why this is called 3 times
fun Component.replaceEmoteIds(player: Player? = null, insert: Boolean = true): Component {
var msg = GlobalTranslator.render(this, player?.locale() ?: Locale.US)
val serialized = msg.serialize()
emojy.config.emotes.firstOrNull { ":${it.id}:" in serialized }?.let { emote ->
if (emote.checkPermission(player)) {
msg = msg.replaceText(
TextReplacementConfig.builder()
.matchLiteral(":${emote.id}:")
.replacement(emote.getFormattedUnicode(insert = insert))
.build()
)
}
}
emojy.config.gifs.firstOrNull { ":${it.id}:" in serialized }?.let { gif ->
if (gif.checkPermission(player)) {
msg = msg.replaceText(
TextReplacementConfig.builder()
.match(":${gif.id}:")
.replacement(gif.getFormattedUnicode(insert = insert))
.build()
)
}
}
return msg
}
| 0 | Kotlin | 0 | 1 | 667db18254a58f3af82142d6302972322a277739 | 2,165 | Emojy | MIT License |
src/main/kotlin/org/noordawod/kotlin/restful/freemarker/BaseFreeMarkerRunnable.kt | ndawod | 238,316,713 | false | null | /*
* The MIT License
*
* Copyright 2020 <NAME>. All rights reserved.
*
* 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.
*/
@file:Suppress("unused")
package org.noordawod.kotlin.restful.freemarker
import freemarker.template.Template
import freemarker.template.TemplateException
import io.undertow.server.HttpHandler
import org.noordawod.kotlin.core.extension.withExtension
/**
* An [HttpHandler] that orchestrates the task to prepare a data model,
* an [output buffer][java.io.BufferedWriter], and then using a FreeMarker template to
* generate the content and write it to the output buffer.
*
* @param T type of the data model
* @param config configuration for FreeMarker
* @param basePath where template files reside, excluding the trailing slash
*/
abstract class BaseFreeMarkerRunnable<T : Any> protected constructor(
protected val config: FreeMarkerConfiguration,
protected val basePath: String
) : Runnable {
/**
* Extension for template files.
*/
protected abstract val fileExtension: String
/**
* The data model itself is evaluated in [run] and stored here momentarily.
*/
protected lateinit var model: T
/**
* Provider function for model of type [T].
*/
protected abstract fun modelProvider(): T
/**
* Prepares a [buffer][java.io.BufferedWriter] to write the FreeMarker output to.
*/
protected abstract fun prepareWriter(): java.io.BufferedWriter
/**
* The FreeMarker template file that resides under [basePath], excluding a leading slash.
*/
protected abstract fun getTemplateFile(): String
/**
* Allow extended classes to modify the FreeMarker template before it's processed.
*
* @param template the FreeMarker template to modify
*/
protected open fun modifyTemplate(template: Template) {
// NO-OP
}
@Throws(TemplateException::class, java.io.IOException::class)
override fun run() {
// Prepare the model so all other abstract or overloaded methods have access to it.
model = modelProvider()
// Logical file path + configured template extension.
val filePath = getTemplateFile().withExtension(fileExtension)
// The location of the FreeMarker template is always under the configured base path.
val template = config.getTemplate("$basePath/$filePath")
// Allow extended classes to modify the FreeMarker template, if needed.
modifyTemplate(template)
// Prepare the writer buffer and generate the content into it.
prepareWriter().apply {
template.process(model, this)
flush()
}
}
}
| 0 | Kotlin | 0 | 0 | b8f31fda60e8807e02353b5154ddbd08d68ebabf | 3,572 | kotlin-restful | MIT License |
app/src/main/java/com/github/jing332/tts_server_android/ui/systts/edit/plugin/PluginTtsParamsEditView.kt | jing332 | 536,800,727 | false | null | package com.github.jing332.tts_server_android.ui.systts.edit.plugin
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import com.github.jing332.tts_server_android.R
import com.github.jing332.tts_server_android.databinding.SysttsPluginParamsEditViewBinding
import com.github.jing332.tts_server_android.model.speech.tts.PluginTTS
import com.github.jing332.tts_server_android.ui.systts.edit.BaseParamsEditView
import com.github.jing332.tts_server_android.ui.view.widget.Seekbar
class PluginTtsParamsEditView
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defaultStyle: Int = 0) :
BaseParamsEditView<SysttsPluginParamsEditViewBinding, PluginTTS>(context, attrs, defaultStyle) {
override var tts: PluginTTS? = null
override fun setData(tts: PluginTTS) {
super.setData(tts)
binding.apply {
seekRate.valueFormatter = Seekbar.ValueFormatter { _, progress ->
if (progress == 0) context.getString(R.string.follow_system_or_read_aloud_app)
else progress.toString()
}
seekPitch.valueFormatter = Seekbar.ValueFormatter { _, progress ->
if (progress == 0) context.getString(R.string.follow_system_or_read_aloud_app)
else progress.toString()
}
seekRate.value = tts.rate
seekVolume.value = tts.volume
seekPitch.value = tts.pitch
seekRate.onSeekBarChangeListener = object : Seekbar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: Seekbar, progress: Int, fromUser: Boolean) {
}
override fun onStopTrackingTouch(seekBar: Seekbar) {
tts.rate = seekBar.value as Int
}
}
seekVolume.onSeekBarChangeListener = object : Seekbar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: Seekbar, progress: Int, fromUser: Boolean) {
}
override fun onStopTrackingTouch(seekBar: Seekbar) {
tts.volume = seekBar.value as Int
}
}
seekPitch.onSeekBarChangeListener = object : Seekbar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: Seekbar, progress: Int, fromUser: Boolean) {
}
override fun onStopTrackingTouch(seekBar: Seekbar) {
tts.pitch = seekBar.value as Int
}
}
}
}
} | 6 | Kotlin | 127 | 1,393 | 8e07e8842cf4cec70154041fcd6a64ad2352d8c8 | 2,585 | tts-server-android | MIT License |
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Smog.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.rounded.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Outline.Smog: ImageVector
get() {
if (_smog != null) {
return _smog!!
}
_smog = Builder(name = "Smog", defaultWidth = 512.0.dp, defaultHeight = 512.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) {
moveTo(19.0f, 24.0f)
lineTo(17.0f, 24.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f)
horizontalLineToRelative(2.0f)
arcTo(1.0f, 1.0f, 0.0f, false, true, 19.0f, 24.0f)
close()
moveTo(13.0f, 24.0f)
lineTo(1.0f, 24.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f)
lineTo(13.0f, 22.0f)
arcTo(1.0f, 1.0f, 0.0f, false, true, 13.0f, 24.0f)
close()
moveTo(23.0f, 20.0f)
lineTo(11.0f, 20.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f)
lineTo(23.0f, 18.0f)
arcTo(1.0f, 1.0f, 0.0f, false, true, 23.0f, 20.0f)
close()
moveTo(7.0f, 20.0f)
lineTo(5.0f, 20.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f)
lineTo(7.0f, 18.0f)
arcTo(1.0f, 1.0f, 0.0f, false, true, 7.0f, 20.0f)
close()
moveTo(19.0f, 16.0f)
lineTo(17.0f, 16.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f)
horizontalLineToRelative(2.0f)
arcTo(1.0f, 1.0f, 0.0f, false, true, 19.0f, 16.0f)
close()
moveTo(13.0f, 16.0f)
lineTo(1.0f, 16.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 0.0f, -2.0f)
lineTo(13.0f, 14.0f)
arcTo(1.0f, 1.0f, 0.0f, false, true, 13.0f, 16.0f)
close()
moveTo(16.0f, 12.0f)
arcToRelative(5.0f, 5.0f, 0.0f, false, true, -2.336f, -0.579f)
arcToRelative(6.271f, 6.271f, 0.0f, false, true, -5.536f, -0.152f)
arcToRelative(0.587f, 0.587f, 0.0f, false, false, -0.571f, 0.028f)
arcTo(5.0f, 5.0f, 0.0f, false, true, 0.134f, 5.829f)
arcTo(4.95f, 4.95f, 0.0f, false, true, 3.811f, 2.138f)
arcToRelative(5.092f, 5.092f, 0.0f, false, true, 2.374f, 0.0f)
arcToRelative(0.277f, 0.277f, 0.0f, false, false, 0.283f, -0.074f)
arcToRelative(6.033f, 6.033f, 0.0f, false, true, 8.8f, -0.287f)
curveToRelative(0.065f, 0.065f, 0.217f, 0.219f, 0.734f, 0.219f)
arcToRelative(4.978f, 4.978f, 0.0f, false, true, 3.9f, 1.875f)
arcToRelative(0.4f, 0.4f, 0.0f, false, false, 0.193f, 0.148f)
arcToRelative(3.579f, 3.579f, 0.0f, false, true, 1.438f, 0.129f)
arcToRelative(3.443f, 3.443f, 0.0f, false, true, 2.348f, 2.433f)
horizontalLineToRelative(0.0f)
arcToRelative(3.5f, 3.5f, 0.0f, false, true, -4.341f, 4.282f)
curveToRelative(-0.274f, -0.079f, -0.333f, -0.032f, -0.358f, -0.011f)
arcTo(4.932f, 4.932f, 0.0f, false, true, 16.0f, 12.0f)
close()
moveTo(13.614f, 9.409f)
arcToRelative(2.108f, 2.108f, 0.0f, false, true, 0.986f, 0.245f)
arcToRelative(3.041f, 3.041f, 0.0f, false, false, 3.294f, -0.327f)
arcToRelative(2.266f, 2.266f, 0.0f, false, true, 2.2f, -0.384f)
arcToRelative(1.5f, 1.5f, 0.0f, false, false, 1.857f, -1.858f)
horizontalLineToRelative(0.0f)
arcToRelative(1.455f, 1.455f, 0.0f, false, false, -0.978f, -1.014f)
arcToRelative(1.6f, 1.6f, 0.0f, false, false, -0.642f, -0.06f)
arcToRelative(2.231f, 2.231f, 0.0f, false, true, -1.984f, -0.885f)
curveToRelative(-1.04f, -1.6f, -3.361f, -0.663f, -4.5f, -1.937f)
arcToRelative(4.022f, 4.022f, 0.0f, false, false, -5.866f, 0.191f)
arcToRelative(2.271f, 2.271f, 0.0f, false, true, -2.266f, 0.706f)
arcToRelative(3.09f, 3.09f, 0.0f, false, false, -1.447f, 0.0f)
arcTo(3.0f, 3.0f, 0.0f, false, false, 2.651f, 8.867f)
arcToRelative(3.067f, 3.067f, 0.0f, false, false, 3.882f, 0.712f)
arcToRelative(2.584f, 2.584f, 0.0f, false, true, 2.554f, -0.065f)
arcToRelative(4.06f, 4.06f, 0.0f, false, false, 3.638f, 0.1f)
arcTo(2.055f, 2.055f, 0.0f, false, true, 13.614f, 9.409f)
close()
}
}
.build()
return _smog!!
}
private var _smog: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 5,612 | icons | MIT License |
waypoints-api/src/main/kotlin/de/md5lukas/waypoints/api/Statistics.kt | Sytm | 211,378,928 | false | {"Kotlin": 445837, "Java": 10057} | package de.md5lukas.waypoints.api
/** This interface provides access to some usage statistics of the plugin */
interface Statistics {
/** The total amount of waypoints in the database. Counts every [Type] */
val totalWaypoints: Int
/** The total amount of waypoints of the type [Type.PRIVATE] */
val privateWaypoints: Int
/** The total amount of waypoints of the type [Type.DEATH] */
val deathWaypoints: Int
/** The total amount of waypoints of the type [Type.PUBLIC] */
val publicWaypoints: Int
/** The total amount of waypoints of the type [Type.PERMISSION] */
val permissionWaypoints: Int
/** The total amount of folders in the database. Counts every [Type] */
val totalFolders: Int
/** The total amount of folders of the type [Type.PRIVATE] */
val privateFolders: Int
/** The total amount of folders of the type [Type.PUBLIC] */
val publicFolders: Int
/** The total amount of folders of the type [Type.PERMISSION] */
val permissionFolders: Int
/** The size of the SQLite database file as reported by [java.io.File.length] */
val databaseSize: Long
}
| 3 | Kotlin | 8 | 28 | b31e54acb0cb8e93c9713492b1c1a0759f1045ed | 1,105 | waypoints | MIT License |
src/com/amazon/ionelement/impl/FloatElementImpl.kt | QPC-database | 384,651,034 | true | {"Kotlin": 201029, "Java": 11951} | /*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.amazon.ionelement.impl
import com.amazon.ion.IonWriter
import com.amazon.ionelement.api.ElementType
import com.amazon.ionelement.api.FloatElement
import com.amazon.ionelement.api.MetaContainer
import com.amazon.ionelement.api.emptyMetaContainer
internal class FloatElementImpl(
override val doubleValue: Double,
override val annotations: List<String>,
override val metas: MetaContainer
) : AnyElementBase(), FloatElement {
override val type: ElementType get() = ElementType.FLOAT
override fun copy(annotations: List<String>, metas: MetaContainer): FloatElement =
FloatElementImpl(doubleValue, annotations, metas)
override fun writeContentTo(writer: IonWriter) = writer.writeFloat(doubleValue)
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FloatElementImpl
// compareTo() distinguishes between 0.0 and -0.0 while `==` operator does not.
if (doubleValue.compareTo(other.doubleValue) != 0) return false
if (annotations != other.annotations) return false
// Note: metas intentionally omitted!
return true
}
override fun hashCode(): Int {
var result = doubleValue.compareTo(0.0).hashCode() // <-- causes 0e0 to have a different hash code than -0e0
result = 31 * result + doubleValue.hashCode()
result = 31 * result + annotations.hashCode()
// Note: metas intentionally omitted!
return result
}
} | 0 | null | 0 | 1 | f491dccb9cdf9ee2f4bceb70e97d91a245d27df7 | 2,141 | ion-element-kotlin | Apache License 2.0 |
message-component/src/main/java/com/kotlin/android/message/widget/EmptyViewBinder.kt | R-Gang-H | 538,443,254 | false | null | package com.kotlin.android.message.widget
import com.kotlin.android.message.R
import com.kotlin.android.message.databinding.MessageViewEmptyBinding
import com.kotlin.android.widget.adapter.multitype.adapter.binder.MultiTypeBinder
/**
* Created by zhaoninglongfei on 2022/5/12
*
*/
class EmptyViewBinder : MultiTypeBinder<MessageViewEmptyBinding>() {
override fun layoutId(): Int = R.layout.message_view_empty
override fun areContentsTheSame(other: MultiTypeBinder<*>): Boolean {
return other is EmptyViewBinder
}
} | 0 | Kotlin | 0 | 1 | e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28 | 541 | Mtime | Apache License 2.0 |
library/src/main/java/com/d10ng/compose/ui/show/Popover.kt | D10NGYANG | 445,078,597 | false | {"Kotlin": 380265} | package com.d10ng.compose.ui.show
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.defaultMinSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.CornerRadius
import androidx.compose.ui.geometry.RoundRect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpOffset
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Popup
import androidx.compose.ui.window.PopupPositionProvider
import androidx.compose.ui.window.PopupProperties
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import com.d10ng.compose.ui.AppColor
import com.d10ng.compose.ui.AppText
import com.d10ng.compose.utils.next
/**
* Popover 气泡弹出框
* @Author d10ng
* @Date 2023/9/18 14:19
*/
/**
* Popover 气泡弹出框
* @param expanded Boolean 是否展开
* @param onDismissRequest Function0<Unit> 关闭回调
* @param offset DpOffset 偏移量
* @param dark Boolean 是否暗色
* @param properties PopupProperties 弹出框属性
* @param content [@androidx.compose.runtime.Composable] Function0<Unit> 内容
*/
@Composable
fun Popover(
expanded: Boolean,
onDismissRequest: () -> Unit,
offset: DpOffset = DpOffset(0.dp, 0.dp),
dark: Boolean = false,
properties: PopupProperties = PopupProperties(focusable = true),
content: @Composable () -> Unit
) {
val expandedStates = remember { MutableTransitionState(false) }
expandedStates.targetState = expanded
if (expandedStates.currentState || expandedStates.targetState) {
var placement by remember { mutableStateOf(PopoverPlacement.BottomCenter) }
val density = LocalDensity.current
val popupPositionProvider = remember(offset, density) {
DropdownMenuPositionProvider(
offset,
density
) { parentBounds, menuBounds ->
placement = calculatePlacement(parentBounds, menuBounds)
}
}
val bgColor = remember(dark) {
if (dark) AppColor.Neutral.body else Color.White
}
Popup(
onDismissRequest = onDismissRequest,
popupPositionProvider = popupPositionProvider,
properties = properties
) {
PopoverContent(
bgColor = bgColor,
placement = placement,
content = content
)
}
}
}
/**
* Popover 气泡弹出框纵向列表
* @param value Set<String> 列表数据
* @param dark Boolean 是否暗色
* @param onClick Function1<String, Unit> 点击回调
*/
@Composable
fun PopoverColumnItems(
value: Set<String>,
dark: Boolean = false,
onClick: (String) -> Unit
) {
Column {
value.forEachIndexed { index, text ->
PopoverColumnItem(
text = text,
border = index != value.size - 1,
dark = dark,
onClick = { onClick(text) }
)
}
}
}
/**
* Popover 气泡弹出框纵向列表项
* @param text String 文本
* @param border Boolean 是否显示分割线
* @param dark Boolean 是否暗色
* @param onClick Function0<Unit> 点击回调
*/
@Composable
fun PopoverColumnItem(
text: String,
border: Boolean = true,
dark: Boolean = false,
onClick: () -> Unit
) {
val contentColor = remember(dark) {
if (dark) Color.White else AppColor.Neutral.title
}
val lineColor = remember(dark) {
if (dark) Color.White.next(-0.5) else AppColor.Neutral.line
}
ConstraintLayout(
modifier = Modifier
.defaultMinSize(minWidth = 130.dp)
.clickable(onClick = onClick)
) {
val (label, line) = createRefs()
Text(
text = text,
style = AppText.Normal.Body.default,
color = contentColor,
modifier = Modifier
.padding(16.dp)
.constrainAs(label) {
start.linkTo(parent.start)
end.linkTo(parent.end)
top.linkTo(parent.top)
bottom.linkTo(parent.bottom)
}
)
if (border) {
Box(
modifier = Modifier
.padding(horizontal = 16.dp)
.height(1.dp)
.background(lineColor)
.constrainAs(line) {
width = Dimension.fillToConstraints
start.linkTo(parent.start)
end.linkTo(parent.end)
bottom.linkTo(parent.bottom)
}
)
}
}
}
// 弹出位置
enum class PopoverPlacement(val shape: (Density) -> GenericShape) {
// 下方左侧
BottomStart(
{ density ->
getShape(
density,
{ _ -> Point(getSize(34.5.dp, density), 0f) },
{ _ -> Point(getSize(27.dp, density), getSize(10.dp, density)) },
{ _ -> Point(getSize(42.dp, density), getSize(10.dp, density)) }
)
}
),
// 下方中间
BottomCenter(
{ density ->
getShape(
density,
{ size -> Point(size.width / 2, 0f) },
{ size -> Point(size.width / 2 - getSize(7.5.dp, density), getSize(10.dp, density)) },
{ size -> Point(size.width / 2 + getSize(7.5.dp, density), getSize(10.dp, density)) }
)
}
),
// 下方右侧
BottomEnd(
{ density ->
getShape(
density,
{ size -> Point(size.width - getSize(34.5.dp, density), 0f) },
{ size -> Point(size.width - getSize(42.dp, density), getSize(10.dp, density)) },
{ size -> Point(size.width - getSize(27.dp, density), getSize(10.dp, density)) }
)
}
),
// 上方左侧
TopStart(
{ density ->
getShape(
density,
{ size -> Point(getSize(34.5.dp, density), size.height) },
{ size -> Point(getSize(27.dp, density), size.height - getSize(10.dp, density)) },
{ size -> Point(getSize(42.dp, density), size.height - getSize(10.dp, density)) }
)
}
),
// 上方中间
TopCenter(
{ density ->
getShape(
density,
{ size -> Point(size.width / 2, size.height) },
{ size -> Point(size.width / 2 - getSize(7.5.dp, density), size.height - getSize(10.dp, density)) },
{ size -> Point(size.width / 2 + getSize(7.5.dp, density), size.height - getSize(10.dp, density)) }
)
}
),
// 上方右侧
TopEnd(
{ density ->
getShape(
density,
{ size -> Point(size.width - getSize(34.5.dp, density), size.height) },
{ size -> Point(size.width - getSize(42.dp, density), size.height - getSize(10.dp, density)) },
{ size -> Point(size.width - getSize(27.dp, density), size.height - getSize(10.dp, density)) }
)
}
),
}
private data class Point(val x: Float, val y: Float)
private fun getShape(density: Density, top: (Size) -> Point, start: (Size) -> Point, end: (Size) -> Point): GenericShape {
return GenericShape { size, _ ->
val topPoint = top(size)
val startPoint = start(size)
val endPoint = end(size)
// 画三角形
moveTo(topPoint.x, topPoint.y)
lineTo(endPoint.x, endPoint.y)
lineTo(startPoint.x, startPoint.y)
lineTo(topPoint.x, topPoint.y)
// 画矩形
val margin = getSize(10.dp, density)
val radius = getSize(8.dp, density)
addRoundRect(RoundRect(
left = margin,
top = margin,
right = size.width - margin,
bottom = size.height - margin,
cornerRadius = CornerRadius(radius, radius)
))
close()
}
}
private fun getSize(value: Dp, density: Density) = run { with(density) { value.roundToPx().toFloat() } }
// Size defaults.
private val MenuVerticalMargin = 0.dp
@Composable
private fun PopoverContent(
placement: PopoverPlacement,
bgColor: Color = Color.White,
content: @Composable () -> Unit
) {
val density = LocalDensity.current
val shape = remember(placement, density) {
placement.shape(density)
}
Surface(
shape = shape,
color = bgColor,
tonalElevation = 1.dp,
shadowElevation = 1.dp
) {
Box(
modifier = Modifier.padding(10.dp)
) {
content()
}
}
}
@Immutable
private data class DropdownMenuPositionProvider(
val contentOffset: DpOffset,
val density: Density,
val onPositionCalculated: (IntRect, IntRect) -> Unit = { _, _ -> }
) : PopupPositionProvider {
override fun calculatePosition(
anchorBounds: IntRect,
windowSize: IntSize,
layoutDirection: LayoutDirection,
popupContentSize: IntSize
): IntOffset {
// The min margin above and below the menu, relative to the screen.
val verticalMargin = with(density) { MenuVerticalMargin.roundToPx() }
// The content offset specified using the dropdown offset parameter.
val contentOffsetX = with(density) { contentOffset.x.roundToPx() }
val contentOffsetY = with(density) { contentOffset.y.roundToPx() }
// Compute horizontal position.
val toHCenter = anchorBounds.left + anchorBounds.width / 2 - popupContentSize.width / 2 + contentOffsetX
val toRight = anchorBounds.left + contentOffsetX - with(density) { 10.dp.roundToPx() }
val toLeft = anchorBounds.right - contentOffsetX - popupContentSize.width + with(density) { 10.dp.roundToPx() }
val toDisplayRight = windowSize.width - popupContentSize.width
val toDisplayLeft = 0
val x = if (layoutDirection == LayoutDirection.Ltr) {
sequenceOf(
toHCenter,
toRight,
toLeft,
// If the anchor gets outside of the window on the left, we want to position
// toDisplayLeft for proximity to the anchor. Otherwise, toDisplayRight.
if (anchorBounds.left >= 0) toDisplayRight else toDisplayLeft
)
} else {
sequenceOf(
toHCenter,
toLeft,
toRight,
// If the anchor gets outside of the window on the right, we want to position
// toDisplayRight for proximity to the anchor. Otherwise, toDisplayLeft.
if (anchorBounds.right <= windowSize.width) toDisplayLeft else toDisplayRight
)
}.firstOrNull {
it >= 0 && it + popupContentSize.width <= windowSize.width
} ?: toLeft
// Compute vertical position.
val toBottom = maxOf(anchorBounds.bottom + contentOffsetY, verticalMargin)
val toTop = anchorBounds.top - contentOffsetY - popupContentSize.height
val toCenter = anchorBounds.top - popupContentSize.height / 2
val toDisplayBottom = windowSize.height - popupContentSize.height - verticalMargin
val y = sequenceOf(toBottom, toTop, toCenter, toDisplayBottom).firstOrNull {
it >= verticalMargin &&
it + popupContentSize.height <= windowSize.height - verticalMargin
} ?: toTop
onPositionCalculated(
anchorBounds,
IntRect(x, y, x + popupContentSize.width, y + popupContentSize.height)
)
return IntOffset(x, y)
}
}
private fun calculatePlacement(
parentBounds: IntRect,
menuBounds: IntRect
): PopoverPlacement {
if (parentBounds.top >= menuBounds.bottom) {
// Parent is above the menu.
return if (parentBounds.topCenter.x == menuBounds.topCenter.x) {
PopoverPlacement.TopCenter
} else if (parentBounds.topCenter.x > menuBounds.topCenter.x) {
PopoverPlacement.TopEnd
} else {
PopoverPlacement.TopStart
}
} else {
// Parent is overlapping the menu vertically.
return if (parentBounds.topCenter.x == menuBounds.topCenter.x) {
PopoverPlacement.BottomCenter
} else if (parentBounds.topCenter.x > menuBounds.topCenter.x) {
PopoverPlacement.BottomEnd
} else {
PopoverPlacement.BottomStart
}
}
} | 0 | Kotlin | 1 | 9 | bf371e5479f1ba2b3d00cada554f47686ed22012 | 13,467 | DLJetpackComposeUtil | MIT License |
libs/etterlatte-database/src/main/kotlin/DataSourceBuilder.kt | navikt | 417,041,535 | false | {"Kotlin": 5618023, "TypeScript": 1317735, "Handlebars": 21854, "Shell": 10666, "HTML": 1776, "Dockerfile": 745, "CSS": 598} | package no.nav.etterlatte.libs.database
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import no.nav.etterlatte.libs.common.appIsInGCP
import no.nav.etterlatte.libs.common.isProd
import org.flywaydb.core.Flyway
import org.flywaydb.core.api.output.MigrateResult
import org.slf4j.LoggerFactory
import javax.sql.DataSource
object DataSourceBuilder {
private const val MAX_POOL_SIZE = 10
fun createDataSource(env: Map<String, String>): DataSource = createDataSource(ApplicationProperties.fromEnv(env))
fun createDataSource(properties: ApplicationProperties) =
createDataSource(
jdbcUrl = properties.jdbcUrl,
username = properties.dbUsername,
password = <PASSWORD>,
)
fun createDataSource(
jdbcUrl: String,
username: String,
password: String,
maxPoolSize: Int = MAX_POOL_SIZE,
): DataSource {
val hikariConfig =
HikariConfig().also {
it.jdbcUrl = jdbcUrl
it.username = username
it.password = <PASSWORD>
it.transactionIsolation = "TRANSACTION_SERIALIZABLE"
it.initializationFailTimeout = 6000
it.maximumPoolSize = maxPoolSize
it.validate()
}
return HikariDataSource(hikariConfig)
}
}
fun DataSource.migrate(): MigrateResult =
try {
Flyway.configure()
.dataSource(this)
.apply {
val dblocationsMiljoe = mutableListOf("db/migration")
if (appIsInGCP()) {
dblocationsMiljoe.add("db/gcp")
}
if (isProd()) {
dblocationsMiljoe.add("db/prod")
}
locations(*dblocationsMiljoe.toTypedArray())
}
.load()
.migrate()
} catch (e: Exception) {
LoggerFactory.getLogger(this::class.java).error("Fikk feil under Flyway-migrering", e)
throw e
}
fun jdbcUrl(
host: String,
port: Int,
databaseName: String,
): String = "jdbc:postgresql://$host:$port/$databaseName"
| 25 | Kotlin | 0 | 6 | e84b73f3decfa2cadfb02364fbd71ca96efbd948 | 2,181 | pensjon-etterlatte-saksbehandling | MIT License |
src/main/kotlin/io/vlang/lang/psi/types/VlangTypeEx.kt | vlang | 754,996,747 | false | null | package io.vlang.lang.psi.types
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.UserDataHolder
import com.intellij.psi.PsiElement
import io.vlang.lang.psi.VlangMethodDeclaration
interface VlangTypeEx : UserDataHolder {
fun name(): String
fun qualifiedName(): String
fun readableName(context: PsiElement): String
fun module(): String
fun anchor(): PsiElement?
fun accept(visitor: VlangTypeVisitor)
fun isAssignableFrom(rhs: VlangTypeEx, project: Project): Boolean
fun isEqual(rhs: VlangTypeEx): Boolean
fun isBuiltin(): Boolean
fun substituteGenerics(nameMap: Map<String, VlangTypeEx>): VlangTypeEx
fun ownMethodsList(project: Project): List<VlangMethodDeclaration>
fun methodsList(project: Project, visited: MutableSet<VlangTypeEx> = LinkedHashSet(5)): List<VlangMethodDeclaration>
fun findMethod(project: Project, name: String): VlangMethodDeclaration?
}
| 4 | null | 5 | 33 | 5b05a7b1f71ef8dcd7f26425a756259081fe5122 | 939 | intellij-v | MIT License |
extensionslibrary/src/main/java/de/uriegel/activityextensions/async/Async.kt | uriegel | 355,117,020 | false | {"Kotlin": 8619} | package de.uriegel.activityextensions.async
import java.util.*
import kotlin.concurrent.schedule
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
suspend fun delay(delayInMilliseconds: Long) {
return suspendCoroutine { continuation ->
Timer("Async Delay", false).schedule(delayInMilliseconds) {
continuation.resume(Unit)
}
}
} | 0 | Kotlin | 0 | 0 | d8dae3b662b53b687c1aced504aa59cb80985345 | 389 | ActivityExtensions | MIT License |
extensionslibrary/src/main/java/de/uriegel/activityextensions/async/Async.kt | uriegel | 355,117,020 | false | {"Kotlin": 8619} | package de.uriegel.activityextensions.async
import java.util.*
import kotlin.concurrent.schedule
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine
suspend fun delay(delayInMilliseconds: Long) {
return suspendCoroutine { continuation ->
Timer("Async Delay", false).schedule(delayInMilliseconds) {
continuation.resume(Unit)
}
}
} | 0 | Kotlin | 0 | 0 | d8dae3b662b53b687c1aced504aa59cb80985345 | 389 | ActivityExtensions | MIT License |
src/main/day08/Part1.kt | ollehagner | 572,141,655 | false | null | package day08
import common.Point
import readInput
typealias TreeRow = List<Tree>
typealias Column = List<Int>
fun main() {
// val input = readInput("day08/testinput.txt")
val input = readInput("day08/input.txt")
val inputRows = inputAsRows(input)
val inputRowsReversed = inputRows.map { it.reversed() }
val inputColumns = inputAsColumns(inputRows)
val inputColumnsReversed = inputColumns.map { it.reversed() }
val treesInSight = listOf(inputRows, inputRowsReversed, inputColumns, inputColumnsReversed).flatten()
.map { trees -> inSight(trees) }
.flatten()
.toSet()
.count();
println("Day 08 part 1, trees in sight: $treesInSight")
}
fun inSight(trees: TreeRow): Set<Tree> {
return trees
.drop(1)
.fold(listOf(trees.first())) { acc, tree ->
if(tree.height > acc.maxOf { it.height }) acc + tree else acc
}
.toSet()
}
fun inputAsRows(input: List<String>): List<TreeRow> {
return input
.mapIndexed { y, row ->
row.withIndex()
.map { indexedValue ->
Tree(indexedValue.value.digitToInt(), Point(indexedValue.index, y))
}
}
}
fun inputAsColumns(input: List<TreeRow>): List<TreeRow> {
return (0 until input.first().size).map { x ->
input.mapIndexed { y, trees ->
trees[x]
}
}
}
data class Tree(val height: Int, val position: Point) | 0 | Kotlin | 0 | 0 | b935fcfb465152f08307399eb85ee8a8a335f1a3 | 1,463 | aoc2022 | Apache License 2.0 |
container-tasks-gradle-plugin/src/main/kotlin/jekyll/task/JekyllExecTask.kt | mpetuska | 482,828,109 | false | null | package dev.petuska.container.jekyll.task
import dev.petuska.container.task.ContainerExecTask
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.Internal
import org.gradle.api.tasks.Optional
import org.gradle.api.tasks.UntrackedTask
import org.gradle.api.tasks.options.Option
import java.io.File
@Suppress("LeakingThis")
@UntrackedTask(because = "Must always run")
public abstract class JekyllExecTask : ContainerExecTask("jekyll") {
@get:Input
@get:Option(
option = "safe",
description = "Disable non-whitelisted plugins, caching to disk, and ignore symbolic links."
)
@get:Optional
public abstract val safe: Property<Boolean>
@get:Internal
protected open val command: String? = null
init {
group = "jekyll"
description = "Executes jekyll command"
image.setFinal("docker.io/jekyll/jekyll")
executable.setFinal("jekyll")
addContainerVolume(
project.provider { project.buildDir.resolve(".bundle/$name").also(File::mkdirs) },
project.provider { File("/usr/local/bundle/") }
)
}
override fun prepareContainerArgs(mode: Mode): List<String> {
val args = super.prepareContainerArgs(mode).toMutableList()
if (mode == PODMAN) args += "-e=JEKYLL_ROOTLESS=1"
return args
}
protected override fun prepareCommandArgs(mode: Mode): List<String> {
val args = super.prepareCommandArgs(mode).toMutableList()
command?.let { args.add(0, it) }
args += prepareJekyllArgs(mode)
return args
}
protected open fun prepareJekyllArgs(mode: Mode): List<String> {
val args = args.get().toMutableList()
if (safe.getOrElse(false)) args += "--safe"
return args
}
}
| 10 | Kotlin | 0 | 2 | 05265b4ec9dd977c863fd86c11991648aa1990a2 | 1,705 | container-tasks-gradle | Apache License 2.0 |
src/commonTest/kotlin/com/jeffpdavidson/kotwords/formats/AcrossLiteSanitizerTest.kt | jpd236 | 143,651,464 | false | null | package com.jeffpdavidson.kotwords.formats
import com.jeffpdavidson.kotwords.model.Puzzle
import kotlin.test.Test
import kotlin.test.assertEquals
class AcrossLiteSanitizerTest {
@Test
fun mapGivenToSanitizedClueNumbers() {
// Skip 2-Down, 4-Across, and 5-Across/Down; add a fake 7-Down
val rawGrid = listOf(
"1 X 2 . . . .",
"X X X . X 3 4",
"5 X X . 6 X 7",
"8 X X . 9 X X",
". . . . 10 X X"
)
val grid = rawGrid.map { row ->
row.split(" ").map { square ->
when (square) {
"." -> Puzzle.Cell(cellType = Puzzle.CellType.BLOCK)
"X" -> Puzzle.Cell(solution = "X")
else -> Puzzle.Cell(solution = "X", number = square)
}
}
}
val expectedSanitizedMap = mapOf(
"1" to "1",
"2" to "3",
"3" to "6",
"4" to "7",
"5" to "8",
"6" to "9",
"8" to "10",
"9" to "11",
"10" to "12",
)
assertEquals(expectedSanitizedMap, AcrossLiteSanitizer.mapGivenToSanitizedClueNumbers(grid))
}
@Test
fun sanitizeClue_normalClue() {
val givenClue = "Just a normal clue"
val givenToSanitizedClueNumMap: Map<String, String> = mapOf()
assertEquals(
"Just a normal clue",
AcrossLiteSanitizer.sanitizeClue(givenClue, givenToSanitizedClueNumMap, true)
)
}
@Test
fun sanitizeClue_simpleReplacement() {
val givenClue = "See 25-Down"
val givenToSanitizedClueNumMap = mapOf("25" to "27")
assertEquals("See 27-Down", AcrossLiteSanitizer.sanitizeClue(givenClue, givenToSanitizedClueNumMap, true))
}
@Test
fun sanitizeClue_complexReplacements() {
val givenClue = "Where the end of 17-, 25- and 47-Across and 14- and 28-Down may be found"
val givenToSanitizedClueNumMap = mapOf("14" to "14", "17" to "17", "25" to "26", "28" to "29", "47" to "49")
assertEquals(
"Where the end of 17-, 26- and 49-Across and 14- and 29-Down may be found",
AcrossLiteSanitizer.sanitizeClue(givenClue, givenToSanitizedClueNumMap, true)
)
}
@Test
fun sanitizeClue_specialCharacters() {
val givenClue = "★Clue with a <i>star</i>"
val givenToSanitizedClueNumMap: Map<String, String> = mapOf()
assertEquals(
"*Clue with a \"star\"",
AcrossLiteSanitizer.sanitizeClue(givenClue, givenToSanitizedClueNumMap, true)
)
}
@Test
fun sanitizeClue_specialCharacters_doNotSanitizeCharacters() {
val givenClue = "★Clue with a <i>star</i>"
val givenToSanitizedClueNumMap: Map<String, String> = mapOf()
assertEquals(
"★Clue with a \"star\"",
AcrossLiteSanitizer.sanitizeClue(givenClue, givenToSanitizedClueNumMap, false)
)
}
} | 8 | Kotlin | 2 | 10 | a934756f63e898b4e061fbceadab5414e90dd16c | 3,019 | kotwords | Apache License 2.0 |
src/commonMain/kotlin/org/tix/integrations/jira/issue/WorklogRecord.kt | ncipollo | 336,920,234 | false | {"Kotlin": 601503} | package org.tix.integrations.jira.issue
import kotlinx.serialization.Serializable
import org.tix.integrations.jira.user.User
@Serializable
data class WorklogRecord(
val self: String = "",
val author: User? = null,
val updateAuthor: User? = null,
val comment: String = "",
val created: Long? = null,
val started: Long? = null,
val timeSpent: String = "",
val timeSpendSeconds: Int = 0,
val id: String = "",
val issueId: String = ""
)
| 8 | Kotlin | 0 | 3 | 02f87c827c1159af055f5afc5481afd45c013703 | 475 | tix-core | MIT License |
mockzilla-management-ui/common/src/desktopTest/kotlin/com/apadmi/mockzilla/desktop/ui/widgets/devicetabs/DeviceTabsViewModelTests.kt | Apadmi-Engineering | 570,496,992 | false | {"Kotlin": 392773, "Dart": 99321, "Ruby": 10530, "Swift": 5769, "Shell": 995} | package com.apadmi.mockzilla.desktop.ui.widgets.devicetabs
import com.apadmi.mockzilla.desktop.engine.device.ActiveDeviceSelector
import com.apadmi.mockzilla.desktop.engine.device.Device
import com.apadmi.mockzilla.desktop.engine.device.StatefulDevice
import com.apadmi.mockzilla.desktop.ui.widgets.devicetabs.DeviceTabsViewModel.*
import com.apadmi.mockzilla.testutils.SelectedDeviceMonitoringViewModelBaseTest
import com.apadmi.mockzilla.testutils.dummymodels.dummy
import app.cash.turbine.test
import io.mockative.Mock
import io.mockative.classOf
import io.mockative.given
import io.mockative.mock
import io.mockative.thenDoNothing
import io.mockative.verify
import org.junit.Test
import kotlin.test.assertEquals
import kotlinx.coroutines.flow.flowOf
class DeviceTabsViewModelTests : SelectedDeviceMonitoringViewModelBaseTest() {
@Mock
private val activeDeviceSelectorMock = mock(classOf<ActiveDeviceSelector>())
private fun createSut() = DeviceTabsViewModel(activeDeviceMonitorMock.also {
given(it).invocation { onDeviceConnectionStateChange }.thenReturn(flowOf())
}, activeDeviceSelectorMock, testScope.backgroundScope)
@Test
fun `onChangeDevice - calls through`() = runBlockingTest {
/* Setup */
given(activeDeviceMonitorMock).invocation { allDevices }.thenReturn(emptyList())
given(activeDeviceSelectorMock).invocation { updateSelectedDevice(Device.dummy()) }.thenDoNothing()
val sut = createSut()
sut.state.test {
/* Run Test */
sut.onChangeDevice(State.DeviceTabEntry.dummy().copy(underlyingDevice = Device.dummy()))
/* Verify */
verify(activeDeviceSelectorMock).invocation { updateSelectedDevice(Device.dummy()) }
.wasInvoked()
assertEquals(State(emptyList()), awaitItem())
}
}
@Test
fun `addNewDevice - clears active device`() = runBlockingTest {
/* Setup */
given(activeDeviceMonitorMock).invocation { allDevices }.thenReturn(emptyList())
given(activeDeviceSelectorMock).invocation { clearSelectedDevice() }.thenDoNothing()
val sut = createSut()
/* Run Test */
sut.addNewDevice()
/* Verify */
verify(activeDeviceSelectorMock).invocation { clearSelectedDevice() }.wasInvoked()
}
@Suppress("TOO_LONG_FUNCTION")
@Test
fun `reloadData - pulls latest data from monitor - updates state`() = runBlockingTest {
/* Setup */
val dummyActiveDevice = Device.dummy().copy(ip = "device1")
given(activeDeviceMonitorMock).invocation { allDevices }.thenReturn(
listOf(
StatefulDevice(
dummyActiveDevice,
"Device Name 1",
isConnected = false,
connectedAppPackage = "package"
),
StatefulDevice(
Device.dummy(),
"Device Name 2",
isConnected = true,
connectedAppPackage = "package"
),
)
)
val sut = createSut()
sut.state.test {
skipItems(1)
/* Run Test */
sut.reloadData(dummyActiveDevice)
/* Verify */
assertEquals(
State(
listOf(
State.DeviceTabEntry(
"Device Name 1",
isActive = true,
isConnected = false,
dummyActiveDevice
),
State.DeviceTabEntry(
"Device Name 2",
isActive = false,
isConnected = true,
Device.dummy()
)
)
),
awaitItem()
)
}
}
}
| 11 | Kotlin | 7 | 25 | b5896121f3899c64d03c078adaae6482f95d6a2f | 3,990 | Mockzilla | MIT License |
app/src/main/java/org/p2p/wallet/jupiter/ui/tokens/presenter/SearchSwapTokensMapper.kt | p2p-org | 306,035,988 | false | {"Kotlin": 4709924, "HTML": 3064848, "Java": 296719, "Groovy": 1601, "Shell": 1252, "JavaScript": 807} | package org.p2p.wallet.jupiter.ui.tokens.presenter
import org.p2p.uikit.model.AnyCellItem
import org.p2p.wallet.R
import org.p2p.wallet.jupiter.interactor.model.SwapTokenModel
class SearchSwapTokensMapper(
private val commonMapper: SwapTokensCommonMapper,
) {
suspend fun toCellItems(
foundSwapTokens: List<SwapTokenModel>
): List<AnyCellItem> = commonMapper.foundTokensGroup(foundSwapTokens)
private suspend fun SwapTokensCommonMapper.foundTokensGroup(
foundSwapTokens: List<SwapTokenModel>
): List<AnyCellItem> = buildList {
val sectionHeader = createSectionHeader(R.string.swap_tokens_section_search_result)
val searchResultTokens = foundSwapTokens.map { it.toTokenFinanceCellModel(isSearchResult = true) }
this += sectionHeader
this += searchResultTokens
}
}
| 4 | Kotlin | 18 | 33 | bdce0fdac847a83678d2111788d55f0e2de7a165 | 840 | key-app-android | MIT License |
app/src/main/kotlin/co/netguru/baby/monitor/client/feature/onboarding/VoiceRecordingsSettingsFragment.kt | netguru | 143,860,032 | false | null | package co.netguru.baby.monitor.client.feature.onboarding
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import androidx.navigation.fragment.findNavController
import co.netguru.baby.monitor.client.R
import co.netguru.baby.monitor.client.common.base.BaseFragment
import co.netguru.baby.monitor.client.feature.analytics.Screen
import co.netguru.baby.monitor.client.feature.settings.ConfigurationViewModel
import kotlinx.android.synthetic.main.fragment_voice_recordings_setting.*
import javax.inject.Inject
class VoiceRecordingsSettingsFragment : BaseFragment() {
override val layoutResource = R.layout.fragment_voice_recordings_setting
override val screen: Screen = Screen.VOICE_RECORDINGS_SETTING
@Inject
lateinit var factory: ViewModelProvider.Factory
private val viewModel by lazy { ViewModelProviders.of(this, factory)[ConfigurationViewModel::class.java] }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
featureDNextBtn.setOnClickListener {
findNavController().navigate(R.id.featureDToConnecting)
}
featureDSwitch.setOnCheckedChangeListener { buttonView, isChecked ->
viewModel.setUploadEnabled(isChecked)
}
}
}
| 19 | Kotlin | 7 | 18 | 3c3d8838de7ed8a340ebb79a64f249681669abf2 | 1,372 | baby-monitor-client-android | Apache License 2.0 |
library/src/main/java/com/mux/stats/sdk/muxstats/PlayerUtils.kt | muxinc | 567,824,540 | false | {"Kotlin": 152250} | package com.mux.stats.sdk.muxstats
import android.net.Uri
import androidx.media3.common.Format
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.Player
import androidx.media3.common.Tracks
import com.mux.android.util.oneOf
import com.mux.stats.sdk.core.model.VideoData
import com.mux.stats.sdk.core.util.MuxLogger
internal const val PLAYER_STATE_POLL_MS = 150L
private const val LOG_TAG = "PlayerUtils"
/**
* Returns true if any media track in the given [Tracks] object had a video MIME type
*/
fun Tracks.hasAtLeastOneVideoTrack(): Boolean {
return groups.map { it.mediaTrackGroup }
.filter { trackGroup -> trackGroup.length > 0 }
.map { trackGroup -> trackGroup.getFormat(0) }
.find { format -> format.sampleMimeType?.contains("video") ?: false }
.let { foundVideoTrack -> foundVideoTrack != null }
}
/**
* Maps the formats of the tracks in a [Tracks.Group] to some other type
*/
fun <R> Tracks.Group.mapFormats(block: (Format) -> R): List<R> {
val retList = mutableListOf<R>()
for (i in 0 until length) {
retList.add(block(getTrackFormat(i)))
}
return retList
}
/**
* Handles an ExoPlayer position discontinuity
*/
@JvmSynthetic // Hides from java
fun MuxStateCollector.handlePositionDiscontinuity(reason: Int) {
when (reason) {
Player.DISCONTINUITY_REASON_SEEK_ADJUSTMENT, Player.DISCONTINUITY_REASON_SEEK -> {
// Called when seeking starts. Player will move to READY when seeking is over
seeking()
}
else -> {} // ignored
}
}
/**
* Handles changes to playWhenReady.
*/
@JvmSynthetic
fun MuxStateCollector.handlePlayWhenReady(
playWhenReady: Boolean,
@Player.State playbackState: Int
) {
if (playWhenReady) {
play()
if (playbackState == Player.STATE_READY) {
// If we were already READY when playWhenReady is set, then we are definitely also playing
playing()
}
} else if (muxPlayerState != MuxPlayerState.PAUSED) {
pause()
}
}
/**
* Asynchronously watch player playback position, collecting periodic updates out-of-band from the
* normal callback flow.
*/
@JvmSynthetic
fun MuxStateCollector.watchPlayerPos(player: Player) {
playerWatcher = MuxStateCollector.PlayerWatcher(
PLAYER_STATE_POLL_MS,
this,
player
) { it, _ -> it.currentPosition }
playerWatcher?.start()
}
/**
* Handles a change of basic ExoPlayer state
*/
@JvmSynthetic // Hidden from Java callers, since the only ones are external
fun MuxStateCollector.handleExoPlaybackState(
@Player.State playbackState: Int,
playWhenReady: Boolean
) {
if (this.muxPlayerState == MuxPlayerState.PLAYING_ADS) {
// Normal playback events are ignored during ad playback.
return
}
when (playbackState) {
Player.STATE_BUFFERING -> {
MuxLogger.d(LOG_TAG, "entering BUFFERING")
buffering()
}
Player.STATE_READY -> {
MuxLogger.d(LOG_TAG, "entering READY")
// We're done seeking after we get back to STATE_READY
if (muxPlayerState == MuxPlayerState.SEEKING) {
// TODO <em> playing() and pause() handle rebuffering, why not also seeking
seeked()
}
// If playWhenReady && READY, we're playing or else we're paused
if (playWhenReady) {
playing()
} else if (muxPlayerState != MuxPlayerState.PAUSED) {
pause()
}
}
Player.STATE_ENDED -> {
MuxLogger.d(LOG_TAG, "entering ENDED")
ended()
}
Player.STATE_IDLE -> {
MuxLogger.d(LOG_TAG, "entering IDLE")
if (muxPlayerState.oneOf(MuxPlayerState.PLAY, MuxPlayerState.PLAYING)) {
// If we are playing/preparing to play and go idle, the player was stopped
pause()
}
}
} // when (playbackState)
} // fun handleExoPlaybackState
@JvmSynthetic
fun MuxStateCollector.handleMediaItemChanged(mediaItem: MediaItem) {
mediaItem.localConfiguration?.let { localConfig ->
val sourceUrl = localConfig.uri;
val sourceDomain = sourceUrl.authority
val videoData = VideoData().apply {
videoSourceDomain = sourceDomain
videoSourceUrl = sourceUrl.toString()
}
videoDataChange(videoData)
}
// Also pick up data from MediaMetadata
handleMediaMetadata(mediaItem.mediaMetadata)
}
@JvmSynthetic
fun MuxStateCollector.handleMediaMetadata(mediaMetadata: MediaMetadata) {
// explicitly make those ! into ?
val posterUrl: Uri? = mediaMetadata.artworkUri
val title: CharSequence? = mediaMetadata.title
val videoData = VideoData().apply {
posterUrl?.let { videoPosterUrl = it.toString() }
title?.let { videoTitle = it.toString() }
}
videoDataChange(videoData)
}
| 0 | Kotlin | 2 | 5 | 62b129b7338df132ebb0a0985595d043f016e58e | 4,672 | mux-stats-sdk-media3 | Apache License 2.0 |
src/main/kotlin/dev/retrotv/data/utils/CollectionUtils.kt | retrotv-maven-repo | 671,819,166 | false | {"Kotlin": 35974} | @file:JvmName("CollectionUtils")
package dev.retrotv.data.utils
/**
* List에서 중복되는 데이터를 제거하고 반환합니다.
* orgOrder를 true로 설정할 경우 반환 List가 원본 List와 동일한 순서로 유지되며, 중복 데이터는 첫번째 값만 유지됩니다.
*
* @param values 중복을 제거할 list
* @param orgOrder 원본 데이터와의 동일한 순서 유지여부
* @return 중복이 제거된 list
*/
fun <T> removeDuplicates(values: List<T>, orgOrder: Boolean = false): List<T> {
var newValues = values.toSet().toMutableList()
if (orgOrder) {
val orderValues = mutableListOf<T>()
values.forEach { org ->
newValues.forEachIndexed { i, new ->
if (org == new) {
orderValues.add(newValues.removeAt(i))
return@forEach
}
}
}
newValues = orderValues
}
return newValues.toList()
}
| 0 | Kotlin | 0 | 0 | bf6063b1751d82c138b71e7a9cdd4572c045bcad | 802 | data-utils | MIT License |
src/day22/Parser.kt | g0dzill3r | 576,012,003 | false | null | package day22
import readInput
import java.io.File
import java.lang.IllegalStateException
import java.util.regex.Pattern
enum class Direction {
LEFT, RIGHT;
companion object {
fun parse (encoded: Char): Direction {
return when (encoded) {
'L' -> Direction.LEFT
'R' -> Direction.RIGHT
else -> throw IllegalArgumentException ("Found a: $encoded")
}
}
}
}
enum class Facing (val value: Int, val render: Char) {
LEFT(2, '<'), RIGHT(0, '>'), UP(3, '^'), DOWN(1, 'v');
val invert: Facing
get () = when (this) {
LEFT -> RIGHT
RIGHT -> LEFT
UP -> DOWN
DOWN -> UP
}
val left: Facing
get () = turn (Direction.LEFT)
val right: Facing
get () = turn (Direction.RIGHT)
fun turn (direction: Direction): Facing {
when (direction) {
Direction.LEFT -> {
return when (this) {
LEFT -> DOWN
UP -> LEFT
RIGHT -> UP
DOWN -> RIGHT
}
}
Direction.RIGHT -> {
return when (this) {
LEFT -> UP
UP -> RIGHT
RIGHT -> DOWN
DOWN -> LEFT
}
}
}
}
fun same (other: Facing): Boolean = same (this, other)
companion object {
val SAME = mutableMapOf<Pair<Facing, Facing>, Boolean>().apply {
Facing.values().forEach {
this[Pair(it, it)] = true
this[Pair(it, it.invert)] = false
}
val set = { f1: Facing, f2: Facing, same: Boolean ->
this[Pair(f1, f2)] = same
this[Pair(f2, f1)] = same
}
set (UP, LEFT, false)
set (UP, RIGHT, true)
set (DOWN, LEFT, true)
set (DOWN, RIGHT, false)
}
fun same (f1: Facing, f2: Facing): Boolean = SAME[Pair(f1, f2)] as Boolean
}
}
enum class Tile (val encoded: Char) {
WALL ('#'), FLOOR ('.')
}
data class Point (val x: Int, val y: Int) {
fun add (other: Point): Point = Point (x + other.x, y + other.y)
fun move (facing: Facing): Point = add (delta (facing))
override fun toString(): String = "($x, $y)"
companion object {
fun delta (facing: Facing): Point {
return when (facing) {
Facing.UP -> Point (0, - 1)
Facing.DOWN -> Point (0, 1)
Facing.RIGHT -> Point (+ 1, 0)
Facing.LEFT -> Point (- 1, 0)
}
}
}
}
sealed class Step {
data class Forward (val steps: Int) : Step () {
override fun toString (): String = "$steps"
}
data class Turn (val direction: Direction) : Step () {
override fun toString (): String = "$direction"
}
}
fun loadSimple(): Board = Board.parse (File ("src/day22/day22-simple.txt").readText())
fun loadBoard (example: Boolean): Board {
val input = readInput(22, example)
val board = Board.parse (input)
return board
}
fun main (args: Array<String>) {
val example = true
val board = loadBoard(example)
board.dump ()
return
} | 0 | Kotlin | 0 | 0 | 6ec11a5120e4eb180ab6aff3463a2563400cc0c3 | 3,334 | advent_of_code_2022 | Apache License 2.0 |
app/src/main/java/io/github/kdesp73/petadoption/ui/components/InfoBox.kt | KDesp73 | 776,598,529 | false | {"Kotlin": 412576, "Shell": 1165} | package io.github.kdesp73.petadoption.ui.components
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.em
@Composable
fun InfoBox(
modifier: Modifier = Modifier,
label: String,
info: Any?,
width: Dp = 150.dp,
height: Dp = 80.dp,
infoFontSize: Float = 4.em.value
) {
MyCard(
modifier = modifier
.size(width, height),
) {
Column (
modifier = Modifier
.padding(2.dp)
.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(10.dp),
horizontalAlignment = Alignment.CenterHorizontally
){
Text(text = label, color = Color.Gray)
Text(
modifier = Modifier.horizontalScroll(rememberScrollState()),
text = info.toString(),
fontSize = infoFontSize.em,
color = MaterialTheme.colorScheme.onSecondaryContainer
)
}
}
}
@Composable
fun InfoBoxClickable(
modifier: Modifier = Modifier,
label: String,
info: Any?,
width: Dp = 100.dp,
height: Dp = 40.dp,
infoFontSize: Float = 5.em.value,
action: () -> Unit = {}
) {
InfoBox(
label = label,
info = info,
width = width,
height = height,
infoFontSize = infoFontSize,
modifier = modifier.clickable {
action()
}
)
}
@Preview
@Composable
fun InfoBoxPreview(){
InfoBox(label = "Type", info = "Dog", width = 100.dp, height = 80.dp)
}
| 0 | Kotlin | 0 | 0 | 768a32b99bae1639b5f50cb3ad6e07713505a108 | 2,273 | PawrfectMatch | MIT License |
app/src/main/kotlin/io/github/wykopmobilny/ui/modules/profile/links/related/ProfileRelatedPresenter.kt | otwarty-wykop-mobilny | 374,160,630 | false | null | package io.github.wykopmobilny.ui.modules.profile.badge
import io.github.wykopmobilny.api.profile.ProfileApi
import io.github.wykopmobilny.base.BasePresenter
import io.github.wykopmobilny.base.Schedulers
import io.github.wykopmobilny.utils.intoComposite
class BadgePresenter(
val schedulers: Schedulers,
val profileApi: ProfileApi,
) : BasePresenter<BadgeView>() {
var page = 1
lateinit var username: String
fun loadData(shouldRefresh: Boolean) {
if (shouldRefresh) page = 1
profileApi.getBadges(username, page)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe(
{
if (it.isNotEmpty()) {
page++
view?.addDataToAdapter(it, shouldRefresh)
} else {
view?.disableLoading()
}
},
{ view?.showErrorDialog(it) },
)
.intoComposite(compositeObservable)
}
}
| 7 | null | 4 | 47 | 85b54b736f5fbcd6f62305779ed7ae2085c3b136 | 1,072 | wykop-android | MIT License |
source-downloader-core/src/main/kotlin/xyz/shoaky/sourcedownloader/SourceDownloaderApplication.kt | shoaky009 | 607,575,763 | false | null | package xyz.shoaky.sourcedownloader
import com.google.common.reflect.ClassPath
import com.vladmihalcea.hibernate.type.json.JsonType
import jakarta.annotation.PreDestroy
import org.slf4j.LoggerFactory
import org.springframework.aot.hint.MemberCategory
import org.springframework.aot.hint.RuntimeHints
import org.springframework.aot.hint.RuntimeHintsRegistrar
import org.springframework.beans.factory.InitializingBean
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.ImportRuntimeHints
import org.springframework.context.event.EventListener
import org.springframework.core.env.Environment
import xyz.shoaky.sourcedownloader.component.*
import xyz.shoaky.sourcedownloader.component.supplier.*
import xyz.shoaky.sourcedownloader.config.SourceDownloaderProperties
import xyz.shoaky.sourcedownloader.core.*
import xyz.shoaky.sourcedownloader.core.config.ComponentConfig
import xyz.shoaky.sourcedownloader.core.config.ProcessorConfig
import xyz.shoaky.sourcedownloader.external.qbittorrent.QbittorrentConfig
import xyz.shoaky.sourcedownloader.sdk.PathPattern
import xyz.shoaky.sourcedownloader.sdk.component.*
import java.net.URL
import kotlin.reflect.KClass
@SpringBootApplication
@ImportRuntimeHints(SourceDownloaderApplication.ApplicationRuntimeHints::class)
@EnableConfigurationProperties(SourceDownloaderProperties::class)
class SourceDownloaderApplication(
private val environment: Environment,
private val componentManager: SdComponentManager,
private val processorManager: ProcessorManager,
private val pluginManager: PluginManager,
private val processorStorages: List<ProcessorConfigStorage>,
private val componentStorages: List<ComponentConfigStorage>,
private val componentSupplier: List<SdComponentSupplier<*>>
) : InitializingBean {
@EventListener(ApplicationReadyEvent::class)
fun initApplication() {
log.info("Database file located:${
environment.getProperty("spring.datasource.url")
?.removePrefix("jdbc:h2:file:")
}")
val processorConfigs = processorStorages.flatMap { it.getAllProcessorConfig() }
for (processorConfig in processorConfigs) {
processorManager.createProcessor(processorConfig)
}
componentManager.getAllTrigger()
.forEach {
it.start()
}
}
@PreDestroy
fun stopApplication() {
pluginManager.destroyPlugins()
componentManager.getAllTrigger()
.forEach {
it.stop()
}
}
private fun loadAndInitPlugins() {
pluginManager.loadPlugins()
pluginManager.initPlugins()
val plugins = pluginManager.getPlugins()
plugins.forEach {
val description = it.description()
val fullName = description.fullName()
log.info("成功加载插件$fullName")
}
}
private fun registerComponentSuppliers() {
componentManager.registerSupplier(
*componentSupplier.toTypedArray()
)
componentManager.registerSupplier(
*getObjectSuppliers().toTypedArray()
)
val types = componentManager.getSuppliers()
.map { it.supplyTypes() }
.flatten()
.distinct()
.groupBy({ it.klass.simpleName }, { it.typeName })
log.info("组件注册完成:$types")
}
private fun createComponents() {
for (componentStorage in componentStorages) {
componentStorage
.getAllComponentConfig()
.forEach(this::createFromConfigs)
}
}
private fun createFromConfigs(key: String, configs: List<ComponentConfig>) {
val componentKClass = Components.fromName(key)?.klass
?: throw ComponentException.unsupported("未知组件类型:$key")
configs.forEach {
val type = ComponentType(it.type, componentKClass)
componentManager.createComponent(it.name, type, ComponentProps.fromMap(it.props))
log.info("成功创建组件${type.klass.simpleName}:${it.type}:${it.name}")
}
}
companion object {
internal val log = LoggerFactory.getLogger(SourceDownloaderApplication::class.java)
@JvmStatic
fun main(args: Array<String>) {
setupProxy()
val springApplication = SpringApplication(SourceDownloaderApplication::class.java)
springApplication.mainApplicationClass = SourceDownloaderApplication::class.java
springApplication.run(*args)
}
private fun setupProxy() {
val env = System.getenv()
val urlStr = env["http_proxy"] ?: env["HTTP_PROXY"] ?: env["https_proxy"] ?: env["HTTPS_PROXY"]
urlStr?.also {
val url = URL(it)
System.setProperty("http.proxyHost", url.host)
System.setProperty("http.proxyPort", url.port.toString())
System.setProperty("https.proxyHost", url.host)
System.setProperty("https.proxyPort", url.port.toString())
}
}
}
class ApplicationRuntimeHints : RuntimeHintsRegistrar {
override fun registerHints(hints: RuntimeHints, classLoader: ClassLoader?) {
hints.reflection().registerType(JsonType::class.java, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)
hints.reflection().registerType(ProcessorConfig::class.java, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)
hints.reflection().registerType(ProcessorConfig.Options::class.java, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)
hints.reflection().registerType(Regex::class.java, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)
hints.reflection().registerType(PathPattern::class.java, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)
hints.reflection().registerType(ProcessorConfig.ComponentId::class.java, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)
hints.reflection().registerType(ProcessorConfig.Options::class.java, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)
hints.reflection().registerType(ComponentConfig::class.java, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)
hints.reflection().registerType(QbittorrentConfig::class.java, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS)
ClassPath.from(this::class.java.classLoader)
.getTopLevelClasses("xyz.shoaky.sourcedownloader.component.supplier")
.filter { it.simpleName.contains("supplier", true) }
.map { it.load() }
.forEach {
hints.reflection().registerType(it, MemberCategory.DECLARED_FIELDS)
hints.reflection().registerType(it, MemberCategory.INVOKE_PUBLIC_METHODS)
}
}
}
override fun afterPropertiesSet() {
// 加载出现异常不让应用完成启动
loadAndInitPlugins()
log.info("支持的组件类型:${ComponentType.types()}")
registerComponentSuppliers()
createComponents()
}
// FIXME native image会失败,后面再看
private fun getObjectSuppliers(): List<SdComponentSupplier<*>> {
return ClassPath.from(this::class.java.classLoader)
.getTopLevelClasses("xyz.shoaky.sourcedownloader.component.supplier")
.filter { it.simpleName.contains("supplier", true) }
.map { it.load().kotlin }
.filterIsInstance<KClass<SdComponentSupplier<*>>>()
.mapNotNull {
it.objectInstance
}
}
// private fun getObjectSuppliers(): List<SdComponentSupplier<*>> {
// return listOf(
// QbittorrentSupplier,
// RssSourceSupplier,
// GeneralFileMoverSupplier,
// RunCommandSupplier,
// ExpressionItemFilterSupplier,
// FixedScheduleTriggerSupplier,
// UrlDownloaderSupplier,
// MockDownloaderSupplier,
// TouchItemDirectorySupplier,
// DynamicTriggerSupplier,
// SendHttpRequestSupplier,
// AiVariableProviderSupplier,
// SystemFileSourceSupplier,
// MetadataVariableProviderSupplier,
// JackettSourceSupplier,
// AnitomVariableProviderSupplier,
// SeasonProviderSupplier,
// CleanEmptyDirectorySupplier,
// )
// }
} | 1 | Kotlin | 0 | 5 | 16c265c082112aad122bb8a59cad6308e35da098 | 8,589 | source-downloader | Apache License 2.0 |
lib/src/main/java/com/sha/rxrequester/exception/ExceptionInterceptor.kt | thasneemp | 216,811,559 | true | {"Kotlin": 33828, "Java": 660} | package com.sha.rxrequester.exception
import com.sha.rxrequester.Presentable
import com.sha.rxrequester.RxRequester
import io.reactivex.functions.Consumer
data class InterceptorArgs(
val requester: RxRequester,
val presentable: Presentable,
val serverErrorContract: Class<*>?,
var inlineHandling: ((Throwable) -> Boolean)?
)
class ExceptionInterceptor(private val args: InterceptorArgs) : Consumer<Throwable> {
override fun accept(throwable: Throwable) {
throwable.printStackTrace()
args.presentable.hideLoading()
// inline handling of the error
if (args.inlineHandling != null && args.inlineHandling!!(throwable))
return
ExceptionProcessor.process(
throwable = throwable,
presentable = args.presentable,
serverErrorContract = args.serverErrorContract,
requester = args.requester
)
}
} | 0 | null | 0 | 0 | ad38fff6e7061212d80ec8e201ca59bc58feb728 | 957 | RxRequester | Apache License 2.0 |
app/src/main/java/org/mightyfrog/android/twitterapponlyauthsample/data/search/Status.kt | mightyfrog | 149,490,148 | false | null | package org.mightyfrog.android.twitterapponlyauthsample.data.search
import com.google.gson.annotations.SerializedName
data class Status(@SerializedName("created_at")
var createdAt: String?,
@SerializedName("id")
var id: Long,
@SerializedName("id_str")
var idStr: String?,
@SerializedName("text")
var text: String?,
@SerializedName("truncated")
var truncated: Boolean?,
@SerializedName("entities")
var entities: Entities?,
@SerializedName("metadata")
var metadata: Metadata?,
@SerializedName("source")
var source: String?,
@SerializedName("in_reply_to_status_id")
var inReplyToStatusId: Any?, // just a sample, nbd
@SerializedName("in_reply_to_status_id_str")
var inReplyToStatusIdStr: Any?,
@SerializedName("in_reply_to_user_id")
var inReplyToUserId: Any?,
@SerializedName("in_reply_to_user_id_str")
var inReplyToUserIdStr: Any?,
@SerializedName("in_reply_to_screen_name")
var inReplyToScreenName: Any?,
@SerializedName("user")
var user: User?,
@SerializedName("geo")
var geo: Any?,
@SerializedName("coordinates")
var coordinates: Any?,
@SerializedName("place")
var place: Any?,
@SerializedName("contributors")
var contributors: Any?,
@SerializedName("is_quote_status")
var isQuoteStatus: Boolean?,
@SerializedName("retweet_count")
var retweetCount: Int?,
@SerializedName("favorite_count")
var favoriteCount: Int?,
@SerializedName("favorited")
var favorited: Boolean?,
@SerializedName("retweeted")
var retweeted: Boolean?,
@SerializedName("possibly_sensitive")
var possiblySensitive: Boolean?,
@SerializedName("lang")
var lang: String?) | 0 | Kotlin | 0 | 1 | e8f6516ac8c6553a810e4d5b7cf5e7462751a8aa | 2,420 | Twitter-App-Only-Authentication | Apache License 2.0 |
app/src/main/java/com/devcommop/myapplication/utils/NotificationApiInstance.kt | pareekdevansh | 648,905,400 | false | null | package com.devcommop.myapplication.utils
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class NotificationApiInstance {
companion object{
private val retrofit by lazy {
Retrofit.Builder()
.baseUrl(Constants.FCM_BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
val api by lazy{
retrofit.create(NotificationApi::class.java)
}
}
} | 0 | Kotlin | 0 | 0 | d0fda60a15fe2c7bd93596cf6582fccdbccb788a | 499 | Social-Jaw | MIT License |
app/src/main/java/com/anshtya/movieinfo/navigation/MovieInfoDestination.kt | anshtya | 704,151,092 | false | {"Kotlin": 252581} | package com.anshtya.movieinfo.navigation
import androidx.annotation.StringRes
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Home
import androidx.compose.material.icons.outlined.Person
import androidx.compose.material.icons.outlined.Search
import androidx.compose.material.icons.rounded.Home
import androidx.compose.material.icons.rounded.Person
import androidx.compose.material.icons.rounded.Search
import androidx.compose.ui.graphics.vector.ImageVector
import com.anshtya.movieinfo.R
enum class MovieInfoDestination(
@StringRes val titleId: Int,
val selectedIcon: ImageVector,
val icon: ImageVector
) {
HOME(
titleId = R.string.home,
selectedIcon = Icons.Rounded.Home,
icon = Icons.Outlined.Home
),
SEARCH(
titleId = R.string.search,
selectedIcon = Icons.Rounded.Search,
icon = Icons.Outlined.Search
),
YOU(
titleId = R.string.you,
selectedIcon = Icons.Rounded.Person,
icon = Icons.Outlined.Person
)
} | 1 | Kotlin | 0 | 1 | 2f44b6e36602ad1d0c2896e1c950aed50a989814 | 1,059 | MovieInfo | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.