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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/onirutla/metalgearcharacter/data/Constant.kt | onirutlA | 413,748,454 | false | null | package com.onirutla.metalgearcharacter.data
import androidx.recyclerview.widget.DiffUtil
object Differentiator : DiffUtil.ItemCallback<MetalGearCharacter>() {
override fun areItemsTheSame(
oldItem: MetalGearCharacter,
newItem: MetalGearCharacter
): Boolean = oldItem.name == newItem.name
override fun areContentsTheSame(
oldItem: MetalGearCharacter,
newItem: MetalGearCharacter
): Boolean = oldItem == newItem
} | 0 | Kotlin | 0 | 0 | b5f1580a5f4c8ef510485765b380c05e5034e9ff | 466 | metal-gear-characters | Apache License 2.0 |
engine/util/src/main/java/cc/cryptopunks/crypton/util/ext/CoroutineScope.kt | cryptopunkscc | 202,181,919 | false | {"Kotlin": 523158, "Shell": 6362} | package cc.cryptopunks.crypton.util.ext
import kotlinx.coroutines.CompletionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.DisposableHandle
import kotlinx.coroutines.Job
fun CoroutineScope.invokeOnClose(handler: CompletionHandler): DisposableHandle =
coroutineContext[Job]!!.invokeOnCompletion(handler)
| 9 | Kotlin | 2 | 7 | 33dc96367c3a4eb869800b6a0ac84f302bd68502 | 337 | crypton | MIT License |
app/src/main/java/com/computer/inu/sqkakaotalk/Fragment/FriendListFragment.kt | jung2929 | 178,861,046 | false | null | package com.computer.inu.sqkakaotalk.Fragment
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.helper.ItemTouchHelper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.Glide
import com.computer.inu.sqkakaotalk.*
import com.computer.inu.sqkakaotalk.Adapter.BirthdayFriendListRecyclerViewAdapter
import com.computer.inu.sqkakaotalk.Adapter.EmoticonShopRecyclerViewAdapter
import com.computer.inu.sqkakaotalk.Adapter.FavoriteFriendListRecyclerViewAdapter
import com.computer.inu.sqkakaotalk.Adapter.FriendListRecyclerViewAdapter
import com.computer.inu.sqkakaotalk.Data.*
import com.computer.inu.sqkakaotalk.Main.MainActivity
import com.computer.inu.sqkakaotalk.delete.DeleteFriendInfoResponse
import com.computer.inu.sqkakaotalk.get.*
import com.computer.inu.sqkakaotalk.network.ApplicationController
import com.computer.inu.sqkakaotalk.network.NetworkService
import com.computer.inu.sqkakaotalk.network.SqNetworkService
import com.computer.inu.sqkakaotalk.post.PostChatResponse
import com.computer.inu.sqkakaotalk.post.PostLoginResponse
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import kotlinx.android.synthetic.main.activity_emoticon_shop.*
import kotlinx.android.synthetic.main.activity_friend_list_fragment.*
import kotlinx.android.synthetic.main.activity_friend_list_fragment.view.*
import kotlinx.android.synthetic.main.activity_in_message.*
import kotlinx.android.synthetic.main.activity_login.*
import kotlinx.android.synthetic.main.activity_sign_up2.*
import org.jetbrains.anko.support.v4.ctx
import org.jetbrains.anko.support.v4.startActivity
import org.jetbrains.anko.support.v4.toast
import org.json.JSONObject
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class FriendListFragment : Fragment() {
val networkService: NetworkService by lazy {
ApplicationController.instance.networkService
}
val SqnetworkService: SqNetworkService by lazy {
ApplicationController.instance.SqnetworkService
}
companion object {
private var instance : FriendListFragment?=null
@Synchronized
fun getInstance(size : String) :FriendListFragment{
if(instance==null) {
instance = FriendListFragment().apply {
arguments=Bundle().apply {
putString("size", FriendData.size.toString())
}
}
}
return instance!!
}
val FriendData : ArrayList<FriendData> by lazy {
ArrayList<FriendData>()
}
}
lateinit var BirthdayFriendListRecyclerViewAdapter: BirthdayFriendListRecyclerViewAdapter
lateinit var FavoriteFriendListRecyclerViewAdapter: FavoriteFriendListRecyclerViewAdapter
lateinit var FriendListRecyclerViewAdapter: FriendListRecyclerViewAdapter
val BirthdayFriendData : ArrayList<BirthdayFriendData> by lazy {
ArrayList<BirthdayFriendData>()
}
val FavoriteFriendData : ArrayList<FavoriteFriendData> by lazy {
ArrayList<FavoriteFriendData>()
}
override fun onPause() {
super.onPause()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val homeFragmentView: View = inflater!!.inflate(R.layout.activity_friend_list_fragment, container, false)
BirthdayFriendListRecyclerViewAdapter=
BirthdayFriendListRecyclerViewAdapter(context!!, BirthdayFriendData)
BirthdayFriendData.add(BirthdayFriendData("김무현", "4월 28일 생일입니다!"))
homeFragmentView.rl_friend_list_birthdatpeople.adapter = BirthdayFriendListRecyclerViewAdapter
homeFragmentView.rl_friend_list_birthdatpeople.layoutManager = LinearLayoutManager(context!!)
getFavoriteFriendListpost()
getFriendListpost()
val simpleItemTouchCallback =
object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
toast("on Move")
return true
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {
val position = viewHolder.adapterPosition
deleteFriendPost(FriendData[position].Email.toString())
FriendData.removeAt(position)
FriendListRecyclerViewAdapter.notifyItemRemoved(position)
tv_friend_list_count.setText(FriendData.size.toString())
}
}
val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback)
itemTouchHelper.attachToRecyclerView(homeFragmentView.rl_friend_list_listpeople)
return homeFragmentView
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
/* if (SharedPreferenceController.getIMAGE(ctx).isNotEmpty()){ //통신 이전 부분
val decodedString = Base64.decode(SharedPreferenceController.getIMAGE(ctx), Base64.DEFAULT)
val decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
iv_friend_mypicture.setImageBitmap(decodedByte)
}*/
iv_friend_addid.setOnClickListener {
/* val fragment = FriendListFragment() // Fragment 생성
val bundle = Bundle(1) // 파라미터는 전달할 데이터 개수
bundle.putString("size", FriendData.size.toString())
fragment.setArguments(bundle)*/
var intent = Intent(ctx,AddKakaotalkIdActivity::class.java)
intent.putExtra("size", FriendData.size)
startActivity(intent)
}
ll_friend_addfriend.visibility = View.GONE
iv_friend_finishaddfriend.setOnClickListener {
ll_friend_addfriend.visibility = View.GONE //친구추가 X 버튼
rl_friend_color.visibility = View.GONE
}
rl_friend_color.visibility = View.GONE
iv_friend_plusfriend.setOnClickListener {
ll_friend_addfriend.visibility = View.VISIBLE
rl_friend_color.visibility = View.VISIBLE
}
rl_friend_color.setOnClickListener {
ll_friend_addfriend.visibility = View.GONE //친구추가 X 버튼
rl_friend_color.visibility = View.GONE
}
iv_friend_birthdayfriendlis_button.setOnClickListener {
if (rl_friend_list_birthdatpeople.visibility == View.VISIBLE) {
iv_friend_birthdayfriendlis_button.setImageResource(R.drawable.downbutton)
rl_friend_list_birthdatpeople.visibility = View.GONE
} else if (rl_friend_list_birthdatpeople.visibility == View.GONE) {
iv_friend_birthdayfriendlis_button.setImageResource(R.drawable.upbutton)
rl_friend_list_birthdatpeople.visibility = View.VISIBLE
}
}
iv_friend_favorite_button.setOnClickListener {
if (rl_friend_list_favoritepeople.visibility == View.VISIBLE) {
rl_friend_list_favoritepeople.visibility = View.GONE
iv_friend_favorite_button.setImageResource(R.drawable.downbutton)
} else if (rl_friend_list_favoritepeople.visibility == View.GONE) {
rl_friend_list_favoritepeople.visibility = View.VISIBLE
iv_friend_favorite_button.setImageResource(R.drawable.upbutton)
}
}
iv_friend_recommend_button.setOnClickListener {
if (rl_friend_list_recommend.visibility == View.VISIBLE) {
rl_friend_list_recommend.visibility = View.GONE
iv_friend_recommend_button.setImageResource(R.drawable.downbutton)
} else if (rl_friend_list_recommend.visibility == View.GONE) {
rl_friend_list_recommend.visibility = View.VISIBLE
iv_friend_recommend_button.setImageResource(R.drawable.upbutton)
}
}
iv_friend_plus_button.setOnClickListener {
if (rl_friend_list_plus.visibility == View.VISIBLE) {
rl_friend_list_plus.visibility = View.GONE
iv_friend_plus_button.setImageResource(R.drawable.downbutton)
} else if (rl_friend_list_plus.visibility == View.GONE) {
rl_friend_list_plus.visibility = View.VISIBLE
iv_friend_plus_button.setImageResource(R.drawable.upbutton)
}
}
iv_friend_list_button.setOnClickListener {
if (rl_friend_list_listpeople.visibility == View.VISIBLE) {
rl_friend_list_listpeople.visibility = View.GONE
iv_friend_list_button.setImageResource(R.drawable.downbutton)
} else if (rl_friend_list_listpeople.visibility == View.GONE) {
rl_friend_list_listpeople.visibility = View.VISIBLE
iv_friend_list_button.setImageResource(R.drawable.upbutton)
}
}
rl_friend_list_myprofile.setOnClickListener {
val intent = Intent(ctx, MyprofileActivity::class.java)
ctx.startActivity(intent)
(ctx as MainActivity).overridePendingTransition(R.anim.sliding_up, R.anim.stay)
}
if (SharedPreferenceController.getKaKaOAuthorization(ctx).isNotEmpty()) { //카카오 로그인일때 통신
getUserKAKAOInfoPost()
} else if(SharedPreferenceController.getSQAuthorization(ctx).isNotEmpty()){
getMyProfile() //sq 통신
getMyprofilePost()
}
}
override fun onResume() {
super.onResume()
ll_friend_addfriend.visibility=View.GONE //친구추가 X 버튼
rl_friend_color.visibility=View.GONE
getFriendListpost()
getMyProfile()
getFavoriteFriendListpost()
/* if (SharedPreferenceController.getIMAGE(ctx).isNotEmpty()){ //통신전 사진 이미지
val decodedString = Base64.decode(SharedPreferenceController.getIMAGE(ctx), Base64.DEFAULT)
val decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.size)
iv_friend_mypicture.setImageBitmap(decodedByte)
}*/
}
fun getFriendListpost() {
var getFriendListResponse : Call<GetFriendResponse> = SqnetworkService.getFriendResponse("application/json",SharedPreferenceController.getSQAuthorization(ctx))
getFriendListResponse.enqueue(object : Callback<GetFriendResponse> {
override fun onResponse(call: Call<GetFriendResponse>?, response: Response<GetFriendResponse>?) {
Log.v("TAG", "친구목록 불러오기")
if (response!!.isSuccessful) {
FriendData.clear()
val FriendDataList = response.body()!!.result!!
for (i in 0..FriendDataList.size - 1) {
FriendData.add(FriendData(FriendDataList[i].Name,FriendDataList[i].Email,FriendDataList[i].Prof_img,FriendDataList[i].Back_img,FriendDataList[i]?.Status))
}
FriendListRecyclerViewAdapter= FriendListRecyclerViewAdapter(context!!, FriendData)
rl_friend_list_listpeople.adapter = FriendListRecyclerViewAdapter
rl_friend_list_listpeople.layoutManager = LinearLayoutManager(context!!)
tv_friend_list_count.setText(FriendData.size.toString())
}else {
}
}
override fun onFailure(call: Call<GetFriendResponse>?, t: Throwable?) {
Log.v("TAG", "통신 실패 = " + t.toString())
toast("통신실패")
}
})
}
fun getFavoriteFriendListpost() {
var getFavoriteFriendListResponse : Call<GetFavoriteResponse> = SqnetworkService.getFavoriteResponse("application/json",SharedPreferenceController.getSQAuthorization(ctx))
getFavoriteFriendListResponse.enqueue(object : Callback<GetFavoriteResponse> {
override fun onResponse(call: Call<GetFavoriteResponse>?, response: Response<GetFavoriteResponse>?) {
Log.v("TAG", "친구목록 불러오기")
if (response!!.isSuccessful) {
FavoriteFriendData.clear()
val FavoriteFriendDataList = response.body()!!.result!!
for (i in 0..FavoriteFriendDataList.size-1) {
FavoriteFriendData.add(FavoriteFriendData(FavoriteFriendDataList[i].Email,FavoriteFriendDataList[i].Name,FavoriteFriendDataList[i].Prof_img,FavoriteFriendDataList[i].Back_img,FavoriteFriendDataList[i]?.Status))
}
FavoriteFriendListRecyclerViewAdapter= FavoriteFriendListRecyclerViewAdapter(context!!, FavoriteFriendData)
rl_friend_list_favoritepeople.adapter = FavoriteFriendListRecyclerViewAdapter
rl_friend_list_favoritepeople.layoutManager = LinearLayoutManager(context!!)
}else {
}
}
override fun onFailure(call: Call<GetFavoriteResponse>?, t: Throwable?) {
Log.v("TAG", "통신 실패 = " + t.toString())
toast("통신실패")
}
})
}
fun deleteFriendPost(Friend_Email:String){
var jsonObject = JSONObject()
jsonObject.put("Friend_Email",Friend_Email)
val gsonObject = JsonParser().parse(jsonObject.toString()) as JsonObject
var deleteFriendResponse: Call<DeleteFriendInfoResponse> = SqnetworkService.deleteFriendInfoResponse("application/json",
SharedPreferenceController.getSQAuthorization(ctx),gsonObject)
deleteFriendResponse.enqueue(object : Callback<DeleteFriendInfoResponse> {
override fun onResponse(call: Call<DeleteFriendInfoResponse>?, response: Response<DeleteFriendInfoResponse>?) {
Log.v("TAG", "삭제")
if (response!!.isSuccessful) {
if(response.body()!!.message=="성공") {
toast("차단완료")
}
}
}
override fun onFailure(call: Call<DeleteFriendInfoResponse>?, t: Throwable?) {
Log.v("TAG", "통신 실패 = " +t.toString())
}
})
}
fun getMyprofilePost(){
var jsonObject = JSONObject()
jsonObject.put("Email",SharedPreferenceController.getEmail(ctx))
jsonObject.put("Pw", SharedPreferenceController.getPW(ctx))
//Gson 라이브러리의 Json Parser을 통해 객체를 Json으로!
val gsonObject = JsonParser().parse(jsonObject.toString()) as JsonObject
var postLoginResponse: Call<PostLoginResponse> = SqnetworkService.postLoginResponse("application/json",gsonObject)
postLoginResponse.enqueue(object : Callback<PostLoginResponse> {
override fun onResponse(call: Call<PostLoginResponse>?, response: Response<PostLoginResponse>?) {
Log.v("TAG", "보드 서버 통신 연결")
if (response!!.isSuccessful) {
if(response.body()!!.message=="성공") {
tv_friend_myname.setText(response.body()!!.result[0].Name.toString())
}
}
}
override fun onFailure(call: Call<PostLoginResponse>?, t: Throwable?) {
Log.v("TAG", "통신 실패 = " +t.toString())
}
})
}
fun getMyProfile(){
var getProfileResponse: Call<GetprofileResponse> = SqnetworkService.getprofileResponse("application/json",SharedPreferenceController.getSQAuthorization(ctx))
getProfileResponse.enqueue(object : Callback<GetprofileResponse> {
override fun onResponse(call: Call<GetprofileResponse>?, response: Response<GetprofileResponse>?) {
if (response!!.isSuccessful) {
if(response.body()!!.message=="성공"){
rv_tv_friend_friendcontents.setText(response.body()!!.result.Status.toString())
Glide.with(ctx).load(response.body()!!.result.Prof_img.toString()).into(iv_friend_mypicture)
}
}
else{
Log.v("TAG", "채팅 실패")
}
}
override fun onFailure(call: Call<GetprofileResponse>?, t: Throwable?) {
Log.v("TAG", "통신 실패 = " +t.toString())
}
})
}
fun getUserKAKAOInfoPost(){
var getUserInfomationResponse: Call<GetUserInfomationResponse> = networkService.getUserInfomationResponse("Bearer "+SharedPreferenceController.getKaKaOAuthorization(ctx))
getUserInfomationResponse.enqueue(object : Callback<GetUserInfomationResponse> {
override fun onResponse(call: Call<GetUserInfomationResponse>?, response: Response<GetUserInfomationResponse>?) {
Log.v("TAG", "보드 서버 통신 연결")
if (response!!.isSuccessful) {
tv_friend_myname.text = response.body()!!.properties.nickname
Glide.with(ctx).load(response.body()!!.properties.profile_image.toString()).into(iv_friend_mypicture)
}
else{
Log.v("TAG", "마이페이지 서버 값 전달 실패")
}
}
override fun onFailure(call: Call<GetUserInfomationResponse>?, t: Throwable?) {
Log.v("TAG", "통신 실패 = " +t.toString())
}
})
}
} | 0 | Kotlin | 1 | 0 | 8ae2c8bd8f693694be275eb884ca1cf726acfe83 | 17,780 | kakaotalk_mock_android_mudol | MIT License |
kotlin/src/nativeMain/kotlin/main.kt | emmabritton | 358,239,150 | false | {"Rust": 18706, "Kotlin": 13302, "JavaScript": 8960} | fun main(args: Array<String>) {
start(args)
} | 0 | Rust | 0 | 0 | c041d145c9ac23ce8d7d7f48e419143c73daebda | 49 | advent-of-code | MIT License |
examples/src/main/kotlin/basic/scatter/DataLabelsHover.kt | jfftonsic | 232,934,146 | true | {"Kotlin": 38288, "JavaScript": 2633} | package basic.scatter
import scientifik.plotly.Plotly
import scientifik.plotly.makeFile
import scientifik.plotly.models.Mode
import scientifik.plotly.models.Type
import scientifik.plotly.trace
fun main() {
val plot = Plotly.plot2D {
trace {
x = listOf(1, 2, 3, 4)
y = listOf(10, 15, 13, 17)
mode = Mode.markers
type = Type.scatter
name = "Team A"
text = listOf("A-1", "A-2", "A-3", "A-4", "A-5")
marker { size = 12 }
}
trace {
x = listOf(2, 3, 4, 5)
y = listOf(10, 15, 13, 17)
mode = Mode.lines
type = Type.scatter
name = "Team B"
text = listOf("B-a", "B-b", "B-c", "B-d", "B-e")
marker { size = 12 }
}
layout {
title = "Data Labels Hover"
xaxis {
range = 0.75 to 5.25
}
yaxis {
range = 0.0 to 8.0
}
}
}
plot.makeFile()
}
| 0 | null | 0 | 0 | e2ffdea55d9149b0b07e764f67206619f0374c4b | 1,045 | plotly.kt | Apache License 2.0 |
kraken/src/main/kotlin/glitch/kraken/object/json/impl/channel.kt | GlitchLib | 146,582,041 | false | null | package glitch.kraken.`object`.json.impl
import com.google.gson.annotations.SerializedName
import glitch.api.objects.enums.BroadcasterType
import glitch.kraken.`object`.json.AuthChannel
import glitch.kraken.`object`.json.Channel
import java.awt.Color
import java.time.Instant
import java.util.*
/**
*
* @author Damian Staszewski [[email protected]]
* @version %I%, %G%
* @since 1.0
*/
data class ChannelImpl(
@SerializedName(value = "id", alternate = ["_id"])
override val id: Long,
@SerializedName(value = "username", alternate = ["login", "name"])
override val username: String,
override val displayName: String,
override val createdAt: Instant,
override val updatedAt: Instant,
override val logo: String,
override val mature: Boolean,
@SerializedName("status")
override val title: String,
override val broadcasterLanguage: Locale,
override val game: String,
override val language: Locale,
override val partner: Boolean,
override val videoBanner: String,
override val profileBanner: String,
override val profileBannerBackgroundColor: Color,
override val url: String,
override val views: Long,
override val followers: Long
) : Channel
/**
*
* @author Damian Staszewski [[email protected]]
* @version %I%, %G%
* @since 1.0
*/
data class AuthChannelImpl(
@SerializedName(value = "id", alternate = ["_id"])
override val id: Long,
@SerializedName(value = "username", alternate = ["login", "name"])
override val username: String,
override val displayName: String,
override val createdAt: Instant,
override val updatedAt: Instant,
override val logo: String,
override val mature: Boolean,
@SerializedName("status")
override val title: String,
override val broadcasterLanguage: Locale,
override val game: String,
override val language: Locale,
override val partner: Boolean,
override val videoBanner: String,
override val profileBanner: String,
override val profileBannerBackgroundColor: Color,
override val url: String,
override val views: Long,
override val followers: Long,
override val broadcasterType: BroadcasterType,
override val email: String,
override val streamKey: String
) : AuthChannel | 15 | null | 3 | 12 | 81283227ee6c3b63866fe1371959a72f8b0d2640 | 2,478 | glitch | MIT License |
sample/src/test/java/me/lazy_assedninja/sample/repository/RoomRepositoryTest.kt | henryhuang1219 | 357,838,778 | false | null | package me.lazy_assedninja.sample.repository
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import me.lazy_assedninja.sample.common.TestUtil
import me.lazy_assedninja.sample.db.RoomDb
import me.lazy_assedninja.sample.db.UserDao
import me.lazy_assedninja.sample.vo.User
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.Mockito.*
@RunWith(JUnit4::class)
class RoomRepositoryTest {
private val dao = mock(UserDao::class.java)
private lateinit var repository: RoomRepository
private lateinit var testUser: User
@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
@Before
fun init() {
val db = mock(RoomDb::class.java)
`when`(db.userDao()).thenReturn(dao)
`when`(db.runInTransaction(any())).thenCallRealMethod()
repository = RoomRepository(db, dao)
testUser = TestUtil.createUser(
id = 1L,
name = "Lazy-assed Ninja",
email = "<EMAIL>",
password = "<PASSWORD>"
)
}
@Test
fun insertUsers() {
repository.insertUsers(testUser)
verify(dao).insertUsers(testUser)
}
@Test
fun updateUsers() {
repository.updateUsers(testUser)
verify(dao).updateUsers(testUser)
}
@Test
fun deleteUsers() {
repository.deleteUsers(testUser)
verify(dao).deleteUsers(testUser)
}
@Test
fun getUser() {
val dbData = MutableLiveData<User>()
`when`(dao.getUser(1L)).thenReturn(dbData)
repository.getUser(1L)
verify(dao).getUser(1L)
}
@Test
fun loadAllUsers() {
val dbData = MutableLiveData<List<User>>()
`when`(dao.loadAllUsers()).thenReturn(dbData)
repository.loadAllUsers()
verify(dao).loadAllUsers()
}
} | 0 | Kotlin | 0 | 0 | 1764dc963f179b2710f189aebf5c45664d51daad | 1,963 | Android-Demo | Apache License 2.0 |
platform/lang-impl/testSources/com/intellij/openapi/roots/ModuleLevelLibrariesInRootModelTest.kt | tonyroberts | 264,702,177 | false | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.roots.impl.libraries.LibraryTableImplUtil
import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar
import com.intellij.testFramework.ApplicationRule
import com.intellij.testFramework.assertions.Assertions.assertThat
import com.intellij.testFramework.rules.ProjectModelRule
import org.junit.Before
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
@Suppress("UsePropertyAccessSyntax")
class ModuleLevelLibrariesInRootModelTest {
companion object {
@JvmField
@ClassRule
val appRule = ApplicationRule()
}
@Rule
@JvmField
val projectModel = ProjectModelRule()
lateinit var module: Module
@Before
fun setUp() {
module = projectModel.createModule()
}
@Test
fun `add edit remove unnamed module library`() {
run {
val model = createModifiableModel(module)
val library = model.moduleLibraryTable.createLibrary()
assertThat(model.moduleLibraryTable.libraries.single()).isEqualTo(library)
val libraryEntry = dropModuleSourceEntry(model, 1).single() as LibraryOrderEntry
assertThat(libraryEntry.isModuleLevel).isTrue()
assertThat(libraryEntry.libraryName).isNull()
assertThat(libraryEntry.library).isEqualTo(library)
assertThat(libraryEntry.scope).isEqualTo(DependencyScope.COMPILE)
assertThat(libraryEntry.isExported).isFalse()
assertThat(libraryEntry.libraryLevel).isEqualTo(LibraryTableImplUtil.MODULE_LEVEL)
assertThat(model.findLibraryOrderEntry(library)).isEqualTo(libraryEntry)
assertThat((library as LibraryEx).isDisposed).isFalse()
val committed = commitModifiableRootModel(model)
val committedEntry = dropModuleSourceEntry(committed, 1).single() as LibraryOrderEntry
assertThat(committedEntry.scope).isEqualTo(DependencyScope.COMPILE)
assertThat(committedEntry.isExported).isFalse()
assertThat(committedEntry.isModuleLevel).isTrue()
assertThat(committedEntry.libraryName).isNull()
assertThat(committedEntry.library).isEqualTo(library)
assertThat(committedEntry.libraryLevel).isEqualTo(LibraryTableImplUtil.MODULE_LEVEL)
assertThat(library.isDisposed).isTrue()
assertThat((committedEntry.library as LibraryEx).isDisposed).isFalse()
}
val root = projectModel.baseProjectDir.newVirtualDirectory("lib")
run {
val model = createModifiableModel(module)
val library = model.moduleLibraryTable.libraries.single()
val libraryModel = library.modifiableModel
libraryModel.addRoot(root, OrderRootType.CLASSES)
libraryModel.commit()
val libraryEntry = dropModuleSourceEntry(model, 1).single() as LibraryOrderEntry
assertThat(libraryEntry.getFiles(OrderRootType.CLASSES).single()).isEqualTo(root)
libraryEntry.scope = DependencyScope.RUNTIME
libraryEntry.isExported = true
assertThat(model.findLibraryOrderEntry(library)).isEqualTo(libraryEntry)
val committed = commitModifiableRootModel(model)
val committedEntry = dropModuleSourceEntry(committed, 1).single() as LibraryOrderEntry
assertThat(committedEntry.getFiles(OrderRootType.CLASSES).single()).isEqualTo(root)
assertThat((library as LibraryEx).isDisposed).isTrue()
assertThat((committedEntry.library as LibraryEx).isDisposed).isFalse()
assertThat(committedEntry.scope).isEqualTo(DependencyScope.RUNTIME)
assertThat(committedEntry.isExported).isTrue()
}
run {
val model = createModifiableModel(module)
val library = model.moduleLibraryTable.libraries.single()
model.moduleLibraryTable.removeLibrary(library)
assertThat(model.moduleLibraryTable.libraries).isEmpty()
assertThat(model.orderEntries).hasSize(1)
assertThat(model.findLibraryOrderEntry(library)).isNull()
val committed = commitModifiableRootModel(model)
assertThat(committed.orderEntries).hasSize(1)
assertThat((library as LibraryEx).isDisposed).isTrue()
}
}
@Test
fun `add rename remove module library`() {
run {
val model = createModifiableModel(module)
val library = model.moduleLibraryTable.createLibrary("foo")
assertThat(model.moduleLibraryTable.libraries.single()).isEqualTo(library)
val libraryEntry = dropModuleSourceEntry(model, 1).single() as LibraryOrderEntry
assertThat(libraryEntry.libraryName).isEqualTo("foo")
assertThat(libraryEntry.library).isEqualTo(library)
val committed = commitModifiableRootModel(model)
val committedEntry = dropModuleSourceEntry(committed, 1).single() as LibraryOrderEntry
assertThat(committedEntry.libraryName).isEqualTo("foo")
assertThat(committedEntry.library).isEqualTo(library)
}
run {
val model = createModifiableModel(module)
val library = model.moduleLibraryTable.libraries.single()
val libraryModel = library.modifiableModel
libraryModel.name = "bar"
libraryModel.commit()
val libraryEntry = dropModuleSourceEntry(model, 1).single() as LibraryOrderEntry
assertThat(libraryEntry.libraryName).isEqualTo("bar")
val committed = commitModifiableRootModel(model)
val committedEntry = dropModuleSourceEntry(committed, 1).single() as LibraryOrderEntry
assertThat(committedEntry.libraryName).isEqualTo("bar")
}
run {
val model = createModifiableModel(module)
val libraryEntry = dropModuleSourceEntry(model, 1).single() as LibraryOrderEntry
model.removeOrderEntry(libraryEntry)
assertThat(model.moduleLibraryTable.libraries).isEmpty()
assertThat(model.orderEntries).hasSize(1)
val committed = commitModifiableRootModel(model)
assertThat(committed.orderEntries).hasSize(1)
}
}
@Test
fun `add module library and dispose`() {
val model = createModifiableModel(module)
val library = model.moduleLibraryTable.createLibrary("foo")
val libraryEntry = dropModuleSourceEntry(model, 1).single() as LibraryOrderEntry
assertThat(libraryEntry.library).isEqualTo(library)
model.dispose()
dropModuleSourceEntry(ModuleRootManager.getInstance(module), 0)
assertThat((library as LibraryEx).isDisposed).isTrue()
}
} | 1 | null | 1 | 1 | fa602b2874ea4eb59442f9937b952dcb55910b6e | 6,530 | intellij-community | Apache License 2.0 |
fluxo-core/src/commonMain/kotlin/kt/fluxo/core/SideEffectsStrategy.kt | fluxo-kt | 566,869,438 | false | null | @file:Suppress("CanSealedSubClassBeObject")
package kt.fluxo.core
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.receiveAsFlow
import kt.fluxo.core.SideEffectsStrategy.RECEIVE
import kt.fluxo.core.annotation.InternalFluxoApi
import kotlin.jvm.JvmField
/**
* Strategies for side effects sharing from the [Store].
* When in doubt, use the [default][RECEIVE] one.
*/
public sealed interface SideEffectsStrategy {
/**
* [Channel]-based strategy with sharing through the [receiveAsFlow].
* Default choice.
* Supports multiple subscribers.
* One side effect emitted to one subscriber only and **the order of subscribers unspecified**.
*
* @see kotlinx.coroutines.flow.receiveAsFlow
* @see SHARE
* @see CONSUME
*/
public object RECEIVE : SideEffectsStrategy {
/** @hide */
@InternalFluxoApi
override fun toString(): String = "RECEIVE"
}
/**
* [Channel]-based strategy with sharing through the [consumeAsFlow].
*
* **Restricts the count of subscribers to 1**. Consumes the underlying [Channel] completely on the first subscription from the flow!
* The resulting flow can be collected only once and throws [IllegalStateException] when trying to collect it more than once.
*
* Attempting to subscribe or resubscribe to side effects from an already subscribed [Store] result in an exception.
* Requires creating of a new [Store] for each subscriber!
*
* **In the most cases you need [RECEIVE] or [SHARE] strategies instead of this one!**
*
* @see kotlinx.coroutines.flow.consumeAsFlow
* @see RECEIVE
* @see SHARE
*/
public object CONSUME : SideEffectsStrategy {
/** @hide */
@InternalFluxoApi
override fun toString(): String = "CONSUME"
}
/**
* [MutableSharedFlow]-based strategy. Shares emitted side effects among all subscribers in a broadcast fashion,
* so that all collectors get all emitted side effects.
*
* Keeps a [specified number][replay] of the most recent values in its replay cache. Every new subscriber first gets
* the values from the replay cache and then gets new emitted values.
*
* @param replay the number of side effects replayed to new subscribers (can't be negative, defaults to zero).
*
* @see kotlinx.coroutines.flow.MutableSharedFlow
*/
public class SHARE(
@JvmField
public val replay: Int,
) : SideEffectsStrategy {
public constructor() : this(replay = 0)
/** @hide */
@InternalFluxoApi
override fun toString(): String = "SHARE(replay=$replay)"
/** @hide */
@InternalFluxoApi
override fun equals(other: Any?): Boolean = this === other || other is SHARE && replay == other.replay
/** @hide */
@InternalFluxoApi
override fun hashCode(): Int = replay
}
/**
* Completely turns off side effects.
* Saves a bit of app memory, and sometimes brain cells (as a purer way is to use only state & intents).
*/
public object DISABLE : SideEffectsStrategy {
/** @hide */
@InternalFluxoApi
override fun toString(): String = "DISABLE"
}
}
| 9 | Kotlin | 1 | 5 | 475f65186b273f02e875c59176dd3a4af0b0365f | 3,373 | fluxo-mvi | Apache License 2.0 |
shared/src/commonTest/kotlin/pw/binom/proxy/StreamBridgeTest.kt | caffeine-mgn | 655,800,935 | false | {"Kotlin": 257491, "Shell": 43} | package pw.binom
import pw.binom.io.*
import pw.binom.network.SocketClosedException
import pw.binom.proxy.readBinary
import pw.binom.proxy.testChannel
import pw.binom.proxy.writeBinary
import pw.binom.testing.Testing
import pw.binom.testing.shouldContentEquals
import pw.binom.testing.shouldEquals
import kotlin.random.Random
import kotlin.test.Test
class StreamBridgeTest {
@Test
fun simpleCopyTest() = Testing.async {
val inputData = Random.nextBytes(1024 * 1024 * 2)
var len = 0uL
ByteArrayInput(inputData).use { input ->
val output = ByteArrayOutput()
val copyResult = ByteBuffer(DEFAULT_BUFFER_SIZE).use { buffer ->
StreamBridge.copy(
left = input.asyncInput(),
right = output.asyncOutput(),
buffer = buffer,
sizeProvider = { len = it },
)
}
output.toByteArray() shouldContentEquals inputData
len shouldEquals inputData.size.toULong()
copyResult shouldEquals StreamBridge.ReasonForStopping.LEFT
}
}
@Test
fun outputClosedTest() = Testing.async {
val inputData = Random.nextBytes(1024 * 1024 * 2)
var len = 0uL
val maxLen = DEFAULT_BUFFER_SIZE * 2
ByteArrayInput(inputData).use { input ->
val output = OutputWithLimit(maxLen)
val copyResult = ByteBuffer(DEFAULT_BUFFER_SIZE).use { buffer ->
StreamBridge.copy(
left = input.asyncInput(),
right = output.asyncOutput(),
buffer = buffer,
sizeProvider = { len = it },
)
}
output.toByteArray() shouldContentEquals inputData.copyOf(maxLen)
len shouldEquals maxLen.toULong()
copyResult shouldEquals StreamBridge.ReasonForStopping.RIGHT
}
}
@Test
fun testing() = Testing.async {
val inputData1 = Random.nextBytes(100)
val inputData2 = Random.nextBytes(200)
val inputData3 = Random.nextBytes(300)
var left: AsyncChannel? = null
var right: AsyncChannel? = null
test("multi-direction coping") {
left = testChannel {
writeBinary(inputData1)
readBinary(inputData1.size) shouldContentEquals inputData1
writeBinary(inputData2)
readBinary(inputData2.size) shouldContentEquals inputData2
writeBinary(inputData3)
readBinary(inputData3.size) shouldContentEquals inputData3
}
right = testChannel {
readBinary(inputData1.size) shouldContentEquals inputData1
writeBinary(inputData1)
readBinary(inputData2.size) shouldContentEquals inputData2
writeBinary(inputData2)
readBinary(inputData3.size) shouldContentEquals inputData3
writeBinary(inputData3)
}
}
StreamBridge.sync(
left = left!!,
right = right!!,
bufferSize = 100
)
}
class OutputWithLimit(val maxLen: Int) : ByteArrayOutput() {
override fun write(data: ByteBuffer): DataTransferSize {
if (this.size >= maxLen) {
throw SocketClosedException()
}
return super.write(data)
}
}
}
| 0 | Kotlin | 0 | 0 | de01d70de0dc9461183c2b82de63824cabfa5076 | 3,471 | proxy-bridge | Apache License 2.0 |
pumping/src/main/kotlin/com/dpm/pumping/workout/repository/WorkoutRepository.kt | depromeet | 627,802,875 | false | null | package com.dpm.pumping.workout.repository
import com.dpm.pumping.workout.domain.entity.Workout
import org.springframework.data.mongodb.repository.MongoRepository
import java.time.LocalDateTime
interface WorkoutRepository : MongoRepository<Workout, String> {
fun findAllByCurrentCrewAndUserIdAndCreateDateBetween(
crewId: String, userId: String, startDate: LocalDateTime, endDate: LocalDateTime
): List<Workout>?
fun deleteAllByUserId(userId: String)
}
| 3 | Kotlin | 0 | 2 | 366e951c11eafc9369aa0095337579ffb23f7ec6 | 477 | pumping-server | Apache License 2.0 |
processor/src/main/java/io/michaelrocks/lightsaber/processor/generation/model/KeyRegistry.kt | MichaelRocks | 33,447,127 | false | null | /*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.generation.model
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.lightsaber.processor.model.Dependency
data class KeyRegistry(
val type: Type.Object,
val keys: Map<Dependency, Key>
)
| 2 | null | 8 | 121 | 802be34a7f294848379a4889009ed6de260661f7 | 841 | lightsaber | Apache License 2.0 |
libs/kotlin-reflection/src/main/kotlin/net/corda/kotlin/reflect/types/JavaFunction.kt | corda | 346,070,752 | false | {"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.kotlin.reflect.types
import java.lang.reflect.Method
import java.util.Objects
import kotlin.reflect.KParameter
import kotlin.reflect.KType
import kotlin.reflect.KTypeParameter
import kotlin.reflect.KVisibility
import kotlin.reflect.full.starProjectedType
class JavaFunction<V>(
override val javaMethod: Method,
private val instanceClass: Class<*>
): KFunctionInternal<V>, Function<V> {
override val annotations: List<Annotation>
get() = TODO("Not yet implemented")
override val isAbstract: Boolean
get() = isAbstract(javaMethod)
override val isFinal: Boolean
get() = isFinal(javaMethod)
override val isOpen: Boolean
get() = isOpen(javaMethod)
override val isExternal: Boolean
get() = false
override val isInfix: Boolean
get() = false
override val isInline: Boolean
get() = false
override val isOperator: Boolean
get() = false
override val isSuspend: Boolean
get() = false
override val name: String
get() = javaMethod.name
override val parameters: List<KParameter>
get() = javaMethod.createParameters(instanceClass, isExtension = false, emptyList())
override val returnType: KType
get() = javaMethod.returnType.kotlin.starProjectedType
override val typeParameters: List<KTypeParameter>
get() = TODO("Not yet implemented")
override val visibility: KVisibility?
get() = getVisibility(javaMethod)
override val signature: MemberSignature
get() = javaMethod.toSignature()
override fun asFunctionFor(instanceClass: Class<*>, isExtension: Boolean) = JavaFunction<V>(javaMethod, instanceClass)
override fun withJavaMethod(method: Method) = JavaFunction<V>(method, instanceClass)
override fun call(vararg args: Any?): V {
TODO("JavaFunction.call(): Not yet implemented")
}
override fun callBy(args: Map<KParameter, Any?>): V {
TODO("JavaFunction.callBy(): Not yet implemented")
}
override fun equals(other: Any?): Boolean {
return when {
other === this -> true
other !is JavaFunction<*> -> false
else -> name == other.name && javaMethod == other.javaMethod
}
}
override fun hashCode(): Int {
return Objects.hash(name, javaMethod)
}
override fun toString(): String {
return "fun $name: $javaMethod"
}
}
| 11 | Kotlin | 27 | 69 | d478e119ab288af663910f9a2df42a7a7b9f5bce | 2,439 | corda-runtime-os | Apache License 2.0 |
app/src/main/kotlin/com/lightteam/modpeide/ui/settings/fragments/AboutFragment.kt | ArtyomSilchenko | 276,799,927 | true | {"Kotlin": 599951, "HTML": 11957} | /*
* Licensed to the Light Team Software (Light Team) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The Light Team licenses this file to You 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.lightteam.modpeide.ui.settings.fragments
import android.os.Bundle
import android.view.View
import androidx.navigation.NavController
import androidx.navigation.fragment.findNavController
import androidx.preference.Preference
import com.lightteam.modpeide.BuildConfig
import com.lightteam.modpeide.R
import com.lightteam.modpeide.ui.base.fragments.DaggerPreferenceFragmentCompat
import com.lightteam.modpeide.utils.extensions.isUltimate
class AboutFragment : DaggerPreferenceFragmentCompat() {
companion object {
private const val KEY_ABOUT_AND_CHANGELOG = "ABOUT_AND_CHANGELOG"
private const val KEY_PRIVACY_POLICY = "PRIVACY_POLICY"
}
private lateinit var navController: NavController
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
navController = findNavController()
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preference_about, rootKey)
val isUltimate = requireContext().isUltimate()
val changelog = findPreference<Preference>(KEY_ABOUT_AND_CHANGELOG)
changelog?.setOnPreferenceClickListener {
navController.navigate(R.id.changeLogDialog)
true
}
if (isUltimate) {
changelog?.setTitle(R.string.pref_about_ultimate_title)
}
changelog?.summary = String.format(
getString(R.string.pref_about_summary),
BuildConfig.VERSION_NAME,
BuildConfig.VERSION_CODE
)
val privacy = findPreference<Preference>(KEY_PRIVACY_POLICY)
privacy?.setOnPreferenceClickListener {
navController.navigate(R.id.privacyPolicyDialog)
true
}
}
} | 0 | null | 0 | 0 | 58e293bd68d06647a80377f2d2b19cf747239a7c | 2,640 | ModPE-IDE | Apache License 2.0 |
app/src/main/kotlin/org/cuberite/android/MainActivity.kt | cuberite | 73,719,506 | false | {"Kotlin": 96820} | package org.cuberite.android
import android.Manifest
import android.content.SharedPreferences
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.activity.result.contract.ActivityResultContracts.RequestPermission
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.systemBars
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Icon
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.core.content.edit
import androidx.lifecycle.compose.LifecycleResumeEffect
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import org.cuberite.android.extension.isExternalStorageGranted
import org.cuberite.android.ui.console.navigation.navigateToConsole
import org.cuberite.android.ui.control.navigation.navigateToControl
import org.cuberite.android.ui.navigation.CuberiteNavGraph
import org.cuberite.android.ui.navigation.TopLevelNavigation
import org.cuberite.android.ui.navigation.TopLevelNavigation.Console
import org.cuberite.android.ui.navigation.TopLevelNavigation.Control
import org.cuberite.android.ui.navigation.TopLevelNavigation.Settings
import org.cuberite.android.ui.settings.navigation.navigateToSettings
import org.cuberite.android.ui.theme.CuberiteTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
enableEdgeToEdge()
super.onCreate(savedInstanceState)
setContent {
CuberiteTheme {
Cuberite()
}
}
}
}
@Composable
fun Cuberite() {
val navController = rememberNavController()
val navBackStackEntry by navController.currentBackStackEntryAsState()
val currentDestination = navBackStackEntry?.destination
val permissionLauncher = rememberLauncherForActivityResult(RequestPermission()) { isGranted ->
MainApplication.preferences.edit {
if (isGranted) {
putString("cuberiteLocation", "${MainApplication.publicDir}/cuberite-server")
} else {
putString("cuberiteLocation", "${MainApplication.privateDir}/cuberite-server")
}
}
}
var showPermissionPopup by remember { mutableStateOf(false) }
PermissionCheckSideEffect(
preferences = MainApplication.preferences,
onRequest = { showPermissionPopup = true },
onPause = { showPermissionPopup = false },
)
Scaffold(
modifier = Modifier.fillMaxSize(),
bottomBar = {
NavigationBar {
TopLevelNavigation.entries.forEach { navigation ->
val selected = remember(currentDestination?.route) {
currentDestination?.route == navigation.route
}
NavigationBarItem(
selected = selected,
onClick = {
when (navigation) {
Control -> navController.navigateToControl()
Console -> navController.navigateToConsole()
Settings -> navController.navigateToSettings()
}
},
icon = {
Icon(
painter = painterResource(navigation.iconRes),
contentDescription = null,
)
},
label = {
Text(text = stringResource(navigation.labelRes))
},
)
}
}
},
) { innerPadding ->
CuberiteNavGraph(
navController = navController,
modifier = Modifier.padding(innerPadding),
)
}
if (showPermissionPopup) {
PermissionPopup(
onDismiss = { showPermissionPopup = false },
onConfirm = {
permissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE)
},
)
}
}
@Composable
private fun PermissionPopup(
onDismiss: () -> Unit,
onConfirm: () -> Unit,
) {
AlertDialog(
onDismissRequest = onDismiss,
confirmButton = {
TextButton(onClick = onConfirm) {
Text(text = stringResource(R.string.ok))
}
},
title = {
Text(text = stringResource(R.string.status_permissions_needed))
},
text = {
Text(text = stringResource(R.string.message_externalstorage_permission))
}
)
}
@Composable
private fun PermissionCheckSideEffect(
preferences: SharedPreferences,
onRequest: () -> Unit,
onPause: () -> Unit,
) {
val context = LocalContext.current
val location = remember {
preferences.getString("cuberiteLocation", "")
}
LifecycleResumeEffect(true) {
if (!context.isExternalStorageGranted) {
if (location!!.isEmpty() || location.startsWith(MainApplication.publicDir)) {
onRequest()
}
} else if (location!!.isEmpty() || location.startsWith(MainApplication.privateDir)) {
preferences.edit {
putString("cuberiteLocation", "${MainApplication.publicDir}/cuberite-server")
}
}
onPauseOrDispose {
onPause()
}
}
}
| 2 | Kotlin | 6 | 80 | 31eaf4962ba9c6ddeee0bb27755ff5edc952bd08 | 6,352 | android | Apache License 2.0 |
kotlin/src/main/kotlin/by/jprof/telegram/bot/kotlin/KotlinMentionsUpdateProcessor.kt | JavaBy | 367,980,780 | false | null | package by.jprof.telegram.bot.kotlin
import by.jprof.telegram.bot.core.UpdateProcessor
import by.jprof.telegram.bot.kotlin.dao.KotlinMentionsDAO
import by.jprof.telegram.bot.kotlin.model.KotlinMentions
import by.jprof.telegram.bot.kotlin.model.UserStatistics
import dev.inmo.tgbotapi.bot.RequestsExecutor
import dev.inmo.tgbotapi.extensions.api.send.media.sendPhoto
import dev.inmo.tgbotapi.extensions.utils.asCommonMessage
import dev.inmo.tgbotapi.extensions.utils.asMessageUpdate
import dev.inmo.tgbotapi.requests.abstracts.MultipartFile
import dev.inmo.tgbotapi.types.chat.Chat
import dev.inmo.tgbotapi.types.message.abstracts.CommonMessage
import dev.inmo.tgbotapi.types.message.abstracts.FromUserMessage
import dev.inmo.tgbotapi.types.message.content.TextContent
import dev.inmo.tgbotapi.types.update.abstracts.Update
import dev.inmo.tgbotapi.utils.PreviewFeature
import io.ktor.utils.io.streams.asInput
import java.io.InputStream
import java.time.Duration
import java.time.Instant
import org.apache.logging.log4j.LogManager
import org.jetbrains.skija.Data
import org.jetbrains.skija.EncodedImageFormat
import org.jetbrains.skija.Font
import org.jetbrains.skija.Image
import org.jetbrains.skija.Paint
import org.jetbrains.skija.Surface
import org.jetbrains.skija.TextLine
import org.jetbrains.skija.Typeface
@PreviewFeature
class KotlinMentionsUpdateProcessor(
private val kotlinMentionsDAO: KotlinMentionsDAO,
private val bot: RequestsExecutor,
) : UpdateProcessor {
companion object {
private val logger = LogManager.getLogger(KotlinMentionsUpdateProcessor::class.java)!!
private val kotlinRegex =
"([kкκ]+[._\\-/#*\\\\+=]{0,2}[оo0aа]+[._\\-/#*\\\\+=]{0,2}[тtτ]+[._\\-/#*\\\\+=]{0,2}[лlλ]+[._\\-/#*\\\\+=]{0,2}[ие1ieіι]+[._\\-/#*\\\\+=]{0,2}[нnHνη]+)".toRegex(
setOf(RegexOption.IGNORE_CASE, RegexOption.MULTILINE)
)
}
override suspend fun process(update: Update) {
val message = update.asMessageUpdate()?.data?.asCommonMessage() ?: return
when (val content = message.content) {
is TextContent -> if (!kotlinRegex.containsMatchIn(content.text)) return
else -> return
}
logger.info("Kotlin mentioned!")
val now = Instant.now()
val user = (message as? FromUserMessage)?.user ?: return
val chat = message.chat
val mentions = kotlinMentionsDAO.get(chat.id.chatId) ?: KotlinMentions(
chat.id.chatId,
now
)
val timeSinceLastMention = Duration.between(mentions.lastMention, now)
if (timeSinceLastMention.toMinutes() >= 15) {
incident(message, chat, timeSinceLastMention)
}
val oldUserStatistics = mentions.usersStatistics[user.id.chatId] ?: UserStatistics(0, now)
val newUserStatistics = oldUserStatistics.copy(count = oldUserStatistics.count + 1, lastMention = now)
kotlinMentionsDAO.save(
mentions.copy(
lastMention = now,
usersStatistics = mentions.usersStatistics + (user.id.chatId to newUserStatistics)
)
)
}
private suspend fun incident(
message: CommonMessage<*>,
chat: Chat,
timeSinceLastMention: Duration,
) {
val templateImage = Image.makeFromEncoded(
this::class.java.getResourceAsStream("/template.png")!!
.use(InputStream::readBytes)
)
val surface = Surface.makeRasterN32Premul(templateImage.width, templateImage.height)
val canvas = surface.canvas
canvas.drawImage(templateImage, 0F, 0F)
val typeface = Typeface.makeFromData(
Data.makeFromBytes(
this::class.java.getResourceAsStream("/ComingSoon-Regular.ttf")!!
.use(InputStream::readBytes)
)
)
val font = Font(typeface, 32F)
val line = TextLine.make(
"%02dd:%02dh:%02dm:%02ds".format(
timeSinceLastMention.toDaysPart(),
timeSinceLastMention.toHoursPart(),
timeSinceLastMention.toMinutesPart(),
timeSinceLastMention.toSecondsPart()
),
font
)
val paint = Paint().apply {
color = 0xFFB8B19E.toInt()
}
canvas.drawTextLine(
line,
700F,
260F,
paint
)
val snapshot = surface.makeImageSnapshot() ?: return
val data = snapshot.encodeToData(EncodedImageFormat.JPEG, 95) ?: return
bot.sendPhoto(
chat = chat,
fileId = MultipartFile(
filename = "darryl.jpeg",
inputSource = { data.bytes.inputStream().asInput() }
),
replyToMessageId = message.messageId,
)
logger.info("Kotlin mention reported!")
}
}
| 21 | Kotlin | 2 | 2 | 7e0f2c68e3acc9ff239effa34f5823e4ef8212c9 | 4,908 | jprof_by_bot | MIT License |
app/src/main/java/com/darekbx/cari/testapplication/testdata/roomdatabase/TestRoomDatabase.kt | darekbx | 221,463,518 | false | {"Kotlin": 53035, "Python": 41553} | package com.darekbx.cari.testapplication.testdata.roomdatabase
import android.content.Context
import androidx.room.*
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.*
class TestRoomDatabase {
@Entity(tableName = "person")
class PersonDto(
@PrimaryKey(autoGenerate = true) var id: Long? = null,
@ColumnInfo(name = "name") var name: String = "",
@ColumnInfo(name = "age") var age: Int = 0,
@ColumnInfo(name = "active") var active: Boolean = false,
@ColumnInfo(name = "company_id") var companyId: Long? = null,
@ColumnInfo(name = "created") var created: Long? = null
)
@Entity(tableName = "company")
class CompanyDto(
@PrimaryKey(autoGenerate = true) var id: Long? = null,
@ColumnInfo(name = "name") var name: String = "",
@ColumnInfo(name = "address") var address: String = ""
)
@Database(entities = arrayOf(PersonDto::class, CompanyDto::class), version = 3)
abstract class TestDatabase : RoomDatabase() {
companion object {
val DB_NAME = "room_db"
}
abstract fun copanyDao(): CompanyDao
abstract fun personDao(): PersonDao
}
@Dao
interface CompanyDao {
@Insert
fun add(companyDto: CompanyDto): Long
}
@Dao
interface PersonDao {
@Insert
fun add(personDto: PersonDto): Long
}
fun createTestDatabase(context: Context) {
CoroutineScope(Dispatchers.IO).launch {
val database = Room.databaseBuilder(context, TestDatabase::class.java, TestDatabase.DB_NAME)
.addMigrations(object: Migration(1, 2) {
override fun migrate(database: SupportSQLiteDatabase) { }
})
.addMigrations(object: Migration(2, 3) {
override fun migrate(database: SupportSQLiteDatabase) { }
})
.build()
with (database){
clearAllTables()
val companyDao = copanyDao()
val companyOneId = companyDao.add(CompanyDto(name = "Company One", address = "Milky Road 1, 02412 NY"))
val companyTwoId = companyDao.add(CompanyDto(name = "Company Two", address = "Star Road 42, 46321 LA"))
val now = Calendar.getInstance().timeInMillis
personDao().run {
add(PersonDto(name = "<NAME>", age = 35, active = true, companyId = companyOneId, created = now))
add(PersonDto(name = "<NAME>", age = 56, active = false, companyId = companyOneId, created = now))
add(PersonDto(name = "<NAME>", age = 19, active = true, companyId = companyTwoId, created = now))
add(PersonDto(name = "<NAME>", age = 43, active = true, companyId = companyTwoId, created = now))
val random = Random()
(0..100).forEach { i ->
add(
PersonDto(
name = (0..200).joinToString(),
age = random.nextInt(100),
active = true,
companyId = companyOneId,
created = now
)
)
}
}
close()
}
}
}
} | 0 | Kotlin | 0 | 0 | dce717f69ad2e11e91e50db3add8ff8f88e7fe1c | 3,594 | CARI | Apache License 2.0 |
app/src/main/java/com/goldenowl/ecommerceapp/data/Order.kt | Catelt | 556,541,382 | false | {"Kotlin": 403481, "Batchfile": 284} | package com.goldenowl.ecommerceapp.data
import com.goldenowl.ecommerceapp.utilities.MAX
import com.goldenowl.ecommerceapp.utilities.MIN
import com.goldenowl.ecommerceapp.utilities.TRACKING_NUMBER
import java.util.*
data class Order(
val id: String = (MIN..MAX).random().toString(),
var products: List<ProductOrder> = emptyList(),
var trackingNumber: String = TRACKING_NUMBER,
var total: Float = 0F,
var status: Int = 0,
var timeCreated: Date = Date(),
var shippingAddress: String = "",
var payment: String = "",
var isTypePayment: Int = 0,
var delivery: Delivery? = null,
var promotion: String = ""
) {
fun getUnits(): Int {
var result = 0
for (product in products) {
result += product.units
}
return result
}
}
| 1 | Kotlin | 0 | 0 | 15b2a23bc7daf1834520fd5a74a9bf4038ab756d | 811 | E-Commerce-Application | MIT License |
src/main/kotlin/com/rathanak/dawg/SpellCorrector.kt | khmerlang | 270,342,444 | false | {"Kotlin": 6231} | package com.rathanak.dawg
import com.sun.org.apache.xerces.internal.impl.xs.opti.SchemaDOM.traverse
import java.util.*
class SpellCorrector {
var tst: TST = TST()
private var EDIT_LIMIT: Int = 3
private var SUGGESTED_WORD_LIST_LIMIT: Int = 10
var inputString: String?= null
var suggestedWords: PriorityQueue<PQElement> = PriorityQueue<PQElement>(10)
init {
WordTree().createNode(tst)
}
fun correct(str: String) : LinkedHashMap<String, Int>{
if (str.isNullOrEmpty()) {
throw IllegalArgumentException("Input string is blank.")
}
if (tst.root == null) {
throw IllegalArgumentException("Node not found.")
}
inputString = str
tst.root?.let { traverse(it, "") }
var outputMap: LinkedHashMap<String, Int> = LinkedHashMap<String, Int>()
var i = 0
while (!suggestedWords.isEmpty() && i < SUGGESTED_WORD_LIST_LIMIT) {
val element = suggestedWords.poll()
if (getEditDistance(str, element.word) <= EDIT_LIMIT) {
outputMap[element.word] = element.editDistance
i++
}
}
return outputMap
}
fun traverse(root: Node, str: String) {
if (root == null) {
return
}
val distance: Int = getEditDistance(inputString!!, str + root.ch)
if (str.length < inputString!!.length
&& getEditDistance(str, inputString!!.substring(0, str.length + 1)) > EDIT_LIMIT
) {
return
} else if (str.length > inputString!!.length + EDIT_LIMIT) {
return
} else if (Math.abs(str.length - inputString!!.length) <= EDIT_LIMIT && distance > EDIT_LIMIT) {
return
}
// recursively traverse through the nodes for words
root.left?.let { traverse(it, str) }
if (root.isEnd === true && distance <= EDIT_LIMIT) {
suggestedWords.add(root.frequency?.let { PQElement(str + root.ch, distance, it) })
}
root.mid?.let { traverse(it, str + root.ch) }
root.right?.let { traverse(it, str) }
}
private fun getEditDistance(a: String, b: String): Int {
val costs = IntArray(b.length + 1)
for (j in costs.indices) costs[j] = j
for (i in 1..a.length) {
costs[0] = i
var nw = i - 1
for (j in 1..b.length) {
val cj = Math.min(
1 + Math.min(costs[j], costs[j - 1]),
if (a[i - 1] === b[j - 1]) nw else nw + 1
)
nw = costs[j]
costs[j] = cj
}
}
return costs[b.length]
}
} | 0 | Kotlin | 0 | 0 | 2d603b3f222226a3e56064796142c13af3be911e | 2,721 | tst-algorithm | MIT License |
modules/data/src/main/java/com/tradwang/centre/entry/NetEntry.kt | GitTradWang | 194,192,539 | false | null | package com.tradwang.centre.entry
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
import android.os.Parcel
import android.os.Parcelable
import com.tradwang.common.getTimeSpan
/**
* Project Name : CommonStudy
* Package Name : com.tradwang.homemodule.bean
* @since 2018/2/27 10: 25
* @author : TradWang
* @email : <EMAIL>
* @version :
* @describe :
*/
data class ArticleListBean(
val curPage: Int,
val datas: MutableList<ArticleBean>,
val offset: Int,
val over: Boolean,
val pageCount: Int,
val size: Int,
val total: Int
)
@Entity(tableName = "article", indices = [Index(value = ["id"], unique = true)])
data class ArticleBean(
@PrimaryKey
val id: Int,
val apkLink: String,
val author: String,
val chapterId: Int,
val chapterName: String,
val collect: Boolean,
val courseId: Int,
val desc: String,
val envelopePic: String,
val link: String,
val niceDate: String,
val origin: String,
val projectLink: String,
val publishTime: Long,
val title: String,
val visible: Int,
val zan: Int
) {
fun getFormatPublishTime(): String {
return publishTime.getTimeSpan()
}
}
data class TreeRootBean(
val children: List<Children>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val visible: Int
)
data class Children(
val children: List<Children>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val visible: Int
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.createTypedArrayList(CREATOR),
parcel.readInt(),
parcel.readInt(),
parcel.readString(),
parcel.readInt(),
parcel.readInt(),
parcel.readInt()) {
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeTypedList(children)
parcel.writeInt(courseId)
parcel.writeInt(id)
parcel.writeString(name)
parcel.writeInt(order)
parcel.writeInt(parentChapterId)
parcel.writeInt(visible)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Children> {
override fun createFromParcel(parcel: Parcel): Children {
return Children(parcel)
}
override fun newArray(size: Int): Array<Children?> {
return arrayOfNulls(size)
}
}
}
data class BannerBean(
val desc: String,
val id: Int,
val imagePath: String,
val isVisible: Int,
val order: Int,
val title: String,
val type: Int,
val url: String
)
data class LoginBean(
val collectIds: List<Int>,
val id: Int,
val type: Int,
val icon: String,
val email: String,
val password: String,
val username: String
) | 0 | Kotlin | 0 | 0 | 45c092eadc96c9ab61395d2a88a8a0e5c060ac66 | 3,184 | dev_template | Apache License 2.0 |
src/main/kotlin/com/nikichxp/tgbot/config/AppConfig.kt | NikichXP | 395,716,371 | false | {"Kotlin": 138066, "Dockerfile": 252} | package com.nikichxp.tgbot.config
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.context.properties.ConstructorBinding
@ConfigurationProperties(prefix = "app")
@ConstructorBinding
class AppConfig(
var adminId: Long,
var webhook: String,
var localEnv: Boolean,
var tokens: Tokens,
var tracer: Tracer
) {
companion object {
class Tokens(
var nikichBot: String?,
var allMyStuffBot: String?
)
class Tracer(
var store: Boolean = false,
var ttl: Long = 1
)
}
} | 0 | Kotlin | 0 | 1 | f0351cf87c7da89d40f70218f31e2d41dbd52e22 | 625 | tgbot | Apache License 2.0 |
graphql-dgs-client/src/test/kotlin/com/netflix/graphql/dgs/client/GraphqlSSESubscriptionGraphQLClientTest.kt | Netflix | 317,375,887 | false | {"Kotlin": 1530406, "Java": 286741, "HTML": 14098, "Python": 8827, "TypeScript": 3328, "JavaScript": 2934, "Makefile": 1328} | /*
* Copyright 2023 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.graphql.dgs.client
import com.netflix.graphql.dgs.autoconfig.DgsAutoConfiguration
import com.netflix.graphql.dgs.subscriptions.graphql.sse.DgsGraphQLSSEAutoConfig
import com.netflix.graphql.dgs.subscriptions.sse.DgsSSEAutoConfig
import com.netflix.graphql.dgs.subscriptions.websockets.DgsWebSocketAutoConfig
import org.junit.jupiter.api.Assertions.assertThrows
import org.junit.jupiter.api.Test
import org.springframework.boot.autoconfigure.EnableAutoConfiguration
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.web.server.LocalServerPort
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.WebClientResponseException
import reactor.test.StepVerifier
@SpringBootTest(
classes = [DgsAutoConfiguration::class, DgsGraphQLSSEAutoConfig::class, TestApp::class],
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT
)
@EnableAutoConfiguration(exclude = [DgsSSEAutoConfig::class, DgsWebSocketAutoConfig::class])
internal class GraphqlSSESubscriptionGraphQLClientTest {
@LocalServerPort
var port: Int? = null
@Test
fun `A successful subscription should publish ticks`() {
val client = GraphqlSSESubscriptionGraphQLClient("/subscriptions", WebClient.create("http://localhost:$port"))
val reactiveExecuteQuery =
client.reactiveExecuteQuery("subscription {numbers}", emptyMap()).mapNotNull { r -> r.data["numbers"] }
StepVerifier.create(reactiveExecuteQuery)
.expectNext(1, 2, 3)
.expectComplete()
.verify()
}
@Test
fun `An error on the subscription should send the error as a response and end the subscription`() {
val client = GraphqlSSESubscriptionGraphQLClient("/subscriptions", WebClient.create("http://localhost:$port"))
val reactiveExecuteQuery = client.reactiveExecuteQuery("subscription {withError}", emptyMap())
StepVerifier.create(reactiveExecuteQuery)
.consumeNextWith { r -> r.hasErrors() }
.expectComplete()
.verify()
}
@Test
fun `A connection error should result in a WebClientException`() {
val client = GraphqlSSESubscriptionGraphQLClient("/wrongurl", WebClient.create("http://localhost:$port"))
assertThrows(WebClientResponseException.NotFound::class.java) {
client.reactiveExecuteQuery("subscription {withError}", emptyMap()).blockLast()
}
}
@Test
fun `A badly formatted query should result in a WebClientException`() {
val client = GraphqlSSESubscriptionGraphQLClient("/subscriptions", WebClient.create("http://localhost:$port"))
assertThrows(WebClientResponseException.BadRequest::class.java) {
client.reactiveExecuteQuery("invalid query", emptyMap()).blockLast()
}
}
@Test
fun `An invalid query should result in a WebClientException`() {
val client = GraphqlSSESubscriptionGraphQLClient("/subscriptions", WebClient.create("http://localhost:$port"))
assertThrows(WebClientResponseException.BadRequest::class.java) {
client.reactiveExecuteQuery("subscriptions { unkownField }", emptyMap()).blockLast()
}
}
}
| 88 | Kotlin | 289 | 3,037 | bd2d0c524e70a9d1d625d518a94926c7b53a7e7c | 3,889 | dgs-framework | Apache License 2.0 |
androidunsplash/src/main/java/com/kc/unsplash/api/Orientation.kt | jeanclaudesoft | 345,122,551 | true | {"Java Properties": 2, "Gradle": 4, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Text": 1, "Ignore List": 3, "XML": 11, "Proguard": 2, "Kotlin": 18, "Java": 23} | package com.kc.unsplash.api
enum class Orientation private constructor(orientation: String) {
LANDSCAPE("landscape"),
PORTRAIT("portrait"),
SQUARISH("squarish");
var orientation: String
internal set
init {
this.orientation = orientation
}
}
| 0 | null | 0 | 0 | 53c018c363573a296e3b82e27084265ece0cc206 | 285 | AndroidUnplash | MIT License |
feature/recorddetails/src/main/java/org/expenny/feature/recorddetails/view/RecordDetailsDeleteDialog.kt | expenny-application | 712,607,222 | false | {"Kotlin": 890931} | package org.expenny.feature.recorddetails.view
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import org.expenny.core.resources.R
import org.expenny.core.ui.foundation.ExpennyAlertDialog
import org.expenny.core.ui.foundation.ExpennyButton
import org.expenny.core.ui.foundation.ExpennyButtonSize
import org.expenny.core.ui.foundation.ExpennyButtonStyle
import org.expenny.core.ui.foundation.ExpennyText
@Composable
internal fun RecordDetailsDeleteDialog(
onDismiss: () -> Unit,
onConfirm: () -> Unit,
) {
ExpennyAlertDialog(
onDismissRequest = onDismiss,
title = {
ExpennyText(text = stringResource(R.string.delete_record_question_label))
},
content = {
ExpennyText(
text = stringResource(R.string.delete_record_paragraph),
maxLines = Int.MAX_VALUE
)
},
confirmButton = {
ExpennyButton(
style = ExpennyButtonStyle.Text,
size = ExpennyButtonSize.Small,
onClick = onConfirm,
label = {
ExpennyText(text = stringResource(R.string.delete_button))
}
)
},
dismissButton = {
ExpennyButton(
style = ExpennyButtonStyle.Text,
size = ExpennyButtonSize.Small,
onClick = onDismiss,
label = {
ExpennyText(text = stringResource(R.string.cancel_button))
}
)
}
)
} | 0 | Kotlin | 0 | 0 | 2077cd7bf02fcae059c13bd9f5fda677d9149854 | 1,593 | expenny-android | Apache License 2.0 |
src/main/kotlin/net/orandja/holycube6/modules/DebugWrench.kt | AarnoldGad | 667,135,202 | false | null | package net.orandja.holycube6.modules
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableMap
import net.minecraft.block.*
import net.minecraft.block.enums.RailShape
import net.minecraft.block.enums.SlabType
import net.minecraft.entity.Entity
import net.minecraft.entity.decoration.ItemFrameEntity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.item.ItemStack
import net.minecraft.item.Items
import net.minecraft.nbt.NbtCompound
import net.minecraft.nbt.NbtList
import net.minecraft.nbt.NbtString
import net.minecraft.recipe.Ingredient
import net.minecraft.recipe.ShapedRecipe
import net.minecraft.recipe.ShapelessRecipe
import net.minecraft.recipe.book.CraftingRecipeCategory
import net.minecraft.registry.Registries
import net.minecraft.server.network.ServerPlayerEntity
import net.minecraft.server.world.ServerWorld
import net.minecraft.state.property.Property
import net.minecraft.util.ActionResult
import net.minecraft.util.Hand
import net.minecraft.util.Identifier
import net.minecraft.util.collection.DefaultedList
import net.minecraft.util.math.BlockPos
import net.orandja.holycube6.accessor.ItemFrameEntityAccessor
import net.orandja.holycube6.modules.WrenchBlockState.Companion.EMPTY_LIST
import net.orandja.holycube6.recipes.CustomRemainedShapelessRecipe
import net.orandja.holycube6.utils.sendHUD
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable
import java.util.*
import java.util.stream.Collectors
fun ItemStack.isWrench(): Boolean {
return isOf(Items.DEBUG_STICK) && nbt?.contains("holywrench") ?: false && nbt?.getBoolean("holywrench")!!
}
private fun ItemStack.asWrench(callback: (stack: ItemStack) -> Unit) {
if (this.isWrench()) {
callback.invoke(this)
}
}
private fun ItemStack.getWrenchProperty(state: BlockState): Property<*>? {
if (isWrench()) {
if (nbt?.contains("DebugProperty") == true) {
val propertyName = getSubNbt("DebugProperty")!!.getString(Registries.BLOCK.getId(state.block).toString())
if (!propertyName.equals("")) {
return state.block.stateManager.getProperty(propertyName)
}
}
return WrenchBlockState.getProperties(state.block)[0]
}
return null
}
private fun <T> Array<T>.toCollection(): Collection<T> {
return Arrays.stream(this).collect(Collectors.toList()) as Collection<T>
}
private fun BlockState.isWrencheable(): Boolean {
return WrenchBlockState.WrenchBlockStates.containsKey(block)
}
class WrenchBlockState(
block: Block,
values: Map<Property<*>, Collection<*>>,
val validate: (blockState: BlockState, property: Property<*>) -> Boolean = alwaysTrue
) {
companion object {
val EMPTY_LIST: ImmutableList<Property<*>> = ImmutableList.copyOf(emptyList())
val alwaysTrue: (blockState: BlockState, property: Property<*>) -> Boolean = { _, _ -> true }
val WrenchBlockStates: MutableMap<Block, WrenchBlockState> = mutableMapOf()
fun getProperties(block: Block): ImmutableList<Property<*>> {
return WrenchBlockStates[block]?.getProperties() ?: EMPTY_LIST
}
fun getValues(block: Block, property: Property<*>): Collection<*> {
return WrenchBlockStates[block]!!.getValues(property)
}
fun isAllowed(state: BlockState, property: Property<*>): Boolean {
return WrenchBlockStates[state.block]?.validate?.invoke(state, property) ?: false
}
}
private val allowed = ImmutableMap.copyOf(values)
init {
WrenchBlockStates[block] = this
}
fun getProperties(): ImmutableList<Property<*>> {
return ImmutableList.copyOf(allowed.keys)
}
fun getValues(property: Property<*>): Collection<*> {
return allowed[property]!!
}
}
class DebugWrench {
companion object {
private fun Property<*>.toPair(): Pair<Property<*>, Collection<*>> {
return this to this.values
}
private fun Property<*>.toMap(): Map<Property<*>, Collection<*>> {
return mapOf(this.toPair())
}
private fun Property<*>.ofValues(vararg values: Any): Pair<Property<*>, Collection<*>> {
return this to values.toCollection()
}
private fun Property<*>.with(vararg props: Property<*>): Map<Property<*>, Collection<*>> {
return mapOf(this.toPair(), *props.map { it.toPair() }.toTypedArray())
}
private fun Property<*>.forBlocks(vararg blocks: Block, validate: (blockState: BlockState, property: Property<*>) -> Boolean = WrenchBlockState.alwaysTrue) {
blocks.forEach {
WrenchBlockState(it, this.toMap(), validate)
}
}
private fun Map<Property<*>, Collection<*>>.forBlocks(vararg blocks: Block, validate: (blockState: BlockState, property: Property<*>) -> Boolean = WrenchBlockState.alwaysTrue) {
blocks.forEach {
WrenchBlockState(it, this, validate)
}
}
private fun Pair<Property<*>, Collection<*>>.forBlocks(vararg blocks: Block, validate: (blockState: BlockState, property: Property<*>) -> Boolean = WrenchBlockState.alwaysTrue) {
blocks.forEach {
WrenchBlockState(it, mapOf(this), validate)
}
}
init {
MushroomBlock.NORTH
.with(MushroomBlock.EAST, MushroomBlock.WEST, MushroomBlock.SOUTH, MushroomBlock.UP, MushroomBlock.DOWN)
.forBlocks(Blocks.BROWN_MUSHROOM_BLOCK, Blocks.RED_MUSHROOM_BLOCK, Blocks.MUSHROOM_STEM)
BigDripleafBlock.FACING
.forBlocks(Blocks.BIG_DRIPLEAF, Blocks.BIG_DRIPLEAF_STEM)
SmallDripleafBlock.FACING
.forBlocks(Blocks.SMALL_DRIPLEAF)
LightningRodBlock.FACING
.forBlocks(Blocks.LIGHTNING_ROD)
EndRodBlock.FACING
.forBlocks(Blocks.END_ROD)
ChainBlock.AXIS
.forBlocks(Blocks.CHAIN)
DoorBlock.FACING
.with(
DoorBlock.OPEN,
DoorBlock.HINGE)
.forBlocks(
Blocks.OAK_DOOR, Blocks.SPRUCE_DOOR, Blocks.BIRCH_DOOR, Blocks.JUNGLE_DOOR, Blocks.ACACIA_DOOR, Blocks.DARK_OAK_DOOR,
Blocks.IRON_DOOR,
Blocks.CRIMSON_DOOR, Blocks.WARPED_DOOR,
Blocks.MANGROVE_DOOR, Blocks.CHERRY_DOOR, Blocks.BAMBOO_DOOR)
TrapdoorBlock.FACING
.with(TrapdoorBlock.OPEN, TrapdoorBlock.HALF)
.forBlocks(
Blocks.OAK_TRAPDOOR, Blocks.SPRUCE_TRAPDOOR, Blocks.BIRCH_TRAPDOOR, Blocks.JUNGLE_TRAPDOOR, Blocks.ACACIA_TRAPDOOR, Blocks.DARK_OAK_TRAPDOOR,
Blocks.IRON_TRAPDOOR,
Blocks.CRIMSON_TRAPDOOR, Blocks.WARPED_TRAPDOOR,
Blocks.MANGROVE_TRAPDOOR, Blocks.CHERRY_TRAPDOOR, Blocks.BAMBOO_TRAPDOOR)
PillarBlock.AXIS
.forBlocks(
Blocks.OAK_LOG, Blocks.SPRUCE_LOG, Blocks.BIRCH_LOG, Blocks.JUNGLE_LOG, Blocks.ACACIA_LOG, Blocks.DARK_OAK_LOG,
Blocks.MANGROVE_LOG, Blocks.CHERRY_LOG, Blocks.BAMBOO_BLOCK,
Blocks.STRIPPED_OAK_LOG, Blocks.STRIPPED_SPRUCE_LOG, Blocks.STRIPPED_BIRCH_LOG, Blocks.STRIPPED_JUNGLE_LOG, Blocks.STRIPPED_ACACIA_LOG, Blocks.STRIPPED_DARK_OAK_LOG,
Blocks.STRIPPED_MANGROVE_LOG, Blocks.STRIPPED_CHERRY_LOG, Blocks.STRIPPED_BAMBOO_BLOCK,
Blocks.QUARTZ_PILLAR, Blocks.PURPUR_PILLAR)
FenceBlock.NORTH
.with(FenceBlock.EAST, FenceBlock.WEST, FenceBlock.SOUTH)
.forBlocks(
Blocks.OAK_FENCE, Blocks.SPRUCE_FENCE, Blocks.BIRCH_FENCE, Blocks.JUNGLE_FENCE, Blocks.ACACIA_FENCE, Blocks.DARK_OAK_FENCE,
Blocks.CRIMSON_FENCE, Blocks.WARPED_FENCE, Blocks.NETHER_BRICK_FENCE,
Blocks.MANGROVE_FENCE, Blocks.CHERRY_FENCE, Blocks.BAMBOO_FENCE)
PaneBlock.NORTH
.with(PaneBlock.EAST, PaneBlock.WEST, PaneBlock.SOUTH)
.forBlocks(
Blocks.IRON_BARS, Blocks.GLASS_PANE,
Blocks.WHITE_STAINED_GLASS_PANE, Blocks.LIGHT_GRAY_STAINED_GLASS_PANE, Blocks.GRAY_STAINED_GLASS_PANE, Blocks.BLACK_STAINED_GLASS_PANE,
Blocks.RED_STAINED_GLASS_PANE, Blocks.GREEN_STAINED_GLASS_PANE, Blocks.BLUE_STAINED_GLASS_PANE,
Blocks.MAGENTA_STAINED_GLASS_PANE, Blocks.CYAN_STAINED_GLASS_PANE, Blocks.YELLOW_STAINED_GLASS_PANE,
Blocks.LIGHT_BLUE_STAINED_GLASS_PANE, Blocks.LIME_STAINED_GLASS_PANE,
Blocks.PINK_STAINED_GLASS_PANE, Blocks.PURPLE_STAINED_GLASS_PANE,
Blocks.ORANGE_STAINED_GLASS_PANE, Blocks.BROWN_STAINED_GLASS_PANE)
WallBlock.UP
.with(WallBlock.NORTH_SHAPE, WallBlock.EAST_SHAPE, WallBlock.WEST_SHAPE, WallBlock.SOUTH_SHAPE)
.forBlocks(
Blocks.COBBLESTONE_WALL, Blocks.MOSSY_COBBLESTONE_WALL,
Blocks.STONE_BRICK_WALL, Blocks.MOSSY_STONE_BRICK_WALL,
Blocks.GRANITE_WALL, Blocks.ANDESITE_WALL, Blocks.DIORITE_WALL,
Blocks.BRICK_WALL, Blocks.PRISMARINE_WALL, Blocks.END_STONE_BRICK_WALL,
Blocks.SANDSTONE_WALL, Blocks.RED_SANDSTONE_WALL,
Blocks.NETHER_BRICK_WALL, Blocks.RED_NETHER_BRICK_WALL,
Blocks.BLACKSTONE_WALL, Blocks.POLISHED_BLACKSTONE_WALL, Blocks.POLISHED_BLACKSTONE_BRICK_WALL,
Blocks.COBBLED_DEEPSLATE_WALL, Blocks.DEEPSLATE_BRICK_WALL, Blocks.DEEPSLATE_TILE_WALL, Blocks.POLISHED_DEEPSLATE_WALL)
SkullBlock.ROTATION
.forBlocks(Blocks.SKELETON_SKULL, Blocks.WITHER_SKELETON_SKULL, Blocks.PLAYER_HEAD, Blocks.ZOMBIE_HEAD, Blocks.CREEPER_HEAD, Blocks.DRAGON_HEAD)
WallSkullBlock.FACING
.forBlocks(Blocks.SKELETON_WALL_SKULL, Blocks.WITHER_SKELETON_WALL_SKULL, Blocks.PLAYER_WALL_HEAD, Blocks.ZOMBIE_WALL_HEAD, Blocks.CREEPER_WALL_HEAD, Blocks.DRAGON_WALL_HEAD)
AnvilBlock.FACING
.forBlocks(Blocks.ANVIL, Blocks.CHIPPED_ANVIL, Blocks.DAMAGED_ANVIL)
RedstoneLampBlock.LIT
.forBlocks(Blocks.REDSTONE_LAMP)
HayBlock.AXIS
.forBlocks(Blocks.HAY_BLOCK)
LightBlock.LEVEL_15
.forBlocks(Blocks.LIGHT)
RepeaterBlock.FACING
.with(RepeaterBlock.DELAY)
.forBlocks(Blocks.REPEATER)
ComparatorBlock.FACING
.with(ComparatorBlock.MODE)
.forBlocks(Blocks.COMPARATOR)
HopperBlock.FACING
.forBlocks(Blocks.HOPPER)
DropperBlock.FACING
.forBlocks(Blocks.DROPPER)
DispenserBlock.FACING
.forBlocks(Blocks.DISPENSER)
ObserverBlock.FACING
.forBlocks(Blocks.OBSERVER)
StairsBlock.FACING
.with(StairsBlock.HALF, StairsBlock.SHAPE)
.forBlocks(
Blocks.OAK_STAIRS, Blocks.SPRUCE_STAIRS, Blocks.BIRCH_STAIRS, Blocks.JUNGLE_STAIRS, Blocks.ACACIA_STAIRS, Blocks.DARK_OAK_STAIRS,
Blocks.MANGROVE_STAIRS, Blocks.CHERRY_STAIRS, Blocks.BAMBOO_STAIRS, Blocks.BAMBOO_MOSAIC_STAIRS,
Blocks.CRIMSON_STAIRS, Blocks.WARPED_STAIRS,
Blocks.STONE_STAIRS, Blocks.MOSSY_STONE_BRICK_STAIRS, Blocks.COBBLESTONE_STAIRS, Blocks.MOSSY_COBBLESTONE_STAIRS, Blocks.STONE_BRICK_STAIRS,
Blocks.GRANITE_STAIRS, Blocks.DIORITE_STAIRS, Blocks.ANDESITE_STAIRS,
Blocks.POLISHED_GRANITE_STAIRS, Blocks.POLISHED_DIORITE_STAIRS, Blocks.POLISHED_ANDESITE_STAIRS,
Blocks.SANDSTONE_STAIRS, Blocks.SMOOTH_SANDSTONE_STAIRS, Blocks.RED_SANDSTONE_STAIRS, Blocks.SMOOTH_RED_SANDSTONE_STAIRS,
Blocks.BRICK_STAIRS, Blocks.PRISMARINE_STAIRS, Blocks.PRISMARINE_BRICK_STAIRS, Blocks.DARK_PRISMARINE_STAIRS,
Blocks.NETHER_BRICK_STAIRS, Blocks.RED_NETHER_BRICK_STAIRS,
Blocks.QUARTZ_STAIRS, Blocks.SMOOTH_QUARTZ_STAIRS,
Blocks.PURPUR_STAIRS, Blocks.END_STONE_BRICK_STAIRS,
Blocks.BLACKSTONE_STAIRS, Blocks.POLISHED_BLACKSTONE_BRICK_STAIRS, Blocks.POLISHED_BLACKSTONE_STAIRS,
Blocks.OXIDIZED_CUT_COPPER_STAIRS, Blocks.WEATHERED_CUT_COPPER_STAIRS, Blocks.EXPOSED_CUT_COPPER_STAIRS, Blocks.CUT_COPPER_STAIRS,
Blocks.WAXED_OXIDIZED_CUT_COPPER_STAIRS, Blocks.WAXED_WEATHERED_CUT_COPPER_STAIRS, Blocks.WAXED_EXPOSED_CUT_COPPER_STAIRS, Blocks.WAXED_CUT_COPPER_STAIRS,
Blocks.COBBLED_DEEPSLATE_STAIRS, Blocks.POLISHED_DEEPSLATE_STAIRS, Blocks.DEEPSLATE_TILE_STAIRS, Blocks.DEEPSLATE_BRICK_STAIRS)
SlabBlock.TYPE
.ofValues(SlabType.BOTTOM, SlabType.TOP)
.forBlocks(
Blocks.OAK_SLAB, Blocks.SPRUCE_SLAB, Blocks.BIRCH_SLAB, Blocks.JUNGLE_SLAB, Blocks.ACACIA_SLAB, Blocks.DARK_OAK_SLAB,
Blocks.MANGROVE_SLAB, Blocks.CHERRY_SLAB, Blocks.BAMBOO_SLAB, Blocks.BAMBOO_MOSAIC_SLAB,
Blocks.CRIMSON_SLAB, Blocks.WARPED_SLAB, Blocks.PETRIFIED_OAK_SLAB,
Blocks.STONE_SLAB, Blocks.SMOOTH_STONE_SLAB, Blocks.COBBLESTONE_SLAB, Blocks.MOSSY_COBBLESTONE_SLAB, Blocks.STONE_BRICK_SLAB, Blocks.MOSSY_STONE_BRICK_SLAB,
Blocks.GRANITE_SLAB, Blocks.DIORITE_SLAB, Blocks.ANDESITE_SLAB,
Blocks.POLISHED_GRANITE_SLAB, Blocks.POLISHED_DIORITE_SLAB, Blocks.POLISHED_ANDESITE_SLAB,
Blocks.SANDSTONE_SLAB, Blocks.CUT_SANDSTONE_SLAB, Blocks.SMOOTH_SANDSTONE_SLAB, Blocks.RED_SANDSTONE_SLAB, Blocks.CUT_RED_SANDSTONE_SLAB, Blocks.SMOOTH_RED_SANDSTONE_SLAB,
Blocks.BRICK_SLAB, Blocks.PRISMARINE_SLAB, Blocks.PRISMARINE_BRICK_SLAB, Blocks.DARK_PRISMARINE_SLAB,
Blocks.NETHER_BRICK_SLAB, Blocks.RED_NETHER_BRICK_SLAB,
Blocks.QUARTZ_SLAB, Blocks.SMOOTH_QUARTZ_SLAB,
Blocks.PURPUR_SLAB, Blocks.END_STONE_BRICK_SLAB,
Blocks.BLACKSTONE_SLAB, Blocks.POLISHED_BLACKSTONE_SLAB, Blocks.POLISHED_BLACKSTONE_BRICK_SLAB,
Blocks.OXIDIZED_CUT_COPPER_SLAB, Blocks.WEATHERED_CUT_COPPER_SLAB, Blocks.EXPOSED_CUT_COPPER_SLAB, Blocks.CUT_COPPER_SLAB,
Blocks.WAXED_OXIDIZED_CUT_COPPER_SLAB, Blocks.WAXED_WEATHERED_CUT_COPPER_SLAB, Blocks.WAXED_EXPOSED_CUT_COPPER_SLAB, Blocks.WAXED_CUT_COPPER_SLAB,
Blocks.COBBLED_DEEPSLATE_SLAB, Blocks.POLISHED_DEEPSLATE_SLAB, Blocks.DEEPSLATE_TILE_SLAB, Blocks.DEEPSLATE_BRICK_SLAB){ state, property -> property == SlabBlock.TYPE && !state.get(property).equals(SlabType.DOUBLE) }
GlazedTerracottaBlock.FACING
.forBlocks(Blocks.WHITE_GLAZED_TERRACOTTA, Blocks.ORANGE_GLAZED_TERRACOTTA, Blocks.MAGENTA_GLAZED_TERRACOTTA, Blocks.LIGHT_BLUE_GLAZED_TERRACOTTA, Blocks.YELLOW_GLAZED_TERRACOTTA, Blocks.LIME_GLAZED_TERRACOTTA, Blocks.PINK_GLAZED_TERRACOTTA, Blocks.GRAY_GLAZED_TERRACOTTA, Blocks.LIGHT_GRAY_GLAZED_TERRACOTTA, Blocks.CYAN_GLAZED_TERRACOTTA, Blocks.PURPLE_GLAZED_TERRACOTTA, Blocks.BLUE_GLAZED_TERRACOTTA, Blocks.BROWN_GLAZED_TERRACOTTA, Blocks.GREEN_GLAZED_TERRACOTTA, Blocks.RED_GLAZED_TERRACOTTA, Blocks.BLACK_GLAZED_TERRACOTTA)
PistonBlock.FACING
.forBlocks(Blocks.PISTON, Blocks.STICKY_PISTON) { state, _ -> !state.get(PistonBlock.EXTENDED) }
RailBlock.SHAPE
.ofValues(RailShape.NORTH_SOUTH, RailShape.ASCENDING_NORTH, RailShape.ASCENDING_SOUTH, RailShape.NORTH_EAST, RailShape.EAST_WEST, RailShape.ASCENDING_EAST, RailShape.ASCENDING_WEST, RailShape.SOUTH_EAST, RailShape.SOUTH_WEST, RailShape.NORTH_WEST)
.forBlocks(Blocks.RAIL)
PoweredRailBlock.SHAPE
.ofValues(RailShape.NORTH_SOUTH, RailShape.ASCENDING_NORTH, RailShape.ASCENDING_SOUTH, RailShape.EAST_WEST, RailShape.ASCENDING_EAST, RailShape.ASCENDING_WEST)
.forBlocks(Blocks.POWERED_RAIL, Blocks.ACTIVATOR_RAIL)
DetectorRailBlock.SHAPE
.ofValues(RailShape.NORTH_SOUTH, RailShape.ASCENDING_NORTH, RailShape.ASCENDING_SOUTH, RailShape.EAST_WEST, RailShape.ASCENDING_EAST, RailShape.ASCENDING_WEST)
.forBlocks(Blocks.DETECTOR_RAIL)
}
fun hackShapedRecipe(
identifier: Identifier,
group: String,
category: CraftingRecipeCategory,
width: Int,
height: Int,
input: DefaultedList<Ingredient>,
output: ItemStack,
showNotification: Boolean
): ShapedRecipe {
if (identifier.namespace == "holycube6" && identifier.path == "holywrench") {
output.orCreateNbt.apply tag@{
putBoolean("holywrench", true)
put("display", NbtCompound().apply display@{
[email protected]("Lore", NbtList().apply lore@{
add(
0,
NbtString.of("[{\"text\":\"La plus simple des façons de modifier vos blockStates.\",\"italic\":false}]")
)
})
[email protected]("Name", "[{\"text\":\"MarliWrench\",\"italic\":true}]")
})
}
}
return ShapedRecipe(identifier, group, category, width, height, input, output, showNotification)
}
fun hackShapelessRecipe(
identifier: Identifier,
group: String,
category: CraftingRecipeCategory,
output: ItemStack,
input: DefaultedList<Ingredient>
): ShapelessRecipe {
if (identifier.namespace == "holycube6" && identifier.path == "deepslate_coal") {
return CustomRemainedShapelessRecipe(
identifier,
group,
category,
output,
input,
mapOf(Items.COAL_ORE to Items.STONE)
)
}
return ShapelessRecipe(identifier, group, category, output, input)
}
fun processBlockBreakingAction(
player: ServerPlayerEntity,
pos: BlockPos,
world: ServerWorld,
info: CallbackInfo
) {
player.mainHandStack.asWrench {
it.item.canMine(world.getBlockState(pos), world, pos, player)
info.cancel()
}
}
fun allowWrench(player: PlayerEntity, stack: ItemStack): Boolean {
return player.isCreativeLevelTwoOp || stack.isWrench()
}
fun getProperties(state: BlockState, stack: ItemStack): ImmutableList<Property<*>> {
if (stack.isWrench() && state.isWrencheable()) {
val property = stack.getWrenchProperty(state) ?: return EMPTY_LIST
if (WrenchBlockState.isAllowed(state, property)) {
return WrenchBlockState.getProperties(state.block)
}
}
return EMPTY_LIST
}
fun <T> getValues(state: BlockState, property: Property<*>): Collection<T> {
@Suppress("UNCHECKED_CAST")
return WrenchBlockState.getValues(state.block, property) as Collection<T>
}
fun interactItemFrame(
frameEntity: Any,
player: PlayerEntity,
hand: Hand,
info: CallbackInfoReturnable<ActionResult>
) {
val itemFrame = frameEntity as? ItemFrameEntity ?: return
player.getStackInHand(hand).asWrench {
itemFrame.isInvisible = !itemFrame.isInvisible
if (player is ServerPlayerEntity)
player.sendHUD("Invisible: ${itemFrame.isInvisible.toString().uppercase()}")
info.setReturnValue(ActionResult.PASS)
}
}
fun attackItemFrame(frameEntity: Any, attacker: Entity): Boolean {
val player = attacker as? PlayerEntity ?: return false
if (!player.mainHandStack.isWrench()) {
return false
}
val itemFrame = frameEntity as? ItemFrameEntityAccessor ?: return false
itemFrame.fixed = !itemFrame.fixed
if (player is ServerPlayerEntity)
player.sendHUD("Fixed: ${itemFrame.fixed.toString().uppercase()}")
return true
}
}
}
| 0 | Kotlin | 0 | 0 | 50591c86c8c3ed74c567d2182088736f7c9f3128 | 20,989 | fabric-mod-s6 | Creative Commons Zero v1.0 Universal |
mefab/src/main/java/io/hussienfahmy/mefab/MeFabRestricted.kt | Hussienfahmy | 441,770,057 | false | {"Kotlin": 32838} | package io.hussienfahmy.mefab
/**
* Me fab restricted.
* as [io.hussienfahmy.mefab.models.Point] and [io.hussienfahmy.mefab.enums.Position] used in [MovableExpandedFloatingActionButton]
* so they must be public so i need to prevent user from using them
*/
@RequiresOptIn(
level = RequiresOptIn.Level.ERROR,
message = "This is internal API for MeFab library, please don't rely on it."
)
public annotation class MeFabRestricted | 0 | Kotlin | 2 | 14 | cf88755a9ed3ce134e507f9d36cf0246872313a1 | 438 | MeFab | MIT License |
app/src/main/java/com/ojhdtapp/parabox/ui/theme/FontSize.kt | Parabox-App | 482,740,446 | false | {"Kotlin": 931869, "Java": 70712} | package com.ojhdtapp.parabox.ui.theme
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.ui.unit.TextUnit
import androidx.compose.ui.unit.sp
data class FontSize(
val title: TextUnit = 20.sp
)
val LocalFontSize = compositionLocalOf { FontSize() }
val MaterialTheme.fontSize: FontSize
@Composable
@ReadOnlyComposable
get() = LocalFontSize.current | 0 | Kotlin | 5 | 98 | 044d9ed13bce54d28c8e95f344239f7ee8e6c451 | 530 | Parabox | MIT License |
swc-binding/src/main/kotlin/dev/yidafu/swc/dsl/TsEnumMember.kt | yidafu | 745,507,915 | false | {"Kotlin": 1532978, "JavaScript": 1186983, "TypeScript": 52873, "Rust": 15241, "Shell": 2012} | package dev.yidafu.swc.dsl
import dev.yidafu.swc.types.*
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> IdentifierImpl
*/
fun TsEnumMember.identifier(block: Identifier.() -> Unit): Identifier {
return IdentifierImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> StringLiteralImpl
*/
fun TsEnumMember.stringLiteral(block: StringLiteral.() -> Unit): StringLiteral {
return StringLiteralImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> ThisExpressionImpl
*/
fun TsEnumMember.thisExpression(block: ThisExpression.() -> Unit): ThisExpression {
return ThisExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> ArrayExpressionImpl
*/
fun TsEnumMember.arrayExpression(block: ArrayExpression.() -> Unit): ArrayExpression {
return ArrayExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> ObjectExpressionImpl
*/
fun TsEnumMember.objectExpression(block: ObjectExpression.() -> Unit): ObjectExpression {
return ObjectExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> FunctionExpressionImpl
*/
fun TsEnumMember.functionExpression(block: FunctionExpression.() -> Unit): FunctionExpression {
return FunctionExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> UnaryExpressionImpl
*/
fun TsEnumMember.unaryExpression(block: UnaryExpression.() -> Unit): UnaryExpression {
return UnaryExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> UpdateExpressionImpl
*/
fun TsEnumMember.updateExpression(block: UpdateExpression.() -> Unit): UpdateExpression {
return UpdateExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> BinaryExpressionImpl
*/
fun TsEnumMember.binaryExpression(block: BinaryExpression.() -> Unit): BinaryExpression {
return BinaryExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> AssignmentExpressionImpl
*/
fun TsEnumMember.assignmentExpression(block: AssignmentExpression.() -> Unit): AssignmentExpression {
return AssignmentExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> MemberExpressionImpl
*/
fun TsEnumMember.memberExpression(block: MemberExpression.() -> Unit): MemberExpression {
return MemberExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> SuperPropExpressionImpl
*/
fun TsEnumMember.superPropExpression(block: SuperPropExpression.() -> Unit): SuperPropExpression {
return SuperPropExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> ConditionalExpressionImpl
*/
fun TsEnumMember.conditionalExpression(block: ConditionalExpression.() -> Unit): ConditionalExpression {
return ConditionalExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> CallExpressionImpl
*/
fun TsEnumMember.callExpression(block: CallExpression.() -> Unit): CallExpression {
return CallExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> NewExpressionImpl
*/
fun TsEnumMember.newExpression(block: NewExpression.() -> Unit): NewExpression {
return NewExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> SequenceExpressionImpl
*/
fun TsEnumMember.sequenceExpression(block: SequenceExpression.() -> Unit): SequenceExpression {
return SequenceExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> BooleanLiteralImpl
*/
fun TsEnumMember.booleanLiteral(block: BooleanLiteral.() -> Unit): BooleanLiteral {
return BooleanLiteralImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> NullLiteralImpl
*/
fun TsEnumMember.nullLiteral(block: NullLiteral.() -> Unit): NullLiteral {
return NullLiteralImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> NumericLiteralImpl
*/
fun TsEnumMember.numericLiteral(block: NumericLiteral.() -> Unit): NumericLiteral {
return NumericLiteralImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> BigIntLiteralImpl
*/
fun TsEnumMember.bigIntLiteral(block: BigIntLiteral.() -> Unit): BigIntLiteral {
return BigIntLiteralImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> RegExpLiteralImpl
*/
fun TsEnumMember.regExpLiteral(block: RegExpLiteral.() -> Unit): RegExpLiteral {
return RegExpLiteralImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> JSXTextImpl
*/
fun TsEnumMember.jSXText(block: JSXText.() -> Unit): JSXText {
return JSXTextImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> TemplateLiteralImpl
*/
fun TsEnumMember.templateLiteral(block: TemplateLiteral.() -> Unit): TemplateLiteral {
return TemplateLiteralImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> TaggedTemplateExpressionImpl
*/
fun TsEnumMember.taggedTemplateExpression(block: TaggedTemplateExpression.() -> Unit): TaggedTemplateExpression {
return TaggedTemplateExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> ArrowFunctionExpressionImpl
*/
fun TsEnumMember.arrowFunctionExpression(block: ArrowFunctionExpression.() -> Unit): ArrowFunctionExpression {
return ArrowFunctionExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> ClassExpressionImpl
*/
fun TsEnumMember.classExpression(block: ClassExpression.() -> Unit): ClassExpression {
return ClassExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> YieldExpressionImpl
*/
fun TsEnumMember.yieldExpression(block: YieldExpression.() -> Unit): YieldExpression {
return YieldExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> MetaPropertyImpl
*/
fun TsEnumMember.metaProperty(block: MetaProperty.() -> Unit): MetaProperty {
return MetaPropertyImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> AwaitExpressionImpl
*/
fun TsEnumMember.awaitExpression(block: AwaitExpression.() -> Unit): AwaitExpression {
return AwaitExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> ParenthesisExpressionImpl
*/
fun TsEnumMember.parenthesisExpression(block: ParenthesisExpression.() -> Unit): ParenthesisExpression {
return ParenthesisExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> JSXMemberExpressionImpl
*/
fun TsEnumMember.jSXMemberExpression(block: JSXMemberExpression.() -> Unit): JSXMemberExpression {
return JSXMemberExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> JSXNamespacedNameImpl
*/
fun TsEnumMember.jSXNamespacedName(block: JSXNamespacedName.() -> Unit): JSXNamespacedName {
return JSXNamespacedNameImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> JSXEmptyExpressionImpl
*/
fun TsEnumMember.jSXEmptyExpression(block: JSXEmptyExpression.() -> Unit): JSXEmptyExpression {
return JSXEmptyExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> JSXElementImpl
*/
fun TsEnumMember.jSXElement(block: JSXElement.() -> Unit): JSXElement {
return JSXElementImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> JSXFragmentImpl
*/
fun TsEnumMember.jSXFragment(block: JSXFragment.() -> Unit): JSXFragment {
return JSXFragmentImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> TsTypeAssertionImpl
*/
fun TsEnumMember.tsTypeAssertion(block: TsTypeAssertion.() -> Unit): TsTypeAssertion {
return TsTypeAssertionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> TsConstAssertionImpl
*/
fun TsEnumMember.tsConstAssertion(block: TsConstAssertion.() -> Unit): TsConstAssertion {
return TsConstAssertionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> TsNonNullExpressionImpl
*/
fun TsEnumMember.tsNonNullExpression(block: TsNonNullExpression.() -> Unit): TsNonNullExpression {
return TsNonNullExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> TsAsExpressionImpl
*/
fun TsEnumMember.tsAsExpression(block: TsAsExpression.() -> Unit): TsAsExpression {
return TsAsExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> TsSatisfiesExpressionImpl
*/
fun TsEnumMember.tsSatisfiesExpression(block: TsSatisfiesExpression.() -> Unit): TsSatisfiesExpression {
return TsSatisfiesExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> TsInstantiationImpl
*/
fun TsEnumMember.tsInstantiation(block: TsInstantiation.() -> Unit): TsInstantiation {
return TsInstantiationImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> PrivateNameImpl
*/
fun TsEnumMember.privateName(block: PrivateName.() -> Unit): PrivateName {
return PrivateNameImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> OptionalChainingExpressionImpl
*/
fun TsEnumMember.optionalChainingExpression(block: OptionalChainingExpression.() -> Unit): OptionalChainingExpression {
return OptionalChainingExpressionImpl().apply(block)
}
/**
* TsEnumMember#init: Expression
* extension function for create Expression -> InvalidImpl
*/
fun TsEnumMember.invalid(block: Invalid.() -> Unit): Invalid {
return InvalidImpl().apply(block)
}
fun TsEnumMember.span(block: Span.() -> Unit): Span {
return Span().apply(block)
} | 1 | Kotlin | 0 | 0 | fecf831e1b47f4693eba781e74d3cf7df22dfac7 | 11,006 | swc-binding | Apache License 2.0 |
android/app/src/main/java/com/smarttoni/database/DbOpenHelper.kt | karthikv8058 | 359,537,229 | false | null | package com.smarttoni.database
import android.content.Context
import com.smarttoni.MainApplication
import com.smarttoni.entities.DaoMaster
import com.smarttoni.entities.DaoMaster.dropAllTables
import com.smarttoni.entities.DaoSession
import org.greenrobot.greendao.database.Database
class DbOpenHelper(context: Context, name: String) : DaoMaster.OpenHelper(context, name) {
override fun onUpgrade(db: Database?, oldVersion: Int, newVersion: Int) {
//super.onUpgrade(db, oldVersion, newVersion)
dropAllTables(db, true)
onCreate(db)
}
companion object {
val DB_NAME = "smartoni.db"
fun getDaoSession(context: Context): DaoSession {
return (context.applicationContext as MainApplication).daoSession
}
}
}
| 1 | null | 1 | 1 | a2d21a019d8a67f0c3b52c102b6961e558219732 | 785 | kitchen-app | MIT License |
repository/src/main/java/com/architecture/repository/weather/remote/model/WeatherModel.kt | hoanggiang063 | 275,876,192 | false | null | package com.architecture.repository.weather.remote.model
import com.google.gson.annotations.SerializedName
data class WeatherModel(
@SerializedName("city")
var city: City,
@SerializedName("list")
var list: List<ForeCast>
)
data class City(
@SerializedName("id")
var id: String,
@SerializedName("name")
var name: String,
@SerializedName("coord")
var coord: CityCoord,
@SerializedName("country")
var country: String,
@SerializedName("population")
var population: Int = 0,
@SerializedName("timeZone")
var timeZone: String
)
data class CityCoord(
@SerializedName("lon")
var lon: Double = 0.0,
@SerializedName("lat")
var lat: Double = 0.0
)
data class ForeCast(
@SerializedName("dt")
var dt: Long = 0,
@SerializedName("sunrise")
var sunrise: Double = 0.0,
@SerializedName("sunset")
var sunset: Double = 0.0,
@SerializedName("temp")
var temp: Temperature,
@SerializedName("feels_like")
var feels_like: FeelsLike,
@SerializedName("pressure")
var pressure: Int = 0,
@SerializedName("humidity")
var humidity: Int = 0,
@SerializedName("weather")
var weather: List<Weather>,
@SerializedName("speed")
var speed: Double = 0.0,
@SerializedName("deg")
var deg: Double = 0.0,
@SerializedName("clouds")
var clouds: Double = 0.0,
@SerializedName("rain")
var rain: Double = 0.0
)
data class Temperature(
@SerializedName("day")
var day: Double = 0.0,
@SerializedName("min")
var min: Double = 0.0,
@SerializedName("max")
var max: Double = 0.0,
@SerializedName("night")
var night: Double = 0.0,
@SerializedName("eve")
var eve: Double = 0.0,
@SerializedName("morn")
var morn: Double = 0.0
)
data class FeelsLike(
@SerializedName("day")
var day: Double = 0.0,
@SerializedName("night")
var night: Double = 0.0,
@SerializedName("eve")
var eve: Double = 0.0,
@SerializedName("morn")
var morn: Double = 0.0
)
data class Weather(
@SerializedName("id")
var id: String,
@SerializedName("main")
var main: String,
@SerializedName("description")
var description: String,
@SerializedName("icon")
var icon: String
)
| 0 | Kotlin | 0 | 3 | 40ec6d77c381984dc178e01c990ef1a74fe85886 | 2,306 | weatherdemo | Apache License 2.0 |
sdk/fido2/src/androidTest/java/com/ibm/security/verifysdk/fido2/model/PublicKeyCredentialParametersTest.kt | ibm-security-verify | 430,929,749 | false | {"Kotlin": 609948} | package com.ibm.security.verifysdk.fido2.model
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.ibm.security.verifysdk.testutils.json
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
import org.skyscreamer.jsonassert.JSONAssert
@RunWith(AndroidJUnit4::class)
class PublicKeyCredentialParametersTest {
@Test
fun testSerialization_withAlg() {
val params = PublicKeyCredentialParameters(
type = PublicKeyCredentialType.PUBLIC_KEY,
alg = 1L // Example COSEAlgorithmIdentifier
)
val jsonString = json.encodeToString(PublicKeyCredentialParameters.serializer(), params)
val expectedJson = """{"type":"public-key","alg":1}"""
JSONAssert.assertEquals(expectedJson, jsonString, false)
}
@Test
fun testSerialization_withoutAlg() {
val params = PublicKeyCredentialParameters(
type = PublicKeyCredentialType.PUBLIC_KEY,
alg = null
)
val jsonString = json.encodeToString(PublicKeyCredentialParameters.serializer(), params)
val expectedJson = """{"type":"public-key"}"""
assertEquals(expectedJson, jsonString)
}
@Test
fun testDeserialization_withAlg() {
val jsonString = """{"type":"public-key","alg":1}"""
val params = json.decodeFromString(PublicKeyCredentialParameters.serializer(), jsonString)
assertEquals(PublicKeyCredentialType.PUBLIC_KEY, params.type)
assertEquals(1L, params.alg)
}
@Test
fun testDeserialization_withoutAlg() {
val jsonString = """{"type":"public-key"}"""
val params = json.decodeFromString(PublicKeyCredentialParameters.serializer(), jsonString)
assertEquals(PublicKeyCredentialType.PUBLIC_KEY, params.type)
assertNull(params.alg)
}
@Test
fun testEquality() {
val params1 = PublicKeyCredentialParameters(
type = PublicKeyCredentialType.PUBLIC_KEY,
alg = 1L
)
val params2 = PublicKeyCredentialParameters(
type = PublicKeyCredentialType.PUBLIC_KEY,
alg = 1L
)
assertEquals(params1, params2)
}
@Test
fun testInequality_differentType() {
val params1 = PublicKeyCredentialParameters(
type = PublicKeyCredentialType.PUBLIC_KEY,
alg = 1L
)
val params2 = PublicKeyCredentialParameters(
type = PublicKeyCredentialType.PUBLIC_KEY, // Same type
alg = 2L // Different alg
)
assertNotEquals(params1, params2)
}
@Test
fun testInequality_differentAlg() {
val params1 = PublicKeyCredentialParameters(
type = PublicKeyCredentialType.PUBLIC_KEY,
alg = 1L
)
val params2 = PublicKeyCredentialParameters(
type = PublicKeyCredentialType.PUBLIC_KEY,
alg = null // Different alg
)
assertNotEquals(params1, params2)
}
@Test
fun testInequality_differentTypeAndAlg() {
val params1 = PublicKeyCredentialParameters(
type = PublicKeyCredentialType.PUBLIC_KEY,
alg = 1L
)
val params2 = PublicKeyCredentialParameters(
type = PublicKeyCredentialType.PUBLIC_KEY, // Same type
alg = 2L // Different alg
)
assertNotEquals(params1, params2)
}
} | 1 | Kotlin | 4 | 0 | af071f85e2b63e7c2e42460d57296a9865b61dbd | 3,509 | verify-sdk-android | MIT License |
api-common/src/main/kotlin/io/qalipsis/api/scenario/DefaultScenarioSpecificationsKeeper.kt | qalipsis | 428,742,260 | false | {"Kotlin": 757187, "Dockerfile": 2015} | /*
* Copyright 2022 AERIS IT Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package io.qalipsis.api.scenario
import io.micronaut.context.annotation.Property
import io.qalipsis.api.context.ScenarioName
import jakarta.inject.Singleton
import java.util.Optional
/**
* Default implementation of the [ScenarioSpecificationsKeeper].
*
* @author Eric Jessé
*/
@Singleton
internal class DefaultScenarioSpecificationsKeeper(
private val injector: Injector,
@Property(name = "scenarios-selectors") private val scenariosSelectors: Optional<String>
) : ScenarioSpecificationsKeeper {
override val scenariosSpecifications = mutableMapOf<ScenarioName, ConfiguredScenarioSpecification>()
override fun reload() {
scenariosSpecifications.clear()
scenariosSpecifications.putAll(ClasspathScenarioInitializer.reload(injector, scenariosSelectors.orElse(null)))
}
}
| 1 | Kotlin | 0 | 0 | 2c0b2934d97fcefe2405ace95e2a908175151658 | 1,417 | qalipsis-api | Apache License 2.0 |
style/schedules/src/androidMain/kotlin/com/paligot/confily/style/schedules/card/ScheduleCard.android.kt | GerardPaligot | 444,230,272 | false | null | package com.paligot.confily.style.schedules.card
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.paligot.confily.style.theme.Conferences4HallTheme
import kotlinx.collections.immutable.persistentListOf
@OptIn(ExperimentalLayoutApi::class)
@Suppress("UnusedPrivateMember")
@Preview
@Composable
private fun SmallScheduleCardPreview() {
Conferences4HallTheme {
SmallScheduleCard(
title = "Designers x Developers : Ça match \uD83D\uDC99 ou ça match \uD83E\uDD4A ?",
speakersUrls = persistentListOf("", ""),
speakersLabel = "<NAME> and <NAME>",
contentDescription = null,
onClick = {},
onFavoriteClick = {}
)
}
}
@Suppress("UnusedPrivateMember")
@Preview
@Composable
private fun ScheduleCardPreview() {
Conferences4HallTheme {
MediumScheduleCard(
title = "Designers x Developers : Ça match \uD83D\uDC99 ou ça match \uD83E\uDD4A ?",
speakersUrls = persistentListOf("", ""),
speakersLabel = "<NAME> and <NAME>",
contentDescription = null,
onClick = {},
onFavoriteClick = {}
)
}
}
@Suppress("UnusedPrivateMember")
@Preview
@Composable
private fun ScheduleCardFavoritePreview() {
Conferences4HallTheme {
MediumScheduleCard(
title = "Designers x Developers : Ça match \uD83D\uDC99 ou ça match \uD83E\uDD4A ?",
speakersUrls = persistentListOf("", ""),
speakersLabel = "<NAME> and <NAME>",
isFavorite = true,
contentDescription = null,
onClick = {},
onFavoriteClick = {}
)
}
}
| 9 | null | 6 | 143 | 8c0985b73422d6b388012d79c7ab33c054dc55c1 | 1,789 | Confily | Apache License 2.0 |
app/src/androidTest/kotlin/io/crypto/bitstamp/adapter/PricePagerAdapterTest.kt | MGaetan89 | 111,290,623 | false | null | package io.crypto.bitstamp.adapter
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import io.crypto.bitstamp.R
import io.crypto.bitstamp.activity.PricesActivity
import io.crypto.bitstamp.fragment.PriceOrderBookFragment
import io.crypto.bitstamp.fragment.PriceOverviewFragment
import io.crypto.bitstamp.fragment.PriceTransactionsFragment
import io.crypto.bitstamp.model.TradingPair
import org.assertj.android.api.Assertions.assertThat
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class PricePagerAdapterTest {
@JvmField
@Rule
var activityRule = ActivityTestRule(PricesActivity::class.java)
private lateinit var adapter: PricePagerAdapter
private lateinit var tradingPair: TradingPair
@Before
fun before() {
val fragmentManager = this.activityRule.activity.supportFragmentManager
val resources = this.activityRule.activity.resources
this.tradingPair = TradingPair(
8, 2, "Litecoin / U.S. dollar", "5.0 USD",
"LTC/USD", TradingPair.Trading.Enabled, "ltcusd"
)
this.adapter = PricePagerAdapter(this.tradingPair, resources, fragmentManager)
}
@Test
fun getCount() {
assertThat(this.adapter.count).isEqualTo(3)
}
@Test
fun getItem_first() {
val fragment = this.adapter.getItem(0)
assertThat(fragment).isInstanceOf(PriceOverviewFragment::class.java)
assertThat(fragment.arguments).hasSize(1)
assertThat(fragment.arguments).hasKey(TradingPair.EXTRA)
assertThat(fragment.arguments?.getParcelable<TradingPair>(TradingPair.EXTRA)).isEqualTo(this.tradingPair)
}
@Test
fun getItem_second() {
val fragment = this.adapter.getItem(1)
assertThat(fragment).isInstanceOf(PriceOrderBookFragment::class.java)
assertThat(fragment.arguments).hasSize(1)
assertThat(fragment.arguments).hasKey(TradingPair.EXTRA)
assertThat(fragment.arguments?.getParcelable<TradingPair>(TradingPair.EXTRA)).isEqualTo(this.tradingPair)
}
@Test
fun getItem_third() {
val fragment = this.adapter.getItem(2)
assertThat(fragment).isInstanceOf(PriceTransactionsFragment::class.java)
assertThat(fragment.arguments).hasSize(1)
assertThat(fragment.arguments).hasKey(TradingPair.EXTRA)
assertThat(fragment.arguments?.getParcelable<TradingPair>(TradingPair.EXTRA)).isEqualTo(this.tradingPair)
}
@Test(expected = IllegalArgumentException::class)
fun getItem_unknown() {
this.adapter.getItem(3)
}
@Test
fun getPageTitle_first() {
assertThat(this.adapter.getPageTitle(0)).isEqualTo(this.activityRule.activity.getString(R.string.overview))
}
@Test
fun getPageTitle_second() {
assertThat(this.adapter.getPageTitle(1)).isEqualTo(this.activityRule.activity.getString(R.string.order_book))
}
@Test
fun getPageTitle_third() {
assertThat(this.adapter.getPageTitle(2)).isEqualTo(this.activityRule.activity.getString(R.string.transactions))
}
@Test(expected = IllegalArgumentException::class)
fun getPageTitle_unknown() {
this.adapter.getPageTitle(3)
}
}
| 0 | Kotlin | 2 | 5 | a7a92e45c23ba4714627599f103057349d5e254a | 3,088 | Bitcoin | Apache License 2.0 |
core/src/main/java/com/alvayonara/mealsfood/core/ui/FoodAdapter.kt | alvayonara | 307,544,464 | false | null | package com.alvayonara.mealsfood.core.ui
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.alvayonara.mealsfood.core.R
import com.alvayonara.mealsfood.core.databinding.ItemRowFoodGridBinding
import com.alvayonara.mealsfood.core.databinding.ItemRowFoodListBinding
import com.alvayonara.mealsfood.core.databinding.ItemRowPopularFoodBinding
import com.alvayonara.mealsfood.core.domain.model.Food
import com.bumptech.glide.Glide
class FoodAdapter constructor(private val typeView: Int) :
RecyclerView.Adapter<FoodAdapter.FoodViewHolder>() {
private var listFoods = ArrayList<Food>()
var onItemClick: ((Food) -> Unit)? = null
companion object {
const val TYPE_POPULAR_FOOD = 0
const val TYPE_GRID = 1
const val TYPE_LIST = 2
}
fun setFoods(foods: List<Food>?) {
if (foods == null) return
listFoods.clear()
listFoods.addAll(foods)
notifyDataSetChanged()
}
fun clearFoods() {
val size: Int = listFoods.size
if (size > 0) {
for (i in 0 until size) {
listFoods.removeAt(0)
}
notifyItemRangeRemoved(0, size)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FoodViewHolder {
val rowLayout = when (typeView) {
TYPE_POPULAR_FOOD -> R.layout.item_row_popular_food
TYPE_GRID -> R.layout.item_row_food_grid
TYPE_LIST -> R.layout.item_row_food_list
else -> throw IllegalArgumentException("Invalid view type")
}
val view = LayoutInflater.from(parent.context).inflate(
rowLayout,
parent,
false
)
return FoodViewHolder(view)
}
override fun getItemCount(): Int = listFoods.size
override fun onBindViewHolder(holder: FoodViewHolder, position: Int) =
holder.bindItem(listFoods[position], typeView)
inner class FoodViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private lateinit var bindingRowPopularFoodBinding: ItemRowPopularFoodBinding
private lateinit var bindingRowFoodGrid: ItemRowFoodGridBinding
private lateinit var bindingRowFoodList: ItemRowFoodListBinding
fun bindItem(food: Food, typeView: Int) {
when (typeView) {
TYPE_POPULAR_FOOD -> bindingRowPopularFoodBinding = ItemRowPopularFoodBinding.bind(itemView)
TYPE_GRID -> bindingRowFoodGrid = ItemRowFoodGridBinding.bind(itemView)
TYPE_LIST -> bindingRowFoodList = ItemRowFoodListBinding.bind(itemView)
}
val foodImageView = when (typeView) {
TYPE_POPULAR_FOOD -> bindingRowPopularFoodBinding.ivFoodPopular
TYPE_GRID -> bindingRowFoodGrid.ivFood
TYPE_LIST -> bindingRowFoodList.ivFoodFavorite
else -> throw IllegalArgumentException("Invalid view type")
}
val foodTextView = when (typeView) {
TYPE_POPULAR_FOOD -> bindingRowPopularFoodBinding.tvFoodPopular
TYPE_GRID -> bindingRowFoodGrid.tvFood
TYPE_LIST -> bindingRowFoodList.tvFoodFavorite
else -> throw IllegalArgumentException("Invalid view type")
}
food.let {
Glide.with(itemView.context)
.load(it.strMealThumb)
.into(foodImageView)
foodTextView.text = it.strMeal
}
}
init {
itemView.setOnClickListener {
onItemClick?.invoke(listFoods[adapterPosition])
}
}
}
} | 0 | Kotlin | 2 | 4 | 52a46f41c396db5b35c8bd7888f930ace320836b | 3,775 | MealsFood | Apache License 2.0 |
webapi-core/src/main/java/com/tuuzed/webapi/ConverterUtils.kt | tuuzedarchive | 171,901,230 | false | null | package com.tuuzed.webapi
import okhttp3.Response
import okhttp3.ResponseBody
import okio.BufferedSource
import java.io.IOException
import java.io.InputStream
import java.io.Reader
import java.lang.reflect.Method
object ConverterUtils {
@Suppress("UNCHECKED_CAST")
@JvmStatic
@Throws(IOException::class)
fun <T> tryConvert(converter: Converter, method: Method, args: Array<Any?>?, response: Response): T {
val returnType = ParameterizedTypeImpl(method.genericReturnType)
return when (val dataType = returnType.ownerType) {
Response::class.java -> response as T
ResponseBody::class.java -> (response.body() ?: throw WebApiException.emptyResponseBody()) as T
InputStream::class.java -> response.body()?.byteStream() as T ?: throw WebApiException.emptyResponseBody()
Reader::class.java -> response.body()?.charStream() as T ?: throw WebApiException.emptyResponseBody()
String::class.java -> response.body()?.string() as T ?: throw WebApiException.emptyResponseBody()
ByteArray::class.java -> response.body()?.bytes() as T ?: throw WebApiException.emptyResponseBody()
BufferedSource::class.java -> response.body()?.source() as T ?: throw WebApiException.emptyResponseBody()
null -> throw WebApiException.unsupportedReturnTypes()
else -> return converter.convert(dataType, args, response)
}
}
} | 0 | Kotlin | 0 | 0 | 717d85a302f5b44f2805ed3faf79ac032e8c8e41 | 1,444 | webapi | Apache License 2.0 |
src/main/kotlin/com/github/versusfm/kotlinsql/ast/FromClause.kt | versus-fm | 720,887,840 | false | {"Kotlin": 68668} | package com.github.versusfm.kotlinsql.ast
import com.github.versusfm.kotlinsql.query.QueryContext
import com.github.versusfm.kotlinsql.util.JoinType
import java.lang.RuntimeException
sealed interface FromClause : QueryNode {
data class FromTable(val tableName: String) : FromClause {
override fun compile(context: QueryContext<*>): String {
return "FROM \"${tableName}\""
}
}
data class JoinTable(val tableName: String, val joinType: JoinType) : FromClause {
internal var condition: ConditionClause? = null
override fun compile(context: QueryContext<*>): String {
return when (condition) {
null -> {
throw RuntimeException("Condition cannot be empty")
}
else -> if (joinType.fragment == null) {
"JOIN \"${tableName}\" ON ${condition?.compile(context)}"
} else {
"${joinType.fragment} JOIN \"${tableName}\" ON ${condition?.compile(context)}"
}
}
}
}
} | 0 | Kotlin | 0 | 0 | dfc10c6fbc4cabe572b064daa205cbd489aa1e5d | 1,085 | kotlin-query | MIT License |
src/main/kotlin/nft/freeport/processor/cms/nft/AttachToNFTEventProcessor.kt | rodrigoieh | 437,271,281 | false | null | package nft.freeport.processor.cms.nft
import nft.freeport.listener.event.AttachToNFT
import nft.freeport.listener.event.SmartContractEventData
import nft.freeport.processor.cms.CmsConfig
import nft.freeport.processor.cms.CmsExistingNftRelatedEventProcessor
import nft.freeport.processor.cms.strapi.StrapiService
import org.slf4j.LoggerFactory
import javax.enterprise.context.ApplicationScoped
@ApplicationScoped
class AttachToNFTEventProcessor(override val strapiService: StrapiService) :
CmsExistingNftRelatedEventProcessor<AttachToNFT> {
private val log = LoggerFactory.getLogger(javaClass)
override val supportedClass = AttachToNFT::class.java
override fun process(eventData: SmartContractEventData<out AttachToNFT>, nftId: Long, minter: String) {
if (!minter.equals(eventData.event.sender, true)) {
log.warn("Received AttachToNFT event for NFT {} from non-minter {}. Skip.", nftId, eventData.event.sender)
return
}
strapiService.create(CmsConfig.Routes::nftCid, NftCid(nftId, eventData.event.sender, eventData.event.cid))
}
} | 0 | null | 0 | 0 | 1bb284acbd01b94b80a4e6d20c1672f191fbfe77 | 1,103 | freeport-sc-event-listener | Apache License 2.0 |
composeApp/src/commonMain/kotlin/network/chaintech/chartscmp/ui/linechart/GridLineChart.kt | Chaintech-Network | 819,210,577 | false | {"Kotlin": 145665, "Swift": 522} | package network.chaintech.chartscmp.ui.linechart
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.dp
import network.chaintech.chartsLib.ui.linechart.model.IntersectionPoint
import network.chaintech.chartscmp.theme.font_color
import network.chaintech.chartscmp.theme.gray_light
import network.chaintech.chartscmp.theme.green_dark
import network.chaintech.chartscmp.theme.magenta_dark
import network.chaintech.chartscmp.theme.purple_dark
import network.chaintech.chartscmp.theme.white_color
import network.chaintech.cmpcharts.axis.AxisProperties
import network.chaintech.cmpcharts.common.extensions.formatToSinglePrecision
import network.chaintech.cmpcharts.common.model.Point
import network.chaintech.cmpcharts.common.ui.GridLinesUtil
import network.chaintech.cmpcharts.common.ui.SelectionHighlightPoint
import network.chaintech.cmpcharts.common.ui.SelectionHighlightPopUp
import network.chaintech.cmpcharts.common.ui.ShadowUnderLine
import network.chaintech.cmpcharts.ui.linechart.LineChart
import network.chaintech.cmpcharts.ui.linechart.model.Line
import network.chaintech.cmpcharts.ui.linechart.model.LineChartProperties
import network.chaintech.cmpcharts.ui.linechart.model.LinePlotData
import network.chaintech.cmpcharts.ui.linechart.model.LineStyle
import network.chaintech.composeapp.generated.resources.Res
import network.chaintech.composeapp.generated.resources.Roboto_Regular
import org.jetbrains.compose.resources.Font
@Composable
fun SingleLineChartWithGridLines(pointsData: List<Point>) {
val textMeasurer = rememberTextMeasurer()
val steps = 5
val xAxisProperties = AxisProperties(
font = FontFamily(
Font(Res.font.Roboto_Regular, weight = FontWeight.Normal)
),
stepSize = 30.dp,
topPadding = 105.dp,
labelColor = font_color,
lineColor = font_color,
stepCount = pointsData.size - 1,
labelFormatter = { i -> pointsData[i].x.toInt().toString() },
labelPadding = 15.dp
)
val yAxisProperties = AxisProperties(
font = FontFamily(
Font(Res.font.Roboto_Regular, weight = FontWeight.Normal)
),
stepCount = steps,
labelColor = font_color,
lineColor = font_color,
labelPadding = 20.dp,
labelFormatter = { i ->
val yMin = pointsData.minOf { it.y }
val yMax = pointsData.maxOf { it.y }
val yScale = (yMax - yMin) / steps
((i * yScale) + yMin).formatToSinglePrecision()
}
)
val lineChartProperties = LineChartProperties(
linePlotData = LinePlotData(
lines = listOf(
Line(
dataPoints = pointsData,
LineStyle(
color = purple_dark
),
IntersectionPoint(
color = green_dark
),
SelectionHighlightPoint(
color = magenta_dark
),
ShadowUnderLine(),
SelectionHighlightPopUp(
textMeasurer = textMeasurer,
backgroundColor = magenta_dark,
labelColor = white_color,
labelTypeface = FontWeight.Bold
)
)
)
),
xAxisProperties = xAxisProperties,
yAxisProperties = yAxisProperties,
gridLines = GridLinesUtil(color = gray_light)
)
LineChart(
modifier = Modifier
.fillMaxWidth()
.height(300.dp),
lineChartProperties = lineChartProperties
)
} | 2 | Kotlin | 11 | 110 | bb93c3345f5e3f9fd8bcb67508bc291c421a5cce | 3,992 | CMPCharts | Apache License 2.0 |
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/pipes/BatchEnvironmentVariablePropertyDsl.kt | F43nd1r | 643,016,506 | false | null | package com.faendir.awscdkkt.generated.services.pipes
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.Unit
import software.amazon.awscdk.services.pipes.CfnPipe
@Generated
public fun buildBatchEnvironmentVariableProperty(initializer: @AwsCdkDsl
CfnPipe.BatchEnvironmentVariableProperty.Builder.() -> Unit):
CfnPipe.BatchEnvironmentVariableProperty =
CfnPipe.BatchEnvironmentVariableProperty.Builder().apply(initializer).build()
| 1 | Kotlin | 0 | 0 | e08d201715c6bd4914fdc443682badc2ccc74bea | 481 | aws-cdk-kt | Apache License 2.0 |
ypreview/src/main/java/me/yangcx/preview/ui/multiple/image/AdapterMultipleImage.kt | qiushui95 | 160,495,639 | false | null | package me.yangcx.preview.ui.multiple.image
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.bumptech.glide.request.RequestOptions
import me.yangcx.preview.R
import me.yangcx.preview.entity.ImageData
import me.yangcx.preview.ui.multiple.base.AdapterBasePreview
/**
* create by 97457
* create at 2018/12/06
*/
internal class AdapterMultipleImage(inflater: LayoutInflater, requestOptions: RequestOptions, dataList: List<ImageData>) : AdapterBasePreview(inflater, requestOptions, dataList) {
override fun createView(inflater: LayoutInflater, container: ViewGroup): View {
return inflater.inflate(R.layout.item_multiple_preview_image, container, false)
}
} | 0 | Kotlin | 0 | 0 | 249a3bf3bf3f259d2b42d5d39feb2c0d915a8c56 | 714 | MyModulesAndDemos | Apache License 2.0 |
ComposeKtor/app/src/main/java/com/bitmask/android/compose/compose/ktor/MainActivity.kt | PeterLee298 | 825,998,539 | false | {"Kotlin": 59436, "Java": 14316} | package com.bitmask.android.compose.compose.ktor
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.bitmask.android.compose.compose.ktor.ui.theme.ComposeKtorTheme
import com.bitmask.android.compose.compose.ktor.viewmodel.SpaceXViewModel
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
ComposeKtorTheme {
Scaffold(modifier = Modifier.fillMaxSize()) { innerPadding ->
MainScreen(modifier = Modifier.padding(innerPadding))
}
}
}
}
}
@Composable
fun MainScreen(modifier: Modifier = Modifier,viewModel: SpaceXViewModel = SpaceXViewModel()) {
val launches by viewModel.launches.collectAsState()
LaunchedEffect(key1 = Unit, block = {
viewModel.getLaunches()
})
if (launches.isNullOrEmpty()) {
Text(text = "No data")
} else {
LazyColumn {
launches.forEach {
item {
Text(text = "${it.id} ${it.details}")
}
}
}
}
}
@Composable
fun Greeting(name: String, modifier: Modifier = Modifier) {
Text(
text = "Hello $name!",
modifier = modifier
)
}
@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
ComposeKtorTheme {
Greeting("Android")
}
} | 0 | Kotlin | 0 | 0 | f667bbb1917db2d2f037db29d341a1b971748b66 | 2,066 | android-practice | Apache License 2.0 |
src/main/kotlin/com/memoizr/assertk/FloatAssert.kt | memoizr | 64,342,420 | false | {"Kotlin": 78262} | package com.memoizr.assertk
import org.assertj.core.api.AbstractFloatAssert
import org.assertj.core.api.Assertions
class FloatAssert internal constructor(
subjectUnderTest: Float?,
override val assertion: AbstractFloatAssert<*> = Assertions.assertThat(subjectUnderTest)) :
AbstractAssertBuilder<FloatAssert, Float>(subjectUnderTest, FloatAssert::class.java) {
infix fun isLessThan(expected: Float): FloatAssert {
assertion.isLessThan(expected)
return this
}
infix fun isLessThanOrEqualTo(expected: Float): FloatAssert {
assertion.isLessThanOrEqualTo(expected)
return this
}
infix fun isGreaterThan(expected: Float): FloatAssert {
assertion.isGreaterThan(expected)
return this
}
infix fun isGreaterThanOrEqualTo(expected: Float): FloatAssert {
assertion.isGreaterThanOrEqualTo(expected)
return this
}
infix fun isBetween(expected: ClosedRange<Float>): FloatAssert {
assertion.isBetween(expected.start, expected.endInclusive)
return this
}
infix fun isStrictlyBetween(expected: ClosedRange<Float>): FloatAssert {
assertion.isStrictlyBetween(expected.start, expected.endInclusive)
return this
}
infix fun isCloseTo(expected: Float): Close {
return Close(expected, assertion, this)
}
infix fun _is(expected: NumberSelector): FloatAssert {
when (expected) {
zero -> assertion.isZero()
notZero -> assertion.isNotZero()
positive -> assertion.isPositive()
notPositive -> assertion.isNotPositive()
negative -> assertion.isNegative()
notNegative -> assertion.isNotNegative()
}
return this
}
class Close(private val actual: Float, private val assertion: AbstractFloatAssert<*>, private val assert: FloatAssert) {
infix fun withinOffset(expected: Float): FloatAssert {
assertion.isCloseTo(actual, Assertions.within(expected))
return assert
}
infix fun withinPercentage(expected: Number): FloatAssert {
assertion.isCloseTo(actual, Assertions.withinPercentage(expected.toDouble()))
return assert
}
}
}
infix fun Float.isLessThan(expected: Float): FloatAssert =
expect that this isLessThan expected
infix fun Float.isLessThanOrEqualTo(expected: Float): FloatAssert =
expect that this isLessThanOrEqualTo expected
infix fun Float.isGreaterThan(expected: Float): FloatAssert =
expect that this isGreaterThan expected
infix fun Float.isGreaterThanOrEqualTo(expected: Float): FloatAssert =
expect that this isGreaterThanOrEqualTo expected
infix fun Float.isBetween(expected: ClosedRange<Float>): FloatAssert =
expect that this isBetween expected
infix fun Float.isStrictlyBetween(expected: ClosedRange<Float>): FloatAssert =
expect that this isStrictlyBetween expected
infix fun Float.isCloseTo(expected: Float): FloatAssert.Close =
expect that this isCloseTo expected
infix fun Float._is(expected: NumberSelector): FloatAssert =
expect that this _is expected
| 3 | Kotlin | 2 | 22 | 83324f346435a550b665f0e58eb86f0a9eace879 | 3,197 | assertk-core | Apache License 2.0 |
camera/integration-tests/camerapipetestapp/src/main/java/androidx/camera/integration/camera2/pipe/visualizations/Paints.kt | RikkaW | 389,105,112 | false | null | /*
* Copyright 2020 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.camera.integration.camera2.pipe.visualizations
import android.content.Context
import android.graphics.Paint
import android.text.TextPaint
import androidx.camera.integration.camera2.pipe.R
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
/** Uniform paints to be used in all graphs */
class Paints(private val context: Context) {
val whiteFillPaint =
Paint().apply {
color = ContextCompat.getColor(context, R.color.graphDataColor)
style = Paint.Style.FILL_AND_STROKE
strokeWidth = 1f
}
val missingDataPaint =
Paint().apply {
color = ContextCompat.getColor(context, R.color.missingDataColor)
style = Paint.Style.STROKE
strokeWidth = ResourcesCompat.getFloat(context.resources, R.dimen.mediumStrokeWidth)
}
val latencyDataPaint =
Paint().apply {
color = ContextCompat.getColor(context, R.color.latencyDataColor)
style = Paint.Style.STROKE
strokeWidth = ResourcesCompat.getFloat(context.resources, R.dimen.mediumStrokeWidth)
}
val graphDataPaint =
Paint().apply {
color = ContextCompat.getColor(context, R.color.graphDataColor)
style = Paint.Style.STROKE
strokeWidth = ResourcesCompat.getFloat(context.resources, R.dimen.thickStrokeWidth)
}
val dividerLinePaint =
Paint().apply {
color = ContextCompat.getColor(context, R.color.whiteTransparent)
style = Paint.Style.STROKE
strokeWidth = ResourcesCompat.getFloat(context.resources, R.dimen.dividerStrokeWidth)
}
val keyValueValuePaint =
TextPaint().apply {
color = ContextCompat.getColor(context, R.color.graphDataColor)
textSize = ResourcesCompat.getFloat(context.resources, R.dimen.keyValueValueTextSize)
textAlign = Paint.Align.RIGHT
}
}
| 28 | null | 937 | 7 | 6d53f95e5d979366cf7935ad7f4f14f76a951ea5 | 2,607 | androidx | Apache License 2.0 |
src/main/kotlin/no/nav/styringsinformasjon/api/maalekort/MaalekortApi.kt | navikt | 648,145,512 | false | null | package no.nav.styringsinformasjon.api.maalekort
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import no.nav.styringsinformasjon.persistence.DatabaseInterface
import no.nav.styringsinformasjon.persistence.deleteMaalekortXmlByUuidList
import no.nav.styringsinformasjon.persistence.fetchEveryMaalekortXml
import java.util.*
const val deleteRequestHeader = "maalekort-uuid"
const val errorMessageMissingHeader = "Mangler '$deleteRequestHeader' i header på request, eller ugyldig UUID-format"
private fun errorMessageNotFound(uuid: String) = "Fant ikke målekort med uuid: $uuid"
fun Routing.registerMaalekortApi(
databaseAccess: DatabaseInterface
) {
route("/api/v1/maalekort") {
authenticate("basic-auth") {
get {
call.respond(databaseAccess.fetchEveryMaalekortXml().map { entry -> mapOf(entry.uuid to entry.xml) })
}
delete {
val listOfMaalekortToDelete = validateUuidHeader(call.request.headers["maalekort-uuid"])
listOfMaalekortToDelete?.let { uuidList ->
val rowsDeleted = databaseAccess.deleteMaalekortXmlByUuidList(uuidList)
if (rowsDeleted == 0) {
call.respond(
status = HttpStatusCode.NotFound,
message = errorMessageNotFound(uuidList.joinToString(","))
)
}
call.respond(
status = HttpStatusCode.OK,
message = "Slettet $rowsDeleted målekort fra databasen"
)
}
call.respond(
status = HttpStatusCode.BadRequest,
message = errorMessageMissingHeader
)
}
}
}
}
private fun validateUuidHeader(header: String?): List<UUID>? {
return header?.let {
val headerUuids = header.trim().split(",")
return@let try {
headerUuids.map { uuid -> UUID.fromString(uuid.trim()) }
} catch (e: IllegalArgumentException) {
null
}
}
}
| 0 | Kotlin | 0 | 0 | be20ebb57873f4a72c2f760ad66880efdbd83d9b | 2,253 | maalekort-altinn2-adapter | MIT License |
mrz/src/main/kotlin/fr/coppernic/lib/mrz/MrzParser.kt | Coppernic | 414,913,794 | false | null | package fr.coppernic.lib.mrz
import fr.coppernic.lib.log.MrzParserDefines
import fr.coppernic.lib.mrz.model.ErrorType
import fr.coppernic.lib.mrz.model.MrzFormat
import fr.coppernic.lib.mrz.model.MrzParserException
import fr.coppernic.lib.mrz.parser.MrzParserOptions
import fr.coppernic.lib.mrz.parser.ParserFactory
import fr.coppernic.lib.mrz.parser.extensions.divide
import fr.coppernic.lib.mrz.parser.extensions.separate
class MrzParser {
fun parseOrNull(s: String, opt: MrzParserOptions = MrzParserOptions()): Mrz? {
return try {
parse(s, opt)
} catch (e: Exception) {
null
}
}
fun parse(s: String, opt: MrzParserOptions = MrzParserOptions()): Mrz {
return parseLines(s.separate(), opt)
}
fun parseLinesOrNull(lines: List<String>, opt: MrzParserOptions = MrzParserOptions()): Mrz? {
return try {
parseLines(lines, opt)
} catch (e: Exception) {
null
}
}
fun parseLines(lines: List<String>, opt: MrzParserOptions = MrzParserOptions()): Mrz {
if (lines.isEmpty()) {
throw MrzParserException(ErrorType.WrongFormat("Not enough lines (Actual ${lines.size})"))
}
// Handle case where one single line is given. Make it more understandable for parser
val newLines = if (lines.size == 1) {
handleSingleLine(lines[0])
} else {
lines
}
val format = getFormat(newLines)
val parser = ParserFactory.make(format)
return parser.parse(newLines, opt)
}
companion object {
private val docRange = 0..4
}
/**
* Return format of MRZ
*/
internal fun getFormat(lines: List<String>): MrzFormat {
val first = lines.getOrElse(0) { "" }
if (first.length < 5) {
throw MrzParserException(ErrorType.WrongFormat("Not enough length (Actual ${first.length})"))
}
val docType = first.substring(docRange)
val lineCount = lines.size
val lineLen = lines.getAndVerifyLen()
var format: MrzFormat? = null
MrzFormat.values().forEach {
if (
it.lineCount == lineCount &&
it.lineLen == lineLen &&
// We are testing the document type against the first letters of the MRZ.
docType.startsWith(it.type) &&
// If length of format type is greater, then it means that it is more precise. So we should
// take the most precise format.
it.type.length >= format?.type?.length ?: 0
) {
format = it
}
}
return format ?: throw MrzParserException(ErrorType.WrongFormat())
}
internal fun handleSingleLine(line: String): MutableList<String> {
val potential = MrzFormat.values().firstOrNull {
if (MrzParserDefines.verbose) {
MrzParserDefines.LOG.trace("$it : ${line.length} == ${it.lineCount * it.lineLen}")
}
(line.length == it.lineCount * it.lineLen)
} ?: throw MrzParserException(ErrorType.WrongFormat("Not enough lines (Actual 1)"))
return line.divide(potential.lineCount)
}
/**
* Get the length of a line and throw an error if lines do not have the same length
*/
internal fun List<String>.getAndVerifyLen(): Int {
val len = getOrNull(0)?.length ?: throw MrzParserException(ErrorType.WrongFormat())
return if (all { it.length == len }) {
len
} else {
throw MrzParserException(ErrorType.WrongFormat())
}
}
}
| 0 | Kotlin | 0 | 1 | 30db7ade14cb2976088372fbad42a4e61ef06f5e | 3,665 | mrz-parser | Apache License 2.0 |
kover-gradle-plugin/src/functionalTest/templates/sources/different-packages/main/kotlin/Sources.kt | Kotlin | 394,574,917 | false | {"Kotlin": 730643, "Java": 23398} | package org.jetbrains.foo
class ExampleClass {
fun used(value: Int): Int {
return value + 1
}
fun unused(value: Long): Long {
return value - 1
}
}
| 60 | Kotlin | 53 | 1,346 | 1acc0548ad33b0aeeccd4e95078490997abf2d54 | 181 | kotlinx-kover | Apache License 2.0 |
reposilite-backend/src/integration/kotlin/com/reposilite/storage/infrastructure/FileSystemStorageProviderIntegrationTest.kt | dzikoysk | 96,474,388 | false | null | /*
* Copyright (c) 2022 dzikoysk
*
* 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.reposilite.storage.infrastructure
import com.reposilite.journalist.backend.InMemoryLogger
import com.reposilite.status.FailureFacade
import com.reposilite.storage.StorageProviderFactory
import com.reposilite.storage.StorageProviderIntegrationTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.io.TempDir
import java.io.File
internal class FileSystemStorageProviderIntegrationTest : StorageProviderIntegrationTest() {
@TempDir
lateinit var rootDirectory: File
@BeforeEach
fun setup() {
val logger = InMemoryLogger()
val failureFacade = FailureFacade(logger)
super.storageProvider = StorageProviderFactory.createStorageProvider(failureFacade, rootDirectory.toPath(), "test-storage", "fs --quota 1MB")
}
} | 13 | Kotlin | 85 | 541 | 2d116b595c64c6b5a71b694ba6d044c40ef16b6a | 1,384 | reposilite | Apache License 2.0 |
presentation/src/main/java/com/moizaandroid/moiza/ui/post/crerate/CreatePostActivity.kt | Software-Meister-High-School-Community | 452,152,042 | false | null | package com.moizaandroid.moiza.ui.post.crerate
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.compose.setContent
import com.moizaandroid.moiza.ui.post.request.ReplayPostScreen
class CreatePostActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ReplayPostScreen(onPrevious = { finish() }) {
}
}
}
} | 8 | Kotlin | 0 | 4 | 9e2521871663805a4b50f23497dfee972bab1766 | 490 | MOIZA_Android | MIT License |
app/src/test/kotlin/com/ayatk/biblio/data/remote/util/QueryBuilderTest.kt | ayatk | 101,084,816 | false | null | /*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.data.remote.util
import com.ayatk.biblio.data.remote.exception.NarouOutOfRangeException
import com.ayatk.biblio.infrastructure.database.entity.enums.OutputOrder
import org.hamcrest.CoreMatchers.`is`
import org.junit.Assert.assertThat
import org.junit.Test
@Suppress("TooManyFunctions")
class QueryBuilderTest {
@Test
fun setNcodeQueryTest() {
val ans = mapOf(Pair("out", "json"), Pair("ncode", "n1234ab"))
assertThat(ans, `is`(QueryBuilder().ncode("n1234ab").build()))
}
@Test
fun setNcodeArrayQueryTest() {
val ncodeArray = arrayOf("n1234ab", "n2345bc", "n3456cd")
val ans = mapOf(Pair("out", "json"), Pair("ncode", ncodeArray.joinToString("-")))
assertThat(ans, `is`(QueryBuilder().ncode(*ncodeArray).build()))
}
@Test
fun setLimitQueryTest() {
val ans = mapOf(Pair("out", "json"), Pair("lim", "300"))
assertThat(ans, `is`(QueryBuilder().size(300).build()))
}
@Test
fun throwLimitQueryTest() {
val throwNums = arrayOf(
0, // zero
-1, // negative value
501 // over value
)
throwNums.forEach {
try {
QueryBuilder().size(it).build()
} catch (e: NarouOutOfRangeException) {
assertThat("out of output limit (1 ~ 500)", `is`(e.message))
}
}
}
@Test
fun setStartQueryTest() {
val ans = mapOf(Pair("out", "json"), Pair("st", "300"))
assertThat(ans, `is`(QueryBuilder().start(300).build()))
}
@Test
fun throwStartQueryTest() {
val throwNums = arrayOf(
0, // zero
-1, // negative value
2001 // over value
)
throwNums.forEach {
try {
QueryBuilder().start(it).build()
} catch (e: NarouOutOfRangeException) {
assertThat("out of start number (1 ~ 2000)", `is`(e.message))
}
}
}
@Test
fun setOrderQueryTest() {
val ans = mapOf(Pair("out", "json"))
OutputOrder.values().forEach {
assertThat(ans.plus(Pair("order", it.id)), `is`(QueryBuilder().order(it).build()))
}
}
@Test
fun setSearchWordsTest() {
// ほげ
val ans = mapOf(Pair("out", "json"), Pair("word", "%E3%81%BB%E3%81%92"))
assertThat(ans, `is`(QueryBuilder().searchWords("ほげ").build()))
}
@Test
fun setSearchWordsArrayQueryTest() {
val wordsArray = arrayOf("ほげ", "ふが", "ぴよ")
// ほげ+ふが+ぴよ
val ans = mapOf(
Pair("out", "json"),
Pair("word", "%E3%81%BB%E3%81%92+%E3%81%B5%E3%81%8C+%E3%81%B4%E3%82%88")
)
assertThat(ans, `is`(QueryBuilder().searchWords(*wordsArray).build()))
}
@Test
fun setNotSearchWordsTest() {
// ほげ
val ans = mapOf(Pair("out", "json"), Pair("notword", "%E3%81%BB%E3%81%92"))
assertThat(ans, `is`(QueryBuilder().notWords("ほげ").build()))
}
@Test
fun setNotSearchWordsArrayQueryTest() {
val wordsArray = arrayOf("ほげ", "ふが", "ぴよ")
// ほげ+ふが+ぴよ
val ans = mapOf(
Pair("out", "json"),
Pair("notword", "%E3%81%BB%E3%81%92+%E3%81%B5%E3%81%8C+%E3%81%B4%E3%82%88")
)
assertThat(ans, `is`(QueryBuilder().notWords(*wordsArray).build()))
}
@Test
fun setPickupTest() {
val ans = mapOf(Pair("out", "json"))
assertThat(ans.plus(Pair("ispickup", "1")), `is`(QueryBuilder().pickup(true).build()))
assertThat(ans.plus(Pair("ispickup", "0")), `is`(QueryBuilder().pickup(false).build()))
}
}
| 31 | Kotlin | 1 | 5 | 61f23685042860379cce53635207452b14afae22 | 3,940 | biblio | Apache License 2.0 |
app/src/main/java/com/swayy/musicpark/data/remote/dto/Song/Format.kt | gideonrotich | 557,405,183 | false | {"Kotlin": 274873} | package com.swayy.musicpark.data.remote.dto.Song
data class Format(
val bitrate: Int,
val name: String,
val sampleBits: Int,
val sampleRate: Int,
val type: String
) | 0 | Kotlin | 6 | 58 | aa7ce4d7d4481a76b28de61a82d27958f92192d0 | 185 | MusicPark | MIT License |
sample-screen-first/src/main/java/screenswitchersample/first/FirstDialogFactory.kt | JayNewstrom | 48,964,076 | false | null | package screenswitchersample.first
import android.app.Dialog
import android.content.Context
import com.jaynewstrom.screenswitcher.dialogmanager.DialogFactory
import javax.inject.Inject
internal class FirstDialogFactory @Inject constructor() : DialogFactory {
override fun createDialog(context: Context): Dialog {
return FirstDialog(context)
}
}
private class FirstDialog(context: Context) : Dialog(context) {
init {
setContentView(R.layout.first_dialog)
}
}
| 1 | Kotlin | 2 | 2 | 565a513435ba6c1935ca8c3586aee183fd2d7b17 | 493 | ScreenSwitcher | Apache License 2.0 |
src/test/java/site/hirecruit/hr/thirdParty/aws/sns/service/HrSesServiceTest.kt | themoment-team | 473,691,285 | false | {"Kotlin": 205045, "Dockerfile": 1004, "Shell": 97} | package site.hirecruit.hr.thirdParty.aws.sns.service
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import site.hirecruit.hr.thirdParty.aws.service.CredentialService
import site.hirecruit.hr.thirdParty.aws.service.SesCredentialService
import site.hirecruit.hr.thirdParty.aws.ses.dto.SesRequestDto
import site.hirecruit.hr.thirdParty.aws.ses.service.HrSesServiceImpl
import site.hirecruit.hr.thirdParty.aws.ses.service.component.templateEmail.SesTemplateEmailComponentImpl
import software.amazon.awssdk.services.sesv2.SesV2Client
import software.amazon.awssdk.services.sesv2.model.*
class HrSesServiceTest {
@Test @Disabled
@DisplayName("실제로 ses sdk 랑 상호작용하여 결과를 만들어내는 테스트:: disabled")
fun createSendEmailRequestAndSend(
@Autowired credentialService: SesCredentialService
){
// Given
val emailRequest = SendEmailRequest.builder()
.content(
EmailContent.builder()
.simple(
Message.builder()
.subject(Content.builder()
.data("HiRecruit | 하이리쿠르트 테스트 이메일 입니다.")
.charset("UTF-8")
.build())
.body(Body.builder()
.text(
Content.builder()
.data("테스트 이메일 입니다")
.charset("UTF-8").build()
).build()
).build()
).build()
).destination(Destination.builder()
.toAddresses("<EMAIL>") // sandbox mode:: only verified email
.build()
).fromEmailAddress("<EMAIL>")
.build()
// When
val sendEmail = credentialService.getSdkClient().sendEmail(emailRequest)
// Then
assertThat(sendEmail.sdkHttpResponse().isSuccessful).isTrue
}
@Test
@DisplayName("단건의 templateEmail을 destination에게 정상적으로 보낼 수 있다.")
fun templateEmailWasSendSuccessfulToDestination(){
// Given
val sesV2Client: SesV2Client = mockk()
val sendEmailRequest: SendEmailRequest = mockk()
val sesCredentialService: CredentialService = mockk()
val sesTemplateEmailComponentImpl: SesTemplateEmailComponentImpl = mockk()
val templateSesRequestDto: SesRequestDto.TemplateSesRequestDto = mockk()
// mocking
every { sesTemplateEmailComponentImpl.createTemplateEmailRequest(templateSesRequestDto) }.returns(sendEmailRequest)
every { sesCredentialService.getSdkClient() }.returns(sesV2Client)
every { sesV2Client.sendEmail(sendEmailRequest).sdkHttpResponse().isSuccessful }.returns(true)
every { templateSesRequestDto.destinationDto.toAddress }.returns(listOf())
// when:: emailTemplate을 이용한 이메일을 보낸다.
val hrSesServiceImpl = HrSesServiceImpl(sesTemplateEmailComponentImpl, sesCredentialService)
hrSesServiceImpl.sendEmailWithEmailTemplate(templateSesRequestDto)
// then
verify(exactly = 1) {sesTemplateEmailComponentImpl.createTemplateEmailRequest(any()) }
verify(exactly = 1) { sesCredentialService.getSdkClient() }
verify(exactly = 1) { sesV2Client.sendEmail(sendEmailRequest) }
}
} | 2 | Kotlin | 0 | 16 | 6dbf1779257a5ecde9f51c9878bc0cb8871f5336 | 3,622 | HiRecruit-server | MIT License |
app/src/main/java/com/zorro/kotlin/samples/ui/database/fragment/DatabaseFragment.kt | pangli | 233,767,207 | false | null | package com.zorro.kotlin.samples.ui.database.fragment
import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.view.ViewPager
import android.view.View
import android.widget.TextView
import com.gyf.immersionbar.ImmersionBar
import com.zorro.kotlin.baselibs.base.BackHandlerHelper
import com.zorro.kotlin.baselibs.base.FragmentBackHandler
import com.zorro.kotlin.samples.R
import com.zorro.kotlin.samples.mvp.contract.TestContract
import com.zorro.kotlin.samples.mvp.presenter.TestPresenter
import com.zorro.kotlin.samples.ui.base.ZorroBaseMvpFragment
import com.zorro.kotlin.samples.ui.database.adapter.TabLayoutPagerAdapter
import com.zorro.kotlin.samples.utils.ActivityHelper
import kotlinx.android.synthetic.main.include_toolbar_layout.iv_right
import kotlinx.android.synthetic.main.include_toolbar_layout.toolbar
import kotlinx.android.synthetic.main.include_toolbar_tab_layout.*
import kotlinx.android.synthetic.main.toolbar_tab_layout.*
/**
* @author Zorro
* @date 2019/12/19
* @desc 资料库
*/
class DatabaseFragment : ZorroBaseMvpFragment<TestContract.View, TestContract.Presenter>(),
TestContract.View, FragmentBackHandler {
private val mTitle = mutableListOf("通用资料", "产品资料")
private lateinit var fragmentList: MutableList<Fragment>
private var onTabSelectedListener: MyOnTabSelectedListener? = null
companion object {
fun newInstance(): DatabaseFragment = DatabaseFragment()
}
override fun createPresenter(): TestContract.Presenter = TestPresenter()
override fun attachLayoutRes(): Int = R.layout.toolbar_tab_layout
override fun initView(view: View) {
super.initView(view)
ImmersionBar.setTitleBar(this, toolbar)
iv_right.visibility = View.VISIBLE
initTab()
}
override fun bindListener(view: View) {
onTabSelectedListener = MyOnTabSelectedListener()
tab_layout.addOnTabSelectedListener(onTabSelectedListener!!)
iv_right.setOnClickListener(onClickListener)
}
override fun lazyLoad() {
}
/**
* tab_layout tab 初始化
*/
private fun initTab() {
fragmentList =
mutableListOf(
CommonInformationFragment.newInstance(),
ProductInformationFragment.newInstance()
)
vp_fragment.adapter = TabLayoutPagerAdapter(childFragmentManager, mTitle, fragmentList)
vp_fragment.offscreenPageLimit = mTitle.size
tab_layout.setupWithViewPager(vp_fragment)
for (i in 0 until tab_layout.tabCount) {
val tab = tab_layout.getTabAt(i)//获得每一个tab
if (tab != null) {
tab.setCustomView(R.layout.item_tab_view)//给每一个tab设置view
val item = tab.customView as TextView
item.textSize = if (i == 0) 18f else 15f
item.isSelected = i == 0
item.text = mTitle[i]//设置tab上的文字
}
}
vp_fragment.addOnPageChangeListener(pageListener)
}
/**
* ViewPager 页面改变监听
*/
private val pageListener = object : ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
}
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
}
override fun onPageSelected(position: Int) {
if (position == 0) {
(fragmentList[1] as ProductInformationFragment).onBackPressed()
} else if (position == 1) {
(fragmentList[0] as CommonInformationFragment).onBackPressed()
}
}
}
/**
* TabLayout OnTabSelectedListener
*/
private inner class MyOnTabSelectedListener : TabLayout.OnTabSelectedListener {
override fun onTabSelected(tab: TabLayout.Tab) {
val item = tab.customView as TextView
item.textSize = 18f
item.isSelected = true
}
override fun onTabUnselected(tab: TabLayout.Tab) {
val item = tab.customView as TextView
item.textSize = 15f
item.isSelected = false
}
override fun onTabReselected(tab: TabLayout.Tab) {
}
}
/**
* view 点击事件
*/
private val onClickListener = View.OnClickListener { view ->
when (view.id) {
R.id.iv_right -> {
ActivityHelper.jumpToWebSocketActivity(context!!)
}
}
}
override fun onDestroyView() {
if (onTabSelectedListener != null)
tab_layout.removeOnTabSelectedListener(onTabSelectedListener!!)
vp_fragment.removeOnPageChangeListener(pageListener)
super.onDestroyView()
}
/**
* Fragment返回键
*/
override fun onBackPressed(): Boolean = BackHandlerHelper.handleBackPress(this)
} | 1 | Kotlin | 1 | 2 | bf9cfaad4bcfb83d69647483c8f0ba1a73783891 | 4,902 | KotlinMvp | Apache License 2.0 |
RopeWaysAPI/src/main/kotlin/ru/ropeways/api/utill/Constants.kt | AlFilippov | 514,555,720 | false | null | package ru.ropeways.api.utill
const val LONGITUDE = "lon"
const val LATITUDE = "lat"
const val YANDEX_API_KEY_HEADER = "X-Yandex-API-Key" | 0 | Kotlin | 0 | 1 | b8587bef3897931289bc003f15ecf472c30a7fc4 | 138 | RopeWaysBackend | Apache License 2.0 |
src/main/kotlin/com/bq/poeditor/gradle/Main.kt | masmovil | 233,856,332 | true | {"Kotlin": 61024, "Shell": 1123} | /*
* Copyright 2020 BQ
*
* 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.bq.poeditor.gradle
/**
* Only for testing purposes.
*/
@Suppress("MagicNumber")
fun main() {
val apiToken = "your_api_token"
val projectId = 1234567890
val resDirPath = "your_res_dir_path"
val defaultLanguage = "en"
PoEditorStringsImporter.importPoEditorStrings(apiToken, projectId, defaultLanguage, resDirPath)
} | 1 | Kotlin | 0 | 0 | 8c59a812a13a4d4ff443ce277d82ac54c46ab6b0 | 935 | poeditor-android-gradle-plugin | Apache License 2.0 |
libraries/rib-base/src/main/java/com/badoo/ribs/routing/state/action/single/Ext.kt | badoo | 170,855,556 | false | {"Kotlin": 934999} | package com.badoo.ribs.routing.state.action.single
import android.os.Parcelable
import com.badoo.ribs.core.Node
import com.badoo.ribs.routing.state.RoutingContext
import com.badoo.ribs.routing.transition.TransitionDirection
import com.badoo.ribs.routing.transition.TransitionElement
internal fun <C : Parcelable> Node<*>.createTransitionElements(
item: RoutingContext.Resolved<C>,
direction: TransitionDirection,
addedOrRemoved: Boolean
): List<TransitionElement<C>> {
val elements = mutableListOf<TransitionElement<C>>()
if (isViewless) {
children.forEach {
elements += it.createTransitionElements(
item, direction, addedOrRemoved
)
}
} else {
view?.let { ribView ->
elements += TransitionElement(
configuration = item.routing.configuration, // TODO consider passing the whole RoutingElement
direction = direction,
addedOrRemoved = addedOrRemoved,
identifier = identifier,
view = ribView.androidView
)
}
}
return elements
}
| 34 | Kotlin | 50 | 162 | cec2ca936ed17ddd7720b4b7f8fca4ce12033a89 | 1,137 | RIBs | Apache License 2.0 |
godot-kotlin/godot-library/src/nativeGen/kotlin/godot/PHashTranslation.kt | utopia-rise | 238,721,773 | false | {"Kotlin": 655494, "Shell": 171} | // THIS FILE IS GENERATED! DO NOT EDIT IT MANUALLY! ALL CHANGES TO IT WILL BE OVERWRITTEN ON EACH BUILD
package godot
import godot.icalls._icall_Unit_Object
import godot.internal.utils.getMethodBind
import godot.internal.utils.invokeConstructor
import kotlinx.cinterop.COpaquePointer
open class PHashTranslation : Translation() {
override fun __new(): COpaquePointer = invokeConstructor("PHashTranslation", "PHashTranslation")
open fun generate(from: Translation) {
val mb = getMethodBind("PHashTranslation","generate")
_icall_Unit_Object( mb, this.ptr, from)
}
}
| 17 | Kotlin | 17 | 286 | 8d51f614df62a97f16e800e6635ea39e7eb1fd62 | 581 | godot-kotlin-native | MIT License |
app/src/main/java/com/flowfoundation/wallet/page/walletcreate/fragments/mnemonic/WalletCreateMnemonicViewModel.kt | Outblock | 692,942,645 | false | {"Kotlin": 2425609, "Java": 104150} | package com.flowfoundation.wallet.page.walletcreate.fragments.mnemonic
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.flowfoundation.wallet.utils.logd
import com.flowfoundation.wallet.utils.viewModelIOScope
import com.flowfoundation.wallet.wallet.Wallet
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class WalletCreateMnemonicViewModel : ViewModel() {
val mnemonicList = MutableLiveData<List<MnemonicModel>>()
fun loadMnemonic() {
viewModelIOScope(this) {
val str = Wallet.store().mnemonic()
withContext(Dispatchers.Main) {
val list = str.split(" ").mapIndexed { index, s -> MnemonicModel(index + 1, s) }
val result = mutableListOf<MnemonicModel>()
(0 until list.size / 2).forEach { i ->
result.add(list[i])
result.add(list[i + list.size / 2])
}
mnemonicList.value = result
}
logd("Mnemonic", str)
}
}
} | 62 | Kotlin | 5 | 0 | 2426c3e1fa04986395d95dfd5fa6ae18fcf11043 | 1,076 | FRW-Android | Apache License 2.0 |
src/main/kotlin/nu/peg/mobilion/mobilionapi/config/WebConfig.kt | jmesserli | 127,414,573 | false | null | package nu.peg.mobilion.mobilionapi.config
import org.springframework.stereotype.Component
import org.springframework.web.servlet.config.annotation.CorsRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
@Component
class WebConfig : WebMvcConfigurer {
override fun addCorsMappings(registry: CorsRegistry) {
registry.addMapping("/**")
}
} | 0 | Kotlin | 0 | 0 | 2ccae2715a35e61a31d97278c6bbe138f4bac09d | 386 | mobilion-api | MIT License |
android_sdk/buildSrc/src/main/kotlin/Utils.kt | siarhei-luskanau | 79,257,367 | false | null | import java.io.File
import org.apache.tools.ant.taskdefs.condition.Os
fun pathOf(vararg folders: String?) =
folders.filterNotNull().joinToString(separator = File.separator)
fun platformExecutable(name: String, ext: String = "exe"): String =
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
"$name.$ext"
} else {
name
}
| 0 | Kotlin | 0 | 1 | a364c332ab2aca3ed1df3affbf17d52d9f2dcce3 | 342 | android-iot-doorbell | MIT License |
examples/cordapp-sweepstake/states/src/main/kotlin/com/r3/corda/lib/accounts/examples/sweepstake/contracts/states/TeamState.kt | corda | 170,131,330 | false | {"Kotlin": 149237, "Dockerfile": 724} | package com.r3.corda.lib.accounts.examples.sweepstake.contracts.states
import com.r3.corda.lib.accounts.examples.sweepstake.contracts.contracts.TournamentContract
import net.corda.core.contracts.BelongsToContract
import net.corda.core.contracts.LinearState
import net.corda.core.contracts.UniqueIdentifier
import net.corda.core.identity.AbstractParty
import net.corda.core.identity.AnonymousParty
import net.corda.core.serialization.CordaSerializable
import java.security.PublicKey
@BelongsToContract(TournamentContract::class)
data class TeamState(val team: WorldCupTeam,
val assignedToPlayer: Boolean? = false,
val owningKey: PublicKey? = null,
val isStillPlaying: Boolean? = false,
override val linearId: UniqueIdentifier = UniqueIdentifier()) : LinearState {
override val participants: List<AbstractParty>
get() = listOfNotNull(owningKey).map { AnonymousParty(it) }
}
@CordaSerializable
data class WorldCupTeam(val teamName: String, val isAssigned: Boolean) | 28 | Kotlin | 38 | 35 | c2428c28c341d6f9649390e202ff3b02c25cb2f3 | 1,060 | accounts | Apache License 2.0 |
retrofit/src/test/java/com/crazylegend/retrofit/FakeViewEvent.kt | FunkyMuse | 168,687,007 | false | {"Kotlin": 1666612} | package com.crazylegend.retrofit
import com.crazylegend.retrofit.viewstate.event.ViewEventContract
import com.crazylegend.retrofit.viewstate.event.ViewStatefulEvent
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
class FakeViewEvent : ViewEventContract {
private val state = Channel<ViewStatefulEvent>(Channel.BUFFERED)
val event = state.receiveAsFlow()
override suspend fun provideEvent(viewStatefulEvent: ViewStatefulEvent) {
state.send(viewStatefulEvent)
}
} | 0 | Kotlin | 92 | 759 | b38417f2b0791f42d5857b1e0f61785fcb840226 | 529 | KAHelpers | MIT License |
api/src/main/java/mufanc/easyhook/api/hook/HookCreator.kt | Mufanc | 460,466,174 | false | {"Kotlin": 26558} | package mufanc.easyhook.api.hook
import de.robv.android.xposed.XC_MethodHook
import de.robv.android.xposed.XposedBridge
import de.robv.android.xposed.callbacks.XCallback
import mufanc.easyhook.api.catch
import mufanc.easyhook.api.reflect.findConstructor
import mufanc.easyhook.api.reflect.findMethod
import java.lang.reflect.Constructor
import java.lang.reflect.Method
private typealias HookCallback = (XC_MethodHook.MethodHookParam) -> Unit
private typealias HookReplacement = (XC_MethodHook.MethodHookParam) -> Any?
class HookCreator @PublishedApi internal constructor(
@PublishedApi internal val target: Class<*>
) {
class Hooker @PublishedApi internal constructor(priority: Int): XC_MethodHook(priority) {
private lateinit var beforeCall: HookCallback
private lateinit var afterCall: HookCallback
private lateinit var replacement: HookReplacement
override fun beforeHookedMethod(param: MethodHookParam) {
catch {
if (this::replacement.isInitialized) {
param.result = replacement(param)
return
}
if (this::beforeCall.isInitialized) {
beforeCall(param)
}
}
}
override fun afterHookedMethod(param: MethodHookParam) {
catch {
if (this::afterCall.isInitialized) afterCall(param)
}
}
fun before(callback: HookCallback) {
beforeCall = callback
}
fun after(callback: HookCallback) {
afterCall = callback
}
fun replace(func: HookReplacement) {
replacement = func
}
}
inline fun method(
filter: Method.() -> Boolean,
priority: Int = XCallback.PRIORITY_DEFAULT,
initializer: Hooker.(Method) -> Unit
) {
target.findMethod(filter)?.let {
XposedBridge.hookMethod(it, Hooker(priority).apply { initializer(this, it) })
} ?: throw NoSuchMethodError()
}
inline fun constructor(
filter: Constructor<*>.() -> Boolean,
priority: Int = XCallback.PRIORITY_DEFAULT,
initializer: Hooker.(Constructor<*>) -> Unit
) {
target.findConstructor(filter)?.let {
XposedBridge.hookMethod(it, Hooker(priority).apply { initializer(this, it) })
} ?: throw NoSuchMethodError()
}
}
| 0 | Kotlin | 3 | 9 | e812a2808b0aab66e83ed3e5e646bdb7f1ffa3dc | 2,426 | EasyHook | MIT License |
walletconnect/src/test/java/com/trustwallet/walletconnect/WCCipherTests.kt | trustwallet | 196,442,557 | false | null | package com.trustwallet.walletconnect
import android.os.Build
import com.trustwallet.walletconnect.extensions.hexStringToByteArray
import com.trustwallet.walletconnect.models.WCEncryptionPayload
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [Build.VERSION_CODES.O_MR1])
class WCCipherTests {
@Test
fun test_decrypt() {
val data = "1b3db3674de082d65455eba0ae61cfe7e681c8ef1132e60c8dbd8e52daf18f4fea42cc76366c83351dab6dca52682ff81f828753f89a21e1cc46587ca51ccd353914ffdd3b0394acfee392be6c22b3db9237d3f717a3777e3577dd70408c089a4c9c85130a68c43b0a8aadb00f1b8a8558798104e67aa4ff027b35d4b989e7fd3988d5dcdd563105767670be735b21c4"
val hmac = "a33f868e793ca4fcca964bcb64430f65e2f1ca7a779febeaf94c5373d6df48b3"
val iv = "89ef1d6728bac2f1dcde2ef9330d2bb8"
val key = "5caa3a74154cee16bd1b570a1330be46e086474ac2f4720530662ef1a469662c".hexStringToByteArray()
val payload = WCEncryptionPayload(
data = data,
iv = iv,
hmac = hmac
)
val decrypted = String(WCCipher.decrypt(payload, key), Charsets.UTF_8)
val expected = "{\"id\":1554098597199736,\"jsonrpc\":\"2.0\",\"method\":\"wc_sessionUpdate\",\"params\":[{\"approved\":false,\"chainId\":null,\"accounts\":null}]}"
Assert.assertEquals(expected, decrypted)
}
@Test
fun test_encrypt() {
val expected = "{\"id\":1554098597199736,\"jsonrpc\":\"2.0\",\"method\":\"wc_sessionUpdate\",\"params\":[{\"approved\":false,\"chainId\":null,\"accounts\":null}]}".hexStringToByteArray()
val key = "5caa3a74154cee16bd1b570a1330be46e086474ac2f4720530662ef1a469662c".hexStringToByteArray()
val payload = WCCipher.encrypt(data = expected, key = key)
val decrypted = WCCipher.decrypt(payload, key)
Assert.assertArrayEquals(expected, decrypted)
}
} | 11 | Kotlin | 75 | 86 | 75b2590a7002a0c7ef1c0ee9633aac58eed0c643 | 2,008 | wallet-connect-kotlin | MIT License |
6_kyu/Ease_the_StockBroker.kt | UlrichBerntien | 439,630,417 | false | {"Go": 293606, "Rust": 191729, "Python": 184557, "Lua": 137612, "Assembly": 89144, "C": 76738, "Julia": 35473, "Kotlin": 33204, "R": 27633, "C#": 20860, "Shell": 14326, "Forth": 3750, "PLpgSQL": 2117, "C++": 122} | package solution
import java.math.BigDecimal
import java.text.DecimalFormat
import java.util.*
object OrdersSummary {
private val simpleOrderFormat = Regex("""\s*(\S+)\s+(\d+)\s+(\d+(?:\.\d*))\s+([SB])\s*""")
private val sellStatus = "S"
private val priceFormat = DecimalFormat("#")
fun balanceStatements(lst: String): String {
var accBuy = BigDecimal(0)
var accSell = BigDecimal(0)
val accBadly = LinkedList<String>()
for (simpleOrder in lst.splitToSequence(",")) {
val match = simpleOrderFormat.matchEntire(simpleOrder)
if (match != null) {
val quantity = BigDecimal(match.groupValues[2])
val price = BigDecimal(match.groupValues[3])
val status = match.groupValues[4]
val totalPrice = quantity * price
if (status == sellStatus)
accSell += totalPrice
else
accBuy += totalPrice
} else if (!simpleOrder.isNullOrBlank()) {
accBadly.add(simpleOrder.trim())
}
}
val badly = if (accBadly.isEmpty())
""
else
"; Badly formed ${accBadly.size}: " + accBadly.joinToString(" ;") + " ;"
return "Buy: ${priceFormat.format(accBuy)} Sell: ${priceFormat.format(accSell)}${badly}"
}
}
| 0 | Go | 0 | 0 | 034d7f2bdcebc503b02877f2241e4dd143188b43 | 1,382 | Codewars-Katas | MIT License |
6_kyu/Ease_the_StockBroker.kt | UlrichBerntien | 439,630,417 | false | {"Go": 293606, "Rust": 191729, "Python": 184557, "Lua": 137612, "Assembly": 89144, "C": 76738, "Julia": 35473, "Kotlin": 33204, "R": 27633, "C#": 20860, "Shell": 14326, "Forth": 3750, "PLpgSQL": 2117, "C++": 122} | package solution
import java.math.BigDecimal
import java.text.DecimalFormat
import java.util.*
object OrdersSummary {
private val simpleOrderFormat = Regex("""\s*(\S+)\s+(\d+)\s+(\d+(?:\.\d*))\s+([SB])\s*""")
private val sellStatus = "S"
private val priceFormat = DecimalFormat("#")
fun balanceStatements(lst: String): String {
var accBuy = BigDecimal(0)
var accSell = BigDecimal(0)
val accBadly = LinkedList<String>()
for (simpleOrder in lst.splitToSequence(",")) {
val match = simpleOrderFormat.matchEntire(simpleOrder)
if (match != null) {
val quantity = BigDecimal(match.groupValues[2])
val price = BigDecimal(match.groupValues[3])
val status = match.groupValues[4]
val totalPrice = quantity * price
if (status == sellStatus)
accSell += totalPrice
else
accBuy += totalPrice
} else if (!simpleOrder.isNullOrBlank()) {
accBadly.add(simpleOrder.trim())
}
}
val badly = if (accBadly.isEmpty())
""
else
"; Badly formed ${accBadly.size}: " + accBadly.joinToString(" ;") + " ;"
return "Buy: ${priceFormat.format(accBuy)} Sell: ${priceFormat.format(accSell)}${badly}"
}
}
| 0 | Go | 0 | 0 | 034d7f2bdcebc503b02877f2241e4dd143188b43 | 1,382 | Codewars-Katas | MIT License |
billing/src/main/java/com/pyamsoft/pydroid/billing/BillingConnector.kt | pyamsoft | 48,562,480 | false | null | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.pydroid.billing
import androidx.appcompat.app.AppCompatActivity
/** Abstracts the Play Store Billing client */
public interface BillingConnector {
/**
* Start the billing client
*
* Will automatically manage connections
*/
public fun start(activity: AppCompatActivity)
}
| 4 | Kotlin | 5 | 9 | 23a5ae80f368e94eb5d6968895a2f5ed326720cf | 902 | pydroid | Apache License 2.0 |
src/main/java/com/tang/intellij/lua/editor/structure/LuaFileElement.kt | Benjamin-Dobell | 231,814,734 | false | null | /*
* Copyright (c) 2017. tangzx(<EMAIL>)
*
* 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.tang.intellij.lua.editor.structure
import com.intellij.ide.util.treeView.smartTree.TreeElement
import com.tang.intellij.lua.lang.LuaIcons
import com.tang.intellij.lua.psi.*
/**
* Created by TangZX on 2016/12/13.
*/
class LuaFileElement(private val file: LuaPsiFile) : LuaTreeElement(file, file.name, LuaIcons.FILE) {
override fun getChildren(): Array<TreeElement> {
val visitor = LuaStructureVisitor()
file.acceptChildren(visitor)
visitor.compressChildren()
return visitor.getChildren()
}
}
| 61 | Kotlin | 9 | 83 | 68b0a63d3ddd5bc7be9ed304534b601fedcc8319 | 1,151 | IntelliJ-Luanalysis | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/iot/CfnTopicRuleLocationActionPropertyDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.iot
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.iot.CfnTopicRule
/**
* Describes an action to send device location updates from an MQTT message to an Amazon Location
* tracker resource.
*
* 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.iot.*;
* LocationActionProperty locationActionProperty = LocationActionProperty.builder()
* .deviceId("deviceId")
* .latitude("latitude")
* .longitude("longitude")
* .roleArn("roleArn")
* .trackerName("trackerName")
* // the properties below are optional
* .timestamp(TimestampProperty.builder()
* .value("value")
* // the properties below are optional
* .unit("unit")
* .build())
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iot-topicrule-locationaction.html)
*/
@CdkDslMarker
public class CfnTopicRuleLocationActionPropertyDsl {
private val cdkBuilder: CfnTopicRule.LocationActionProperty.Builder =
CfnTopicRule.LocationActionProperty.builder()
/**
* @param deviceId The unique ID of the device providing the location data.
*/
public fun deviceId(deviceId: String) {
cdkBuilder.deviceId(deviceId)
}
/**
* @param latitude A string that evaluates to a double value that represents the latitude of the
* device's location.
*/
public fun latitude(latitude: String) {
cdkBuilder.latitude(latitude)
}
/**
* @param longitude A string that evaluates to a double value that represents the longitude of the
* device's location.
*/
public fun longitude(longitude: String) {
cdkBuilder.longitude(longitude)
}
/**
* @param roleArn The IAM role that grants permission to write to the Amazon Location resource.
*/
public fun roleArn(roleArn: String) {
cdkBuilder.roleArn(roleArn)
}
/**
* @param timestamp The time that the location data was sampled.
* The default value is the time the MQTT message was processed.
*/
public fun timestamp(timestamp: IResolvable) {
cdkBuilder.timestamp(timestamp)
}
/**
* @param timestamp The time that the location data was sampled.
* The default value is the time the MQTT message was processed.
*/
public fun timestamp(timestamp: CfnTopicRule.TimestampProperty) {
cdkBuilder.timestamp(timestamp)
}
/**
* @param trackerName The name of the tracker resource in Amazon Location in which the location is
* updated.
*/
public fun trackerName(trackerName: String) {
cdkBuilder.trackerName(trackerName)
}
public fun build(): CfnTopicRule.LocationActionProperty = cdkBuilder.build()
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 3,036 | awscdk-dsl-kotlin | Apache License 2.0 |
metrics/core/src/test/kotlin/io/wavebeans/metrics/collector/MetricCollectorSpec.kt | WaveBeans | 174,378,458 | false | {"Kotlin": 1263856, "Shell": 6924, "Dockerfile": 408} | package io.wavebeans.metrics.collector
import assertk.all
import assertk.assertThat
import assertk.assertions.*
import assertk.fail
import io.grpc.ServerBuilder
import io.wavebeans.metrics.MetricObject
import io.wavebeans.metrics.MetricService
import io.wavebeans.metrics.eachIndexed
import io.wavebeans.tests.findFreePort
import org.spekframework.spek2.Spek
import org.spekframework.spek2.lifecycle.CachingMode.*
import org.spekframework.spek2.style.specification.describe
import java.lang.Thread.sleep
object MetricCollectorSpec : Spek({
describe("Single mode") {
describe("Counter") {
val counter by memoized(TEST) { MetricObject.counter("component", "count", "") }
val counterMetricCollector by memoized(TEST) { counter.collector(granularValueInMs = 0) }
val counterMetricCollectorWithTag by memoized(TEST) { counter.withTags("tag" to "value").collector(granularValueInMs = 0) }
beforeEachTest {
MetricService.reset()
MetricService.registerConnector(counterMetricCollector)
MetricService.registerConnector(counterMetricCollectorWithTag)
}
it("should return 2 incremented values on collect") {
counter.increment()
counter.withTags("some-tag" to "some-value").increment()
val counterValues = counterMetricCollector.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValues).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isCloseTo(1.0, 1e-14) }
}
val counterValuesWithTag = counterMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValuesWithTag).isEmpty()
}
it("should return 2 incremented values on collect for counter with tag") {
counter.withTags("tag" to "value").increment()
counter.withTags("tag" to "value", "some-tag" to "some-value").increment()
val counterValuesWithTag = counterMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValuesWithTag).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isCloseTo(1.0, 1e-14) }
}
val counterValues = counterMetricCollector.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValues).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isCloseTo(1.0, 1e-14) }
}
}
it("should return incremented values on collect for each counter") {
counter.increment()
counter.withTags("tag" to "value").increment()
val counterValues = counterMetricCollector.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValues).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isCloseTo(1.0, 1e-14) }
}
val counterValuesWithTag = counterMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValuesWithTag).all {
size().isEqualTo(1)
each { it.prop("value") { it.value }.isCloseTo(1.0, 1e-14) }
}
}
it("should return 2 decremented values on collect") {
counter.decrement()
counter.withTags("some-tag" to "some-value").decrement()
val counterValues = counterMetricCollector.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValues).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isCloseTo(-1.0, 1e-14) }
}
val counterValuesWithTag = counterMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValuesWithTag).isEmpty()
}
it("should return 2 decremented values on collect for counter with tag") {
counter.withTags("tag" to "value").decrement()
counter.withTags("tag" to "value", "some-tag" to "some-value").decrement()
val counterValuesWithTag = counterMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValuesWithTag).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isCloseTo(-1.0, 1e-14) }
}
val counterValues = counterMetricCollector.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValues).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isCloseTo(-1.0, 1e-14) }
}
}
it("should return decremented values on collect for each counter") {
counter.decrement()
counter.withTags("tag" to "value").decrement()
val counterValues = counterMetricCollector.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValues).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isCloseTo(-1.0, 1e-14) }
}
val counterValuesWithTag = counterMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(counterValuesWithTag).all {
size().isEqualTo(1)
each { it.prop("value") { it.value }.isCloseTo(-1.0, 1e-14) }
}
}
it("should merge with another") {
counter.increment()
counterMetricCollector.merge(sequenceOf(
2.0 at 2L,
3.0 at 3L,
5.0 at System.currentTimeMillis() + 5000
))
val values = counterMetricCollector.collectValues(Long.MAX_VALUE)
assertThat(values).eachIndexed(4) { timedValue, idx ->
when (idx) {
0 -> timedValue.isEqualTo(2.0 at 2L)
1 -> timedValue.isEqualTo(3.0 at 3L)
2 -> timedValue.prop("value") { it.value }.isCloseTo(1.0, 1e-14)
3 -> timedValue.prop("value") { it.value }.isCloseTo(5.0, 1e-14)
else -> fail("$idx is not recognized")
}
}
}
}
describe("Time") {
val time by memoized(TEST) { MetricObject.time("component", "time", "") }
val timeMetricCollector by memoized(TEST) { time.collector(granularValueInMs = 0) }
val timeMetricCollectorWithTag by memoized(TEST) { time.withTags("tag" to "value").collector(granularValueInMs = 0) }
beforeEachTest {
MetricService.reset()
MetricService.registerConnector(timeMetricCollector)
MetricService.registerConnector(timeMetricCollectorWithTag)
}
it("should measure time twice") {
time.time(100)
time.withTags("some-tag" to "some-value").time(100)
val values = timeMetricCollector.collectValues(System.currentTimeMillis() + 100)
assertThat(values).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isEqualTo(TimeAccumulator(1, 100)) }
}
val valuesWithTag = timeMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(valuesWithTag).isEmpty()
}
it("should measure time twice for counter with tags") {
time.withTags("tag" to "value").time(100)
time.withTags("tag" to "value", "some-tag" to "some-value").time(100)
val valuesWithTag = timeMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(valuesWithTag).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isEqualTo(TimeAccumulator(1, 100)) }
}
val values = timeMetricCollector.collectValues(System.currentTimeMillis() + 100)
assertThat(values).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isEqualTo(TimeAccumulator(1, 100)) }
}
}
it("should measure time once for counter with tag and twice for tagless") {
time.time(100)
time.withTags("tag" to "value").time(100)
val values = timeMetricCollector.collectValues(System.currentTimeMillis() + 100)
assertThat(values).all {
size().isEqualTo(2)
each { it.prop("value") { it.value }.isEqualTo(TimeAccumulator(1, 100)) }
}
val valuesWithTag = timeMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(valuesWithTag).all {
size().isEqualTo(1)
each { it.prop("value") { it.value }.isEqualTo(TimeAccumulator(1, 100)) }
}
}
it("should merge with another") {
time.time(100)
timeMetricCollector.merge(sequenceOf(
TimeAccumulator(1, 200) at 2L,
TimeAccumulator(1, 300) at 3L,
TimeAccumulator(1, 500) at System.currentTimeMillis() + 5000
))
val values = timeMetricCollector.collectValues(Long.MAX_VALUE)
assertThat(values).eachIndexed(4) { timedValue, idx ->
when (idx) {
0 -> timedValue.isEqualTo(TimeAccumulator(1, 200) at 2L)
1 -> timedValue.isEqualTo(TimeAccumulator(1, 300) at 3L)
2 -> timedValue.prop("value.time") { it.value.time }.isEqualTo(100L)
3 -> timedValue.prop("value.time") { it.value.time }.isEqualTo(500L)
else -> fail("$idx is not recognized")
}
}
}
}
describe("Gauge") {
val gauge by memoized(TEST) { MetricObject.gauge("component", "gauge", "") }
val gaugeMetricCollector by memoized(TEST) { gauge.collector(granularValueInMs = 0) }
val gaugeMetricCollectorWithTag by memoized(TEST) { gauge.withTags("tag" to "value").collector(granularValueInMs = 0) }
beforeEachTest {
MetricService.reset()
MetricService.registerConnector(gaugeMetricCollector)
MetricService.registerConnector(gaugeMetricCollectorWithTag)
}
it("should set and add delta") {
gauge.set(1.0)
gauge.withTags("some-tag" to "some-value").increment(1.0)
val values = gaugeMetricCollector.collectValues(System.currentTimeMillis() + 100)
val valuesWithTag = gaugeMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(values).eachIndexed(2) { timedValue, idx ->
when (idx) {
0 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(true, 1.0))
1 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(false, 1.0))
else -> fail("$idx is not recognized")
}
}
assertThat(valuesWithTag).isEmpty()
}
it("should set and add delta for counter with tag") {
gauge.withTags("tag" to "value").set(1.0)
gauge.withTags("tag" to "value", "some-tag" to "some-value").increment(1.0)
val values = gaugeMetricCollector.collectValues(System.currentTimeMillis() + 100)
val valuesWithTag = gaugeMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(valuesWithTag).eachIndexed(2) { timedValue, idx ->
when (idx) {
0 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(true, 1.0))
1 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(false, 1.0))
else -> fail("$idx is not recognized")
}
}
assertThat(values).eachIndexed(2) { timedValue, idx ->
when (idx) {
0 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(true, 1.0))
1 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(false, 1.0))
else -> fail("$idx is not recognized")
}
}
}
it("should set over the collected value") {
gauge.set(1.0)
gauge.withTags("tag" to "value").increment(1.0)
gauge.withTags("tag" to "value").set(3.0)
gauge.increment(2.1)
val values = gaugeMetricCollector.collectValues(System.currentTimeMillis() + 100)
val valuesWithTag = gaugeMetricCollectorWithTag.collectValues(System.currentTimeMillis() + 100)
assertThat(values).eachIndexed(4) { timedValue, idx ->
when (idx) {
0 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(true, 1.0))
1 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(false, 1.0))
2 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(true, 3.0))
3 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(false, 2.1))
else -> fail("$idx is not recognized")
}
}
assertThat(valuesWithTag).eachIndexed(2) { timedValue, idx ->
when (idx) {
0 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(false, 1.0))
1 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(true, 3.0))
else -> fail("$idx is not recognized")
}
}
}
it("should merge with another") {
gauge.set(1.0)
gaugeMetricCollector.merge(sequenceOf(
GaugeAccumulator(false, 2.0) at 2L,
GaugeAccumulator(false, 3.0) at 3L,
GaugeAccumulator(false, 5.0) at System.currentTimeMillis() + 5000
))
val values = gaugeMetricCollector.collectValues(Long.MAX_VALUE)
assertThat(values).eachIndexed(4) { timedValue, idx ->
when (idx) {
0 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(false, 2.0))
1 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(false, 3.0))
2 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(true, 1.0))
3 -> timedValue.prop("value") { it.value }.isEqualTo(GaugeAccumulator(false, 5.0))
else -> fail("$idx is not recognized")
}
}
}
}
}
describe("Distributed mode") {
describe("One downstream collector") {
val port by memoized(EACH_GROUP) { findFreePort() }
val counter by memoized(EACH_GROUP) { MetricObject.counter("component", "count", "") }
val time by memoized(EACH_GROUP) { MetricObject.time("component", "time", "") }
val gauge by memoized(EACH_GROUP) { MetricObject.gauge("component", "gauge", "") }
val counterUpstream by memoized(EACH_GROUP) {
counter.collector(
downstreamCollectors = listOf("localhost:$port"),
granularValueInMs = 0,
refreshIntervalMs = 0
)
}
val counterUpstreamWithTag by memoized(EACH_GROUP) {
counter.withTags("tag" to "value").collector(
downstreamCollectors = listOf("localhost:$port"),
granularValueInMs = 0,
refreshIntervalMs = 0
)
}
val timeUpstream by memoized(EACH_GROUP) {
time.collector(
downstreamCollectors = listOf("localhost:$port"),
granularValueInMs = 0,
refreshIntervalMs = 0
)
}
val timeUpstreamWithTag by memoized(EACH_GROUP) {
time.withTags("tag" to "value").collector(
downstreamCollectors = listOf("localhost:$port"),
granularValueInMs = 0,
refreshIntervalMs = 0
)
}
val gaugeUpstream by memoized(EACH_GROUP) {
gauge.collector(
downstreamCollectors = listOf("localhost:$port"),
granularValueInMs = 0,
refreshIntervalMs = 0
)
}
val gaugeUpstreamWithTag by memoized(EACH_GROUP) {
gauge.withTags("tag" to "value").collector(
downstreamCollectors = listOf("localhost:$port"),
granularValueInMs = 0,
refreshIntervalMs = 0
)
}
val server by memoized(EACH_GROUP) {
ServerBuilder.forPort(port)
.addService(MetricGrpcService.instance())
.build()
}
beforeGroup {
server.start()
assertThat(counterUpstream.attachCollector()).isTrue()
assertThat(counterUpstreamWithTag.attachCollector()).isTrue()
assertThat(timeUpstream.attachCollector()).isTrue()
assertThat(timeUpstreamWithTag.attachCollector()).isTrue()
assertThat(gaugeUpstream.attachCollector()).isTrue()
assertThat(gaugeUpstreamWithTag.attachCollector()).isTrue()
}
afterGroup {
server.shutdownNow()
counterUpstream.close()
counterUpstreamWithTag.close()
timeUpstream.close()
timeUpstreamWithTag.close()
gaugeUpstream.close()
gaugeUpstreamWithTag.close()
}
it("should attach on first iteration") {
counterUpstream.collectFromDownstream()
assertThat(counterUpstream.awaitAttached()).isTrue()
timeUpstream.collectFromDownstream()
assertThat(timeUpstream.awaitAttached()).isTrue()
gaugeUpstream.collectFromDownstream()
assertThat(gaugeUpstream.awaitAttached()).isTrue()
}
it("should get counter values from downstream collector") {
counter.increment(1.0)
counter.increment(2.0)
counterUpstream.increment(counter, 3.0)
val afterEventMoment = System.currentTimeMillis() + 100
counterUpstream.mergeWithDownstreamCollectors(afterEventMoment)
assertThat(counterUpstream.collectValues(afterEventMoment))
.prop("values.toSet") { it.map { it.value }.toSet() }
.isEqualTo(setOf(1.0, 2.0, 3.0))
}
it("should get counter values from downstream collector respecting tags") {
counter.increment(1.0)
counter.withTags("tag" to "value").increment(2.0)
counterUpstreamWithTag.increment(counter.withTags("anotherTag" to "anotherValue"), 3.0)
val afterEventMoment = System.currentTimeMillis() + 100
counterUpstreamWithTag.mergeWithDownstreamCollectors(afterEventMoment)
assertThat(counterUpstreamWithTag.collectValues(afterEventMoment))
.prop("values.toSet") { it.map { it.value }.toSet() }
.isEqualTo(setOf(2.0))
}
it("should get time values from downstream collector") {
time.time(100)
time.time(200)
timeUpstream.time(time, 300)
val afterEventMoment = System.currentTimeMillis() + 100
timeUpstream.mergeWithDownstreamCollectors(afterEventMoment)
assertThat(timeUpstream.collectValues(afterEventMoment))
.prop("valuesAsSet") { it.map { it.value }.toSet() }
.isEqualTo(setOf(TimeAccumulator(1, 100), TimeAccumulator(1, 200), TimeAccumulator(1, 300)))
}
it("should get time values from downstream collector respecting tags") {
time.time(100)
time.withTags("tag" to "value").time(200)
timeUpstreamWithTag.time(time.withTags("anotherTag" to "anotherValue"), 300)
val afterEventMoment = System.currentTimeMillis() + 100
timeUpstreamWithTag.mergeWithDownstreamCollectors(afterEventMoment)
assertThat(timeUpstreamWithTag.collectValues(afterEventMoment))
.prop("valuesAsSet") { it.map { it.value }.toSet() }
.isEqualTo(setOf(TimeAccumulator(1, 200)))
}
it("should populate gauge values from downstream collector") {
gauge.set(100.0)
gauge.increment(200.0)
gaugeUpstream.gauge(gauge, 300.0)
val afterEventMoment = System.currentTimeMillis() + 100
gaugeUpstream.mergeWithDownstreamCollectors(afterEventMoment)
assertThat(gaugeUpstream.collectValues(afterEventMoment))
.prop("valuesAsSet") { it.map { it.value }.toSet() }
.isEqualTo(setOf(GaugeAccumulator(true, 100.0), GaugeAccumulator(false, 200.0), GaugeAccumulator(true, 300.0)))
}
it("should populate gauge values from downstream collector respecting tags") {
gauge.set(100.0)
gauge.withTags("tag" to "value").increment(200.0)
gaugeUpstreamWithTag.gauge(gauge.withTags("anotherTag" to "anotherValue"), 300.0)
val afterEventMoment = System.currentTimeMillis() + 100
gaugeUpstreamWithTag.mergeWithDownstreamCollectors(afterEventMoment)
assertThat(gaugeUpstreamWithTag.collectValues(afterEventMoment))
.prop("valuesAsSet") { it.map { it.value }.toSet() }
.isEqualTo(setOf(GaugeAccumulator(false, 200.0)))
}
}
describe("Collecting automatically") {
val port by memoized(EACH_GROUP) { findFreePort() }
val counter by memoized(EACH_GROUP) { MetricObject.counter("component1", "name1", "") }
val remoteMetricCollector by memoized(EACH_GROUP) {
counter.collector(
downstreamCollectors = listOf("localhost:$port"),
granularValueInMs = 0,
refreshIntervalMs = 1
)
}
val server by memoized(EACH_GROUP) {
ServerBuilder.forPort(port)
.addService(MetricGrpcService.instance())
.build()
}
beforeGroup {
server.start()
}
afterGroup {
remoteMetricCollector.close()
server.shutdownNow()
}
it("should attach on first iteration") {
assertThat(remoteMetricCollector.awaitAttached()).isTrue()
}
it("should get values from downstream collector") {
counter.increment(1.0)
counter.increment(2.0)
remoteMetricCollector.increment(counter, 3.0)
val afterEventMoment = System.currentTimeMillis() + 100
sleep(500) // wait for upstream metric collector to do a few syncs
assertThat(remoteMetricCollector.collectValues(afterEventMoment))
.prop("values.toSet") { it.map { it.value }.toSet() }
.isEqualTo(setOf(1.0, 2.0, 3.0))
}
}
describe("Two downstream collectors") {
val port1 by memoized(EACH_GROUP) { findFreePort() }
val port2 by memoized(EACH_GROUP) { findFreePort() }
val counter by memoized(EACH_GROUP) { MetricObject.counter("component1_TwoDownstreamCollectors", "name1_TwoDownstreamCollectors", "") }
val remoteMetricCollector by memoized(EACH_GROUP) {
counter.collector(
downstreamCollectors = listOf("localhost:$port1", "localhost:$port2"),
granularValueInMs = 0,
refreshIntervalMs = 1
)
}
val server1 by memoized(EACH_GROUP) {
ServerBuilder.forPort(port1)
.addService(MetricGrpcService.instance())
.build()
}
val server2 by memoized(EACH_GROUP) {
ServerBuilder.forPort(port2)
.addService(MetricGrpcService.instance())
.build()
}
beforeGroup {
server1.start()
server2.start()
// attach to downstream collectors
assertThat(remoteMetricCollector.attachCollector()).isTrue()
}
afterGroup {
remoteMetricCollector.close()
server1.shutdownNow()
server2.shutdownNow()
}
it("should get values from downstream collector") {
assertThat(remoteMetricCollector.isAttached()).isTrue()
counter.increment(1.0)
counter.increment(2.0)
counter.increment(3.0)
counter.increment(4.0)
remoteMetricCollector.increment(counter, 5.0)
remoteMetricCollector.mergeWithDownstreamCollectors(Long.MAX_VALUE)
assertThat(remoteMetricCollector.collectValues(Long.MAX_VALUE))
.prop("values.toList().sorted()") { it.map { it.value }.sorted() }
.isEqualTo(listOf(1.0, 1.0, 2.0, 2.0, 3.0, 3.0, 4.0, 4.0, 5.0))
}
}
}
}) | 26 | Kotlin | 0 | 21 | 2a0eb6b481f0f848a7e66f7cb4c395ddb47952d1 | 27,439 | wavebeans | Apache License 2.0 |
analysis/analysis-api/src/org/jetbrains/kotlin/analysis/api/components/KtSubstitutorProvider.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.components
import org.jetbrains.kotlin.analysis.api.lifetime.withValidityAssertion
import org.jetbrains.kotlin.analysis.api.symbols.KaClassOrObjectSymbol
import org.jetbrains.kotlin.analysis.api.types.KaSubstitutor
public abstract class KaSubstitutorProvider : KaSessionComponent() {
public abstract fun createSubstitutor(
subClass: KaClassOrObjectSymbol,
superClass: KaClassOrObjectSymbol,
): KaSubstitutor?
}
public typealias KtSubstitutorProvider = KaSubstitutorProvider
public interface KaSubstitutorProviderMixIn : KaSessionMixIn {
/**
* Creates a [KaSubstitutor] based on the inheritance relationship between [subClass] and [superClass].
*
* The semantic of resulted [KaSubstitutor] is the substitutor that should be applied to a member of [superClass],
* so it can be called on an instance of [subClass].
*
* Basically, it's a composition of inheritance-based substitutions for all the inheritance chain.
*
* On the following code:
* ```
* class A : B<String>
* class B<T> : C<T, Int>
* class C<X, Y>
* ```
*
* * `createInheritanceTypeSubstitutor(A, B)` returns `KtSubstitutor {T -> String}`
* * `createInheritanceTypeSubstitutor(B, C)` returns `KtSubstitutor {X -> T, Y -> Int}`
* * `createInheritanceTypeSubstitutor(A, C)` returns `KtSubstitutor {X -> T, Y -> Int} andThen KtSubstitutor {T -> String}`
*
* @param subClass the subClass or object symbol.
* @param superClass the super class symbol.
* @return [KaSubstitutor] if [subClass] inherits [superClass] and there are no error types in the inheritance path. Returns `null` otherwise.
*/
public fun createInheritanceTypeSubstitutor(
subClass: KaClassOrObjectSymbol,
superClass: KaClassOrObjectSymbol,
): KaSubstitutor? = withValidityAssertion {
analysisSession.substitutorProvider.createSubstitutor(subClass, superClass)
}
}
public typealias KtSubstitutorProviderMixIn = KaSubstitutorProviderMixIn | 180 | null | 5642 | 48,082 | 2742b94d9f4dbdb1064e65e05682cb2b0badf2fc | 2,291 | kotlin | Apache License 2.0 |
app/src/main/java/com/hewking/demo/res/DemoActivity.kt | hewking | 70,571,658 | false | {"Java": 520648, "Kotlin": 449632} | package com.hewking.demo.res
import android.app.Activity
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.widget.FrameLayout
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.hewking.utils.ResUtil
import com.hewking.utils.dp2px
class DemoActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val tv = TextView(this).apply {
text = "center text"
textSize = dp2px(14f).toFloat()
gravity = Gravity.CENTER
layoutParams = FrameLayout.LayoutParams(-2,-2).apply {
gravity = Gravity.CENTER
}
background = ResUtil.generateGradientDrawable(dp2px(4f).toFloat(), Color.parseColor("#7d3dcc"), Color.parseColor("#944aee"))
}
setContentView(tv)
}
fun Activity.dp2px(size : Float) : Float{
return (resources.displayMetrics.density * size + 0.5).toFloat()
}
fun Activity.px2dp(size : Float) : Float{
return (size.div(resources.displayMetrics.density) + 0.5).toFloat()
}
} | 1 | null | 1 | 1 | 6e9ec477603d75d50f131f03d941bfbdf336095b | 1,177 | HUIKit | MIT License |
app/src/main/java/com/latitude/seventimer/ui/SplashActivity.kt | houtengzhi | 40,753,076 | false | null | package com.latitude.seventimer.ui
import android.os.Bundle
import android.os.Handler
import androidx.appcompat.app.AppCompatActivity
import com.latitude.seventimer.R
import com.latitude.seventimer.base.BaseActivity
import com.latitude.seventimer.ui.weather.MainActivity
/**
*
* Created by cloud on 2019-08-05.
*/
class SplashActivity: BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
}
override fun onStart() {
super.onStart()
Handler().postDelayed(object: Runnable {
override fun run() {
MainActivity.actionStart(this@SplashActivity)
finish()
}
}, 1000)
}
} | 1 | null | 1 | 1 | ff428dc27014611d79eaf397dac093990c3a5917 | 775 | seventimer | Apache License 2.0 |
src/commonTest/kotlin/tech/thatgravyboat/jukebox/UrlTest.kt | ThatGravyBoat | 531,897,224 | false | {"Kotlin": 63342} | package tech.thatgravyboat.jukebox
import io.ktor.http.*
import tech.thatgravyboat.jukebox.utils.Http.plus
import kotlin.test.Test
import kotlin.test.assertTrue
object UrlTest {
@Test
fun resolveUrlTest() {
val uri = Url("http://localhost:8080")
val newURI = uri + "subpath.html"
assertTrue(newURI.toString() == "http://localhost:8080/subpath.html", "Url resolve did not create a valid URI.")
}
@Test
fun resolveQueryUrlTest() {
val uri = Url("http://localhost:8080")
val newURI = uri + "subpath.html?query=true"
assertTrue(newURI.toString() == "http://localhost:8080/subpath.html?query=true", "Url resolve did not create a valid URI with the query.")
}
} | 0 | Kotlin | 0 | 7 | d95e22681b08c879232c300c8c585fcfc1d61dea | 734 | Jukebox | MIT License |
mobile/src/main/java/me/stanis/newsumm/util/network/NetworkChecker.kt | fstanis | 365,047,247 | false | null | /*
* Copyright 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package me.stanis.newsumm.util.network
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import javax.inject.Inject
class NetworkChecker @Inject constructor(private val connectivityManager: ConnectivityManager) {
fun isOnline() = connectivityManager
.getNetworkCapabilities(connectivityManager.activeNetwork)
?.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
?: false
}
| 0 | Kotlin | 0 | 0 | 1e1725bedbb0728b13c21d6ce833f158662980a8 | 1,035 | Newsumm | Apache License 2.0 |
GooglePayCoupons/Android/app/src/main/java/app/nikhil/googlepaycoupons/ui/couponlist/CouponRecyclerView.kt | nikhilbansal97 | 270,763,824 | false | {"Kotlin": 25919} | package app.nikhil.googlepaycoupons.ui.couponlist
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import app.nikhil.googlepaycoupons.data.Coupon
import app.nikhil.googlepaycoupons.databinding.LayoutCouponItemBinding
import app.nikhil.googlepaycoupons.ui.couponlist.CouponRecyclerView.CouponViewHolder
class CouponRecyclerView(
private val couponItems: List<Coupon>,
private val listener: CouponClickListener
) : RecyclerView.Adapter<CouponViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CouponViewHolder =
CouponViewHolder(LayoutCouponItemBinding.inflate(LayoutInflater.from(parent.context)))
override fun getItemCount(): Int = couponItems.size
override fun onBindViewHolder(holder: CouponViewHolder, position: Int) {
holder.bind()
}
inner class CouponViewHolder(private val binding: LayoutCouponItemBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bind() {
val currentCoupon = couponItems[adapterPosition]
binding.couponView.setOnClickListener { listener.onCouponClicked(currentCoupon, binding) }
}
}
interface CouponClickListener {
fun onCouponClicked(coupon: Coupon, couponItemBinding: LayoutCouponItemBinding)
}
} | 0 | Kotlin | 0 | 3 | 01a469640001a50fba4a4640d4e16bf0b662b8d3 | 1,287 | Mobile-UI-Samples | MIT License |
app/src/main/java/shvyn22/flexinglyrics/util/StateEvent.kt | shvyn22 | 348,453,435 | false | {"Kotlin": 129941} | package shvyn22.flexinglyrics.util
import shvyn22.flexinglyrics.data.remote.Track
sealed class StateEvent {
data class NavigateToDetails(val track: Track) : StateEvent()
class Error(val error: StateError) : StateEvent()
object Loading : StateEvent()
data class NavigateToMedia(val url: String) : StateEvent()
}
enum class StateError {
ERROR_FETCHING_DATA,
ERROR_LOADING_IMAGE,
ERROR_PERMISSION_NOT_GRANTED
}
| 0 | Kotlin | 0 | 2 | fc264ac9d38f3d39ab7a74321ba33ad598e31c9a | 439 | FlexingLyrics | MIT License |
src/main/kotlin/lt/codedicted/egzaminai/backend/config/CorsFilter.kt | vsh1ft | 247,971,755 | false | null | package lt.codedicted.egzaminai.backend.config
import javax.servlet.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class CorsFilter : Filter {
override fun doFilter(servletRequest: ServletRequest, servletResponse: ServletResponse, filterChain: FilterChain) {
val response = servletResponse as HttpServletResponse
val request = servletRequest as HttpServletRequest
response.setHeader("Access-Control-Allow-Origin", "*")
response.setHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT,OPTIONS")
response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization")
if ("OPTIONS".equals(request.method, ignoreCase = true)) {
response.status = HttpServletResponse.SC_OK
} else {
filterChain.doFilter(servletRequest, servletResponse)
}
}
}
| 0 | Kotlin | 0 | 0 | 15186fb655c2b19fc1c5e1ad941b0feb6c40c414 | 901 | egzaminai-backend | MIT License |
ObjectDatabase/Repository/src/main/kotlin/org/elkoserver/objectdatabase/QueryMessage.kt | jstuyts | 213,739,601 | false | null | package org.elkoserver.objectdatabase
import com.grack.nanojson.JsonObject
import org.elkoserver.json.EncodeControl
import org.elkoserver.json.JsonLiteralFactory
import org.elkoserver.json.singleElementArray
/**
* Fill in this request's message field with a 'query' request.
*
* @param template Template object for the objects desired.
* @param maxResults Maximum number of result objects to return, or 0 to
* indicate no fixed limit.
*/
internal fun msgQuery(template: JsonObject, tag: String, maxResults: Int) =
JsonLiteralFactory.targetVerb("rep", "query").apply {
addParameter("tag", tag)
@Suppress("SpellCheckingInspection")
val what = JsonLiteralFactory.type("queryi", EncodeControl.ForClientEncodeControl).apply {
addParameter("template", template)
if (0 < maxResults) {
addParameter("limit", maxResults)
}
finish()
}
addParameter("what", singleElementArray(what))
finish()
}
| 5 | null | 1 | 1 | d18864aaa29914c50edcb9ccfbd074a45d3d0498 | 1,065 | Elko | MIT License |
src/test/kotlin/de/tsteffek/model/geometry/LineSegmentTest.kt | tsteffek | 217,909,466 | false | {"Kotlin": 75997} | package de.tsteffek.model.geometry
import io.kotlintest.data.forall
import io.kotlintest.shouldBe
import io.kotlintest.shouldThrow
import io.kotlintest.specs.FreeSpec
import io.kotlintest.tables.row
import io.mockk.every
import io.mockk.mockkStatic
import io.mockk.verify
import de.tsteffek.math.distance
import kotlin.math.PI
import kotlin.math.sqrt
internal class LineSegmentTest : FreeSpec({
"inBoundingBox" {
val point = Point(1, 1)
forall(
row("point in boundingBox", LineSegment(Point(0.5, 0.5), Point(2, 3)), true),
row("point outside of boundingBox", LineSegment(Point(2, 2), Point(1.1, 1.1)), false)
) { case, lineSegment, targetBool ->
lineSegment.inBoundingBox(point) shouldBe targetBool
}
}
"distanceTo" - {
val l = LineSegment(Point(1, 1), Point(2, 2))
val point = Point(1, 2)
val line = Line(1.5, 1)
val parallelLine = Line(1, 1)
"distanceTo Point calls distanceLineToPoint" {
mockkStatic("de.tsteffek.math.GeometryKt")
every { distance(point, l) } returns 13.0
l.distanceTo(point) shouldBe 13.0
verify { distance(point, l) }
}
"distanceTo LineSegment calls distance SegmentToSegment" {
mockkStatic("de.tsteffek.math.GeometryKt")
every { distance(l, l) } returns 13.0
l.distanceTo(l) shouldBe 13.0
verify { distance(l, l) }
}
"distanceTo Line is 0.0 or not implemented if parallel" {
l.distanceTo(line) shouldBe 0.0
shouldThrow<NotImplementedError> {
l.distanceTo(parallelLine)
}
}
}
"companion object" - {
"fromSeveralPoints from 2 points" {
forall(
row(
listOf(
PolarPoint(0, 0, 0),
PolarPoint(PI * 0.25, sqrt(2.0), 1)
),
LineSegment(
Point(0, 0),
Point(1, 1)
)
), row(
listOf(
PolarPoint(0, 0, 2),
PolarPoint(PI * 0.75, sqrt(2.0), 3)
),
LineSegment(
Point(0, 0),
Point(-1, 1)
)
), row(
listOf(
PolarPoint(PI * 1.25, sqrt(2.0), 4),
PolarPoint(PI * 1.5, 1, 5)
),
LineSegment(
Point(-1, -1),
Point(0, -1)
)
)
) { sortedPoints, targetLine ->
val segment = LineSegment.fromSeveralPoints(sortedPoints)
segment shouldBe targetLine
segment.startPoint shouldBe targetLine.startPoint
segment.endPoint shouldBe targetLine.endPoint
}
}
"fromSeveralPoints from 3 points" {
forall(
row(
listOf(
PolarPoint(0, 0, 0),
PolarPoint(PI * 0.25, 0.5, 1),
PolarPoint(PI * 0.25, sqrt(2.0), 2)
),
LineSegment(
Point(0, 0),
Point(1, 1)
)
), row(
listOf(
PolarPoint(0, 0, 2),
PolarPoint(PI * 0.75, 0.5, 2),
PolarPoint(PI * 0.75, sqrt(2.0), 3)
),
LineSegment(
Point(0, 0),
Point(-1, 1)
)
), row(
listOf(
PolarPoint(PI * 1.25, sqrt(2.0), 4),
PolarPoint(PI * 1.25, sqrt(2.0), 4),
PolarPoint(PI * 1.5, 1, 5)
),
LineSegment(
Point(-1, -1),
Point(0, -1)
)
)
) { sortedPoints, targetLine ->
val segment = LineSegment.fromSeveralPoints(sortedPoints)
segment shouldBe targetLine
segment.startPoint shouldBe targetLine.startPoint
segment.endPoint shouldBe targetLine.endPoint
}
}
}
})
| 1 | Kotlin | 1 | 1 | f4b87321a9b9213127e09cc12bb3f7d341a1bc77 | 4,584 | floor-plan-generator | MIT License |
network/core/src/commonMain/kotlin/co/yml/network/core/request/Method.kt | yml-org | 504,124,065 | false | null | package co.yml.network.core.request
/**
* Http method for making a data request.
* @see <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods">https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods</a>
*/
enum class Method {
GET,
POST,
PATCH,
HEAD,
PUT,
DELETE
}
| 1 | Kotlin | 2 | 5 | 2b5162b3e687d81546d9c7ce7a666b3a2b6df889 | 307 | ynetwork-android | Apache License 2.0 |
src/test/kotlin/vip/mystery0/tools/kotlin/utils/StringUtilKtTest.kt | Mystery0Tools | 198,183,336 | false | {"Gradle Kotlin DSL": 3, "Shell": 3, "INI": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Java Properties": 1, "Kotlin": 18, "Java": 9} | package vip.mystery0.tools.kotlin.utils
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
/**
* @author mystery0
* Create at 2020/1/15
*/
internal class StringUtilKtTest {
private val origin = "Hello world!"
private val base64 = "SGVsbG8gd29ybGQh"
private val md5 = "86fb269d190d2c85f6e0468ceca42a20"
private val sha1 = "d3486ae9136e7856bc42212385ea797094475802"
private val sha256 = "c0535e4be2b79ffd93291305436bf889314e4a3faec05ecffcbb7df31ad9e51a"
@Test
fun md5() {
Assertions.assertEquals(origin.md5(), md5)
}
@Test
fun sha1() {
Assertions.assertEquals(origin.sha1(), sha1)
}
@Test
fun sha256() {
Assertions.assertEquals(origin.sha256(), sha256)
}
@Test
fun base64() {
Assertions.assertEquals(origin.base64(), base64)
}
@Test
fun deBase64() {
Assertions.assertEquals(base64.deBase64(), origin)
}
} | 1 | null | 1 | 1 | 4bd3d4f1619432ef30f58fdd36309b088ed94948 | 955 | JavaTools | Apache License 2.0 |
app/src/main/java/com/flexibond/features/dailyPlan/api/PlanRepo.kt | DebashisINT | 579,874,309 | false | null | package com.flexibond.features.dailyPlan.api
import com.flexibond.app.Pref
import com.flexibond.base.BaseResponse
import com.flexibond.features.dailyPlan.model.AllPlanListResponseModel
import com.flexibond.features.dailyPlan.model.GetPlanDetailsResponseModel
import com.flexibond.features.dailyPlan.model.GetPlanListResponseModel
import com.flexibond.features.dailyPlan.model.UpdatePlanListInputParamsModel
import io.reactivex.Observable
/**
* Created by Saikat on 24-12-2019.
*/
class PlanRepo(val apiService: PlanApi) {
fun getPlanList(): Observable<GetPlanListResponseModel> {
return apiService.getPlanList(Pref.session_token!!, Pref.user_id!!)
}
fun updatePlanList(updatePlan: UpdatePlanListInputParamsModel): Observable<BaseResponse> {
return apiService.updatePlanList(updatePlan)
}
fun getPlanDetails(plan_id: String): Observable<GetPlanDetailsResponseModel> {
return apiService.getPlanListDetails(Pref.session_token!!, Pref.user_id!!, plan_id)
}
fun getAllPlanList(): Observable<AllPlanListResponseModel> {
return apiService.getAllPlanList(Pref.session_token!!, Pref.user_id!!)
}
} | 0 | Kotlin | 0 | 0 | 235d01d820be2ccfc627c70e190abc4c9059d144 | 1,159 | Flexibond | Apache License 2.0 |
src/test/java/io/daonomic/schema/json/domain/TitleKotlinTest.kt | daonomic | 131,380,433 | false | null | package io.daonomic.schema.json.domain
import io.daonomic.schema.json.custom.Title
data class TitleKotlinTest(
val noTitle: String,
@Title("This is title")
val withTitle: String
) | 4 | null | 1 | 1 | 6323ae85d38b221ca6ea05b3e4ef4aac82d7e80b | 193 | json-schema | Apache License 2.0 |
questDomain/src/main/java/ru/nekit/android/qls/domain/model/AnswerType.kt | ru-nekit-android | 126,668,350 | false | null | package ru.nekit.android.qls.domain.model
enum class AnswerType {
RIGHT,
WRONG,
EMPTY,
WRONG_INPUT_FORMAT
}
| 0 | Kotlin | 0 | 1 | 37a2037be2ecdbe19607b5fbb9e5f7852320a5a0 | 127 | QuestLockScreen | Apache License 2.0 |
app/src/main/java/com/sebastijanzindl/galore/domain/usecase/UpdateUserProfileUseCase.kt | m1thrandir225 | 743,270,603 | false | {"Kotlin": 400176} | package com.sebastijanzindl.galore.domain.usecase
import com.sebastijanzindl.galore.domain.models.UserProfile
interface UpdateUserProfileUseCase: UseCase<UpdateUserProfileUseCase.Input, UpdateUserProfileUseCase.Output> {
class Input(val updatedProfile: UserProfile)
open class Output(val result: UserProfile?)
} | 0 | Kotlin | 0 | 0 | 3a8523e4c8f38020c909ab04c98275b13bb329d9 | 322 | galore-android | MIT License |
src/main/kotlin/com/gregorysdtaylor/campaignmap/rest/model/PlanetRepository.kt | GregorySDTaylor | 319,462,740 | false | null | package com.gregorysdtaylor.campaignmap.rest.model
import org.springframework.data.repository.CrudRepository
interface PlanetRepository : CrudRepository<Planet, Long> {
} | 1 | Kotlin | 0 | 0 | ee8379b798f50f6de055e06a078d626cecf80c22 | 172 | campaign-map | MIT License |
DiscordBot/src/main/kotlin/commands/CommandHandler.kt | bnshw | 653,802,754 | false | null | package commands
import commands.classes.AuthCommand
import commands.classes.ReceiveCommand
import commands.classes.WhitelistCommand
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent
import net.dv8tion.jda.api.hooks.ListenerAdapter
class CommandHandler : ListenerAdapter() {
override fun onSlashCommandInteraction(event: SlashCommandInteractionEvent) {
when (event.name) {
"whitelist" -> WhitelistCommand().onWhitelistCommand(event)
"whitelist-add" -> WhitelistCommand().onWhitelistCommand(event)
"whitelist-remove" -> WhitelistCommand().onWhitelistCommand(event)
"auth" -> AuthCommand().onAuth(event)
"receive" -> ReceiveCommand().onReceive(event)
}
}
} | 0 | Kotlin | 0 | 0 | bb3e893425030e43492a24ce3d79d1f4cc808f77 | 773 | Minecord | MIT License |
app/src/main/java/com/catp/thundersimlineup/util.kt | runaloop | 220,981,087 | false | null | package com.catp.thundersimlineup
import android.annotation.SuppressLint
import android.view.View
import androidx.core.view.ViewCompat
import androidx.fragment.app.Fragment
import com.google.firebase.analytics.FirebaseAnalytics
import org.threeten.bp.LocalDate
import org.threeten.bp.LocalDateTime
import org.threeten.bp.ZoneId
import toothpick.InjectConstructor
import javax.inject.Inject
import javax.inject.Singleton
inline fun <T> T?.whenNull(block: T?.() -> Unit): T? {
if (this == null) block()
return this@whenNull
}
fun <T> List<T>.lShift(n: Int) =
let { slice(n % size until size) + slice(0 until n % size) }
fun <T> List<T>.rShift(n: Int) =
lShift(size - n % size)
@InjectConstructor
class LocalDateTimeProvider {
fun now(): LocalDateTime = LocalDateTime.now(ZoneId.of("Z"))
}
@InjectConstructor
class LocalDateProvider {
fun now(): LocalDate = LocalDate.now(ZoneId.of("Z"))
}
@InjectConstructor
@Singleton
class StatUtil {
@Inject
lateinit var preferences: com.catp.thundersimlineup.data.Preferences
fun sendViewStat(fragment: Fragment, title: String) {
if (preferences.sendStat)
FirebaseAnalytics.getInstance(fragment.requireContext())
.setCurrentScreen(fragment.requireActivity(), title, null)
}
}
@InjectConstructor
@Singleton
class CrashOnCondition {
val hash = mutableMapOf<String, Int>()
fun crashOnCount(count: Int, message: String) {
println("🤛$message $count $hash")
hash[message].whenNull {
hash[message] = count
}?.let {
hash[message] = it - 1
}
if (hash[message]!! <= 0) {
hash.remove(message)
throw RuntimeException(message)
}
}
fun crashOnlyOnce(message: String) {
hash[message].whenNull {
hash[message] = 1
throw RuntimeException(message)
}
}
}
fun log(str: String) {
if (BuildConfig.DEBUG)
println(str)
}
| 0 | Kotlin | 0 | 0 | e190935d1f24a9586db03b2aa8fcada16232a773 | 1,987 | ThunderSimLineup | Apache License 2.0 |
app/src/main/java/com/vicidroid/amalia/sample/examples/ui/examplefragment1/ExampleFragment1Presenter.kt | vicidroiddev | 171,361,804 | false | null | package com.vicidroid.amalia.sample.examples.ui.examplefragment1
import android.util.Log
import com.vicidroid.amalia.core.BasePresenter
import com.vicidroid.amalia.core.viewdiff.ViewDiff
class ExampleFragment1Presenter : BasePresenter() {
override fun loadInitialState() {
Log.v(TAG_INSTANCE, "loadInitialState()")
pushState(ExampleFragment1ViewState.Loaded(ExampleFragment1ViewDiff()))
}
override fun onViewDiffReceived(viewDiff: ViewDiff) {
updateViewStateSilently {
ExampleFragment1ViewState.Loaded(viewDiff as ExampleFragment1ViewDiff)
}
}
}
| 7 | Kotlin | 0 | 9 | 0a4facc243feefe3f982f7f2915ccc5541dc321b | 610 | amalia | Apache License 2.0 |
paymentsheet/src/main/java/com/stripe/android/paymentsheet/forms/SofortForm.kt | michelleb-stripe | 372,835,879 | true | {"Kotlin": 3206059, "Java": 67346, "Ruby": 6208, "Shell": 328} | package com.stripe.android.paymentsheet.forms
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.unit.dp
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.ViewModel
import com.stripe.android.model.PaymentMethod
import com.stripe.android.model.PaymentMethodCreateParams
import com.stripe.android.paymentsheet.R
import com.stripe.android.paymentsheet.elements.EmailConfig
import com.stripe.android.paymentsheet.elements.NameConfig
import com.stripe.android.paymentsheet.elements.Section
import com.stripe.android.paymentsheet.elements.common.DropDown
import com.stripe.android.paymentsheet.elements.common.DropdownElement
import com.stripe.android.paymentsheet.elements.common.TextField
import com.stripe.android.paymentsheet.elements.common.TextFieldElement
import com.stripe.android.paymentsheet.elements.country.CountryConfig
@Composable
internal fun SofortForm(
viewModel: SofortFormViewModel,
) {
val name = FocusRequester()
val email = FocusRequester()
val nameErrorMessage by viewModel.nameElement.errorMessage.observeAsState(null)
val emailErrorMessage by viewModel.emailElement.errorMessage.observeAsState(null)
Column(modifier = Modifier.padding(top = 30.dp, start = 16.dp, end = 16.dp)) {
Section(R.string.address_label_name, nameErrorMessage) {
TextField(
textFieldElement = viewModel.nameElement,
myFocus = name,
nextFocus = email,
)
}
Section(R.string.becs_widget_email, emailErrorMessage) {
TextField(
textFieldElement = viewModel.emailElement,
myFocus = email,
nextFocus = null,
)
}
Section(R.string.address_label_country, null) {
DropDown(
element = viewModel.countryElement
)
}
}
}
internal class SofortFormViewModel : ViewModel() {
internal var nameElement = TextFieldElement(NameConfig())
internal var emailElement = TextFieldElement(EmailConfig())
internal var countryElement = DropdownElement(CountryConfig())
val params: LiveData<PaymentMethodCreateParams?> =
MediatorLiveData<PaymentMethodCreateParams?>().apply {
addSource(nameElement.input) { postValue(getParams()) }
addSource(nameElement.isComplete) { postValue(getParams()) }
addSource(emailElement.input) { postValue(getParams()) }
addSource(emailElement.isComplete) { postValue(getParams()) }
// Country is a dropdown and so will always be complete.
addSource(countryElement.paymentMethodParams) { postValue(getParams()) }
}
private fun getParams(): PaymentMethodCreateParams? {
Log.d(
"Stripe",
"name: ${nameElement.isComplete.value}, email: ${emailElement.isComplete.value}"
)
return if (nameElement.isComplete.value == true && emailElement.isComplete.value == true) {
PaymentMethodCreateParams.create(
PaymentMethodCreateParams.Sofort(requireNotNull(countryElement.paymentMethodParams.value)),
PaymentMethod.BillingDetails(
name = nameElement.input.value,
email = emailElement.input.value
)
)
} else {
null
}
}
}
| 0 | null | 0 | 1 | ef2197fabeb47436a4119e23dab74041c31320d4 | 3,743 | stripe-android | MIT License |
app/src/main/java/mustafaozhan/github/com/mycurrencies/base/activity/BaseActivity.kt | alkimand | 222,409,076 | true | {"Kotlin": 103428} | package mustafaozhan.github.com.mycurrencies.base.activity
import android.app.AlertDialog
import android.graphics.Typeface
import android.os.Bundle
import androidx.annotation.IdRes
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import dagger.android.AndroidInjection
import de.mateware.snacky.Snacky
import mustafaozhan.github.com.mycurrencies.R
import mustafaozhan.github.com.mycurrencies.base.BaseViewModel
import mustafaozhan.github.com.mycurrencies.extensions.getImageResourceByName
import java.util.Locale
import javax.inject.Inject
/**
* Created by Mustafa Ozhan on 7/10/18 at 9:37 PM on Arch Linux wit Love <3.
*/
abstract class BaseActivity<TViewModel : BaseViewModel> : AppCompatActivity() {
@Inject
protected lateinit var viewModel: TViewModel
@LayoutRes
protected abstract fun getLayoutResId(): Int?
@IdRes
open var containerId: Int = R.id.content
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
viewModel.onLoaded()
getLayoutResId()?.let {
setContentView(it)
replaceFragment(getDefaultFragment(), false)
}
}
protected abstract fun getDefaultFragment(): Fragment?
protected fun setHomeAsUpEnabled(enabled: Boolean) =
supportActionBar?.setDisplayHomeAsUpEnabled(enabled)
fun replaceFragment(fragment: Fragment?, withBackStack: Boolean) =
fragment?.let {
supportFragmentManager.beginTransaction().apply {
if (supportFragmentManager.fragments.size > 0) {
setCustomAnimations(
R.anim.enter_from_right,
R.anim.exit_to_left,
R.anim.enter_from_left,
R.anim.exit_to_right
)
}
replace(containerId, it, it.tag)
if (withBackStack) addToBackStack(it.tag)
commit()
}
}
fun snacky(
text: String,
actionText: String = "",
setIcon: String? = null,
isLong: Boolean = true,
action: () -> Unit = {}
) = Snacky.builder()
.setBackgroundColor(ContextCompat.getColor(this, R.color.blue_grey_800))
.setText(text)
.setIcon(setIcon?.let { getImageResourceByName(setIcon) } ?: R.mipmap.ic_launcher)
.setActivity(this)
.setDuration(if (isLong) Snacky.LENGTH_LONG else Snacky.LENGTH_SHORT)
.setActionText(actionText.toUpperCase(Locale.getDefault()))
.setActionTextColor(ContextCompat.getColor(this, R.color.cyan_700))
.setActionTextTypefaceStyle(Typeface.BOLD)
.setActionClickListener { action() }
.build()
.show()
protected fun showDialog(
title: String,
description: String,
positiveButton: String,
cancelable: Boolean = true,
function: () -> Unit = {}
) {
if (!isFinishing) {
val builder = AlertDialog
.Builder(this, R.style.AlertDialogCustom)
.setIcon(R.mipmap.ic_launcher)
.setTitle(title)
.setMessage(description)
.setPositiveButton(positiveButton) { _, _ -> function() }
.setCancelable(cancelable)
if (cancelable) {
builder.setNegativeButton(getString(R.string.cancel), null)
}
builder.show()
}
}
}
| 0 | null | 0 | 0 | 89f3b23a2265b210c4a4996f23ff4080836c1645 | 3,630 | androidCCC | Apache License 2.0 |
src/me/anno/blocks/chunk/ramless/LayeredChunkContent.kt | AntonioNoack | 354,467,907 | false | null | package me.anno.blocks.chunk.ramless
import me.anno.blocks.block.Block
import me.anno.blocks.block.BlockState
import me.anno.blocks.block.base.Air
import me.anno.blocks.chunk.Chunk.Companion.CS
import me.anno.blocks.chunk.Chunk.Companion.CS2
import me.anno.blocks.chunk.Chunk.Companion.CS3
import me.anno.blocks.chunk.Chunk.Companion.CSm1
import me.anno.blocks.chunk.Chunk.Companion.getY
import me.anno.blocks.registry.BlockRegistry
import me.anno.blocks.utils.readBlockState
import me.anno.blocks.utils.writeBlockState
import java.io.DataInputStream
import java.io.DataOutputStream
class LayeredChunkContent(val layers: Array<BlockState>) : ChunkContent() {
private val isSolid = BooleanArray(layers.size) { layers[it].isSolid }
// todo update this value
private var highestY = layers.lastIndexOf(Air)
override fun getHighestNonAirY(index: Int): Int {
return highestY
}
override fun optimize(): ChunkContent {
val first = layers[0]
for (y in 1 until CS) {
if (layers[y] != first) return this
}
return SimplestChunkContent(first)
}
override fun getBlockState(index: Int): BlockState {
return layers[getY(index)]
}
override fun getBlockNullable(index: Int): Block? {
return layers[getY(index)].block
}
override fun isSolid(index: Int): Boolean {
return isSolid[getY(index)]
}
override fun setBlockInternally(index: Int, newState: BlockState): ChunkContent {
// expand to full size
val content = FullChunkContent()
val blocks = content.blocks
for (y in 0 until CS) {
blocks.fill(content.register(layers[y]), y * CS2, (y + 1) * CS2)
}
val height = content.highestY
height.fill(highestY.toByte())
content.setBlock(index, newState)
return content
}
override fun getAllBlocks(): Array<BlockState> {
val firstState = layers[0]
val states = Array(CS3) { firstState }
for (y in 1 until CS) {
val state = layers[y]
if (state != firstState) {
states.fill(state, y * CS2, (y + 1) * CS2)
}
}
return states
}
override fun getAllBlockTypes(): List<BlockState> {
return layers.toList()
}
override fun fillY(newState: BlockState, y: Int): ChunkContent {
layers[y and CSm1] = newState
isSolid[y and CSm1] = newState.isSolid
return this
}
override fun writeInternally(output: DataOutputStream) {
for (y in 0 until CS) {
output.writeBlockState(layers[y])
}
}
override fun readInternally(input: DataInputStream, registry: BlockRegistry): ChunkContent {
for (y in 0 until CS) {
val newState = input.readBlockState(registry)
layers[y] = newState
isSolid[y] = newState.isSolid
}
return this
}
override fun isCompletelySolid(): Boolean {
for (y in 0 until CS) {
if (!isSolid[y]) return false
}
return true
}
override fun isClosedSolid(): Boolean = isClosedSolid()
override fun containsLights(): Boolean {
for (y in 0 until CS) {
if (layers[y].isLight) return true
}
return false
}
} | 0 | Kotlin | 0 | 0 | 007f224334236822ad74ac12954ea506bf5dd8ce | 3,341 | ModCraft | Apache License 2.0 |
leakcanary-haha/src/test/java/leakcanary/HprofPrimitiveArrayStripperTest.kt | arctouch-carlosottoboni | 197,771,572 | true | {"Kotlin": 540823, "Java": 21807, "Shell": 939} | package leakcanary
import leakcanary.GraphObjectRecord.GraphPrimitiveArrayRecord
import leakcanary.PrimitiveType.BOOLEAN
import leakcanary.PrimitiveType.CHAR
import leakcanary.Record.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.BooleanArrayDump
import leakcanary.Record.HeapDumpRecord.ObjectRecord.PrimitiveArrayDumpRecord.CharArrayDump
import org.assertj.core.api.Assertions.assertThat
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import java.io.File
class HprofPrimitiveArrayStripperTest {
@get:Rule
var testFolder = TemporaryFolder()
private var lastId = 0L
private val id: Long
get() = ++lastId
@Test
fun stripHprof() {
val hprofFile = testFolder.newFile("temp.hprof")
val booleanArray = BooleanArrayDump(id, 1, booleanArrayOf(true, false, true, true))
val charArray = CharArrayDump(id, 1, "Hello World!".toCharArray())
hprofFile.writeRecords(listOf(booleanArray, charArray))
val stripper = HprofPrimitiveArrayStripper()
val strippedFile = stripper.stripPrimitiveArrays(hprofFile)
strippedFile.readHprof { graph ->
val booleanArrays = graph.objects
.filter { it is GraphPrimitiveArrayRecord && it.primitiveType == BOOLEAN }
.map { it.readRecord() as BooleanArrayDump }
.toList()
assertThat(booleanArrays).hasSize(1)
assertThat(booleanArrays[0].id).isEqualTo(booleanArray.id)
assertThat(booleanArrays[0].array).isEmpty()
val charArrays = graph.objects
.filter { it is GraphPrimitiveArrayRecord && it.primitiveType == CHAR }
.map { it.readRecord() as CharArrayDump }
.toList()
assertThat(charArrays).hasSize(1)
assertThat(charArrays[0].id).isEqualTo(charArray.id)
assertThat(charArrays[0].array).isEmpty()
}
}
private fun File.writeRecords(
records: List<Record>
) {
HprofWriter.open(this)
.use { writer ->
records.forEach { record ->
writer.write(record)
}
}
}
fun File.readHprof(block: (HprofGraph) -> Unit) {
val (graph, closeable) = HprofGraph.readHprof(this)
closeable.use {
block(graph)
}
}
} | 0 | Kotlin | 0 | 0 | a7816e3684959a67d86737fe88005b69932cec6b | 2,201 | leakcanary | Apache License 2.0 |
TrabajoMongo/src/main/kotlin/models/Vehiculo.kt | jorgesanchez3212 | 639,365,118 | false | null | package models
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import org.bson.codecs.pojo.annotations.BsonId
import org.litote.kmongo.newId
import serializers.LocalDateSerializer
import java.time.LocalDate
@Serializable
data class Vehiculo(
@BsonId
val _id : String = newId<Trabajador>().toString(),
val marca: String,
val modelo : String,
val matricula : String,
@Serializable(with = LocalDateSerializer::class)
val fechaMatriculacion : LocalDate,
@Serializable(with = LocalDateSerializer::class)
val fechaUltimaRevision : LocalDate
) {
} | 0 | Kotlin | 0 | 0 | 8c34930f0129d834bfe9064900d8e0e3840ce8d4 | 614 | Trabajo-AccesoDatos | Apache License 2.0 |
android-base/basektlib/src/main/java/com/kangraoo/basektlib/widget/toolsbar/LibToolBarListener.kt | smartbackme | 390,677,125 | false | null | package com.kangraoo.basektlib.widget.toolsbar
import android.view.View
import com.kangraoo.basektlib.R
abstract class LibToolBarListener : OnLibToolBarListener {
override fun onLeft(view: View, opt: Int) {
when (view.id) {
R.id.lib_toolbar_left_img1 -> leftImage1(view)
R.id.lib_toolbar_left_img2 -> leftImage2(view)
R.id.lib_toolbar_left_text1 -> onNavigate(view)
R.id.lib_toolbar_left_text2 -> leftText2(view)
}
}
abstract fun leftText2(view: View)
abstract fun leftImage2(view: View)
abstract fun leftImage1(view: View)
override fun onRight(view: View, opt: Int) {
when (view.id) {
R.id.lib_toolbar_right_img1 -> rightImage1(view)
R.id.lib_toolbar_right_img2 -> rightImage2(view)
R.id.lib_toolbar_right_text1 -> rightText1(view)
R.id.lib_toolbar_right_text2 -> rightText2(view)
}
}
abstract fun rightText2(view: View)
abstract fun rightText1(view: View)
abstract fun rightImage2(view: View)
abstract fun rightImage1(view: View)
}
| 0 | Kotlin | 1 | 2 | 39b595a9a7a8bf5176022a51bc3fd63fa536414d | 1,116 | Creative-Challenge-DrawingBoard | MIT License |
app/src/main/java/com/goldenraven/padawanwallet/drawer/SendCoinsBackFragment.kt | thunderbiscuit | 308,999,831 | false | null | /*
* Copyright 2020-2022 thunderbiscuit and contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the ./LICENSE file.
*/
package com.goldenraven.padawanwallet.drawer
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.goldenraven.padawanwallet.R
import com.goldenraven.padawanwallet.databinding.FragmentSendCoinsBackBinding
import com.goldenraven.padawanwallet.utils.SnackbarLevel
import com.goldenraven.padawanwallet.utils.fireSnackbar
class SendCoinsBackFragment : Fragment() {
private lateinit var binding: FragmentSendCoinsBackBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
val toolBarTitle = requireActivity().findViewById<TextView>(R.id.toolbarTitleDrawer)
toolBarTitle.text = getString(R.string.send_coins_back_title)
binding = FragmentSendCoinsBackBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.copyAddressFaucetButton.setOnClickListener {
val clipboard: ClipboardManager = activity?.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip: ClipData = ClipData.newPlainText("Copied address", binding.returnFaucetAddress.text)
clipboard.setPrimaryClip(clip)
fireSnackbar(
requireView(),
SnackbarLevel.INFO,
"Copied address to clipboard!"
)
}
}
} | 40 | Kotlin | 14 | 39 | cc664f697bf9efab540a5cb3b466ddaaf2bc0af3 | 1,901 | padawan-wallet | Apache License 2.0 |
editor/src/main/java/com/miracle/view/imageeditor/view/OnRevokeListener.kt | lauhwong | 95,762,361 | false | null | package com.miracle.view.imageeditor.view
/**
* ## Undo callback
*
* Created by lxw
*/
interface OnRevokeListener {
fun revoke(editorMode: EditorMode)
} | 1 | null | 9 | 29 | 0b5a5656bcf35f11a67538fa09ebacf610014de9 | 162 | ImageEditor | Apache License 2.0 |
src/test/kotlin/tutorial/inaction/Debugging1_ja.kt | ldi-github | 646,043,710 | false | {"Kotlin": 214956} | package tutorial.inaction
import org.junit.jupiter.api.Order
import org.junit.jupiter.api.Test
import shirates.core.configuration.Testrun
import shirates.core.driver.commandextension.tap
import shirates.core.driver.commandextension.tapWithScrollDown
import shirates.core.testcode.UITest
@Testrun("testConfig/android/設定/testrun.properties")
class Debugging1_ja : UITest() {
@Test
@Order(10)
fun missingSelector_ERROR() {
scenario {
case(1) {
action {
it.tap("設計")
}
}
}
}
@Test
@Order(20)
fun watchingSourceXml() {
scenario {
case(1) {
action {
it.tapWithScrollDown("ユーザー補助")
.tapWithScrollDown("ユーザー補助機能のショートカット")
.tap("ユーザー補助機能ボタンと操作")
}
}
}
}
} | 0 | Kotlin | 0 | 1 | 6221bd331e4b2d92f384c0fcd703cd439f6663bc | 916 | shirates-core-samples-ja | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.