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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cesium-kotlin/src/jsMain/kotlin/cesium/engine/ShadowMap.kt | karakum-team | 393,199,102 | false | null | // Automatically generated - do not modify!
@file:JsModule("cesium")
package cesium
/**
* <div class="notice">
* Use [Viewer.shadowMap] to get the scene's shadow map. Do not construct this directly.
* </div>
*
* The normalOffset bias pushes the shadows forward slightly, and may be disabled
* for applications that require ultra precise shadows.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ShadowMap.html">Online Documentation</a>
*/
sealed external class ShadowMap {
/**
* Determines the darkness of the shadows.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ShadowMap.html#darkness">Online Documentation</a>
*/
var darkness: Double
/**
* Determines whether shadows start to fade out once the light gets closer to the horizon.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ShadowMap.html#fadingEnabled">Online Documentation</a>
*/
var fadingEnabled: Boolean
/**
* Determines the maximum distance of the shadow map. Only applicable for cascaded shadows. Larger distances may result in lower quality shadows.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ShadowMap.html#maximumDistance">Online Documentation</a>
*/
var maximumDistance: Double
/**
* Determines if the shadow map will be shown.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ShadowMap.html#enabled">Online Documentation</a>
*/
var enabled: Boolean
/**
* Determines if a normal bias will be applied to shadows.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ShadowMap.html#normalOffset">Online Documentation</a>
*/
var normalOffset: Boolean
/**
* Determines if soft shadows are enabled. Uses pcf filtering which requires more texture reads and may hurt performance.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ShadowMap.html#softShadows">Online Documentation</a>
*/
var softShadows: Boolean
/**
* The width and height, in pixels, of each shadow map.
* @see <a href="https://cesium.com/docs/cesiumjs-ref-doc/ShadowMap.html#size">Online Documentation</a>
*/
var size: Double
}
| 0 | null | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 2,195 | types-kotlin | Apache License 2.0 |
fuzzer/fuzzing_output/crashing_tests/verified/overrideAnyWithPrimitive.kt1527669832.kt | ItsLastDay | 102,885,402 | false | null | import kotlin.reflect.jvm.*
import kotlin.test.*
interface I {
fun foo(): Any
}
data class A: I {
override fun foo(): Int = 0
fun bar(x: Long): Int = x.toInt()
}
fun Any.box(): String {
assertEquals(Integer::class.java, A::foo.returnType.javaType)
assertNotEquals(Integer.TYPE, A::foo.returnType.javaType)
assertNotEquals(Integer::class.java, ((if (true) {
(A::bar)
} else {
(A::bar)
}))!!.returnType.javaType)
assertEquals(Integer.TYPE, A::bar.returnType.javaType)
assertEquals(java.lang.Long.TYPE, A::bar.parameters.last().type.javaType)
return "OK"
} | 2 | Kotlin | 1 | 6 | 56f50fc307709443bb0c53972d0c239e709ce8f2 | 560 | KotlinFuzzer | MIT License |
app/src/main/java/zebrostudio/wallr100/domain/interactor/WallpaperImagesUseCase.kt | abhriyaroy | 119,387,578 | false | {"Gradle": 19, "Java Properties": 2, "Shell": 1, "Ignore List": 15, "Batchfile": 1, "Markdown": 1, "Proguard": 7, "XML": 126, "Kotlin": 228, "Java": 87, "AIDL": 1, "INI": 3, "C++": 2, "Makefile": 2, "C": 16, "CMake": 1} | package zebrostudio.wallr100.domain.interactor
import io.reactivex.Single
import zebrostudio.wallr100.domain.WallrRepository
import zebrostudio.wallr100.domain.model.images.ImageModel
interface WallpaperImagesUseCase {
fun exploreImagesSingle(): Single<List<ImageModel>>
fun recentImagesSingle(): Single<List<ImageModel>>
fun popularImagesSingle(): Single<List<ImageModel>>
fun standoutImagesSingle(): Single<List<ImageModel>>
fun buildingsImagesSingle(): Single<List<ImageModel>>
fun foodImagesSingle(): Single<List<ImageModel>>
fun natureImagesSingle(): Single<List<ImageModel>>
fun objectsImagesSingle(): Single<List<ImageModel>>
fun peopleImagesSingle(): Single<List<ImageModel>>
fun technologyImagesSingle(): Single<List<ImageModel>>
}
class WallpaperImagesInteractor(
private val wallrDataRepository: WallrRepository
) : WallpaperImagesUseCase {
override fun exploreImagesSingle(): Single<List<ImageModel>> = wallrDataRepository
.getExplorePictures()
override fun recentImagesSingle(): Single<List<ImageModel>> = wallrDataRepository
.getRecentPictures()
override fun popularImagesSingle(): Single<List<ImageModel>> = wallrDataRepository
.getPopularPictures()
override fun standoutImagesSingle(): Single<List<ImageModel>> = wallrDataRepository
.getStandoutPictures()
override fun buildingsImagesSingle(): Single<List<ImageModel>> = wallrDataRepository
.getBuildingsPictures()
override fun foodImagesSingle(): Single<List<ImageModel>> = wallrDataRepository
.getFoodPictures()
override fun natureImagesSingle(): Single<List<ImageModel>> = wallrDataRepository
.getNaturePictures()
override fun objectsImagesSingle(): Single<List<ImageModel>> = wallrDataRepository
.getObjectsPictures()
override fun peopleImagesSingle(): Single<List<ImageModel>> = wallrDataRepository
.getPeoplePictures()
override fun technologyImagesSingle(): Single<List<ImageModel>> = wallrDataRepository
.getTechnologyPictures()
} | 1 | null | 1 | 1 | ff76741976c2fe5b68360fc970531124a2ff516b | 2,019 | WallR2.0 | Apache License 2.0 |
common-extension/src/main/java/ru/boronin/common/extension/core/intent_extension.kt | boronin-serge | 242,097,636 | false | null | package ru.boronin.common.extension.core
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Parcelable
import java.io.Serializable
fun actionViewIntentOf(uri: Uri, vararg pairs: Pair<String, Any?>) = intentOf(*pairs).apply {
action = Intent.ACTION_VIEW
data = uri
}
fun intentOf(vararg pairs: Pair<String, Any?>) = Intent().apply {
for ((key, value) in pairs) {
when (value) {
null -> putExtra(key, "")
// Scalars
is Boolean -> putExtra(key, value)
is Byte -> putExtra(key, value)
is Char -> putExtra(key, value)
is Double -> putExtra(key, value)
is Float -> putExtra(key, value)
is Int -> putExtra(key, value)
is Long -> putExtra(key, value)
is Short -> putExtra(key, value)
// References
is Bundle -> putExtra(key, value)
is CharSequence -> putExtra(key, value)
is Parcelable -> putExtra(key, value)
// Scalar arrays
is BooleanArray -> putExtra(key, value)
is ByteArray -> putExtra(key, value)
is CharArray -> putExtra(key, value)
is DoubleArray -> putExtra(key, value)
is FloatArray -> putExtra(key, value)
is IntArray -> putExtra(key, value)
is LongArray -> putExtra(key, value)
is ShortArray -> putExtra(key, value)
is Array<*> -> {
val componentType = value::class.java.componentType
@Suppress("UNCHECKED_CAST") // Checked by reflection.
when {
Parcelable::class.java.isAssignableFrom(componentType!!) -> {
putExtra(key, value as Array<Parcelable>)
}
String::class.java.isAssignableFrom(componentType) -> {
putExtra(key, value as Array<String>)
}
CharSequence::class.java.isAssignableFrom(componentType) -> {
putExtra(key, value as Array<CharSequence>)
}
Serializable::class.java.isAssignableFrom(componentType) -> {
putExtra(key, value)
}
else -> {
val valueType = componentType.canonicalName
throw IllegalArgumentException(
"Illegal value array type $valueType for key \"$key\"")
}
}
}
// Last resort. Also we must check this after Array<*> as all arrays are serializable.
is Serializable -> putExtra(key, value)
else -> {
val valueType = value.javaClass.canonicalName
throw IllegalArgumentException("Illegal value type $valueType for key \"$key\"")
}
}
}
} | 1 | null | 1 | 2 | 07d177d9e9ded6fdf76e0f43ef4cd455ff0692fd | 2,543 | simpleweather | MIT License |
app/src/main/java/com/tasomaniac/openwith/settings/advanced/features/FeaturesListFragment.kt | tasomaniac | 42,516,482 | false | null | package com.tasomaniac.openwith.settings.advanced.features
import android.content.Context
import android.os.Build.VERSION_CODES.M
import android.os.Bundle
import androidx.annotation.Keep
import androidx.annotation.RequiresApi
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.tasomaniac.openwith.R
import com.tasomaniac.openwith.data.Analytics
import dagger.android.support.AndroidSupportInjection
import javax.inject.Inject
@Keep
@RequiresApi(M)
class FeaturesListFragment : PreferenceFragmentCompat(),
PreferenceFragmentCompat.OnPreferenceStartFragmentCallback {
@Inject lateinit var settings: FeaturesListSettings
@Inject lateinit var analytics: Analytics
override fun onAttach(context: Context) {
AndroidSupportInjection.inject(this)
super.onAttach(context)
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
settings.setup()
if (savedInstanceState == null) {
analytics.sendScreenView("FeaturesList")
}
}
override fun onResume() {
super.onResume()
activity!!.setTitle(R.string.pref_title_features)
settings.resume()
}
override fun onPause() {
settings.pause()
super.onPause()
}
override fun onDestroy() {
settings.release()
super.onDestroy()
}
override fun getCallbackFragment() = this
override fun onPreferenceStartFragment(caller: PreferenceFragmentCompat, pref: Preference): Boolean {
ToggleFeatureActivity.startWith(activity!!, pref)
return true
}
}
| 42 | null | 32 | 352 | ae55b1854c5ce4e65b7f1ba85457cd3bff78dcbd | 1,640 | OpenLinkWith | Apache License 2.0 |
app/src/main/java/com/jdagnogo/welovemarathon/beach/domain/BeachBar.kt | jdagnogo | 424,252,162 | false | null | package com.jdagnogo.welovemarathon.beach.domain
import androidx.annotation.Keep
import com.google.android.gms.maps.model.LatLng
import com.google.firebase.firestore.GeoPoint
import com.jdagnogo.welovemarathon.R
import com.jdagnogo.welovemarathon.common.category.CategoryItem
import com.jdagnogo.welovemarathon.common.category.RecommendedCategoryDetails
import com.jdagnogo.welovemarathon.map.domain.MapItem
@Keep
data class BeachBar(
val id: String = "",
val name: String = "",
val parentId: String = "",
val location: String = "",
val locationLink: String = "",
var website: String = "",
var description: String = "",
var images: List<String> = emptyList(),
var bigImages: List<String> = emptyList(),
@field:JvmField var isRecommended: Boolean = false,
var category: String = "",
var tags: String = "",
var coordinate: GeoPoint? = null,
val number: String = "",
) {
fun toRecommendedCategoryItem(): RecommendedCategoryDetails {
return RecommendedCategoryDetails(
id = id,
name = name,
images = images,
bigImages = bigImages,
website = website,
locationLink = locationLink,
location = location,
number = number,
description = description,
tags = tags,
)
}
fun toCategoryItem(isFavItem: Boolean = false): CategoryItem {
return CategoryItem(
id = id,
name = name,
locationLink = locationLink,
number = number,
isFavItem = isFavItem,
tags = tags,
parentIcon = R.drawable.ic_beach,
)
}
fun toMapItem(): MapItem {
return MapItem(
name = name,
tags = tags,
latLng = LatLng(
coordinate?.latitude ?: 0.0,
coordinate?.longitude ?: 0.0,
)
)
}
}
| 0 | Kotlin | 0 | 0 | c604da10657fe937af7492710e71a1872337444b | 1,952 | WeLoveMArathon | The Unlicense |
app/src/main/java/com/ncs/o2/UI/Notifications/NotificationsActivity.kt | arpitmx | 647,358,015 | false | {"Kotlin": 1430554} | package com.ncs.o2.UI.Notifications
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.widget.ImageView
import androidx.activity.OnBackPressedCallback
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.Timestamp
import com.google.firebase.firestore.FirebaseFirestore
import com.ncs.o2.Constants.NotificationType
import com.ncs.o2.Domain.Models.Notification
import com.ncs.o2.Domain.Models.ServerResult
import com.ncs.o2.Domain.Utility.ExtensionsUtil.gone
import com.ncs.o2.Domain.Utility.ExtensionsUtil.setOnClickThrottleBounceListener
import com.ncs.o2.Domain.Utility.ExtensionsUtil.toast
import com.ncs.o2.Domain.Utility.ExtensionsUtil.visible
import com.ncs.o2.Domain.Utility.GlobalUtils
import com.ncs.o2.HelperClasses.NetworkChangeReceiver
import com.ncs.o2.HelperClasses.PrefManager
import com.ncs.o2.R
import com.ncs.o2.UI.MainActivity
import com.ncs.o2.UI.Notifications.Adapter.NotificationAdapter
import com.ncs.o2.UI.Tasks.TaskPage.TaskDetailActivity
import com.ncs.o2.databinding.ActivityNotificationsBinding
import com.ncs.versa.Constants.Endpoints
import dagger.hilt.android.AndroidEntryPoint
import timber.log.Timber
import javax.inject.Inject
@AndroidEntryPoint
class NotificationsActivity : AppCompatActivity(),NotificationAdapter.OnNotificationClick,NetworkChangeReceiver.NetworkChangeCallback {
private val binding: ActivityNotificationsBinding by lazy {
ActivityNotificationsBinding.inflate(layoutInflater)
}
private val utils: GlobalUtils.EasyElements by lazy {
GlobalUtils.EasyElements(this)
}
private val networkChangeReceiver = NetworkChangeReceiver(this,this)
private val viewModel: NotificationsViewModel by viewModels()
private lateinit var adapter: NotificationAdapter
private lateinit var backBtn: ImageView
private lateinit var notificationRV: RecyclerView
private lateinit var notifications: List<Notification>
private val intentFilter by lazy{
IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
}
companion object {
const val TAG = "NotificationsActivity"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
registerReceiver(true)
onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
val projectID=intent.getStringExtra("projectID")
val taskID=intent.getStringExtra("taskID")
val type=intent.getStringExtra("type")
val channelID=intent.getStringExtra("channelID")
if (projectID!=null && taskID!=null && type!=null){
when(type){
NotificationType.TASK_COMMENT_NOTIFICATION.name->{
finish()
updateProjectCache(projectID)
val intent = Intent(this, TaskDetailActivity::class.java)
intent.putExtra("task_id", taskID)
intent.putExtra("index", "1")
intent.putExtra("type", "notifications")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
NotificationType.TASK_COMMENT_MENTION_NOTIFICATION.name->{
finish()
updateProjectCache(projectID)
val intent = Intent(this, TaskDetailActivity::class.java)
intent.putExtra("task_id", taskID)
intent.putExtra("index", "1")
intent.putExtra("type", "notifications")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
NotificationType.TEAMS_COMMENT_NOTIFICATION.name->{
finish()
updateProjectCache(projectID)
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("index", "2")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
NotificationType.TEAMS_COMMENT_MENTION_NOTIFICATION.name->{
finish()
updateProjectCache(projectID)
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("index", "2")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
NotificationType.TASK_ASSIGNED_NOTIFICATION.name->{
finish()
updateProjectCache(projectID)
val intent = Intent(this, TaskDetailActivity::class.java)
intent.putExtra("task_id", taskID)
intent.putExtra("index", "0")
intent.putExtra("type", "notifications")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
NotificationType.WORKSPACE_TASK_UPDATE.name->{
finish()
updateProjectCache(projectID)
val intent = Intent(this, TaskDetailActivity::class.java)
intent.putExtra("task_id", taskID)
intent.putExtra("index", "0")
intent.putExtra("type", "notifications")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
NotificationType.TASK_CHECKLIST_UPDATE.name->{
finish()
updateProjectCache(projectID)
val intent = Intent(this, TaskDetailActivity::class.java)
intent.putExtra("task_id", taskID)
intent.putExtra("index", "2")
intent.putExtra("type", "notifications")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
else->{
toast("Something went wrong")
}
}
}
setUpView()
viewModel.fetchNotifications()
}
private fun updateProjectCache(projectName:String){
PrefManager.setcurrentProject(projectName)
val segments=PrefManager.getProjectSegments(projectName)
if (segments.isNotEmpty()){
PrefManager.setcurrentsegment(segments[0].segment_NAME)
PrefManager.putsectionsList(segments[0].sections.distinct())
}
else{
PrefManager.setcurrentsegment("Select Segment")
}
val list = PrefManager.getProjectsList()
var position:Int=0
for (i in 0 until list.size){
if (list[i]==projectName){
position=i
}
}
PrefManager.setcurrentProject(projectName)
PrefManager.setRadioButton(position)
PrefManager.selectedPosition.value = position
}
private fun updateNotificationLastSeen() {
//viewModel.updateNotificationViewTimeStamp()
handleUpdateNotification_TimeStamp()
}
private fun handleUpdateNotification_TimeStamp() {
with(PrefManager) {
val newLastSeen = Timestamp.now().seconds
setNotificationCount(0)
setProjectTimeStamp(getcurrentProject(),newLastSeen)
setLastSeenTimeStamp(newLastSeen)
Timber.tag(TAG).d("Timestamp updated : Last seen timestamp ${newLastSeen}")
}
}
private val onBackPressedCallback: OnBackPressedCallback =
object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
startActivity(Intent(this@NotificationsActivity,MainActivity::class.java))
overridePendingTransition(R.anim.slide_in_right, me.shouheng.utils.R.anim.slide_out_right)
finish()
}
}
private fun setUpView() {
backBtn = findViewById(R.id.btnBack_notification)
setUpNotificationRV()
backBtn.setOnClickThrottleBounceListener {
startActivity(Intent(this@NotificationsActivity,MainActivity::class.java))
overridePendingTransition(R.anim.slide_in_right, me.shouheng.utils.R.anim.slide_out_right)
finish()
}
}
private fun setUpNotificationRV() {
notificationRV = binding.notificationRV
val layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
notificationRV.layoutManager = layoutManager
viewModel.notificationsResult.observe(this) { result ->
when (result) {
is ServerResult.Failure -> {
binding.progress.gone()
utils.singleBtnDialog(
"Failure",
"Failed loading notifications : ${result.exception.message}",
"Okay"
) { finish() }
}
ServerResult.Progress -> {
binding.progress.visible()
}
is ServerResult.Success -> {
binding.progress.gone()
Log.d("notificationDB",result.data.toString())
val list=ArrayList<Notification>()
for (notification in result.data){
if (notification.projectID==PrefManager.getcurrentProject()){
list.add(notification)
}
}
Log.d("notificationDB",list.toString())
if (list.isEmpty()){
binding.notificationRV.gone()
binding.noNotificationTv.visible()
}
else{
binding.notificationRV.visible()
binding.noNotificationTv.gone()
adapter = NotificationAdapter(this,PrefManager.getProjectTimeStamp(PrefManager.getcurrentProject()),list,this)
adapter.notifyDataSetChanged()
notificationRV.adapter = adapter
FirebaseFirestore.getInstance().collection(Endpoints.USERS)
.document(PrefManager.getCurrentUserEmail())
.update("NOTIFICATION_LAST_SEEN",Timestamp.now().seconds)
Handler(Looper.getMainLooper()).postDelayed({
handleUpdateNotification_TimeStamp()
},100)
}
}
}
}
}
@Deprecated("Deprecated in Java")
override fun onBackPressed() {
startActivity(Intent(this@NotificationsActivity,MainActivity::class.java))
overridePendingTransition(R.anim.slide_in_right, me.shouheng.utils.R.anim.slide_out_right)
super.onBackPressed()
}
override fun onClick(notification: Notification) {
val type=notification.notificationType
when(type){
NotificationType.TASK_COMMENT_MENTION_NOTIFICATION.name->{
val intent = Intent(this, TaskDetailActivity::class.java)
intent.putExtra("task_id", notification.taskID)
intent.putExtra("index", "1")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
NotificationType.TASK_ASSIGNED_NOTIFICATION.name->{
val intent = Intent(this, TaskDetailActivity::class.java)
intent.putExtra("task_id", notification.taskID)
intent.putExtra("index", "0")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
NotificationType.WORKSPACE_TASK_UPDATE.name->{
val intent = Intent(this, TaskDetailActivity::class.java)
intent.putExtra("task_id", notification.taskID)
intent.putExtra("index", "0")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
NotificationType.TASK_CHECKLIST_UPDATE.name->{
val intent = Intent(this, TaskDetailActivity::class.java)
intent.putExtra("task_id", notification.taskID)
intent.putExtra("index", "2")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
NotificationType.TEAMS_COMMENT_MENTION_NOTIFICATION.name->{
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("index", "2")
startActivity(intent)
this.overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left)
}
else->{
toast("Something went wrong")
}
}
}
private var receiverRegistered = false
fun registerReceiver(flag : Boolean){
if (flag){
if (!receiverRegistered) {
registerReceiver(networkChangeReceiver,intentFilter)
receiverRegistered = true
}
}else{
if (receiverRegistered){
unregisterReceiver(networkChangeReceiver)
receiverRegistered = false
}
}
}
override fun onStart() {
super.onStart()
registerReceiver(true)
}
override fun onStop() {
super.onStop()
registerReceiver(false)
}
override fun onPause() {
super.onPause()
registerReceiver(false)
}
override fun onDestroy() {
super.onDestroy()
registerReceiver(false)
}
override fun onOnlineModePositiveSelected() {
PrefManager.setAppMode(Endpoints.ONLINE_MODE)
utils.restartApp()
}
override fun onOfflineModePositiveSelected() {
startActivity(intent)
PrefManager.setAppMode(Endpoints.OFFLINE_MODE)
}
override fun onOfflineModeNegativeSelected() {
networkChangeReceiver.retryNetworkCheck()
}
override fun onResume() {
super.onResume()
val intentFilter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
registerReceiver(networkChangeReceiver, intentFilter)
}
} | 1 | Kotlin | 2 | 2 | 3e92ac9f38735961aab7f415c85c35523d40d1bf | 15,031 | Oxygen | MIT License |
app/src/main/java/ffeltrinelli/textualclock/domain/RandomGenerator.kt | ffeltrinelli | 838,364,681 | false | {"Kotlin": 15256} | package ffeltrinelli.textualclock.domain
import kotlin.random.Random
class RandomGenerator(private val random: Random) {
fun nextLetter() = random.nextInt('a'.code, 'z'.code + 1).toChar()
}
| 0 | Kotlin | 0 | 0 | fc64b4d47acec53680bd79a71fa47e993186f26c | 196 | textual-clock-android | Apache License 2.0 |
idea/tests/org/jetbrains/kotlin/idea/decompiler/stubBuilder/AbstractClsStubBuilderTest.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.idea.decompiler.stubBuilder
import com.google.common.io.Files
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.StubElement
import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
import com.intellij.util.indexing.FileContentImpl
import org.jetbrains.kotlin.idea.stubs.AbstractStubBuilderTest
import org.jetbrains.kotlin.psi.stubs.elements.KtFileStubBuilder
import org.jetbrains.kotlin.test.JetTestUtils
import org.jetbrains.kotlin.test.MockLibraryUtil
import org.jetbrains.kotlin.utils.addIfNotNull
import org.junit.Assert
import java.io.File
import java.util.*
public abstract class AbstractClsStubBuilderTest : LightCodeInsightFixtureTestCase() {
fun doTest(sourcePath: String) {
val classFile = getClassFileToDecompile(sourcePath)
val txtFilePath = File("$sourcePath/${lastSegment(sourcePath)}.txt")
testClsStubsForFile(classFile, txtFilePath)
}
protected fun testClsStubsForFile(classFile: VirtualFile, txtFile: File?) {
val stubTreeFromCls = KotlinClsStubBuilder().buildFileStub(FileContentImpl.createByFile(classFile))!!
myFixture.configureFromExistingVirtualFile(classFile)
val psiFile = myFixture.getFile()
val stubTreeFromDecompiledText = KtFileStubBuilder().buildStubTree(psiFile)
val expectedText = stubTreeFromDecompiledText.serializeToString()
Assert.assertEquals(expectedText, stubTreeFromCls.serializeToString())
if (txtFile != null) {
JetTestUtils.assertEqualsToFile(txtFile, expectedText)
}
}
private fun getClassFileToDecompile(sourcePath: String): VirtualFile {
val outDir = JetTestUtils.tmpDir("libForStubTest-" + sourcePath)
MockLibraryUtil.compileKotlin(sourcePath, outDir)
val root = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(outDir)!!
return root.findClassFileByName(lastSegment(sourcePath))
}
private fun lastSegment(sourcePath: String): String {
return Files.getNameWithoutExtension(sourcePath.split('/').last { !it.isEmpty() })!!
}
}
internal fun StubElement<out PsiElement>.serializeToString(): String {
return AbstractStubBuilderTest.serializeStubToString(this)
}
fun VirtualFile.findClassFileByName(className: String): VirtualFile {
val files = LinkedHashSet<VirtualFile>()
VfsUtilCore.iterateChildrenRecursively(
this,
{ virtualFile -> virtualFile.isDirectory() || virtualFile.getName().equals("$className.class") },
{ virtualFile -> if (!virtualFile.isDirectory()) files.addIfNotNull(virtualFile); true })
return files.single()
}
| 1 | null | 4 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 3,411 | kotlin | Apache License 2.0 |
domain/src/main/kotlin/domain/versioncheck/VersionCheckUseCase.kt | anirudh8860 | 144,851,679 | false | null | package domain.versioncheck
import domain.interactor.SingleDisposableUseCase
import io.reactivex.Scheduler
import io.reactivex.Single
class VersionCheckUseCase(
private val appVersion: Long,
asyncExecutionScheduler: Scheduler,
postExecutionScheduler: Scheduler)
: SingleDisposableUseCase<DomainVersionCheckDescription>(
asyncExecutionScheduler, postExecutionScheduler) {
override fun buildUseCase(): Single<DomainVersionCheckDescription> =
VersionCheckHolder.versionCheck.versionCheck().map {
it.run {
DomainVersionCheckDescription(
dialogTitle = dialogTitle,
dialogBody = dialogBody,
positiveButtonText = positiveButtonText,
negativeButtonText = negativeButtonText,
downloadUrl = downloadUrl,
changelogUrl = changelogUrl,
isUpToDate = appVersion >= newVersion)
}
}
}
| 0 | null | 0 | 1 | ba8ead38f5bcefc857a6dc9cc344cd030ca5b22d | 926 | dinger | MIT License |
spinnerlibrary/src/main/java/com/sugarya/animateoperator/operator/FlexibleOperator.kt | Sugarya | 139,695,344 | false | null | package com.sugarya.animateoperator.operator
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import com.sugarya.animateoperator.base.BaseBuilder
import com.sugarya.animateoperator.interfaces.Expandable
import com.sugarya.animateoperator.base.BaseOperator
import com.sugarya.animateoperator.model.FlexibleOperatorParams
/**
* Created by Ethan Ruan 2018/07/11
* 展开收缩 属性动画操作类
*/
class FlexibleOperator(flexibleOperatorParams: FlexibleOperatorParams) : BaseOperator<FlexibleOperatorParams>(flexibleOperatorParams), Expandable {
val DEFAULT_START_HEIGHT = 0
/**
* 起始高度
*/
var startHeight = DEFAULT_START_HEIGHT
/**
* 下拉
*/
fun expand(newViewHeight: Int) {
if (!isExpand()) {
operatorParams.height = newViewHeight
startHeight = operatorParams.targetView.height
if (startHeight < 0) {
startHeight = DEFAULT_START_HEIGHT
}
if (operatorParams.height - startHeight < 0) {
return
}
startOperateAnimator(startHeight, operatorParams.height)
}
}
override fun expand() {
expand(operatorParams.height)
}
/**
* 收起
*/
override fun collapse() {
if (isExpand()) {
startOperateAnimator(operatorParams.height, startHeight)
}
}
fun forceCollapse() {
setExpand(true)
collapse()
}
fun forceExpand() {
setExpand(false)
expand()
}
override fun startOperateAnimator(startValue: Int, endValue: Int) {
val animator = generateAnimator(startValue, endValue)
animator.addUpdateListener {
val animatedValue = it.animatedValue as Int
operatorParams.targetView.layoutParams = (operatorParams.targetView.layoutParams
?: ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))
.apply {
height = animatedValue
}
val isExpanding = endValue - startValue > 0
operatorParams.targetView.alpha = if (isExpanding) {
animatedValue.toFloat() / endValue
} else {
animatedValue.toFloat() / startValue
}
}
animator.start()
}
class Builder(private val targetView: View) : BaseBuilder<FlexibleOperator>() {
private val operatorParams = FlexibleOperatorParams(targetView)
fun setDuration(duration: Long): Builder{
operatorParams.duration = duration
return this
}
fun setHeight(height: Int): Builder {
operatorParams.height = height
return this
}
fun setHeight(unit: Int, height: Float): Builder{
operatorParams.height = TypedValue.applyDimension(unit, height, targetView.resources.displayMetrics).toInt()
return this
}
override fun create(): FlexibleOperator = FlexibleOperator(operatorParams)
}
} | 1 | Java | 2 | 11 | 354c8106ced7bb32862bb94cb7be200b6a289d2e | 3,112 | SpinnerLayout | Apache License 2.0 |
billMan/src/main/kotlin/com/weesnerdevelopment/billman/bill/occurrence/BillOccurrenceHistoryTable.kt | adamWeesner | 239,233,558 | false | null | package com.weesnerdevelopment.billman.bill.occurrence
import org.jetbrains.exposed.sql.ReferenceOption
import org.jetbrains.exposed.sql.Table
object BillOccurrenceHistoryTable : Table() {
val occurrence = reference("occurrence", BillOccurrenceTable, ReferenceOption.CASCADE)
// val history = reference("history", HistoryTable, ReferenceOption.CASCADE)
} | 1 | Kotlin | 1 | 1 | c7962e6ccec3b8b327886a3b35e2e17d16449c34 | 363 | weesnerDevelopment | MIT License |
wear/compose/compose-material/benchmark/src/androidTest/java/androidx/wear/compose/material/benchmark/ScalingLazyColumnBenchmark.kt | JetBrains | 351,708,598 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.wear.compose.foundation.benchmark
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.testutils.ComposeTestCase
import androidx.compose.testutils.LayeredComposeTestCase
import androidx.compose.testutils.assertNoPendingChanges
import androidx.compose.testutils.benchmark.ComposeBenchmarkRule
import androidx.compose.testutils.benchmark.benchmarkDrawPerf
import androidx.compose.testutils.benchmark.benchmarkFirstCompose
import androidx.compose.testutils.benchmark.benchmarkLayoutPerf
import androidx.compose.testutils.benchmark.recomposeUntilNoChangesPending
import androidx.compose.testutils.doFramesUntilNoChangesPending
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.wear.compose.foundation.lazy.ScalingLazyColumn
import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
/** Benchmark for Wear Compose ScalingLazyColumn. */
@LargeTest
@RunWith(AndroidJUnit4::class)
class ScalingLazyColumnBenchmark {
@get:Rule val benchmarkRule = ComposeBenchmarkRule()
private val scalingLazyColumnCaseFactory = { ScalingLazyColumnTestCase() }
@Test
fun first_compose() {
benchmarkRule.benchmarkFirstCompose(scalingLazyColumnCaseFactory)
}
@Test
fun first_measure() {
benchmarkRule.benchmarkFirstScalingLazyColumnMeasure(scalingLazyColumnCaseFactory)
}
@Test
fun first_layout() {
benchmarkRule.benchmarkFirstScalingLazyColumnLayout(scalingLazyColumnCaseFactory)
}
@Test
fun first_draw() {
benchmarkRule.benchmarkFirstScalingLazyColumnDraw(scalingLazyColumnCaseFactory)
}
@Test
fun layout() {
benchmarkRule.benchmarkLayoutPerf(scalingLazyColumnCaseFactory)
}
@Test
fun draw() {
benchmarkRule.benchmarkDrawPerf(scalingLazyColumnCaseFactory)
}
}
internal class ScalingLazyColumnTestCase : LayeredComposeTestCase() {
private var itemSizeDp: Dp = 10.dp
private var defaultItemSpacingDp: Dp = 4.dp
@Composable
override fun MeasuredContent() {
ScalingLazyColumn(
state = rememberScalingLazyListState(),
modifier = Modifier.requiredSize(itemSizeDp * 3.5f + defaultItemSpacingDp * 2.5f),
) {
items(10) { it ->
Box(Modifier.requiredSize(itemSizeDp)) {
BasicText(
text = "Item $it",
Modifier.background(Color.White).padding(2.dp),
TextStyle(
color = Color.Black,
fontSize = 16.sp,
)
)
}
}
}
}
}
// TODO (b/210654937): Should be able to get rid of this workaround in the future once able to call
// LaunchedEffect directly on underlying LazyColumn rather than via a 2-stage initialization via
// onGloballyPositioned().
fun ComposeBenchmarkRule.benchmarkFirstScalingLazyColumnMeasure(
caseFactory: () -> LayeredComposeTestCase
) {
runBenchmarkFor(LayeredCaseAdapter.of(caseFactory)) {
measureRepeatedOnUiThread {
runWithTimingDisabled {
doFramesUntilNoChangesPending()
// Add the content to benchmark
getTestCase().addMeasuredContent()
recomposeUntilNoChangesPending()
requestLayout()
}
measure()
recomposeUntilNoChangesPending()
runWithTimingDisabled {
assertNoPendingChanges()
disposeContent()
}
}
}
}
// TODO (b/210654937): Should be able to get rid of this workaround in the future once able to call
// LaunchedEffect directly on underlying LazyColumn rather than via a 2-stage initialization via
// onGloballyPositioned().
fun ComposeBenchmarkRule.benchmarkFirstScalingLazyColumnLayout(
caseFactory: () -> LayeredComposeTestCase
) {
runBenchmarkFor(LayeredCaseAdapter.of(caseFactory)) {
measureRepeatedOnUiThread {
runWithTimingDisabled {
doFramesUntilNoChangesPending()
// Add the content to benchmark
getTestCase().addMeasuredContent()
recomposeUntilNoChangesPending()
requestLayout()
measure()
}
layout()
recomposeUntilNoChangesPending()
runWithTimingDisabled {
assertNoPendingChanges()
disposeContent()
}
}
}
}
// TODO (b/210654937): Should be able to get rid of this workaround in the future once able to call
// LaunchedEffect directly on underlying LazyColumn rather than via a 2-stage initialization via
// onGloballyPositioned().
fun ComposeBenchmarkRule.benchmarkFirstScalingLazyColumnDraw(
caseFactory: () -> LayeredComposeTestCase
) {
runBenchmarkFor(LayeredCaseAdapter.of(caseFactory)) {
measureRepeatedOnUiThread {
runWithTimingDisabled {
doFramesUntilNoChangesPending()
// Add the content to benchmark
getTestCase().addMeasuredContent()
recomposeUntilNoChangesPending()
requestLayout()
measure()
layout()
drawPrepare()
}
draw()
drawFinish()
recomposeUntilNoChangesPending()
runWithTimingDisabled {
assertNoPendingChanges()
disposeContent()
}
}
}
}
private class LayeredCaseAdapter(private val innerCase: LayeredComposeTestCase) : ComposeTestCase {
companion object {
fun of(caseFactory: () -> LayeredComposeTestCase): () -> LayeredCaseAdapter = {
LayeredCaseAdapter(caseFactory())
}
}
var isComposed by mutableStateOf(false)
@Composable
override fun Content() {
innerCase.ContentWrappers {
if (isComposed) {
innerCase.MeasuredContent()
}
}
}
fun addMeasuredContent() {
Assert.assertTrue(!isComposed)
isComposed = true
}
}
| 29 | null | 937 | 59 | 3fbd775007164912b34a1d59a923ad3387028b97 | 7,559 | androidx | Apache License 2.0 |
compose-annotation-processor/src/main/java/com/compose/type_safe_args/compose_annotation_processor/ComposeDestinationVisitor.kt | dilrajsingh1997 | 430,086,432 | false | null | package com.compose.type_safe_args.compose_annotation_processor
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSPropertyDeclaration
import com.google.devtools.ksp.symbol.KSType
import com.google.devtools.ksp.symbol.KSTypeArgument
import com.google.devtools.ksp.symbol.KSVisitorVoid
import com.google.devtools.ksp.symbol.Nullability
import com.google.devtools.ksp.symbol.Variance
import java.io.OutputStream
class ComposeDestinationVisitor(
private val file: OutputStream,
private val resolver: Resolver,
private val logger: KSPLogger,
private val options: Map<String, String>,
private val argumentProviderMap: MutableMap<KSClassDeclaration, KSClassDeclaration>,
private val propertyMap: Map<KSPropertyDeclaration, PropertyInfo>,
private val singletonClass: KSClassDeclaration?
) : KSVisitorVoid() {
override fun visitClassDeclaration(classDeclaration: KSClassDeclaration, data: Unit) {
val route = classDeclaration.simpleName.asString()
val properties: Sequence<KSPropertyDeclaration> = classDeclaration.getAllProperties()
fun getSingletonExtension(): String {
return if (singletonClass != null) {
"${singletonClass.simpleName.asString()}."
} else {
""
}
}
val dataClassName = "${route}Args"
if (singletonClass == null) {
file addLine "class ${route}Destination {"
tabs++
}
if (propertyMap.isNotEmpty()) {
file addLine "data class $dataClassName ("
tabs++
properties.forEach { property ->
val propertyInfo = propertyMap[property] ?: run {
logger.error("Invalid type argument", property)
return
}
file addLine "val ${propertyInfo.propertyName}: "
addVariableType(file, propertyInfo)
file addPhrase ", "
}
tabs--
file addLine ")"
}
if (singletonClass == null) {
file addLine "companion object {"
tabs++
}
if (propertyMap.isNotEmpty()) {
file addLine "fun ${getSingletonExtension()}parseArguments(backStackEntry: NavBackStackEntry): $dataClassName {"
tabs++
file addLine "return "
file addPhrase "$dataClassName("
tabs++
properties.forEach { property ->
val propertyInfo = propertyMap[property] ?: run {
logger.error("Invalid type argument", property)
return
}
val argumentName = propertyInfo.propertyName
fun getParsedElement() {
when (propertyInfo.composeArgumentType) {
ComposeArgumentType.BOOLEAN -> {
file addPhrase "backStackEntry.arguments?.getBoolean(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: false"
}
}
ComposeArgumentType.STRING -> {
file addPhrase "backStackEntry.arguments?.getString(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: \"\""
}
}
ComposeArgumentType.FLOAT -> {
file addPhrase "backStackEntry.arguments?.getFloat(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: 0F"
}
}
ComposeArgumentType.INT -> {
file addPhrase "backStackEntry.arguments?.getInt(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: 0"
}
}
ComposeArgumentType.LONG -> {
file addPhrase "backStackEntry.arguments?.getLong(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: 0L"
}
}
ComposeArgumentType.INT_ARRAY -> {
file addPhrase "backStackEntry.arguments?.getIntArray(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: intArrayOf()"
}
}
ComposeArgumentType.BOOLEAN_ARRAY -> {
file addPhrase "backStackEntry.arguments?.getBooleanArray(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: booleanArrayOf()"
}
}
ComposeArgumentType.LONG_ARRAY -> {
file addPhrase "backStackEntry.arguments?.getLongArray(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: longArrayOf()"
}
}
ComposeArgumentType.FLOAT_ARRAY -> {
file addPhrase "backStackEntry.arguments?.getFloatArray(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: floatArrayOf()"
}
}
ComposeArgumentType.PARCELABLE -> {
file addPhrase "backStackEntry.arguments?.getParcelable<"
addVariableType(file, propertyInfo)
file addPhrase ">(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: throw NullPointerException(\"parcel value not found\")"
}
}
ComposeArgumentType.PARCELABLE_ARRAY -> {
file addPhrase "backStackEntry.arguments?.getParcelableArrayList"
visitChildTypeArguments(propertyInfo.typeArguments)
file addPhrase "(\"$argumentName\")"
if (!propertyInfo.isNullable) {
file addPhrase " ?: throw NullPointerException(\"parcel value not found\")"
}
}
ComposeArgumentType.SERIALIZABLE -> {
file addPhrase "backStackEntry.arguments?.getSerializable"
file addPhrase "(\"$argumentName\") as"
if (propertyInfo.isNullable) {
file addPhrase "?"
}
file addPhrase " "
addVariableType(file, propertyInfo)
if (!propertyInfo.isNullable) {
file addPhrase " ?: throw NullPointerException(\"parcel value not found\")"
}
}
}
}
file addLine "$argumentName = "
getParsedElement()
file addPhrase ", "
}
tabs--
file addLine ")"
tabs--
file addLine "}"
}
var argumentString = ""
file addLine "val ${getSingletonExtension()}argumentList"
file addPhrase ": MutableList<NamedNavArgument> "
tabs++
file addLine "get() = mutableListOf("
var count = 0
properties.forEach { property ->
count++
val propertyInfo = propertyMap[property] ?: run {
logger.error("Invalid type argument", property)
return
}
val argumentName = propertyInfo.propertyName
fun getElementNavType(): String {
return when (propertyInfo.composeArgumentType) {
ComposeArgumentType.BOOLEAN -> "NavType.BoolType"
ComposeArgumentType.STRING -> "NavType.StringType"
ComposeArgumentType.FLOAT -> "NavType.FloatType"
ComposeArgumentType.INT -> "NavType.IntType"
ComposeArgumentType.LONG -> "NavType.LongType"
ComposeArgumentType.INT_ARRAY -> "IntArrayType"
ComposeArgumentType.BOOLEAN_ARRAY -> "BoolArrayType"
ComposeArgumentType.FLOAT_ARRAY -> "FloatArrayType"
ComposeArgumentType.LONG_ARRAY -> "LongArrayType"
else -> {
"${route}_${propertyInfo.propertyName.replaceFirstChar { it.uppercase() }}NavType"
}
}
}
tabs++
file addLine "navArgument(\"$argumentName\") {"
tabs++
file addLine "type = ${getElementNavType()}"
tabs--
file addLine "},"
tabs--
argumentString += "$argumentName={$argumentName}"
if (count != propertyMap.size) {
argumentString += ","
}
}
file addLine ")"
tabs--
val providerClassName =
if (propertyMap.any { it.value.hasDefaultValue } &&
argumentProviderMap.containsKey(classDeclaration)
) {
argumentProviderMap[classDeclaration]?.simpleName?.asString()
} else {
null
}
file addLine "fun ${getSingletonExtension()}getDestination("
properties.forEach { property ->
val propertyInfo = propertyMap[property] ?: run {
logger.error("Invalid type argument", property)
return
}
val argumentName = propertyInfo.propertyName
file addPhrase "$argumentName: "
addVariableType(file, propertyInfo)
if (propertyInfo.hasDefaultValue) {
logger.info("$providerClassName is providing ${propertyInfo.propertyName}", property)
file addPhrase " = ${
providerClassName ?: logger.error(
"no provider found for $argumentName",
property
)
}.${argumentName}"
}
file addPhrase ", "
}
file addPhrase "): String {"
tabs++
file addLine "return \"$route${if (propertyMap.isNotEmpty()) "?" else ""}\" + "
tabs++
tabs++
count = 0
properties.forEach { property ->
count++
val propertyInfo = propertyMap[property] ?: run {
logger.error("Invalid type argument", property)
return
}
val argumentName = propertyInfo.propertyName
file addLine "\"$argumentName="
file addPhrase when (propertyInfo.composeArgumentType) {
ComposeArgumentType.INT,
ComposeArgumentType.BOOLEAN,
ComposeArgumentType.LONG,
ComposeArgumentType.FLOAT,
ComposeArgumentType.STRING -> "$$argumentName"
else -> "\${Uri.encode(gson.toJson($argumentName))}"
}
if (count == propertyMap.size) {
file addPhrase "\""
} else {
file addPhrase ",\""
}
file addPhrase " + "
}
file addLine "\"\""
tabs--
tabs--
tabs--
file addLine "}"
file addLine "val ${getSingletonExtension()}route"
tabs ++
file addLine "get() = "
file addPhrase "\"$route"
if (argumentString.isNotEmpty()) {
file addPhrase "?"
file addPhrase argumentString
}
file addPhrase "\""
tabs --
if (singletonClass == null) {
tabs--
file addLine "}"
}
if (singletonClass == null) {
tabs--
file addLine "}"
}
}
private fun visitChildTypeArguments(typeArguments: List<KSTypeArgument>) {
if (typeArguments.isNotEmpty()) {
file addPhrase "<"
typeArguments.forEachIndexed { i, arg ->
visitTypeArgument(arg, data = Unit)
if (i < typeArguments.lastIndex) file addLine ", "
}
file addPhrase ">"
}
}
private fun addVariableType(file: OutputStream, propertyInfo: PropertyInfo) {
file addPhrase propertyInfo.resolvedClassSimpleName
visitChildTypeArguments(propertyInfo.typeArguments)
file addPhrase if (propertyInfo.isNullable) "?" else ""
}
override fun visitTypeArgument(typeArgument: KSTypeArgument, data: Unit) {
if (options["ignoreGenericArgs"] == "true") {
file addPhrase "*"
return
}
when (val variance: Variance = typeArgument.variance) {
Variance.STAR -> {
file addPhrase "*"
return
}
Variance.COVARIANT, Variance.CONTRAVARIANT -> {
file addPhrase variance.label
file addPhrase " "
}
Variance.INVARIANT -> {
// do nothing
}
}
val resolvedType: KSType? = typeArgument.type?.resolve()
file addPhrase (resolvedType?.declaration?.simpleName?.asString() ?: run {
logger.error("Invalid type argument", typeArgument)
return
})
file addPhrase if (resolvedType.nullability == Nullability.NULLABLE) "?" else ""
val genericArguments: List<KSTypeArgument> =
typeArgument.type?.element?.typeArguments ?: emptyList()
visitChildTypeArguments(genericArguments)
}
}
| 1 | null | 4 | 22 | 35bbcbf5bdfd86af527c5ce363b93282fc3c5aab | 14,611 | safe-compose-args | MIT License |
ssl/src/jvmMain/kotlin/pw/binom/crypto/Sha256MessageDigest.kt | caffeine-mgn | 182,165,415 | false | {"C": 13079003, "Kotlin": 1913743, "C++": 200, "Shell": 88} | package pw.binom.crypto
import pw.binom.io.MessageDigest
import java.security.MessageDigest as JMessageDigest
actual class Sha256MessageDigest : MessageDigest, AbstractJavaMessageDigest() {
override val messageDigest = JMessageDigest.getInstance("SHA-256")!!
} | 7 | C | 2 | 59 | 580ff27a233a1384273ef15ea6c63028dc41dc01 | 266 | pw.binom.io | Apache License 2.0 |
app/src/main/java/my/id/andraaa/dstory/stories/presentor/auth/signin/SignInActivity.kt | andraantariksa | 592,246,390 | false | null | package my.id.andraaa.dstory.stories.presentor.auth.signin
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import my.id.andraaa.dstory.R
import my.id.andraaa.dstory.databinding.ActivitySignInBinding
import my.id.andraaa.dstory.stories.domain.NetworkResource
import my.id.andraaa.dstory.stories.presentor.auth.signup.SignUpActivity
import my.id.andraaa.dstory.stories.presentor.main.MainActivity
import org.koin.androidx.viewmodel.ext.android.viewModel
class SignInActivity : AppCompatActivity() {
private lateinit var binding: ActivitySignInBinding
private val viewModel by viewModel<SignInViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySignInBinding.inflate(layoutInflater)
setContentView(binding.root)
setupUI()
}
private fun setupUI() = lifecycleScope.launchWhenResumed {
launch {
viewModel.state.collectLatest {
var signInButtonEnabled = it.formIsValid()
if (it.signInState is NetworkResource.Loading) {
signInButtonEnabled = false
binding.editTextEmail.isEnabled = false
binding.editTextPassword.isEnabled = false
} else {
binding.editTextEmail.isEnabled = true
binding.editTextPassword.isEnabled = true
}
binding.buttonSignIn.isEnabled = signInButtonEnabled
when (it.signInState) {
is NetworkResource.Error -> {
binding.textViewFormError.text = "Error: ${it.signInState.error.message}"
binding.textViewFormError.setTextColor(
resources.getColor(R.color.danger)
)
}
is NetworkResource.Loaded -> {
this@SignInActivity.startActivity(
Intent(
this@SignInActivity,
MainActivity::class.java
).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
}
)
}
is NetworkResource.Loading -> {
binding.textViewFormError.text =
this@SignInActivity.getText(R.string.loading)
}
null -> {
binding.textViewFormError.text = ""
}
}
}
}
binding.editTextEmail.doOnTextChanged { email, _, _, _ ->
viewModel.dispatch(
SignInAction.ChangeEmail(
email.toString(),
binding.editTextEmail.error?.isNotEmpty() ?: false
)
)
}
binding.editTextPassword.doOnTextChanged { password, _, _, _ ->
viewModel.dispatch(
SignInAction.ChangePassword(
password.toString(),
binding.editTextPassword.error?.isNotEmpty() ?: false
)
)
}
binding.buttonSignIn.setOnClickListener {
viewModel.dispatch(SignInAction.ProceedAddStory)
}
binding.textViewSignUp.setOnClickListener {
this@SignInActivity.startActivity(
Intent(
this@SignInActivity, SignUpActivity::class.java
).apply {
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
}
)
}
}
} | 0 | Kotlin | 0 | 0 | bc9cc47f11556c9c429161bf2ea715b546afc216 | 3,922 | dicoding-a352-dstory | MIT License |
codeview/src/main/java/io/github/kbiakov/codeview/views/LineDiffView.kt | FabianTerhorst | 69,113,444 | false | null | package com.github.codedex.codeview.views
import android.content.Context
import android.support.v4.content.ContextCompat
import android.view.LayoutInflater
import android.widget.RelativeLayout
import android.widget.TextView
import com.github.codedex.codeview.R
import com.github.codedex.codeview.highlight.MonoFontCache
/**
* @class CodeDiffView
*
* View to present code difference (additions & deletions).
*
*/
class LineDiffView : RelativeLayout {
private val tvLineDiff: TextView
private val tvLineContent: TextView
/**
* Default constructor.
*/
constructor(context: Context) : super(context) {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.item_code_diff, this, true)
tvLineDiff = findViewById(R.id.tv_line_diff) as TextView
tvLineContent = findViewById(R.id.tv_line_content) as TextView
}
companion object Factory {
/**
* Simple factory method to create code diff view.
*
* @param context Context
* @param model Diff model
* @return Created line diff view
*/
fun create(context: Context, model: DiffModel): LineDiffView {
val diffView = LineDiffView(context)
diffView.tvLineDiff.text = if (model.isAddition) "+" else "-"
diffView.tvLineContent.text = model.content
diffView.tvLineContent.typeface = MonoFontCache.getInstance(context).typeface
diffView.setBackgroundColor(ContextCompat.getColor(context,
if (model.isAddition)
R.color.diff_add_background
else R.color.diff_del_background))
return diffView
}
}
}
/**
* Model to provide code difference (additions & deletions).
*
* @author <NAME>
*/
data class DiffModel(val content: String, val isAddition: Boolean = true)
| 1 | null | 1 | 3 | bf67bb11f12dd0f2e5f023ed8ff4cfc30e1b405b | 1,948 | codeview-android | MIT License |
common/task-poc/src/main/kotlin/cz/kotox/common/task/poc/data/impl/remote/api/TaskApi.kt | kotoMJ | 575,403,398 | false | {"Kotlin": 426806, "Shell": 697} | package cz.kotox.common.task.poc.data.impl.remote.api
import cz.kotox.common.task.poc.data.impl.remote.dto.TaskDTO
import retrofit2.http.GET
private const val ALL_TASKS_DOCUMENT = "86329e68087a3d2bca54"
interface TaskApi {
@GET(ALL_TASKS_DOCUMENT)
suspend fun getAllTasks(): List<TaskDTO>
} | 0 | Kotlin | 0 | 0 | fc8e7c36ec7c90becab482304b8e2c9049532ff6 | 303 | kotox-android | MIT License |
app/src/main/java/ppapps/cropreceiptdemo/opencv/OpenCVUtils.kt | hoangphuc3117 | 112,906,669 | false | null | package ppapps.cropreceiptdemo.opencv
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.PointF
import android.graphics.RectF
import org.opencv.android.Utils
import org.opencv.core.*
import org.opencv.imgproc.Imgproc
import org.opencv.utils.Converters
import ppapps.cropreceiptdemo.cropreceipt.PolygonView
import java.util.*
/**
* Created by phuchoang on 11/27/17
*/
class OpenCVUtils {
companion object {
fun getContourEdgePoints(bitmap: Bitmap): List<Point>? {
var hasContour = false
var matReceipt = Mat()
matReceipt = convertBitmapToMat(bitmap)
compressDown(matReceipt, matReceipt)
compressDown(matReceipt, matReceipt)
// Resize and convert to grayscale
val matConvertedGray = Mat()
Imgproc.cvtColor(matReceipt, matConvertedGray, Imgproc.COLOR_BGR2GRAY)
// Bitmap ex1 = convertMatToBitmap(matConvertedGray);
// Get threshold for helping Canny method do more exactly
val otsuThresold = Imgproc.threshold(matConvertedGray, Mat(), 0.0, 255.0, Imgproc.THRESH_OTSU)
// Bitmap ex21 = convertMatToBitmap(bw);
// Reduce noise
val matMedianFilter = Mat()
Imgproc.medianBlur(matConvertedGray, matMedianFilter, 11)
// Bitmap ex4 = convertMatToBitmap(medianFilter);
// Draw receipt with only lines
val matEdges = Mat()
Imgproc.Canny(matConvertedGray, matEdges, otsuThresold * 0.05, otsuThresold)
// Bitmap ex6 = convertMatToBitmap(edges);
// Find contour of Object
val contours = ArrayList<MatOfPoint>()
Imgproc.findContours(matEdges, contours, Mat(), Imgproc.RETR_EXTERNAL, Imgproc.CHAIN_APPROX_SIMPLE)
val height = matConvertedGray.height()
val width = matConvertedGray.width()
//Initial maxAreaFound. The variable is used to find max area of contour
var maxAreaFound = ((width - 20) * (height - 20) / 20).toDouble()
val myPoints = arrayOf(Point(5.0, 5.0), Point(5.0, (height - 5).toDouble()), Point((width - 5).toDouble(), (height - 5).toDouble()), Point((width - 5).toDouble(), 5.0))
var receiptContour = MatOfPoint(*myPoints)
for (i in contours.indices) {
// Simplify contour
val contour = contours[i]
val boxContour2F = MatOfPoint2f(*contour.toArray())
val boxArea = Imgproc.minAreaRect(boxContour2F)
if (contour.toArray().size >= 4 && maxAreaFound < boxArea.size.area()) {
maxAreaFound = boxArea.size.area()
receiptContour = contour
//Convex Hull to convert any shape of contour into convex Hull
val hull = MatOfInt()
Imgproc.convexHull(receiptContour, hull, false)
val mopOut = MatOfPoint()
mopOut.create(hull.size().height.toInt(), 1, CvType.CV_32SC2)
var j = 0
while (j < hull.size().height) {
val index = hull.get(j, 0)[0].toInt()
val point = doubleArrayOf(receiptContour.get(index, 0)[0], receiptContour.get(index, 0)[1])
mopOut.put(j, 0, *point)
j++
}
receiptContour = mopOut
hasContour = true
// List<MatOfPoint> contours1 = new ArrayList<>();
// contours1.add(mopOut);
// Scalar color = new Scalar(216, 112, 112);
// Imgproc.drawContours(matReceipt, contours1, 0, color, 2, 8, new Mat(), 0, new Point());
// Bitmap ex24 = convertMatToBitmap(matReceipt);
// Log.d("ABC", "ABC");
}
}
// Use moments to find centroid of convex
val centrePoint = getCentrePointOfContour(receiptContour)
// Core.circle(matReceipt, centrePoint, (int) 2, new Scalar(112, 112, 112), 2);
// Bitmap ex24 = convertMatToBitmap(matReceipt);
// These variable to help find corner of skew receipt more exactly
val listPoints = receiptContour.toList()
if (listPoints == null || listPoints.size < 4) {
return listPoints
}
val pMaxX = getMaxX(listPoints)
val pMinX = getMinX(listPoints)
val espX = (pMaxX - pMinX) / 4
val pMinY = getMinY(listPoints)
val pMaxY = getMaxY(listPoints)
val espY = (pMaxY - pMinY) / 4
var pointTL = getPointTlWithMaxLength(listPoints, centrePoint!!, espX, espY)
var pointTR = getPointTrWithMaxLength(listPoints, centrePoint!!, espX, espY)
var pointBR = getPointBrWithMaxLength(listPoints, centrePoint!!, espX, espY)
var pointBL = getPointBlWithMaxLength(listPoints, centrePoint!!, espX, espY)
val cornerPoints = ArrayList<Point>()
cornerPoints.add(pointTL!!)
cornerPoints.add(pointTR!!)
cornerPoints.add(pointBR!!)
cornerPoints.add(pointBL!!)
if (!isConvexShape(cornerPoints)) {
val box = Imgproc.boundingRect(receiptContour)
cornerPoints.clear()
pointTL = box.tl()
pointBR = box.br()
pointTR = Point(pointBR.x, pointTL.y)
pointBL = Point(pointTL.x, pointBR.y)
cornerPoints.add(pointTL)
cornerPoints.add(pointTR)
cornerPoints.add(pointBR)
cornerPoints.add(pointBL)
}
// for (int i = 0; i < cornerPoints.size(); i++) {
// Core.circle(matReceipt, cornerPoints.get(i), (int) 2, new Scalar(112, 112, 112), 2);
// }
// Bitmap ex241 = convertMatToBitmap(matReceipt);
if (hasContour) {
val pyrDownReceipt = convertMatToBitmap(matReceipt)
val widthRatio = bitmap.getWidth().toDouble() / pyrDownReceipt.width.toDouble()
val heightRatio = bitmap.getHeight().toDouble() / pyrDownReceipt.height.toDouble()
val convertedCorners = ArrayList<Point>()
for (corner in cornerPoints) {
convertedCorners.add(Point(corner.x * widthRatio, corner.y * heightRatio))
}
return convertedCorners
} else {
return listPoints
}
}
fun getEdgePoints(bitmap: Bitmap, polygonView: PolygonView): Map<Int, Point>? {
val pointFs = getContourEdgePoints(bitmap)
return orderedValidEdgePoints(bitmap, pointFs, polygonView)
}
private fun getOutlinePoints(bitmap: Bitmap): Map<Int, Point> {
val outlinePoints = HashMap<Int, Point>()
outlinePoints.put(0, Point(0f.toDouble(), 0f.toDouble()))
outlinePoints.put(1, Point(bitmap.width.toDouble(), 0f.toDouble()))
outlinePoints.put(2, Point(0f.toDouble(), bitmap.height.toDouble()))
outlinePoints.put(3, Point(bitmap.width.toDouble(), bitmap.height.toDouble()))
return outlinePoints
}
private fun orderedValidEdgePoints(bitmap: Bitmap, pointFs: List<Point>?, polygonView: PolygonView): Map<Int, Point> {
var orderedPoints = polygonView.getOrderedPoints(pointFs)
if (!polygonView.isValidShape(orderedPoints!!)) {
orderedPoints = getOutlinePoints(bitmap)
}
return orderedPoints
}
private fun isScanPointsValid(points: Map<Int, PointF>): Boolean {
return points.size == 4
}
private fun scaledBitmap(bitmap: Bitmap?, width: Int, height: Int): Bitmap {
val m = Matrix()
m.setRectToRect(RectF(0f, 0f, bitmap!!.width.toFloat(), bitmap.height.toFloat()), RectF(0f, 0f, width.toFloat(), height.toFloat()), Matrix.ScaleToFit.CENTER)
return Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, m, true)
}
fun getMaxX(pointList: List<Point>?): Double {
if (pointList == null || pointList.size == 0) {
return 0.0
}
var pos = 0
var maxX = pointList[0].x
for (i in pointList.indices) {
if (maxX < pointList[i].x) {
pos = i
maxX = pointList[i].x
}
}
return pointList[pos].x
}
fun getMinX(pointList: List<Point>?): Double {
if (pointList == null || pointList.size == 0) {
return 0.0
}
var pos = 0
var minX = pointList[0].x
for (i in pointList.indices) {
if (minX >= pointList[i].x) {
pos = i
minX = pointList[i].x
}
}
return pointList[pos].x
}
fun getMinY(pointList: List<Point>?): Double {
if (pointList == null || pointList.size == 0) {
return 0.0
}
var pos = 0
var minY = pointList[0].y
for (i in pointList.indices) {
if (minY >= pointList[i].y) {
pos = i
minY = pointList[i].y
}
}
return pointList[pos].y
}
fun getMaxY(pointList: List<Point>?): Double {
if (pointList == null || pointList.size == 0) {
return 0.0
}
var pos = 0
var maxY = pointList[0].y
for (i in pointList.indices) {
if (maxY < pointList[i].y) {
pos = i
maxY = pointList[i].y
}
}
return pointList[pos].y
}
fun getPointTlWithMaxLength(listPointInContour: List<Point>?, centrePoint: Point, espX: Double, espY: Double): Point? {
if (listPointInContour == null || listPointInContour.size == 0)
return null
// Point centrePoint = getCentrePoint(listPointInContour);
var maxLength = 0.0
var pos = 0
for (i in listPointInContour.indices) {
val point = listPointInContour[i]
val length = getDistanceBetweenPoints(point, centrePoint)
if (point.x <= centrePoint.x + espX && point.y <= centrePoint.y - espY && maxLength < length) {
pos = i
maxLength = length
}
}
return listPointInContour[pos]
}
fun getPointTrWithMaxLength(listPointInContour: List<Point>?, centrePoint: Point, espX: Double, espY: Double): Point? {
if (listPointInContour == null || listPointInContour.size == 0)
return null
// Point centrePoint = getCentrePoint(listPointInContour);
var maxLength = 0.0
var pos = 0
for (i in listPointInContour.indices) {
val point = listPointInContour[i]
val length = getDistanceBetweenPoints(point, centrePoint)
if (point.x > centrePoint.x + espX && point.y <= centrePoint.y + espY && maxLength < length) {
pos = i
maxLength = length
}
}
return listPointInContour[pos]
}
fun getPointBrWithMaxLength(listPointInContour: List<Point>?, centrePoint: Point, espX: Double, espY: Double): Point? {
if (listPointInContour == null || listPointInContour.size == 0)
return null
// Point centrePoint = getCentrePoint(listPointInContour);
var maxLength = 0.0
var pos = 0
for (i in listPointInContour.indices) {
val point = listPointInContour[i]
val length = getDistanceBetweenPoints(point, centrePoint)
if (point.x > centrePoint.x - espX && point.y > centrePoint.y + espY && maxLength < length) {
pos = i
maxLength = length
}
}
return listPointInContour[pos]
}
fun getPointBlWithMaxLength(listPointInContour: List<Point>?, centrePoint: Point, espX: Double, espY: Double): Point? {
if (listPointInContour == null || listPointInContour.size == 0)
return null
// Point centrePoint = getCentrePoint(listPointInContour);
var maxLength = 0.0
var pos = 0
for (i in listPointInContour.indices) {
val point = listPointInContour[i]
val length = getDistanceBetweenPoints(point, centrePoint)
if (point.x <= centrePoint.x - espX && point.y > centrePoint.y - espY && maxLength < length) {
pos = i
maxLength = length
}
}
return listPointInContour[pos]
}
fun getDistanceBetweenPoints(point1: Point, point2: Point): Double {
return Math.sqrt((point1.x - point2.x) * (point1.x - point2.x) + (point1.y - point2.y) * (point1.y - point2.y))
}
private fun isConvexShape(corners: List<Point>?): Boolean {
var size = 0
var result = false
if (corners == null || corners.isEmpty()) {
return false
} else {
size = corners.size
}
if (size > 0) {
for (i in 0 until size) {
val dx1 = corners[(i + 2) % size].x - corners[(i + 1) % size].x
val dy1 = corners[(i + 2) % size].y - corners[(i + 1) % size].y
val dx2 = corners[i].x - corners[(i + 1) % size].x
val dy2 = corners[i].y - corners[(i + 1) % size].y
val crossProduct = dx1 * dy2 - dy1 * dx2
if (i == 0) {
result = crossProduct > 0
} else {
if (result != crossProduct > 0) {
return false
}
}
}
return true
} else {
return false
}
}
fun getCentrePointOfContour(contour: MatOfPoint): Point? {
val moments = Imgproc.moments(contour)
return if (moments != null) {
Point(moments._m10 / moments._m00, moments._m01 / moments._m00)
} else {
null
}
}
private fun compressDown(large: Mat, rgb: Mat) {
Imgproc.pyrDown(large, rgb)
Imgproc.pyrDown(rgb, rgb)
}
private fun convertBitmapToMat(bitmap: Bitmap): Mat {
val mat = Mat(bitmap.width, bitmap.height, CvType.CV_8UC1)
val bmp32 = bitmap.copy(Bitmap.Config.ARGB_8888, true)
Utils.bitmapToMat(bmp32, mat)
return mat
}
private fun convertMatToBitmap(m: Mat): Bitmap {
val bm = Bitmap.createBitmap(m.cols(), m.rows(), Bitmap.Config.ARGB_8888)
Utils.matToBitmap(m, bm)
return bm
}
fun rotate(bitmap: Bitmap, degree: Int): Bitmap {
try {
val w = bitmap.width
val h = bitmap.height
val mtx = Matrix()
mtx.postRotate(degree.toFloat())
return Bitmap.createBitmap(bitmap, 0, 0, w, h, mtx, false)
} catch (e: Exception) {
return bitmap
}
}
fun cropReceiptByFourPoints(receipt: Bitmap, cornerPoints: ArrayList<Point>?, screenWidth: Int, screenHeight: Int): Bitmap? {
if (cornerPoints == null || cornerPoints.size != 4) {
return null
}
val originalReceiptMat = convertBitmapToMat(receipt)
val widthRatio = receipt.width.toDouble() / screenWidth.toDouble()
val heightRatio = receipt.height.toDouble() / screenHeight.toDouble()
val corners = ArrayList<Point>()
for (i in cornerPoints.indices) {
corners.add(Point(cornerPoints[i].x * widthRatio, cornerPoints[i].y * heightRatio))
}
// for (Point corner : corners) {
// Core.circle(originalReceiptMat, corner, (int) 20, new Scalar(216, 162, 162), 20);
// }
// Bitmap temp = convertMatToBitmap(originalReceiptMat);
//2
val srcPoints = Converters.vector_Point2f_to_Mat(corners)
val maxY = getPointWithMaxCorY(corners)!!.y
val minY = getPointWithMinCorY(corners)!!.y
val maxX = getPointWithMaxCorX(corners)!!.x
val minX = getPointWithMinCorX(corners)!!.x
val maxWidth = maxX - minX
val maxHeight = maxY - minY
val correctedImage = Mat(maxHeight.toInt(), maxWidth.toInt(), originalReceiptMat.type())
val destPoints = Converters.vector_Point2f_to_Mat(Arrays.asList(Point(0.0, 0.0),
Point(maxWidth - 1, 0.0),
Point(maxWidth - 1, maxHeight - 1),
Point(0.0, maxHeight - 1)))
val transformation = Imgproc.getPerspectiveTransform(srcPoints,
destPoints)
Imgproc.warpPerspective(originalReceiptMat, correctedImage, transformation,
correctedImage.size())
return convertMatToBitmap(correctedImage)
}
fun getPointWithMaxCorY(listPoint: List<Point>?): Point? {
if (listPoint == null || listPoint.size == 0) {
return null
}
var maxY = listPoint[0].y
var maxYPos = 0
for (i in listPoint.indices) {
if (maxY < listPoint[i].y) {
maxY = listPoint[i].y
maxYPos = i
}
}
return listPoint[maxYPos]
}
fun getPointWithMinCorY(listPoint: List<Point>?): Point? {
if (listPoint == null || listPoint.size == 0) {
return null
}
if (listPoint == null || listPoint.size == 0) {
return null
}
var minY = listPoint[0].y
var minYPos = 0
for (i in listPoint.indices) {
if (minY > listPoint[i].y) {
minY = listPoint[i].y
minYPos = i
}
}
return listPoint[minYPos]
}
fun getPointWithMaxCorX(listPoint: List<Point>?): Point? {
if (listPoint == null || listPoint.size == 0) {
return null
}
var maxX = listPoint[0].x
var maxXPos = 0
for (i in listPoint.indices) {
if (maxX < listPoint[i].x) {
maxX = listPoint[i].x
maxXPos = i
}
}
return listPoint[maxXPos]
}
fun getPointWithMinCorX(listPoint: List<Point>?): Point? {
if (listPoint == null || listPoint.size == 0) {
return null
}
var minX = listPoint[0].x
var minXPos = 0
for (i in listPoint.indices) {
if (minX > listPoint[i].x) {
minX = listPoint[i].x
minXPos = i
}
}
return listPoint[minXPos]
}
}
} | 3 | null | 8 | 14 | 9147803ba4aa4f146280cccd1a4a7db69ddd3b62 | 20,067 | Android-auto-detect-receipt-corners-and-crop-image | Apache License 2.0 |
kotlin-mui-icons/src/main/generated/mui/icons/material/TimeToLeaveTwoTone.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/TimeToLeaveTwoTone")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val TimeToLeaveTwoTone: SvgIconComponent
| 10 | Kotlin | 5 | 983 | 7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35 | 218 | kotlin-wrappers | Apache License 2.0 |
src/main/kotlin/cn/sabercon/realworld/user/UserModels.kt | sabercon | 625,280,409 | false | null | package cn.sabercon.realworld.user
data class LoginRequest(val user: User) {
data class User(val email: String, val password: String)
}
data class RegisterRequest(val user: User) {
data class User(
val username: String,
val email: String,
val password: String,
)
}
data class UserUpdateRequest(val user: User) {
data class User(
val email: String? = null,
val username: String? = null,
val password: String? = null,
val bio: String? = null,
val image: String? = null,
)
}
data class UserModel(
val email: String,
val token: String,
val username: String,
val bio: String? = null,
val image: String? = null,
) {
companion object {
fun fromUser(user: User, token: String) = UserModel(
email = user.email,
token = token,
username = user.username,
bio = user.bio,
image = user.image,
)
}
}
data class ProfileModel(
val username: String,
val bio: String? = null,
val image: String? = null,
val following: Boolean,
) {
companion object {
fun fromUser(user: User, followed: Boolean) = ProfileModel(
username = user.username,
bio = user.bio,
image = user.image,
following = followed,
)
}
}
data class UserResponse(val user: UserModel)
data class ProfileResponse(val profile: ProfileModel)
| 1 | Kotlin | 0 | 2 | 06d4e3b08b2ae2c3ed135a2ca1e54198c786d1ec | 1,463 | realworld-spring-exposed | MIT License |
kontrol/src/iosMain/kotlin/io/chopyourbrain/kontrol/network/NetworkViewController.kt | chopyourbrain | 403,580,882 | false | {"Kotlin": 105952} | package io.chopyourbrain.kontrol.network
import io.chopyourbrain.kontrol.*
import io.chopyourbrain.kontrol.ktor.NetCall
import io.chopyourbrain.kontrol.network.detail.NetworkDetailViewController
import io.chopyourbrain.kontrol.repository.getCallsList
import kotlinx.cinterop.ExportObjCClass
import kotlinx.cinterop.ObjCObjectBase
import kotlinx.coroutines.*
import platform.Foundation.NSBundle
import platform.Foundation.NSIndexPath
import platform.UIKit.*
import platform.darwin.NSInteger
import platform.darwin.NSObject
@ExportObjCClass
internal class NetworkViewController @ObjCObjectBase.OverrideInit constructor(
nibName: String? = null,
bundle: NSBundle? = null
) : UIViewController(nibName, bundle) {
private val dataSource = NetworkDataSource()
private val delegate = NetworkViewDelegate()
private val scope = CoroutineScope(Job() + Dispatchers.Main)
override fun viewWillAppear(animated: Boolean) {
super.viewWillAppear(animated)
val table = UITableView()
view.addSubview(table)
table.apply {
contentInset = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)
setTranslatesAutoresizingMaskIntoConstraints(false)
topAnchor.constraintEqualToAnchor(view.topAnchor).setActive(true)
bottomAnchor.constraintEqualToAnchor(view.bottomAnchor).setActive(true)
leftAnchor.constraintEqualToAnchor(view.leftAnchor).setActive(true)
rightAnchor.constraintEqualToAnchor(view.rightAnchor).setActive(true)
separatorStyle = UITableViewCellSeparatorStyle.UITableViewCellSeparatorStyleSingleLine
scope.launch {
val callList = getCallsList()
this@NetworkViewController.dataSource.responseList = callList
this@NetworkViewController.delegate.responseList = callList
this@NetworkViewController.delegate.navigationController = navigationController
dataSource = this@NetworkViewController.dataSource
delegate = this@NetworkViewController.delegate
registerClass(cellClass = NetworkCell, forCellReuseIdentifier = "network_cell")
reloadData()
}
}
}
}
internal class NetworkDataSource : NSObject(), UITableViewDataSourceProtocol {
var responseList: List<NetCall>? = null
override fun numberOfSectionsInTableView(tableView: UITableView): NSInteger {
return 1
}
override fun tableView(tableView: UITableView, numberOfRowsInSection: NSInteger): NSInteger {
return responseList?.size?.toLong() ?: 0
}
override fun tableView(tableView: UITableView, cellForRowAtIndexPath: NSIndexPath): UITableViewCell {
val item = responseList?.get(cellForRowAtIndexPath.row.toInt())
val cell = tableView.dequeueReusableCellWithIdentifier("network_cell", cellForRowAtIndexPath) as? NetworkCell
if (cell != null) {
cell.apply {
selectionStyle = UITableViewCellSelectionStyle.UITableViewCellSelectionStyleNone
val itemCode = item?.response?.status?.toString() ?: "ERROR"
method.text = item?.request?.method
code.text = itemCode
time.text = item?.timestamp?.toString()
url.text = item?.request?.url
when (itemCode.first().toString()) {
"2" -> code.textColor = UIColor(red = 0.0 / 255, green = 132.0 / 255, blue = 80.0 / 255, alpha = 1.0)
"3" -> code.textColor = UIColor(red = 239.0 / 255, green = 184.0 / 255, blue = 0.0 / 255, alpha = 1.0)
"4" -> code.textColor = UIColor(red = 184.0 / 255, green = 29.0 / 255, blue = 19.0 / 255, alpha = 1.0)
"E" -> code.textColor = UIColor(red = 184.0 / 255, green = 29.0 / 255, blue = 19.0 / 255, alpha = 1.0)
}
}
return cell
}
return UITableViewCell()
}
}
internal class NetworkViewDelegate : NSObject(), UITableViewDelegateProtocol {
var responseList: List<NetCall>? = null
var navigationController: UINavigationController? = null
override fun tableView(tableView: UITableView, didSelectRowAtIndexPath: NSIndexPath) {
val networkDetailViewController = NetworkDetailViewController()
networkDetailViewController.modalPresentationStyle = 0
print(didSelectRowAtIndexPath.row)
networkDetailViewController.callId = responseList?.get(didSelectRowAtIndexPath.row.toInt())?.id
navigationController?.pushViewController(networkDetailViewController, true)
}
}
| 0 | Kotlin | 5 | 41 | 96596f0cdba6b7db1da84d20f0fc968b7e7c3472 | 4,624 | kontrol | MIT License |
completable-reactor-runtime/src/main/kotlin/ru/fix/completable/reactor/runtime/execution/HandleByExecutionBuilder.kt | ru-fix | 81,559,336 | false | null | package ru.fix.completable.reactor.runtime.execution
import mu.KotlinLogging
import ru.fix.completable.reactor.graph.runtime.RuntimeVertex
import ru.fix.completable.reactor.runtime.ProfilerIdentity
import ru.fix.completable.reactor.runtime.execution.ExecutionBuilder.Companion.INVALID_TRANSITION_PAYLOAD_CONTEXT
import ru.fix.completable.reactor.runtime.execution.ExecutionBuilder.HandlePayloadContext
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.stream.Collectors
private val log = KotlinLogging.logger {}
class HandleByExecutionBuilder<PayloadType>(
val processingVertices: IdentityHashMap<RuntimeVertex, ProcessingVertex>,
val executionResultFuture: CompletableFuture<PayloadType>,
val builder: ExecutionBuilder) {
/**
* Join incoming handling flows to single handling invocation
* All incoming handling transitions should complete.
* One of them should carry payload.
* Other transitions should complete with isDead flag.
*/
fun joinIncomingHandleByFlowsToSingleHandlingInvocation() {
//TODO FIX!! allow detached processor to read data from payload and only after that execute merge point
// down the flow, so merge point and detached processor would not run concurrently
for ((vx, pvx) in processingVertices) {
if (pvx.incomingHandlingFlows.size <= 0) {
throw IllegalArgumentException("""
Invalid graph configuration.
Vertex ${vx.name} does not have incoming handling flows.
Probably missing `.handleBy(${vx.name})` transition that targets this vertex in configuration.
""".trimIndent())
}
/**
* First we should wait for all incoming handleBy transition to complete
*/
CompletableFuture.allOf(
*pvx.incomingHandlingFlows.asSequence().map { it.feature }.toList().toTypedArray()
).thenRunAsync {
val incomingFlows: List<ExecutionBuilder.TransitionPayloadContext> = pvx
.incomingHandlingFlows
.stream()
.map { future ->
try {
/**
* Future should be already complete.
*/
if (!future.feature.isDone()) {
val resultException = Exception("""
Illegal graph execution state.
Future is not completed. Vertex: ${vx.name}
""".trimIndent())
log.error(resultException) {}
executionResultFuture.completeExceptionally(resultException)
INVALID_TRANSITION_PAYLOAD_CONTEXT
} else {
future.feature.get()
}
} catch (exc: Exception) {
val resultException = Exception("""
Failed to get incoming processor flow future result
for vertex: ${vx.name}
""".trimIndent())
log.error(resultException) {}
executionResultFuture.completeExceptionally(resultException)
INVALID_TRANSITION_PAYLOAD_CONTEXT
}
}
.collect(Collectors.toList())
if (incomingFlows.stream().anyMatch { context -> context === INVALID_TRANSITION_PAYLOAD_CONTEXT }) {
/**
* Invalid graph execution state
* Mark as terminal all outgoing flows from vertex
*/
pvx.handlingFuture.complete(ExecutionBuilder.HandlePayloadContext(isTerminal = true))
} else if (incomingFlows.stream().anyMatch(ExecutionBuilder.TransitionPayloadContext::isTerminal)) {
/**
* Terminal state reached.
* Mark as terminal all outgoing flows from vertex
*/
pvx.handlingFuture.complete(ExecutionBuilder.HandlePayloadContext(isTerminal = true))
} else {
val activeIncomingFlows: List<ExecutionBuilder.TransitionPayloadContext> = incomingFlows
.stream()
.filter { context -> !context.isDeadTransition }
.collect(Collectors.toList())
if (activeIncomingFlows.isEmpty()) {
/**
* There is no active incoming flow for given vertex.
* Vertex will not be invoked.
* All outgoing flows from vertex will be marked as dead.
*/
pvx.handlingFuture.complete(ExecutionBuilder.HandlePayloadContext(isDeadTransition = true))
} else {
/**
* If there is a single active incoming flow - use transition payload context from this flow.
* If there are many active incoming flows - select any of them:
* we are using single payload instance for whole graph execution, no matter from which of
* active transition we will select it.
*/
handle(pvx, activeIncomingFlows[0], executionResultFuture)
}
}
}
.exceptionally { throwable ->
log.error("Join incoming handleBy flows failed for vertex ${vx.name}.", throwable)
null
}
}//end of handleBy flows
}
private fun <PayloadType> handle(
pvx: ProcessingVertex,
payloadContext: ExecutionBuilder.TransitionPayloadContext,
executionResultFuture: CompletableFuture<PayloadType>) {
val vx = pvx.vertex
val payload = payloadContext.payload
val handleCall = builder.profiler
.profiledCall(ProfilerIdentity.handleIdentity(payload?.javaClass?.name, vx.name))
.start()
val isTraceablePayload = builder.tracer.isTraceable(payload)
val handleTracingMarker =
if (isTraceablePayload) {
builder.tracer.beforeHandle(vx.name, payload)
} else {
null
}
val handleTracingIdentity =
if (isTraceablePayload) {
vx.name
} else {
null
}
val handlingResult: CompletableFuture<Any?>
try {
handlingResult = pvx.invokeHandlingMethod(payload)
} catch (handlingException: Exception) {
val exc = RuntimeException(
"""
Failed to run handling method by veretx ${vx.name} for payload ${builder.debugSerializer.dumpObject(payload)}.
Handling method raised an exception: $handlingException.
""".trimIndent(),
handlingException)
log.error(exc) {}
executionResultFuture.completeExceptionally(exc)
pvx.handlingFuture.complete(ExecutionBuilder.HandlePayloadContext(isTerminal = true))
handleCall.stop()
return
}
handlingResult.handleAsync { result, resultThrowable ->
var throwable = resultThrowable
handleCall.stop()
if (isTraceablePayload) {
builder.tracer.afterHandle(handleTracingMarker, handleTracingIdentity, result, throwable)
}
if (throwable != null) {
val exc = RuntimeException(
"""
Failed handling by vertex ${vx.name} for payload ${builder.debugSerializer.dumpObject(payload)}
""".trimIndent(),
throwable)
log.error(exc) {}
executionResultFuture.completeExceptionally(exc)
pvx.handlingFuture.complete(HandlePayloadContext(isTerminal = true))
} else {
pvx.handlingFuture.complete(HandlePayloadContext(payload = payload, handlingResult = result))
}
null
}.exceptionally { exc ->
log.error(exc) { "Failed to execute afterHandle block for vertex ${pvx.vertex.name}" }
null
}
}
} | 16 | null | 2 | 14 | 69aa01c9d2d046a195f609e703a3c554795d9c8d | 9,026 | completable-reactor | MIT License |
vector/src/main/java/im/vector/app/features/MainActivity.kt | FaradayApp | 732,727,396 | false | {"Kotlin": 15889711, "Java": 250183, "Shell": 102807, "HTML": 28529, "Python": 25379, "FreeMarker": 7662, "JavaScript": 7070, "Ruby": 3420, "Gherkin": 58} | /*
* Copyright 2019 New Vector Ltd
*
* 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 im.vector.app.features
import android.app.Activity
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Parcelable
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.core.view.isVisible
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import com.airbnb.mvrx.viewModel
import com.bumptech.glide.Glide
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import dagger.hilt.android.AndroidEntryPoint
import im.vector.app.R
import im.vector.app.core.extensions.observeEvent
import im.vector.app.core.extensions.startSyncing
import im.vector.app.core.extensions.vectorStore
import im.vector.app.core.platform.VectorBaseActivity
import im.vector.app.core.pushers.FcmHelper
import im.vector.app.core.settings.connectionmethods.onion.TorEvent
import im.vector.app.core.settings.connectionmethods.onion.TorEventListener
import im.vector.app.core.settings.connectionmethods.onion.TorService
import im.vector.app.core.utils.deleteAllFiles
import im.vector.app.databinding.ActivityMainBinding
import im.vector.app.features.analytics.VectorAnalytics
import im.vector.app.features.analytics.plan.ViewRoom
import im.vector.app.features.home.HomeActivity
import im.vector.app.features.home.ShortcutsHandler
import im.vector.app.features.notifications.NotificationDrawerManager
import im.vector.app.features.pin.UnlockedActivity
import im.vector.app.features.pin.lockscreen.crypto.LockScreenKeyRepository
import im.vector.app.features.pin.lockscreen.pincode.PinCodeHelper
import im.vector.app.features.popup.PopupAlertManager
import im.vector.app.features.session.VectorSessionStore
import im.vector.app.features.signout.hard.SignedOutActivity
import im.vector.app.features.start.StartAppAction
import im.vector.app.features.start.StartAppAndroidService
import im.vector.app.features.start.StartAppViewEvent
import im.vector.app.features.start.StartAppViewModel
import im.vector.app.features.start.StartAppViewState
import im.vector.app.features.themes.ActivityOtherThemes
import im.vector.app.features.ui.UiStateRepository
import im.vector.lib.core.utils.compat.getParcelableExtraCompat
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.parcelize.Parcelize
import org.matrix.android.sdk.api.failure.GlobalError
import org.matrix.android.sdk.api.settings.LightweightSettingsStorage
import org.matrix.android.sdk.api.util.ConnectionType
import timber.log.Timber
import javax.inject.Inject
@Parcelize
data class MainActivityArgs(
val clearCache: Boolean = false,
val clearCredentials: Boolean = false,
val isUserLoggedOut: Boolean = false,
val isAccountDeactivated: Boolean = false,
val isSoftLogout: Boolean = false
) : Parcelable
/**
* This is the entry point of Element Android.
* This Activity, when started with argument, is also doing some cleanup when user signs out,
* clears cache, is logged out, or is soft logged out.
*/
@AndroidEntryPoint
class MainActivity : VectorBaseActivity<ActivityMainBinding>(), UnlockedActivity {
companion object {
private const val EXTRA_ARGS = "EXTRA_ARGS"
private const val EXTRA_NEXT_INTENT = "EXTRA_NEXT_INTENT"
private const val EXTRA_INIT_SESSION = "EXTRA_INIT_SESSION"
private const val EXTRA_ROOM_ID = "EXTRA_ROOM_ID"
private const val ACTION_ROOM_DETAILS_FROM_SHORTCUT = "ROOM_DETAILS_FROM_SHORTCUT"
// Special action to clear cache and/or clear credentials
fun restartApp(activity: Activity, args: MainActivityArgs) {
val intent = Intent(activity, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
intent.putExtra(EXTRA_ARGS, args)
activity.startActivity(intent)
}
fun getIntentToInitSession(activity: Activity): Intent {
val intent = Intent(activity, MainActivity::class.java)
intent.putExtra(EXTRA_INIT_SESSION, true)
return intent
}
fun getIntentWithNextIntent(context: Context, nextIntent: Intent): Intent {
val intent = Intent(context, MainActivity::class.java)
intent.putExtra(EXTRA_NEXT_INTENT, nextIntent)
return intent
}
// Shortcuts can't have intents with parcelables
fun shortcutIntent(context: Context, roomId: String): Intent {
return Intent(context, MainActivity::class.java).apply {
action = ACTION_ROOM_DETAILS_FROM_SHORTCUT
putExtra(EXTRA_ROOM_ID, roomId)
}
}
}
private val startAppViewModel: StartAppViewModel by viewModel()
override fun getBinding() = ActivityMainBinding.inflate(layoutInflater)
override fun getOtherThemes() = ActivityOtherThemes.Launcher
private lateinit var args: MainActivityArgs
@Inject lateinit var notificationDrawerManager: NotificationDrawerManager
@Inject lateinit var uiStateRepository: UiStateRepository
@Inject lateinit var shortcutsHandler: ShortcutsHandler
@Inject lateinit var pinCodeHelper: PinCodeHelper
@Inject lateinit var popupAlertManager: PopupAlertManager
@Inject lateinit var vectorAnalytics: VectorAnalytics
@Inject lateinit var lockScreenKeyRepository: LockScreenKeyRepository
@Inject lateinit var lightweightSettingsStorage: LightweightSettingsStorage
@Inject lateinit var torService: TorService
@Inject lateinit var torEventListener: TorEventListener
@Inject lateinit var fcmHelper: FcmHelper
/**
* In case connection type was changed to ConnectionType.ONION in VectorSettingsConnectionMethodFragment
* and app was killed, it is required to fetch connection type from storage and start TorService.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
shortcutsHandler.updateShortcutsWithPreviousIntent()
if (lightweightSettingsStorage.getConnectionType() == ConnectionType.ONION && !torService.isProxyRunning) {
torService.switchTorPrefState(true)
observeTorEvents()
} else {
handleActivityCreated()
}
}
private fun handleActivityCreated() = with(startAppViewModel) {
onEach {
renderState(it)
}
observeViewEvents {
handleViewEvents(it)
}
handle(StartAppAction.StartApp)
}
/**
* Once Tor Connection is established and proxy port is saved to storage in TorEventBroadcaster,
* app start process can be finished as all network dependencies now would be injected with an updated
* Tor proxy port. In case of a TorService failure app will be started with previously set connection type.
*/
private fun observeTorEvents() {
torEventListener.torEventLiveData.observeEvent(this) { torEvent ->
when (torEvent) {
is TorEvent.ConnectionEstablished -> {
Timber.i("torEventListener.torEventLiveData success onCreate")
views.status.isVisible = false
handleActivityCreated()
fcmHelper.onEnterForeground(activeSessionHolder)
activeSessionHolder.getSafeActiveSession()?.also {
Timber.i("syncService onCreate")
it.syncService().stopAnyBackgroundSync()
}
}
is TorEvent.ConnectionFailed -> {
Timber.i("torEventListener.torEventLiveData failure onCreate")
handleActivityCreated()
}
is TorEvent.TorLogEvent -> {
views.status.text = torEvent.message
views.status.isVisible = true
}
}
}
}
private fun renderState(state: StartAppViewState) {
if (state.mayBeLongToProcess) {
views.status.setText(R.string.updating_your_data)
}
views.status.isVisible = state.mayBeLongToProcess
}
private fun handleViewEvents(event: StartAppViewEvent) {
when (event) {
StartAppViewEvent.StartForegroundService -> handleStartForegroundService()
StartAppViewEvent.AppStarted -> handleAppStarted()
}
}
private fun handleStartForegroundService() {
if (startAppViewModel.shouldStartApp()) {
// Start foreground service, because the operation may take a while
val intent = Intent(this, StartAppAndroidService::class.java)
ContextCompat.startForegroundService(this, intent)
}
}
private fun handleAppStarted() {
if (intent.hasExtra(EXTRA_NEXT_INTENT)) {
// Start the next Activity
startSyncing()
val nextIntent = intent.getParcelableExtraCompat<Intent>(EXTRA_NEXT_INTENT)
startIntentAndFinish(nextIntent)
} else if (intent.hasExtra(EXTRA_INIT_SESSION)) {
startSyncing()
setResult(RESULT_OK)
finish()
} else if (intent.action == ACTION_ROOM_DETAILS_FROM_SHORTCUT) {
startSyncing()
val roomId = intent.getStringExtra(EXTRA_ROOM_ID)
if (roomId?.isNotEmpty() == true) {
navigator.openRoom(this, roomId, trigger = ViewRoom.Trigger.Shortcut)
}
finish()
} else {
args = parseArgs()
if (args.clearCredentials || args.isUserLoggedOut || args.clearCache) {
clearNotifications()
}
// Handle some wanted cleanup
if (args.clearCache || args.clearCredentials) {
doCleanUp()
} else {
startSyncing()
startNextActivityAndFinish()
}
}
}
private fun startSyncing() {
activeSessionHolder.getSafeActiveSession()?.startSyncing(this)
}
private fun clearNotifications() {
// Dismiss all notifications
notificationDrawerManager.clearAllEvents()
// Also clear the dynamic shortcuts
shortcutsHandler.clearShortcuts()
// Also clear the alerts
popupAlertManager.cancelAll()
}
private fun parseArgs(): MainActivityArgs {
val argsFromIntent: MainActivityArgs? = intent.getParcelableExtraCompat(EXTRA_ARGS)
Timber.w("Starting MainActivity with $argsFromIntent")
return MainActivityArgs(
clearCache = argsFromIntent?.clearCache ?: false,
clearCredentials = argsFromIntent?.clearCredentials ?: false,
isUserLoggedOut = argsFromIntent?.isUserLoggedOut ?: false,
isAccountDeactivated = argsFromIntent?.isAccountDeactivated ?: false,
isSoftLogout = argsFromIntent?.isSoftLogout ?: false
)
}
private fun doCleanUp() {
val session = activeSessionHolder.getSafeActiveSession()
if (session == null) {
startNextActivityAndFinish()
return
}
val onboardingStore = session.vectorStore(this)
when {
args.isAccountDeactivated -> {
lifecycleScope.launch {
// Just do the local cleanup
Timber.w("Account deactivated, start app")
activeSessionHolder.clearActiveSession()
doLocalCleanup(clearPreferences = true, onboardingStore)
startNextActivityAndFinish()
}
}
args.clearCredentials && args.clearCache && args.isUserLoggedOut -> {
lifecycleScope.launch {
Toast.makeText(applicationContext, getString(R.string.nuke_activated_notice), Toast.LENGTH_LONG).show()
delay(5000)
clearAppData()
finish()
}
}
args.clearCredentials -> {
lifecycleScope.launch {
try {
session.signOutService().signOut(!args.isUserLoggedOut)
} catch (failure: Throwable) {
displayError(failure)
return@launch
}
Timber.w("SIGN_OUT: success, start app")
activeSessionHolder.clearActiveSession()
doLocalCleanup(clearPreferences = true, onboardingStore)
session.applicationPasswordService().clearSessionParamsStore()
startNextActivityAndFinish()
}
}
args.clearCache -> {
lifecycleScope.launch {
session.clearCache()
doLocalCleanup(clearPreferences = false, onboardingStore)
session.startSyncing(applicationContext)
startNextActivityAndFinish()
}
}
}
}
override fun handleInvalidToken(globalError: GlobalError.InvalidToken) {
// No op here
Timber.w("Ignoring invalid token global error")
}
private suspend fun doLocalCleanup(clearPreferences: Boolean, vectorSessionStore: VectorSessionStore) {
// On UI Thread
Glide.get(this@MainActivity).clearMemory()
if (clearPreferences) {
vectorPreferences.clearPreferences()
uiStateRepository.reset()
pinLocker.unlock()
pinCodeHelper.deletePinCode()
vectorAnalytics.onSignOut()
vectorSessionStore.clear()
lockScreenKeyRepository.deleteSystemKey()
}
withContext(Dispatchers.IO) {
// On BG thread
Glide.get(this@MainActivity).clearDiskCache()
// Also clear cache (Logs, etc...)
deleteAllFiles(this@MainActivity.cacheDir)
}
}
private fun clearAppData() {
try {
// clearing app data
(getSystemService(ACTIVITY_SERVICE) as ActivityManager).clearApplicationUserData() // note: it has a return value!
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun displayError(failure: Throwable) {
if (lifecycle.currentState.isAtLeast(Lifecycle.State.RESUMED)) {
MaterialAlertDialogBuilder(this)
.setTitle(R.string.dialog_title_error)
.setMessage(errorFormatter.toHumanReadable(failure))
.setPositiveButton(R.string.global_retry) { _, _ -> doCleanUp() }
.setNegativeButton(R.string.action_cancel) { _, _ -> startNextActivityAndFinish(ignoreClearCredentials = true) }
.setCancelable(false)
.show()
}
}
private fun startNextActivityAndFinish(ignoreClearCredentials: Boolean = false) {
val intent = when {
args.clearCredentials &&
!ignoreClearCredentials &&
(!args.isUserLoggedOut || args.isAccountDeactivated) -> {
// User has explicitly asked to log out or deactivated his account
navigator.openLogin(this, null)
null
}
args.isSoftLogout -> {
// The homeserver has invalidated the token, with a soft logout
navigator.softLogout(this)
null
}
args.isUserLoggedOut ->
// the homeserver has invalidated the token (password changed, device deleted, other security reasons)
SignedOutActivity.newIntent(this)
activeSessionHolder.hasActiveSession() ->
// We have a session.
// Check it can be opened
if (activeSessionHolder.getActiveSession().isOpenable) {
HomeActivity.newIntent(this, firstStartMainActivity = false, existingSession = true)
} else {
// The token is still invalid
navigator.softLogout(this)
null
}
else -> {
// First start, or no active session
navigator.openLogin(this, null)
null
}
}
startIntentAndFinish(intent)
}
private fun startIntentAndFinish(intent: Intent?) {
intent?.let { startActivity(it) }
finish()
}
}
| 0 | Kotlin | 2 | 0 | d765bc66c3dc1ee2ab2e54f3d1f7bc09896b3708 | 17,290 | Faraday-android | Apache License 2.0 |
app/src/main/java/com/briggin/coroutineplayground/view/PlaygroundActivity.kt | bRiggin | 340,968,559 | false | null | package com.briggin.coroutineplayground.view
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.briggin.coroutineplayground.R
import kotlinx.android.synthetic.main.activity_main.*
class PlaygroundActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.fragmentContainer, PlaygroundFragment.newInstance())
.commit()
}
}
}
| 0 | Kotlin | 0 | 0 | 524494d5a4853ee8d50b210e4457831edbcca669 | 636 | android-coroutine-playground | Apache License 2.0 |
reposilite-backend/src/main/kotlin/com/reposilite/shared/extensions/CdnExtensions.kt | dzikoysk | 96,474,388 | false | null | package com.reposilite.shared.extensions
import com.reposilite.web.http.ErrorResponse
import io.javalin.http.HttpCode.BAD_REQUEST
import net.dzikoysk.cdn.Cdn
import net.dzikoysk.cdn.KCdnFactory
import net.dzikoysk.cdn.source.Source
import panda.std.Result
import panda.std.asError
import panda.std.asSuccess
fun String.createCdnByExtension(): Result<Cdn, Exception> =
when {
endsWith(".cdn") -> KCdnFactory.createStandard().asSuccess()
endsWith(".yml") || endsWith(".yaml") -> KCdnFactory.createYamlLike().asSuccess()
endsWith(".json") -> KCdnFactory.createJsonLike().asSuccess()
else -> UnsupportedOperationException("Unknown format: $this").asError()
}
fun <T : Any> Cdn.validateAndLoad(source: String, testConfiguration: T, configuration: T): Result<T, ErrorResponse> =
load(Source.of(source), testConfiguration) // validate
.flatMap { load(Source.of(source), configuration) }
.mapErr { ErrorResponse(BAD_REQUEST, "Cannot load configuration: ${it.message}") } | 27 | Kotlin | 69 | 446 | aed196d872c427b01951d07be0381b389e8fa0b5 | 1,025 | reposilite | Apache License 2.0 |
kotest-framework/kotest-framework-engine/src/commonMain/kotlin/io/kotest/engine/test/extensions/TestExecutionExtension.kt | rgmz | 398,368,607 | true | {"Kotlin": 3044586, "CSS": 352, "Java": 145} | package io.kotest.engine.test.extensions
import io.kotest.core.test.TestCase
import io.kotest.core.test.TestContext
import io.kotest.core.test.TestResult
internal interface TestExecutionExtension {
suspend fun shouldApply(testCase: TestCase): Boolean = true
suspend fun execute(
test: suspend (TestCase, TestContext) -> TestResult
): suspend (TestCase, TestContext) -> TestResult
}
| 0 | null | 0 | 0 | 7303265bdca3baccac68baba49fc9681ff1b18f0 | 401 | kotest | Apache License 2.0 |
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/player/OpenStateUpdateNotify.kt | Anime-Game-Servers | 642,871,918 | false | {"Kotlin": 1651536} | package data.player
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.Version
import org.anime_game_servers.core.base.annotations.proto.CommandType
import org.anime_game_servers.core.base.annotations.proto.ProtoCommand
@AddedIn(Version.GI_CB2)
@ProtoCommand(CommandType.NOTIFY)
internal interface OpenStateUpdateNotify {
var openStateMap: Map<Int, Int>
}
| 1 | Kotlin | 3 | 6 | b342ff34dfb0f168a902498b53682c315c40d44e | 412 | anime-game-multi-proto | MIT License |
src/main/kotlin/dev/crashteam/keanalytics/client/freekassa/FreeKassaClient.kt | crashteamdev | 643,974,955 | false | null | package dev.crashteam.keanalytics.client.freekassa
import com.fasterxml.jackson.databind.ObjectMapper
import dev.crashteam.keanalytics.client.freekassa.model.FreeKassaPaymentRequestParams
import dev.crashteam.keanalytics.client.freekassa.model.PaymentFormRequestParams
import dev.crashteam.keanalytics.client.freekassa.model.PaymentResponse
import dev.crashteam.keanalytics.config.properties.FreeKassaProperties
import org.apache.commons.codec.digest.DigestUtils
import org.springframework.http.HttpEntity
import org.springframework.http.HttpMethod
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
@Component
class FreeKassaClient(
private val freeKassaProperties: FreeKassaProperties,
private val restTemplate: RestTemplate,
private val objectMapper: ObjectMapper
) {
fun createPaymentFormUrl(paymentFormRequest: PaymentFormRequestParams): String {
val sign = DigestUtils.md5Hex(
"${freeKassaProperties.shopId}:${paymentFormRequest.amount}" +
":${freeKassaProperties.secretWordFirst}:${paymentFormRequest.currency}:${paymentFormRequest.email}"
)
return buildString {
append("$FREEKASSA_BASE_URL/?m=${freeKassaProperties.shopId}&oa=${paymentFormRequest.amount}")
append("¤cy=${paymentFormRequest.currency}&o=${paymentFormRequest.email}&pay=PAY&s=$sign")
append("&em=${paymentFormRequest.email}")
append("&us_paymentid=${paymentFormRequest.orderId}")
append("&us_userid=${paymentFormRequest.userId}")
append("&us_subscriptionid=${paymentFormRequest.subscriptionId}")
append("&us_multiply=${paymentFormRequest.multiply}")
if (paymentFormRequest.referralCode != null) {
append("&us_referralcode=${paymentFormRequest.referralCode}")
}
}
}
private fun generateSign(requestParams: Map<String, Comparable<*>>): String {
val concatValues = requestParams.toSortedMap().values.joinToString(separator = "|")
val signingKey = SecretKeySpec(freeKassaProperties.apiKey!!.encodeToByteArray(), "HmacSHA256")
val mac = Mac.getInstance("HmacSHA256")
mac.init(signingKey)
val rawHmac: ByteArray = mac.doFinal(concatValues.encodeToByteArray())
val hexArray = byteArrayOf(
'0'.code.toByte(),
'1'.code.toByte(),
'2'.code.toByte(),
'3'.code.toByte(),
'4'.code.toByte(),
'5'.code.toByte(),
'6'.code.toByte(),
'7'.code.toByte(),
'8'.code.toByte(),
'9'.code.toByte(),
'a'.code.toByte(),
'b'.code.toByte(),
'c'.code.toByte(),
'd'.code.toByte(),
'e'.code.toByte(),
'f'.code.toByte()
)
val hexChars = ByteArray(rawHmac.size * 2)
for (j in rawHmac.indices) {
val v = rawHmac[j].toInt() and 0xFF
hexChars[j * 2] = hexArray[v ushr 4]
hexChars[j * 2 + 1] = hexArray[v and 0x0F]
}
return String(hexChars)
}
companion object {
const val FREEKASSA_BASE_URL = "https://pay.freekassa.ru"
}
}
| 1 | Kotlin | 0 | 0 | f9b08de7955e840842067a536c06f7b81687a353 | 3,329 | ke-analytics | Apache License 2.0 |
core/domain/src/main/java/com/mayuresh/domain/usecase/GetCountriesDetailsUseCase.kt | mayureshps21 | 700,256,778 | false | {"Kotlin": 215560} | package com.mayuresh.domain.usecase
import com.mayuresh.data.dto.CountryDto
import com.mayuresh.data.model.CountryDetailsModel
import com.mayuresh.data.repository.CountryDetailsRepository
import com.mayuresh.data.util.AppConstants
import com.mayuresh.domain.mapper.CountryDetailsMapper
import com.mayuresh.domain.util.Response
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class GetCountriesDetailsUseCase @Inject constructor(
private val countryDetailsRepository: CountryDetailsRepository
) {
suspend operator fun invoke(code: String): Flow<Response<CountryDetailsModel>> =
flow {
val response = countryDetailsRepository.getCountryDetails(code)
if (response.isSuccessful) {
val countryList = response.body() as List<CountryDto>
if (countryList.isNotEmpty()) {
val result = CountryDetailsMapper().mapFrom(countryList.get(0))
emit(Response.Success(result))
} else {
emit(
Response.Error(
code = AppConstants.API_RESPONSE_ERROR,
message = response.message(),
),
)
}
} else {
emit(
Response.Error(
code = AppConstants.API_RESPONSE_ERROR,
message = response.message()
)
)
}
}
}
| 0 | Kotlin | 0 | 0 | c591e755636dde08108874ef69dfc6776b595a96 | 1,569 | EuropeanCountriesSample | Apache License 2.0 |
MomentumAndroid/src/main/java/com/mwaibanda/momentum/android/presentation/sermon/PlayerScreen.kt | MwaiBanda | 509,266,324 | false | {"Kotlin": 498123, "Swift": 282045, "Ruby": 2617} | package com.mwaibanda.momentum.android.presentation.sermon
import android.content.pm.ActivityInfo
import android.graphics.Rect
import android.net.Uri
import android.util.Log
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatDelegate
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material.Slider
import androidx.compose.material.SliderDefaults
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.CastConnected
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toAndroidRect
import androidx.compose.ui.layout.boundsInWindow
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.mediarouter.app.MediaRouteButton
import androidx.navigation.NavController
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.MediaItem
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.ext.cast.CastPlayer
import com.google.android.exoplayer2.ext.cast.SessionAvailabilityListener
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.ui.AspectRatioFrameLayout
import com.google.android.exoplayer2.ui.StyledPlayerView
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource
import com.google.android.exoplayer2.util.MimeTypes
import com.google.android.gms.cast.MediaInfo
import com.google.android.gms.cast.MediaLoadRequestData
import com.google.android.gms.cast.MediaMetadata
import com.google.android.gms.cast.MediaQueueItem
import com.google.android.gms.cast.framework.CastButtonFactory
import com.google.android.gms.cast.framework.CastContext
import com.google.android.gms.cast.framework.Session
import com.google.android.gms.cast.framework.SessionManagerListener
import com.google.android.gms.common.images.WebImage
import com.mwaibanda.momentum.android.R
import com.mwaibanda.momentum.android.core.exts.formatMinSec
import com.mwaibanda.momentum.android.core.utils.C
import com.mwaibanda.momentum.android.core.utils.PlayerControl
import com.mwaibanda.momentum.android.presentation.components.LockScreenOrientation
import com.mwaibanda.momentum.data.db.MomentumSermon
import com.mwaibanda.momentum.domain.models.Sermon
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun PlayerScreen(
castContext: CastContext,
navController: NavController,
sermonViewModel: SermonViewModel,
showControls: Boolean,
sermon: Sermon,
onShowControls: (Boolean) -> Unit,
canEnterPictureInPicture: (Boolean) -> Unit,
onBounds: (Rect) -> Unit
) {
val context = LocalContext.current
val isLandscape by sermonViewModel.isLandscape.collectAsState()
var isCasting by remember { mutableStateOf(false) }
var currentPlayer: Player? by remember { mutableStateOf(null) }
var lastPosition by remember { mutableStateOf(0L) }
var exoPlayer = remember(context) {
ExoPlayer.Builder(context).build().apply {
val dataSourceFactory = DefaultHttpDataSource.Factory()
val media = MediaItem.Builder()
.setUri(sermon.videoURL)
.setMimeType(MimeTypes.VIDEO_MP4)
.build()
val source = ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(media)
setMediaSource(source)
prepare()
playWhenReady = true
}
}
var castPlayer = remember(context) {
CastPlayer(castContext)
}
LockScreenOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR)
LaunchedEffect(key1 = Unit) {
canEnterPictureInPicture(true)
val currentSermon =
sermonViewModel.getCurrentSermon()
currentSermon?.let {
exoPlayer.apply {
seekTo(it.last_played_time.toLong())
playWhenReady = true // Turn back to true
}
}
currentPlayer = exoPlayer
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
DisposableEffect(key1 = Unit) {
castPlayer.setSessionAvailabilityListener(object : SessionAvailabilityListener {
override fun onCastSessionAvailable() {
currentPlayer?.release()
isCasting = true
castPlayer = CastPlayer(castContext)
val sermonMetadata = MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE)
sermonMetadata.putString(MediaMetadata.KEY_TITLE, sermon.title)
sermonMetadata.putString(MediaMetadata.KEY_ALBUM_ARTIST, sermon.preacher)
sermonMetadata.putString(MediaMetadata.KEY_SERIES_TITLE, sermon.series)
sermonMetadata.addImage(WebImage(Uri.parse(sermon.videoThumbnail)))
val mediaInfo: MediaInfo = MediaInfo.Builder(sermon.videoURL)
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setContentType(MimeTypes.APPLICATION_MP4)
.setMetadata(sermonMetadata).build()
val mediaQueueItem = MediaQueueItem.Builder(mediaInfo).build()
castContext.sessionManager.currentCastSession?.remoteMediaClient?.apply {
load(MediaLoadRequestData.fromJson(mediaQueueItem.toJson()))
}
currentPlayer = castPlayer
lastPosition = exoPlayer.currentPosition
exoPlayer.release()
}
override fun onCastSessionUnavailable() {
isCasting = false
exoPlayer = ExoPlayer.Builder(context).build().apply {
val dataSourceFactory = DefaultHttpDataSource.Factory()
val media = MediaItem.Builder()
.setUri(sermon.videoURL)
.setMimeType(MimeTypes.APPLICATION_MP4)
.build()
val source = ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(media)
setMediaSource(source)
seekTo(castPlayer.currentPosition)
currentPlayer?.release()
prepare()
playWhenReady = true
}
currentPlayer = exoPlayer
}
})
castPlayer.addListener(object : Player.Listener {
override fun onPlaybackStateChanged(playbackState: Int) {
super.onPlaybackStateChanged(playbackState)
when (playbackState) {
Player.STATE_READY -> {
Log.e("Player", "STATE READY")
castPlayer.seekTo(lastPosition)
}
Player.STATE_ENDED -> {}
Player.STATE_BUFFERING, Player.STATE_IDLE -> {}
}
}
})
castContext.sessionManager.addSessionManagerListener(object: SessionManagerListener<Session> {
override fun onSessionEnded(p0: Session, p1: Int) {
TODO("Not yet implemented")
}
override fun onSessionEnding(p0: Session) {
TODO("Not yet implemented")
}
override fun onSessionResumeFailed(p0: Session, p1: Int) {
TODO("Not yet implemented")
}
override fun onSessionResumed(p0: Session, p1: Boolean) {
TODO("Not yet implemented")
}
override fun onSessionResuming(p0: Session, p1: String) {
TODO("Not yet implemented")
}
override fun onSessionStartFailed(p0: Session, p1: Int) {
TODO("Not yet implemented")
}
override fun onSessionStarted(p0: Session, p1: String) {
TODO("Not yet implemented")
}
override fun onSessionStarting(p0: Session) {
TODO("Not yet implemented")
}
override fun onSessionSuspended(p0: Session, p1: Int) {
TODO("Not yet implemented")
}
})
onDispose {
canEnterPictureInPicture(false)
sermonViewModel.addSermon(
MomentumSermon(
id = sermonViewModel.currentSermon?.id ?: "",
last_played_time = lastPosition.toDouble(),
last_played_percentage = (((currentPlayer?.currentPosition?.toFloat() ?: 0f) / (currentPlayer?.duration?.toFloat() ?: 0f)) * 100.0).toInt()
)
) {
sermonViewModel.getWatchSermons()
}
Log.d(
"PlayPercentage",
"Played ${(((exoPlayer.currentPosition.toFloat() / exoPlayer.duration.toFloat()) * 100.0).toInt())}% of the video"
)
castContext.sessionManager.endCurrentSession(true)
exoPlayer.release()
castPlayer.release()
currentPlayer?.release()
}
}
Box(
modifier = Modifier
.background(Color.Black)
.systemBarsPadding()
) {
Player(
Modifier.clickable(
indication = null,
interactionSource = remember { MutableInteractionSource() }
) { onShowControls(true) },
isCasting = isCasting,
player = currentPlayer ?: exoPlayer,
showControls = showControls,
isLandscape = isLandscape,
onShowControls = onShowControls,
onBounds = onBounds
) {
navController.popBackStack()
canEnterPictureInPicture(false)
}
}
}
@Composable
fun Player(
modifier: Modifier = Modifier,
player: Player,
isCasting: Boolean,
showControls: Boolean,
isLandscape: Boolean,
onShowControls: (Boolean) -> Unit,
onBounds: (Rect) -> Unit,
onClosePlayer: () -> Unit
) {
val context = LocalContext.current
var totalDuration by remember { mutableStateOf(0L) }
var currentTime by remember { mutableStateOf(0L) }
var bufferedPercentage by remember { mutableStateOf(0) }
var addDelay by remember { mutableStateOf(false) }
var isPlaying by remember { mutableStateOf(true) }
var count by remember { mutableStateOf(0L) }
val lifecycle = LocalLifecycleOwner.current.lifecycle
LaunchedEffect(key1 = showControls) {
launch {
delay(4500)
if (addDelay) {
delay(4000)
addDelay = false
}
onShowControls(false)
}
launch {
if (isPlaying) {
count++
}
}
}
LaunchedEffect(key1 = count) {
if (isPlaying) {
delay(1000)
currentTime = player.currentPosition.coerceAtLeast(0L)
count++
if (count > 10L) {
count = 0L
}
}
}
val playerView = remember(context) {
StyledPlayerView(context).apply {
resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT
layoutParams = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
setShowSubtitleButton(true)
useController = false
}
}
Box(
modifier = modifier
.fillMaxWidth()
.onGloballyPositioned {
onBounds(
it
.boundsInWindow()
.toAndroidRect()
)
}
.background(Color.Black),
contentAlignment = Alignment.Center
) {
DisposableEffect(key1 = Unit) {
val lifecycleListener = object : DefaultLifecycleObserver {
override fun onCreate(owner: LifecycleOwner) {
super.onCreate(owner)
Log.d("Activity", "Create")
}
override fun onStart(owner: LifecycleOwner) {
super.onStart(owner)
player.playWhenReady = true
}
override fun onResume(owner: LifecycleOwner) {
super.onResume(owner)
playerView.onResume()
}
override fun onStop(owner: LifecycleOwner) {
super.onStop(owner)
playerView.onPause()
player.playWhenReady = false
}
}
val listener = object : Player.Listener {
override fun onEvents(player: Player, events: Player.Events) {
super.onEvents(player, events)
currentTime = player.currentPosition.coerceAtLeast(0L)
totalDuration = player.duration.coerceAtLeast(0L)
bufferedPercentage = player.bufferedPercentage
}
override fun onPlaybackStateChanged(playbackState: Int) {
when (playbackState) {
Player.STATE_READY -> {
Log.e("Player", "STATE READY")
}
Player.STATE_ENDED -> {}
Player.STATE_BUFFERING, Player.STATE_IDLE -> {}
}
}
}
player.addListener(listener)
lifecycle.addObserver(lifecycleListener)
onDispose {
lifecycle.removeObserver(lifecycleListener)
player.removeListener(listener)
player.release()
}
}
if (isCasting) {
Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Icon(
imageVector = Icons.Default.CastConnected,
contentDescription = "Cast Icon",
tint = Color.Gray,
modifier = Modifier.fillMaxSize(0.5f)
)
}
} else {
AndroidView(
modifier = Modifier
.fillMaxSize(),
factory = { playerView }
)
}
LaunchedEffect(key1 = player, block = {
playerView.player = player
})
AnimatedVisibility(
visible = showControls,
enter = fadeIn(),
exit = fadeOut()
) {
PlayerControls(
isPlaying = isPlaying,
isLandscape = isLandscape,
totalDuration = totalDuration,
currentTime = currentTime,
bufferedPercentage = bufferedPercentage,
control = object : PlayerControl {
override fun onPlayPause(isPlayingContent: Boolean) {
if (isPlayingContent) {
player.pause()
} else {
player.play()
}
addDelay = true
isPlaying = isPlaying.not()
}
override fun onSeekBackwards() {
player.seekTo((player.currentPosition) - 30000L)
addDelay = true
}
override fun onSeekForward() {
player.seekTo((player.currentPosition) + 30000L)
addDelay = true
}
override fun onSeekChanged(seekTo: Float) {
player.seekTo(seekTo.toLong())
}
override fun closePlayer() {
onClosePlayer()
}
}
)
}
}
}
@Composable
fun PlayerControls(
isPlaying: Boolean,
isLandscape: Boolean,
totalDuration: Long,
currentTime: Long,
bufferedPercentage: Int,
control: PlayerControl
) {
Box(modifier = Modifier.background(Color.Black.copy(0.6f))) {
Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.SpaceBetween) {
TopControls(
isLandscape = isLandscape,
onClosePlayer = control::closePlayer
)
CenterControls(
isPlaying = isPlaying,
onPlayPause = control::onPlayPause,
onSeekBackwards = control::onSeekBackwards,
onSeekForward = control::onSeekForward
)
BottomControls(
isLandscape = isLandscape,
totalDuration = totalDuration,
currentTime = currentTime,
bufferedPercentage = bufferedPercentage,
onSeekChanged = control::onSeekChanged
)
}
}
}
@Composable
fun TopControls(
isLandscape: Boolean,
onClosePlayer: () -> Unit
) {
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = if (isLandscape) 55.dp else 10.dp)
.padding(top = 15.dp),
horizontalArrangement = Arrangement.Start
) {
IconButton(onClick = {
onClosePlayer()
}) {
Icon(
painter = painterResource(id = R.drawable.ic_baseline_close_24),
contentDescription = "Share button",
tint = Color.White,
modifier = Modifier.size(30.dp)
)
}
AndroidView(
modifier = Modifier.offset(x = -(10).dp),
factory = { context ->
MediaRouteButton(context).apply {
CastButtonFactory.setUpMediaRouteButton(context, this)
}
}
)
}
}
@Composable
fun CenterControls(
isPlaying: Boolean,
onPlayPause: (Boolean) -> Unit,
onSeekBackwards: () -> Unit,
onSeekForward: () -> Unit
) {
Row(
Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceEvenly,
verticalAlignment = Alignment.CenterVertically
) {
IconButton(onClick = onSeekBackwards) {
Icon(
painter = painterResource(id = com.mwaibanda.momentum.android.R.drawable.ic_baseline_replay_30_50),
contentDescription = "rewind button",
tint = Color.White
)
}
IconButton(onClick = {
onPlayPause(isPlaying)
}) {
if (isPlaying) {
Icon(
painter = painterResource(id = com.mwaibanda.momentum.android.R.drawable.ic_baseline_pause_100),
contentDescription = "pause button",
tint = Color.White
)
} else {
Icon(
painter = painterResource(id = com.mwaibanda.momentum.android.R.drawable.ic_baseline_play_arrow_100),
contentDescription = "play button",
tint = Color.White
)
}
}
IconButton(onClick = onSeekForward) {
Icon(
painter = painterResource(id = com.mwaibanda.momentum.android.R.drawable.ic_baseline_forward_30_50),
contentDescription = "fast forward button",
tint = Color.White
)
}
}
}
@Composable
fun BottomControls(
isLandscape: Boolean,
totalDuration: Long,
currentTime: Long,
bufferedPercentage: Int,
onSeekChanged: (seekTo: Float) -> Unit
) {
Column(
Modifier
.fillMaxWidth()
.padding(bottom = 20.dp)
) {
Row(
Modifier
.fillMaxWidth()
.padding(horizontal = if (isLandscape) 55.dp else 10.dp),
horizontalArrangement = Arrangement.SpaceBetween,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = currentTime.formatMinSec(),
color = Color.White,
fontWeight = FontWeight.Bold
)
Row(Modifier.fillMaxWidth(0.85f)) {
Box {
Slider(
value = bufferedPercentage.toFloat(),
enabled = false,
onValueChange = { },
valueRange = 0f..100f,
colors =
SliderDefaults.colors(
disabledThumbColor = Color.Transparent,
disabledActiveTrackColor = Color.Gray
)
)
Slider(
value = currentTime.toFloat(),
valueRange = 0f..totalDuration.toFloat(),
onValueChange = onSeekChanged,
colors = SliderDefaults.colors(
thumbColor = Color.White,
activeTrackColor = Color(C.MOMENTUM_ORANGE),
inactiveTrackColor = Color.White.copy(0.5f)
)
)
}
}
Text(
text = totalDuration.formatMinSec(),
color = Color.White,
fontWeight = FontWeight.Bold
)
}
}
}
| 0 | Kotlin | 4 | 36 | dde77f0319ec4dd5d473e2957264458de9a0197c | 23,186 | Momentum | MIT License |
Highlights/src/androidMain/kotlin/pl/tkadziolka/highlights/extension/NumberExtensions.kt | SnippLog | 389,388,771 | false | null | package pl.tkadziolka.highlights.extension
import android.graphics.Color
internal val maxAlpha get() = 255
internal val Int.red get() = Color.red(this)
internal val Int.green get() = Color.green(this)
internal val Int.blue get() = Color.blue(this)
internal val Int.rgb get() = Color.rgb(red, green, blue)
internal val Int.opaque: Int get() = Color.argb(maxAlpha, red, green, blue) | 0 | Kotlin | 0 | 0 | e1611b53e68d59b9c56767717b0721d2ce27df1d | 387 | Highlights | MIT License |
src/main/kotlin/pl/exbook/exbook/util/retrofit/RetrofitService.kt | Ejden | 339,380,956 | false | null | package pl.exbook.exbook.util.retrofit
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class RetrofitService(val serviceName: String)
| 1 | Kotlin | 0 | 1 | 102b50decb94605e7a085619d585a4135e25ad2a | 170 | exbook-backend | The Unlicense |
src/main/kotlin/org/movietime/webapp/MovieApp.kt | kapil-kr | 284,861,026 | false | null | package org.movietime.webapp
import org.movietime.webapp.resources.MovieResource
import javax.ws.rs.ApplicationPath
import javax.ws.rs.core.Application
@ApplicationPath("/")
open class MovieApp: Application() {
override fun getClasses(): Set<Class<*>> {
// for more detailed resources, use classgraph
return setOf(MovieResource::class.java)
}
} | 0 | Kotlin | 0 | 0 | 1c94e5440544bfcdf44640f94905fff1bf164e55 | 371 | RestEasy-Undertow-Kotlin-Multiproj | Apache License 2.0 |
build-logic/convention/src/main/java/MadifiersLibraryConventionPlugin.kt | MadFlasheroo7 | 662,162,501 | false | null | import com.android.build.api.dsl.LibraryExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
import org.gradle.kotlin.dsl.dependencies
import pro.jayeshseth.madifiers.convention.configureAndroidCompose
import pro.jayeshseth.madifiers.convention.configureKotlinAndroid
import pro.jayeshseth.madifiers.convention.libs
class MadifiersLibraryConventionPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
pluginManager.apply {
apply("madifiers.library.compose")
apply("madifiers.spotless")
apply("org.jetbrains.kotlin.android")
apply("com.vanniktech.maven.publish")
}
extensions.configure<LibraryExtension> {
configureAndroidCompose(this)
configureKotlinAndroid(this)
}
dependencies {
add("implementation", libs.findLibrary("compose-material3").get())
add("implementation", libs.findLibrary("compose-ui").get())
add("implementation", libs.findLibrary("androidx-activity-compose").get())
}
}
}
} | 0 | null | 0 | 18 | 68b1c2c0bb32dd0d52a3b228e50b7b12255fca54 | 1,213 | Madifiers | Apache License 2.0 |
app/src/main/java/com/igor/composebasics/ui/screens/PicturesSearchScreen.kt | igorpk10 | 677,765,066 | false | null | package com.igor.composebasics.ui.screens
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemKey
import coil.compose.AsyncImage
import com.igor.composebasics.R
import com.igor.composebasics.domain.models.Picture
import com.igor.composebasics.ui.components.SearchTextField
import com.igor.composebasics.ui.stateholders.PictureScreenUIState
import com.igor.composebasics.ui.viewmodels.PictureSearchViewModel
@Composable
fun PictureSearchScreen(
viewModel: PictureSearchViewModel,
) {
val pictureState by viewModel.uiState.collectAsState()
PictureSearchScreen(pictureState)
}
@OptIn(ExperimentalMaterial3Api::class)
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@Composable
fun PictureSearchScreen(
state: PictureScreenUIState,
) {
val lazyPictures = state.picturesFlow.collectAsLazyPagingItems()
Scaffold {
Column {
SearchTextField(
searchText = state.query,
onSearchDone = state.onSearchDone,
onSearchChanged = state.onSearchChange
)
LazyColumn(
Modifier
.fillMaxWidth()
.padding(16.dp),
verticalArrangement = Arrangement.spacedBy(16.dp),
) {
items(
count = lazyPictures.itemCount,
key = lazyPictures.itemKey { it.id }
) {
lazyPictures[it]?.let {
AsyncImage(
modifier = Modifier.height(200.dp),
model = it.url,
contentDescription = it.alt,
contentScale = ContentScale.Crop,
placeholder = painterResource(id = R.drawable.placeholder)
)
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 29edf0c682bcd89672a87023e48e9ab833695303 | 2,996 | compose-simple-project | Apache License 2.0 |
app/src/main/java/com/luuu/seven/module/update/ComicUpdateFragment.kt | oteher | 288,484,684 | false | {"Kotlin": 223873} | package com.luuu.seven.module.update
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import com.luuu.seven.R
import com.luuu.seven.adapter.ComicUpdateAdapter
import com.luuu.seven.base.BaseFragment
import com.luuu.seven.bean.ComicUpdateBean
import com.luuu.seven.module.intro.ComicIntroActivity
import com.luuu.seven.util.DataLoadType
import kotlinx.android.synthetic.main.fra_tab_layout.*
/**
* author : dell
* e-mail :
* time : 2017/08/03
* desc :
* version:
*/
class ComicUpdateFragment : BaseFragment(), ComicUpdateContract.View {
companion object {
private val Comic_TYPE = "type"
fun newInstance(type: String): ComicUpdateFragment {
val fragment = ComicUpdateFragment()
val bundle = Bundle()
bundle.putString(Comic_TYPE, type)
fragment.arguments = bundle
return fragment
}
}
private var mUpdateBeanList: MutableList<ComicUpdateBean>? = null
private var mPageNum = 0
private var num = 100
private var type = " "
private val mPresent by lazy { ComicUpdatePresenter(this) }
private var mAdapter: ComicUpdateAdapter? = null
private val mLayoutManager by lazy { GridLayoutManager(mContext, 3) }
override fun onFirstUserVisible() {
mUpdateBeanList = ArrayList()
mPageNum = 0
mPresent.getComicUpdate(num, 0)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
type = it.getString(Comic_TYPE)
num = when(type) {
"全部" -> 100
"原创" -> 1
else -> 0
}
}
}
override fun onUserInvisible() {
}
override fun onUserVisible() {
}
override fun onDestroy() {
super.onDestroy()
mPresent.unsubscribe()
mUpdateBeanList = null
}
override fun initViews() {
recycler.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
refresh.isEnabled = mLayoutManager.findFirstCompletelyVisibleItemPosition() == 0
}
})
refresh.setOnRefreshListener {
mPageNum = 0
mPresent.refreshData(num)
}
}
override fun getContentViewLayoutID(): Int = R.layout.fra_tab_layout
override fun onFirstUserInvisible() {
}
override fun showLoading(isLoading: Boolean) {
}
override fun showError(isError: Boolean) {
}
override fun showEmpty(isEmpty: Boolean) {
}
override fun updateComicList(data: List<ComicUpdateBean>, type: DataLoadType) {
when(type) {
DataLoadType.TYPE_REFRESH_SUCCESS -> {
mUpdateBeanList = data.toMutableList()
if (mAdapter == null) {
initAdapter(data)
} else {
mAdapter!!.setNewData(data)
}
}
DataLoadType.TYPE_LOAD_MORE_SUCCESS -> {
if (data.isEmpty()) {
showToast("没有数据咯")
mAdapter!!.loadMoreEnd()
} else {
mAdapter!!.addData(data)
mAdapter!!.loadMoreComplete()
mUpdateBeanList!!.addAll(data)
}
}
else -> {
}
}
}
override fun judgeRefresh(isRefresh: Boolean) {
refresh.isEnabled = isRefresh
}
private fun initAdapter(updateBeanList: List<ComicUpdateBean>) {
mAdapter = ComicUpdateAdapter(R.layout.item_comic_layout, updateBeanList).apply {
setEnableLoadMore(true)
setOnLoadMoreListener({
mPageNum++
mPresent.loadMoreData(num, mPageNum)
}, recycler)
setOnItemClickListener { _, _, position ->
val mBundle = Bundle()
mBundle.putInt("comicId", mUpdateBeanList!![position].id)
startNewActivity(ComicIntroActivity::class.java, mBundle)
}
}
recycler.layoutManager = mLayoutManager
recycler.adapter = mAdapter
}
} | 0 | null | 0 | 0 | 56d8fc35e2cd2281e9b96806f0d35d9e0c02f3e1 | 4,392 | Seven | MIT License |
processors/src/main/kotlin/com/alecarnevale/claymore/visitors/Visitor.kt | alecarnevale | 559,250,665 | false | {"Kotlin": 92000} | package com.alecarnevale.claymore.visitors
import com.google.devtools.ksp.processing.CodeGenerator
import com.google.devtools.ksp.processing.KSPLogger
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSType
import com.google.devtools.ksp.symbol.KSVisitorVoid
import kotlin.reflect.KClass
abstract class Visitor : KSVisitorVoid() {
protected abstract val codeGenerator: CodeGenerator
protected abstract val resolver: Resolver
protected abstract val logger: KSPLogger
protected abstract val kclass: KClass<*>
private val tag by lazy { "Claymore - Visitor($kclass):" }
protected fun KSClassDeclaration.extractParameter(parameterName: String): KSClassDeclaration? {
// extract the KSType
val annotation = annotations.firstOrNull { it.shortName.getShortName() == kclass.simpleName }
val parameterKsType =
annotation?.arguments?.firstOrNull { it.name?.getShortName() == parameterName }?.value as? KSType
if (parameterKsType == null) {
logger.error("$tag parameter class not found for $parameterName")
return null
}
// extract the KSName
val parameterQualifiedName = parameterKsType.declaration.qualifiedName
if (parameterQualifiedName == null) {
logger.error("$tag qualified name is null for $parameterName")
return null
}
// extract the KSClassDeclaration
val parameterDeclaration = resolver.getClassDeclarationByName(parameterQualifiedName)
if (parameterDeclaration == null) {
logger.error("$tag implementation class not found for $parameterName")
return null
}
return parameterDeclaration
}
protected fun KSClassDeclaration.extractParameters(parameterName: String): List<KSClassDeclaration>? {
// extract all the KSTypes
val annotation = annotations.firstOrNull { it.shortName.getShortName() == kclass.simpleName }
@Suppress("UNCHECKED_CAST")
val parameterKsTypes =
annotation?.arguments?.firstOrNull { it.name?.getShortName() == parameterName }?.value as? List<KSType>
if (parameterKsTypes == null) {
logger.error("$tag parameter class not found for $parameterName")
return null
}
// resolve all the KSTypes
val implementationsProvided: List<KSClassDeclaration> =
parameterKsTypes.mapNotNull { parameterKsType ->
parameterKsType.declaration.qualifiedName?.let { parameterKsName ->
resolver.getClassDeclarationByName(parameterKsName)
}
}
return implementationsProvided
}
protected fun KSClassDeclaration.extractBooleanParameter(parameterName: String): Boolean? {
// extract the KSType
val annotation = annotations.firstOrNull { it.shortName.getShortName() == kclass.simpleName }
val parameterValue =
annotation?.arguments?.firstOrNull { it.name?.getShortName() == parameterName }?.value as? Boolean
if (parameterValue == null) {
logger.error("$tag parameter value not found for $parameterName")
return null
}
return parameterValue
}
} | 1 | Kotlin | 0 | 5 | fedfc34d5d114fff7f3f5063906caf70ea419137 | 3,095 | claymore | Apache License 2.0 |
app/src/main/java/com/example/pokedek/presentasion/fragment/item/ItemDetailFragment.kt | Alstonargodi | 442,473,206 | false | null | package com.example.pokedek.presentasion.fragment.item
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.example.pokedek.R
import com.example.pokedek.databinding.FragmentItemdetailBinding
class ItemDetailFragment : Fragment() {
lateinit var binding : FragmentItemdetailBinding
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentItemdetailBinding.inflate(layoutInflater)
val view = binding.root
val name = arguments?.get("nama")
val effect = arguments?.get("effect")
val link = arguments?.get("link")
val type = arguments?.get("type")
binding.tvTitleitem.setText(name.toString())
binding.tvTypeitem.setText(type.toString())
binding.tvEffectitem.setText(effect.toString())
Glide.with(requireContext())
.load(link)
.into(binding.imgItemdetail)
binding.btnItemhome.setOnClickListener {
// findNavController().navigate(ItemDetailFragmentDirections.actionItemdetailToItem())
}
requireActivity().window.statusBarColor = ContextCompat.getColor(requireContext(), R.color.detailtopitem)
return view
}
} | 0 | Kotlin | 0 | 0 | a548138a792ff8d4954328553f3100f28fec6525 | 1,454 | Pokedex | Apache License 2.0 |
core/src/main/java/id/sansets/infood/core/di/CoreDatabaseModule.kt | sansets | 294,803,938 | false | null | package id.sansets.infood.core.di
import android.content.Context
import androidx.room.Room
import dagger.Module
import dagger.Provides
import id.sansets.infood.core.data.source.local.room.RecipeDao
import id.sansets.infood.core.data.source.local.room.FoodCategoryDao
import id.sansets.infood.core.data.source.local.room.InFoodDatabase
import javax.inject.Singleton
@Module
class CoreDatabaseModule {
@Singleton
@Provides
fun provideDatabase(context: Context): InFoodDatabase =
Room.databaseBuilder(
context,
InFoodDatabase::class.java, "InFood.db"
).fallbackToDestructiveMigration().build()
@Provides
fun provideFoodCategoryDao(database: InFoodDatabase): FoodCategoryDao = database.foodCategoryDao()
@Provides
fun provideFavoriteDao(database: InFoodDatabase): RecipeDao = database.favoriteDao()
} | 0 | Kotlin | 12 | 98 | 7ce8bafa0ea25d7ac6da58abb183c383a2eebae9 | 869 | android-clean-architecture | Apache License 2.0 |
app/src/test/java/com/triviagenai/triviagen/options/OptionsViewModelTest.kt | sidcgithub | 793,551,165 | false | {"Kotlin": 75478} | package com.triviagenai.triviagen.options
import com.triviagenai.triviagen.options.domain.usecase.GetDarkmodePreferenceUseCase
import com.triviagenai.triviagen.options.domain.usecase.SetDarkmodePreferenceUseCase
import com.triviagenai.triviagen.options.presentation.options.OptionsViewModel
import junit.framework.TestCase.assertEquals
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.StandardTestDispatcher
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.runTest
import kotlinx.coroutines.test.setMain
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.times
import org.mockito.Mockito.verify
import org.mockito.Mockito.`when`
import org.mockito.MockitoAnnotations
@ExperimentalCoroutinesApi
class OptionsViewModelTest {
private val testDispatcher = StandardTestDispatcher()
@Mock
private lateinit var getDarkmodePreferenceUseCase: GetDarkmodePreferenceUseCase
@Mock
private lateinit var setDarkmodePreferenceUseCase: SetDarkmodePreferenceUseCase
private lateinit var optionsViewModel: OptionsViewModel
@Before
fun setUp() {
MockitoAnnotations.openMocks(this)
Dispatchers.setMain(testDispatcher)
}
@After
fun tearDown() {
Dispatchers.resetMain()
}
@Test
fun `init should set darkmodeState from use case`() = runTest {
`when`(getDarkmodePreferenceUseCase.invoke()).thenReturn(true)
optionsViewModel = OptionsViewModel(getDarkmodePreferenceUseCase, setDarkmodePreferenceUseCase)
advanceUntilIdle()
assertEquals(true, optionsViewModel.darkmodeState.first())
verify(getDarkmodePreferenceUseCase, times(1)).invoke()
}
@Test
fun `changeDarkmode should toggle darkmodeState and call setDarkmodePreferenceUseCase`() = runTest {
`when`(getDarkmodePreferenceUseCase()).thenReturn(false)
optionsViewModel = OptionsViewModel(getDarkmodePreferenceUseCase, setDarkmodePreferenceUseCase)
optionsViewModel.changeDarkmode()
advanceUntilIdle()
assertEquals(true, optionsViewModel.darkmodeState.first())
verify(setDarkmodePreferenceUseCase, times(1)).invoke(true)
}
}
| 3 | Kotlin | 1 | 2 | 337d72b00a5ed6f022d91d13cb12d3d9122296b7 | 2,400 | ai-trivia-app-android | MIT License |
api/src/test/kotlin/com/krwordcloud/api/KrwordcloudApplicationTests.kt | hoongeun | 332,092,255 | false | {"Python": 62731, "TypeScript": 17448, "Kotlin": 12077, "Shell": 6855, "Smarty": 3311, "HTML": 1721, "CSS": 1064, "Dockerfile": 497, "JavaScript": 337} | package com.krwordcloud.api
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class KrwordcloudApplicationTests {
@Test
fun contextLoads() {
}
}
| 0 | Python | 1 | 0 | 01016f94f86ba4a9d1ea668210a65689a0983641 | 212 | krwordcloud | Beerware License |
android/quest/src/main/java/org/smartregister/fhircore/quest/util/extensions/ConfigExtensions.kt | opensrp | 339,242,809 | false | null | /*
* Copyright 2021-2023 Ona Systems, 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 org.smartregister.fhircore.quest.util.extensions
import androidx.core.os.bundleOf
import androidx.navigation.NavController
import androidx.navigation.NavOptions
import org.smartregister.fhircore.engine.configuration.navigation.NavigationMenuConfig
import org.smartregister.fhircore.engine.configuration.workflow.ActionTrigger
import org.smartregister.fhircore.engine.configuration.workflow.ApplicationWorkflow
import org.smartregister.fhircore.engine.domain.model.ActionConfig
import org.smartregister.fhircore.engine.domain.model.ActionParameter
import org.smartregister.fhircore.engine.domain.model.ActionParameterType
import org.smartregister.fhircore.engine.domain.model.ResourceData
import org.smartregister.fhircore.engine.util.extension.isIn
import org.smartregister.fhircore.quest.navigation.MainNavigationScreen
import org.smartregister.fhircore.quest.navigation.NavigationArg
import org.smartregister.fhircore.quest.ui.shared.QuestionnaireHandler
import org.smartregister.p2p.utils.startP2PScreen
fun List<ActionConfig>.handleClickEvent(
navController: NavController,
resourceData: ResourceData? = null,
navMenu: NavigationMenuConfig? = null
) {
val onClickAction =
this.find { it.trigger.isIn(ActionTrigger.ON_CLICK, ActionTrigger.ON_QUESTIONNAIRE_SUBMISSION) }
onClickAction?.let { theConfig ->
val computedValuesMap = resourceData?.computedValuesMap ?: emptyMap()
val actionConfig = theConfig.interpolate(computedValuesMap)
when (onClickAction.workflow) {
ApplicationWorkflow.LAUNCH_QUESTIONNAIRE -> {
actionConfig.questionnaire?.let { questionnaireConfig ->
val questionnaireConfigInterpolated = questionnaireConfig.interpolate(computedValuesMap)
if (navController.context is QuestionnaireHandler) {
(navController.context as QuestionnaireHandler).launchQuestionnaire<Any>(
context = navController.context,
questionnaireConfig = questionnaireConfigInterpolated,
actionParams = interpolateActionParamsValue(actionConfig, resourceData).toList(),
baseResourceId = resourceData?.baseResourceId,
baseResourceType = resourceData?.baseResourceType?.name
)
}
}
}
ApplicationWorkflow.LAUNCH_PROFILE -> {
actionConfig.id?.let { id ->
val args =
bundleOf(
NavigationArg.PROFILE_ID to id,
NavigationArg.RESOURCE_ID to resourceData?.baseResourceId,
NavigationArg.RESOURCE_CONFIG to actionConfig.resourceConfig,
NavigationArg.PARAMS to interpolateActionParamsValue(actionConfig, resourceData)
)
navController.navigate(MainNavigationScreen.Profile.route, args)
}
}
ApplicationWorkflow.LAUNCH_REGISTER -> {
val args =
bundleOf(
Pair(NavigationArg.REGISTER_ID, actionConfig.id ?: navMenu?.id),
Pair(NavigationArg.SCREEN_TITLE, actionConfig.display ?: navMenu?.display ?: ""),
Pair(NavigationArg.TOOL_BAR_HOME_NAVIGATION, actionConfig.toolBarHomeNavigation),
Pair(NavigationArg.PARAMS, interpolateActionParamsValue(actionConfig, resourceData))
)
// If value != null, we are navigating FROM a register; disallow same register navigation
val currentRegisterId =
navController.currentBackStackEntry?.arguments?.getString(NavigationArg.REGISTER_ID)
val sameRegisterNavigation =
args.getString(NavigationArg.REGISTER_ID) ==
navController.previousBackStackEntry?.arguments?.getString(NavigationArg.REGISTER_ID)
if (!currentRegisterId.isNullOrEmpty() && sameRegisterNavigation) return
else {
navController.navigate(
resId = MainNavigationScreen.Home.route,
args = args,
navOptions =
navController.currentDestination?.id?.let {
navOptions(resId = it, inclusive = actionConfig.popNavigationBackStack == true)
}
)
}
}
ApplicationWorkflow.LAUNCH_REPORT -> {
val args = bundleOf(Pair(NavigationArg.REPORT_ID, actionConfig.id))
navController.navigate(MainNavigationScreen.Reports.route, args)
}
ApplicationWorkflow.LAUNCH_SETTINGS ->
navController.navigate(MainNavigationScreen.Settings.route)
ApplicationWorkflow.DEVICE_TO_DEVICE_SYNC -> startP2PScreen(navController.context)
ApplicationWorkflow.LAUNCH_MAP ->
navController.navigate(
MainNavigationScreen.GeoWidget.route,
bundleOf(NavigationArg.CONFIG_ID to actionConfig.id)
)
else -> return
}
}
}
fun interpolateActionParamsValue(actionConfig: ActionConfig, resourceData: ResourceData?) =
actionConfig
.params
.map { it.interpolate(resourceData?.computedValuesMap ?: emptyMap()) }
.toTypedArray()
/**
* Apply navigation options. Restrict destination to only use a single instance in the back stack.
*/
fun navOptions(resId: Int, inclusive: Boolean = false, singleOnTop: Boolean = true) =
NavOptions.Builder().setPopUpTo(resId, inclusive, true).setLaunchSingleTop(singleOnTop).build()
/**
* Function to convert the elements of an array that have paramType [ActionParameterType.PARAMDATA]
* to a map of [ActionParameter.key] against [ActionParameter](value).
*/
fun Array<ActionParameter>?.toParamDataMap(): Map<String, String> =
this?.asSequence()?.filter { it.paramType == ActionParameterType.PARAMDATA }?.associate {
it.key to it.value
}
?: emptyMap()
| 191 | null | 38 | 50 | 804cf101f47b08f947709509996e8cf8e6f4fc64 | 6,221 | fhircore | Apache License 2.0 |
vertx-lang-kotlin/src/main/kotlin/io/vertx/kotlin/ext/stomp/StompServerHandler.kt | Sammers21 | 142,990,532 | true | {"Kotlin": 1088656, "Java": 878672, "JavaScript": 76098, "Groovy": 22654, "Ruby": 14717, "FreeMarker": 254} | package io.vertx.kotlin.ext.stomp
import io.vertx.ext.stomp.Acknowledgement
import io.vertx.ext.stomp.ServerFrame
import io.vertx.ext.stomp.StompServerConnection
import io.vertx.ext.stomp.StompServerHandler
import io.vertx.kotlin.coroutines.awaitEvent
import io.vertx.kotlin.coroutines.awaitResult
/**
* Configures a handler that get notified when a STOMP frame is received by the server.
* This handler can be used for logging, debugging or ad-hoc behavior.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.receivedFrameHandlerAwait() : ServerFrame {
return awaitEvent{
this.receivedFrameHandler(it)
}
}
/**
* Configures the action to execute when a <code>CONNECT</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.connectHandlerAwait() : ServerFrame {
return awaitEvent{
this.connectHandler(it)
}
}
/**
* Configures the action to execute when a <code>STOMP</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.stompHandlerAwait() : ServerFrame {
return awaitEvent{
this.stompHandler(it)
}
}
/**
* Configures the action to execute when a <code>SUBSCRIBE</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.subscribeHandlerAwait() : ServerFrame {
return awaitEvent{
this.subscribeHandler(it)
}
}
/**
* Configures the action to execute when a <code>UNSUBSCRIBE</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.unsubscribeHandlerAwait() : ServerFrame {
return awaitEvent{
this.unsubscribeHandler(it)
}
}
/**
* Configures the action to execute when a <code>SEND</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.sendHandlerAwait() : ServerFrame {
return awaitEvent{
this.sendHandler(it)
}
}
/**
* Configures the action to execute when a connection with the client is closed.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.closeHandlerAwait() : StompServerConnection {
return awaitEvent{
this.closeHandler(it)
}
}
/**
* Configures the action to execute when a <code>COMMIT</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.commitHandlerAwait() : ServerFrame {
return awaitEvent{
this.commitHandler(it)
}
}
/**
* Configures the action to execute when a <code>ABORT</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.abortHandlerAwait() : ServerFrame {
return awaitEvent{
this.abortHandler(it)
}
}
/**
* Configures the action to execute when a <code>BEGIN</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.beginHandlerAwait() : ServerFrame {
return awaitEvent{
this.beginHandler(it)
}
}
/**
* Configures the action to execute when a <code>DISCONNECT</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.disconnectHandlerAwait() : ServerFrame {
return awaitEvent{
this.disconnectHandler(it)
}
}
/**
* Configures the action to execute when a <code>ACK</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.ackHandlerAwait() : ServerFrame {
return awaitEvent{
this.ackHandler(it)
}
}
/**
* Configures the action to execute when a <code>NACK</code> frame is received.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.nackHandlerAwait() : ServerFrame {
return awaitEvent{
this.nackHandler(it)
}
}
/**
* Called when the client connects to a server requiring authentication. It invokes the configured
* using [io.vertx.ext.stomp.StompServerHandler].
*
* @param connection server connection that contains session ID
* @param login the login
* @param passcode the <PASSWORD>
* @param handler handler receiving the authentication result
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.onAuthenticationRequestAwait(connection : StompServerConnection, login : String, passcode : String) : Boolean {
return awaitResult{
this.onAuthenticationRequest(connection, login, passcode, it)
}
}
/**
* Configures the action to execute when messages are acknowledged.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.onAckHandlerAwait() : Acknowledgement {
return awaitEvent{
this.onAckHandler(it)
}
}
/**
* Configures the action to execute when messages are <strong>not</strong> acknowledged.
*
* @param handler the handler
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.onNackHandlerAwait() : Acknowledgement {
return awaitEvent{
this.onNackHandler(it)
}
}
/**
* Allows customizing the action to do when the server needs to send a `PING` to the client. By default it send a
* frame containing <code>EOL</code> (specification). However, you can customize this and send another frame. However,
* be aware that this may requires a custom client.
* <p/>
* The handler will only be called if the connection supports heartbeats.
*
* @param handler the action to execute when a `PING` needs to be sent.
* @returnthe current [io.vertx.ext.stomp.StompServerHandler] *
* <p/>
* NOTE: This function has been automatically generated from the [io.vertx.ext.stomp.StompServerHandler original] using Vert.x codegen.
*/
suspend fun StompServerHandler.pingHandlerAwait() : StompServerConnection {
return awaitEvent{
this.pingHandler(it)
}
}
| 0 | Kotlin | 0 | 0 | bdf349e87e39aeec85cfbd1a53bae3cb3e420c55 | 8,796 | vertx-stack-generation | Apache License 2.0 |
packet/src/test/java/dev/keiji/openpgp/packet/publickey/PublicKeyEcdhTest.kt | keiji | 591,966,950 | false | null | package dev.keiji.openpgp.packet.publickey
import dev.keiji.openpgp.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
class PublicKeyEcdhTest {
companion object {
private const val SAMPLE1 = "092B06010401DA470F01" +
"002C0B16212C3742" + // 10110001011000100001001011000011011101000010 = 44bits
"03" + // fields length
"01" + // reserved
"08" + // kdfHashFunctionId
"09" // kdfAlgorithm
}
@Test
fun testEncode() {
val expected = SAMPLE1
val data = PublicKeyEcdh().also {
it.ellipticCurveParameter = EllipticCurveParameter.Ed25519
it.ecPoint = byteArrayOf(11, 22, 33, 44, 55, 66)
it.kdfHashFunction = HashAlgorithm.SHA2_256
it.kdfAlgorithm = SymmetricKeyAlgorithm.AES256
}
val actual = ByteArrayOutputStream().let {
data.writeTo(it)
it.toByteArray()
}
assertEquals(expected, actual.toHex(""))
}
@Test
fun testDecode() {
val expected = PublicKeyEcdh().also {
it.ellipticCurveParameter = EllipticCurveParameter.Ed25519
it.ecPoint = byteArrayOf(11, 22, 33, 44, 55, 66)
it.kdfHashFunction = HashAlgorithm.SHA2_256
it.kdfAlgorithm = SymmetricKeyAlgorithm.AES256
}
val data = parseHexString(SAMPLE1)
val actual = PublicKeyEcdh().also {
it.readFrom(ByteArrayInputStream(data))
}
assertTrue(expected.equals(actual))
}
}
| 2 | Kotlin | 0 | 0 | 92cad92ef3afea6b5f19365d671e141897e34305 | 1,729 | openpgp | Apache License 2.0 |
app/src/main/java/com/madebyratik/mincast/data/PodcastsRepo.kt | libhide | 308,572,210 | false | null | package com.madebyratik.mincast.data
import com.madebyratik.mincast.model.Episode
import com.madebyratik.mincast.model.Podcast
interface PodcastsRepo {
fun getPopularPodcasts(): List<Podcast>
fun getRecommendedEpisodes(): List<Episode>
} | 0 | Kotlin | 0 | 0 | 6f933b453833f4046b3bd950b99b5218300a787c | 247 | mincast | MIT License |
libs/db/db-core/src/test/kotlin/net/corda/db/core/utils/BatchPersistenceServiceImplTest.kt | corda | 346,070,752 | false | {"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.db.core.utils
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.Mockito.any
import org.mockito.Mockito.mock
import org.mockito.Mockito.never
import org.mockito.Mockito.times
import org.mockito.kotlin.inOrder
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoInteractions
import org.mockito.kotlin.whenever
import java.sql.Connection
import java.sql.PreparedStatement
@Suppress("MaxLineLength")
class BatchPersistenceServiceImplTest {
private val connection = mock<Connection>()
private val statement = mock<PreparedStatement>()
private val batchPersistenceService = BatchPersistenceServiceImpl()
private var rowCallbackCount = 0
private val batchSizes = mutableListOf<Int>()
private val query: (Int) -> String = { batchSize ->
batchSizes += batchSize
batchSize.toString()
}
private data class Row(val index: Int, val value: String)
private val setRowParametersBlock: (PreparedStatement, Iterator<Int>, Row) -> Unit = { statement, parameterIndex, row ->
statement.setInt(parameterIndex.next(), row.index)
statement.setString(parameterIndex.next(), row.value)
rowCallbackCount++
}
@BeforeEach
fun beforeEach() {
whenever(connection.prepareStatement(any())).thenReturn(statement)
}
@Test
fun `executes single insert when there are less rows than rowsPerInsert parameter`() {
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = (1..4).map { Row(it, it.toString()) },
setRowParametersBlock
)
verify(statement).executeUpdate()
verify(statement, never()).addBatch()
verify(statement, never()).executeBatch()
assertThat(rowCallbackCount).isEqualTo(4)
assertThat(batchSizes).containsOnly(4)
}
@Test
fun `executes single insert when there are equal rows as rowsPerInsert parameter`() {
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = (1..5).map { Row(it, it.toString()) },
setRowParametersBlock
)
verify(statement).addBatch()
verify(statement).executeBatch()
assertThat(rowCallbackCount).isEqualTo(5)
assertThat(batchSizes).containsOnly(5)
}
@Test
fun `returns when there are no rows`() {
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = emptyList(),
setRowParametersBlock
)
verifyNoInteractions(statement)
assertThat(rowCallbackCount).isEqualTo(0)
}
@Test
fun `executes multiple inserts when there are more rows than rowsPerInsert with the last insert having less rows than rowsPerInsert`() {
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = (1..8).map { Row(it, it.toString()) },
setRowParametersBlock
)
verify(statement).executeUpdate()
verify(statement).addBatch()
verify(statement).executeBatch()
assertThat(rowCallbackCount).isEqualTo(8)
assertThat(batchSizes).containsOnly(5, 3)
}
@Test
fun `executes multiple inserts when there are more rows than rowsPerInsert with the last insert having equals rows as rowsPerInsert`() {
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = (1..10).map { Row(it, it.toString()) },
setRowParametersBlock
)
verify(statement, never()).executeUpdate()
verify(statement, times(2)).addBatch()
verify(statement).executeBatch()
assertThat(rowCallbackCount).isEqualTo(10)
assertThat(batchSizes).containsOnly(5, 5)
}
@Test
fun `executes single batch of inserts when there are equal rows as insertsPerBatch x rowsPerInsert`() {
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = (1..15).map { Row(it, it.toString()) },
setRowParametersBlock
)
verify(statement, never()).executeUpdate()
verify(statement, times(3)).addBatch()
verify(statement).executeBatch()
assertThat(rowCallbackCount).isEqualTo(15)
assertThat(batchSizes).containsOnly(5, 5, 5)
}
@Test
fun `executes multiple batches of inserts when the number of rows are a multiple of insertsPerBatch x rowsPerInsert`() {
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = (1..45).map { Row(it, it.toString()) },
setRowParametersBlock
)
verify(statement, never()).executeUpdate()
verify(statement, times(9)).addBatch()
verify(statement, times(3)).executeBatch()
assertThat(rowCallbackCount).isEqualTo(45)
assertThat(batchSizes).containsOnly(5, 5, 5, 5, 5, 5, 5, 5, 5)
}
@Test
fun `executes multiple batches of inserts and a single insert when there are more rows than insertsPerBatch x rowsPerInsert`() {
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = (1..47).map { Row(it, it.toString()) },
setRowParametersBlock
)
verify(statement).executeUpdate()
verify(statement, times(9)).addBatch()
verify(statement, times(3)).executeBatch()
assertThat(rowCallbackCount).isEqualTo(47)
assertThat(batchSizes).containsOnly(5, 5, 5, 5, 5, 5, 5, 5, 5, 2)
}
@Test
fun `parameterIndex updates the index correctly within a single insert statement`() {
val rows = (1..5).map { Row(it, it.toString()) }
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = rows,
setRowParametersBlock
)
inOrder(statement) {
rows.forEachIndexed { rowIndex, (index, value) ->
verify(statement).setInt((rowIndex * 2) + 1, index)
verify(statement).setString((rowIndex * 2) + 2, value)
}
}
}
@Test
fun `parameterIndex updates the index correctly within a single insert statement with less rows than rowsPerInsert`() {
val rows = (1..4).map { Row(it, it.toString()) }
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = rows,
setRowParametersBlock
)
inOrder(statement) {
rows.forEachIndexed { rowIndex, (index, value) ->
verify(statement).setInt((rowIndex * 2) + 1, index)
verify(statement).setString((rowIndex * 2) + 2, value)
}
}
}
@Test
fun `parameterIndex updates the index correctly within a single batch of inserts when the last insert has less rows than rowsPerInsert`() {
val rows = (1..8).map { Row(it, it.toString()) }
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = rows,
setRowParametersBlock
)
inOrder(statement) {
rows.take(5).forEachIndexed { rowIndex, (index, value) ->
verify(statement).setInt((rowIndex * 2) + 1, index)
verify(statement).setString((rowIndex * 2) + 2, value)
}
rows.takeLast(3).forEachIndexed { rowIndex, (index, value) ->
verify(statement).setInt((rowIndex * 2) + 1, index)
verify(statement).setString((rowIndex * 2) + 2, value)
}
}
}
@Test
fun `parameterIndex updates the index correctly across batches of inserts`() {
val rows = (1..16).map { Row(it, it.toString()) }
batchPersistenceService.persistBatch(
connection,
query,
rowsPerInsert = 5,
insertsPerBatch = 3,
rowData = rows,
setRowParametersBlock
)
inOrder(statement) {
rows.chunked(5).map { chunked ->
chunked.forEachIndexed { rowIndex, (index, value) ->
verify(statement).setInt((rowIndex * 2) + 1, index)
verify(statement).setString((rowIndex * 2) + 2, value)
}
}
}
}
}
| 14 | Kotlin | 27 | 69 | 0766222eb6284c01ba321633e12b70f1a93ca04e | 9,175 | corda-runtime-os | Apache License 2.0 |
lib/src/test/kotlin/com/vinted/automerger/testutils/RepoExtension.kt | jenkinsci | 189,257,621 | false | null | package com.vinted.automerger.testutils
import org.eclipse.jgit.api.Git
import org.junit.jupiter.api.extension.AfterEachCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
import java.io.File
open class RepoExtension : BeforeEachCallback, AfterEachCallback {
lateinit var path: File
private set
lateinit var git: Git
private set
override fun beforeEach(context: ExtensionContext) {
path = File.createTempFile("AutomergerTestRepository-${System.currentTimeMillis()}", "")
if (!path.delete()) {
throw RuntimeException("Failed delete $path file")
}
git = Git.init().setDirectory(path).call()
with(git) {
commit().setAllowEmpty(true).setMessage("init commit").call()
}
}
override fun afterEach(context: ExtensionContext) {
if (!path.deleteRecursively()) {
System.err.println("Failed delete temporally created repo folder $path")
}
}
}
| 1 | Kotlin | 4 | 3 | ee00ce245c70bc4919c887b37f476b33157cce76 | 1,050 | git-automerger-plugin | MIT License |
src/test/kotlin/com/ginsberg/advent2022/Day17Test.kt | tginsberg | 568,158,721 | false | {"Kotlin": 113322} | /*
* Copyright (c) 2022 by <NAME>
*/
package com.ginsberg.advent2022
import com.ginsberg.advent2022.Resources.resourceAsString
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
@DisplayName("Day 17")
class Day17Test {
// Arrange
private val input = ">>><<><>><<<>><>>><<<>>><<<><<<>><>><<>>"
@Nested
@DisplayName("Part 1")
inner class Part1 {
@Test
fun `Matches example`() {
// Act
val answer = Day17(input).solvePart1()
// Assert
assertThat(answer).isEqualTo(3068)
}
@Test
fun `Actual answer`() {
// Act
val answer = Day17(resourceAsString("day17.txt")).solvePart1()
// Assert
assertThat(answer).isEqualTo(3151)
}
}
@Nested
@DisplayName("Part 2")
inner class Part2 {
@Test
fun `Matches example`() {
// Act
val answer = Day17(input).solvePart2()
// Assert
assertThat(answer).isEqualTo(1_514_285_714_288L)
}
@Test
fun `Actual answer`() {
// Act
val answer = Day17(resourceAsString("day17.txt")).solvePart2()
// Assert
assertThat(answer).isEqualTo(1560919540245L)
}
}
} | 0 | Kotlin | 2 | 26 | 2cd87bdb95b431e2c358ffaac65b472ab756515e | 1,422 | advent-2022-kotlin | Apache License 2.0 |
app/src/main/java/com/victor/clips/data/FollowItem.kt | Victor2018 | 152,215,979 | false | null | package com.victor.clips.data
/*
* -----------------------------------------------------------------
* Copyright (C) 2018-2028, by Victor, All rights reserved.
* -----------------------------------------------------------------
* File: FollowItem.java
* Author: Victor
* Date: 2019/11/1 9:55
* Description:
* -----------------------------------------------------------------
*/
class FollowItem {
var id: Int = 0
var adIndex: Int = 0
var type: String? = null
var tag: String? = null
var data: FollowInfo? = null
} | 0 | Kotlin | 13 | 45 | ebd31401c63ec5641e69427bd25e41c60f0fa9fd | 543 | FunnyClips | Apache License 2.0 |
technology/kotlin-quarkus/src/main/kotlin/org/acme/kotlin/schooltimetabling/domain/Lesson.kt | TimefoldAI | 630,933,034 | false | null | package org.acme.kotlin.schooltimetabling.domain
import ai.timefold.solver.core.api.domain.entity.PlanningEntity
import ai.timefold.solver.core.api.domain.lookup.PlanningId
import ai.timefold.solver.core.api.domain.variable.PlanningVariable
import com.fasterxml.jackson.annotation.JsonIdentityReference
@PlanningEntity
class Lesson {
@PlanningId
var id: Long? = null
lateinit var subject: String
lateinit var teacher: String
lateinit var studentGroup: String
@JsonIdentityReference
@PlanningVariable
var timeslot: Timeslot? = null
@JsonIdentityReference
@PlanningVariable
var room: Room? = null
// No-arg constructor required for Hibernate and Timefold
constructor()
constructor(id: Long?, subject: String, teacher: String, studentGroup: String) {
this.id = id
this.subject = subject.trim()
this.teacher = teacher.trim()
this.studentGroup = studentGroup.trim()
}
constructor(id: Long?, subject: String, teacher: String, studentGroup: String, timeslot: Timeslot?, room: Room?)
: this(id, subject, teacher, studentGroup) {
this.timeslot = timeslot
this.room = room
}
override fun toString(): String = "$subject($id)"
}
| 13 | null | 31 | 97 | 1821ce36d4605d3b70280920ed99134c7f2e69cd | 1,262 | timefold-quickstarts | Apache License 2.0 |
generator/bin/src/main/kotlin/com/laidpack/sourcerer/generator/flow/setter/BaseSetterHandler.kt | dpnolte | 151,090,095 | false | null | package com.laidpack.sourcerer.generator.flow.setter
import com.github.javaparser.ast.Node
import com.laidpack.sourcerer.generator.flow.BaseHandler
import kotlin.reflect.KClass
abstract class BaseSetterHandler<T : Node>(protected val flow: SetterFlow, targetType: KClass<T>)
: BaseHandler<T>(targetType) {
} | 8 | Kotlin | 1 | 0 | 9513bbc54768e9248c450b0aba125b433c447e68 | 314 | sourcerer | Apache License 2.0 |
lib/src/main/kotlin/com/prosumma/di/Registration.kt | Prosumma | 403,770,130 | false | {"Kotlin": 30615} | package com.prosumma.di
internal sealed class Registration<T> | 0 | Kotlin | 0 | 0 | dea409388efdee393eb07db8e97234e1a2e2be73 | 62 | KoDI | MIT License |
coroutine_cachepro/src/main/java/com/pv_libs/coroutine_cachepro/ApiResult.kt | pv-libs | 262,783,333 | false | null | package com.pv_libs.coroutine_cachepro
sealed class ApiResult<out T> {
data class Success<T>(val data: T) : ApiResult<T>()
class Error(val exception: Exception) : ApiResult<Nothing>()
}
| 0 | Kotlin | 0 | 1 | 8f58ca190302806540c00bb44eff48ec914798ee | 195 | CoroutineCachePro | MIT License |
Core/src/main/kotlin/pw/kmp/gamelet/map/repository/LocalMapRepository.kt | kailan | 82,181,368 | false | {"Kotlin": 37819} | package pw.kmp.gamelet.map.repository
import java.io.File
/**
* A repository of maps in a local folder.
*/
open class LocalMapRepository(val directory: File) : MapRepository {
/**
* Ensure that the folder exists.
*/
override fun setup() {
if (!directory.exists()) {
directory.mkdir()
}
}
/**
* Return a list of all folders in the directory.
*/
override fun getMaps(): Array<File> = directory.listFiles(File::isDirectory)
} | 0 | Kotlin | 0 | 0 | 91fcd588aebbefbe62bd543c5ea5661d1323d5dd | 497 | Gamelet | MIT License |
lib/src/main/kotlin/com/lemonappdev/konsist/api/ext/list/KoTestClassProviderListExt.kt | LemonAppDev | 621,181,534 | false | {"Kotlin": 4854719, "Python": 17926} | package com.lemonappdev.konsist.api.ext.list
import com.lemonappdev.konsist.api.declaration.KoBaseDeclaration
import com.lemonappdev.konsist.api.declaration.KoClassDeclaration
import com.lemonappdev.konsist.api.provider.KoTestClassProvider
/**
* List containing test classes.
*
* @param testPropertyName the test property name to check. By default, "sut".
* @param moduleName the name of the module to check (optional).
* @param sourceSetName the name of the source set to check (optional).
* @return A list containing all test classes.
*/
fun <T : KoTestClassProvider> List<T>.testClasses(
testPropertyName: String = "sut",
moduleName: String? = null,
sourceSetName: String? = null,
): List<KoBaseDeclaration> = flatMap { it.testClasses(testPropertyName, moduleName, sourceSetName) }
/**
* List containing test classes matching the predicate.
*
* @param moduleName the name of the module to check (optional).
* @param sourceSetName the name of the source set to check (optional).
* @param predicate A function that defines the condition to be met by a test class.
* @return A list containing all test classes matching the predicate.
*/
fun <T : KoTestClassProvider> List<T>.testClasses(
moduleName: String? = null,
sourceSetName: String? = null,
predicate: (KoClassDeclaration) -> Boolean,
): List<KoBaseDeclaration> = flatMap { it.testClasses(moduleName, sourceSetName, predicate) }
/**
* List containing declarations with a test.
*
* @param testPropertyName the test property name to check. By default, "sut".
* @param moduleName the name of the module to check (optional).
* @param sourceSetName the name of the source set to check (optional).
* @return A list containing declarations with a test.
*/
fun <T : KoTestClassProvider> List<T>.withTestClass(
testPropertyName: String = "sut",
moduleName: String? = null,
sourceSetName: String? = null,
): List<T> = filter { it.hasTestClasses(testPropertyName, moduleName, sourceSetName) }
/**
* List containing declarations without a test.
*
* @param testPropertyName the test property name to check. By default, "sut".
* @param moduleName the name of the module to check (optional).
* @param sourceSetName the name of the source set to check (optional).
* @return A list containing declarations without a test.
*/
fun <T : KoTestClassProvider> List<T>.withoutTestClass(
testPropertyName: String = "sut",
moduleName: String? = null,
sourceSetName: String? = null,
): List<T> = filterNot { it.hasTestClasses(testPropertyName, moduleName, sourceSetName) }
/**
* List containing declarations with a test matching the predicate.
*
* @param moduleName the name of the module to check (optional).
* @param sourceSetName the name of the source set to check (optional).
* @param predicate A function that defines the condition to be met by a test class.
* @return A list containing declarations with a test matching the predicate.
*/
fun <T : KoTestClassProvider> List<T>.withTestClass(
moduleName: String? = null,
sourceSetName: String? = null,
predicate: (KoClassDeclaration) -> Boolean,
): List<T> = filter { it.hasTestClass(moduleName, sourceSetName, predicate) }
/**
* List containing declarations without a test matching the predicate.
*
* @param moduleName the name of the module to check (optional).
* @param sourceSetName the name of the source set to check (optional).
* @param predicate A function that defines the condition to be met by a test class.
* @return A list containing declarations without a test matching the predicate.
*/
fun <T : KoTestClassProvider> List<T>.withoutTestClass(
moduleName: String? = null,
sourceSetName: String? = null,
predicate: (KoClassDeclaration) -> Boolean,
): List<T> = filterNot { it.hasTestClass(moduleName, sourceSetName, predicate) }
| 5 | Kotlin | 26 | 995 | 603d19e179f59445c5f4707c1528a438e4595136 | 3,910 | konsist | Apache License 2.0 |
lightweightlibrary/src/main/java/com/tradingview/lightweightcharts/api/series/models/PriceFormat.kt | tradingview | 284,986,398 | false | null | package com.tradingview.lightweightcharts.api.series.models
import com.google.gson.annotations.SerializedName
data class PriceFormat(
val formatter: String? = null,
val type: Type? = null,
val precision: Int? = null,
val minMove: Float? = null
) {
enum class Type {
@SerializedName("price")
PRICE,
@SerializedName("volume")
VOLUME,
@SerializedName("percent")
PERCENT,
@SerializedName("custom")
CUSTOM
}
companion object {
fun priceFormatBuiltIn(type: Type, precision: Int, minMove: Float): PriceFormat {
return PriceFormat(type = type, precision = precision, minMove = minMove)
}
fun priceFormatCustom(formatter: String, minMove: Float): PriceFormat {
return PriceFormat(formatter = formatter, minMove = minMove, type = Type.CUSTOM)
}
}
} | 25 | null | 27 | 86 | 08c3dbda653a1d5f78f7c5d47c990c7f9887d9e4 | 897 | lightweight-charts-android | Apache License 2.0 |
lib/src/main/kotlin/be/zvz/klover/tools/io/EmptyInputStream.kt | organization | 673,130,266 | false | null | package be.zvz.klover.tools.io
import java.io.InputStream
/**
* Represents an empty input stream.
*/
class EmptyInputStream : InputStream() {
override fun available(): Int {
return 0
}
override fun read(): Int {
return -1
}
companion object {
val INSTANCE = EmptyInputStream()
}
}
| 1 | Kotlin | 0 | 2 | 06e801808933ff8c627543d579c4be00061eb305 | 335 | Klover | Apache License 2.0 |
testlibrary/src/main/java/com/hyperdimension/testlibrary/MyEditText.kt | Guille88C | 213,553,455 | false | {"Kotlin": 3887} | package com.hyperdimension.testlibrary
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
class MyEditText : AppCompatEditText {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
} | 0 | Kotlin | 0 | 0 | d1918dbc9c3a58e7b99d24fbff6223f4eca4f380 | 474 | AndroidTestLibrary | Apache License 2.0 |
app/src/main/java/com/example/newsapp/domain/usecases/InsertArticleUseCase.kt | milosursulovic | 577,638,138 | false | {"Kotlin": 29536} | package com.example.newsapp.domain.usecases
import com.example.newsapp.data.api.models.Article
import com.example.newsapp.domain.repository.NewsRepository
class InsertArticleUseCase(
private val repository: NewsRepository
) {
suspend operator fun invoke(article: Article) {
repository.insertArticle(article)
}
} | 0 | Kotlin | 0 | 0 | 8f099dd0a4aab91879303caa85838de3f4676874 | 333 | news-app | MIT License |
feature_workdetail/src/main/java/com/andtv/flicknplay/workdetail/domain/GetWorkDetailsUseCase.kt | procoder1128 | 553,094,605 | false | null | /*
* Copyright (C) 2021 Flicknplay
*
* 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.andtv.flicknplay.workdetail.domain
import com.andtv.flicknplay.model.data.remote.toDomainModel
import com.andtv.flicknplay.model.domain.CastDomainModel
import com.andtv.flicknplay.model.domain.PageDomainModel
import com.andtv.flicknplay.model.domain.WorkDomainModel
import com.andtv.flicknplay.model.presentation.model.WorkViewModel
import com.andtv.flicknplay.workdetail.domain.model.ReviewDomainModel
import com.andtv.flicknplay.workdetail.domain.model.VideoDomainModel
import com.andtv.flicknplay.workdetail.domain.model.toWorkDetail
import io.reactivex.Single
import javax.inject.Inject
/**
* Copyright (C) Flicknplay 20-05-2019.
*/
class GetWorkDetailsUseCase @Inject constructor(
private val checkFavoriteWorkUseCase: CheckFavoriteWorkUseCase,
private val getDetailsUseCase: GetDetailsUseCase,
private val getRecommendationByWorkUseCase: GetRecommendationByWorkUseCase,
private val getSimilarByWorkUseCase: GetSimilarByWorkUseCase,
private val getReviewByWorkUseCase: GetReviewByWorkUseCase,
) {
operator fun invoke(workViewModel: WorkViewModel): Single<WorkDetailsDomainWrapper> =
Single.zip(
checkFavoriteWorkUseCase(workViewModel),
getDetailsUseCase(workViewModel.id),
//getRecommendationByWorkUseCase(workViewModel.type, workViewModel.id, 1),
getSimilarByWorkUseCase(workViewModel.type, workViewModel.id, 1),
)
//getReviewByWorkUseCase(workViewModel.type, workViewModel.id, 1),
{ isFavorite, movieDetails, similar->
WorkDetailsDomainWrapper(
isFavorite,
movieDetails.videos?.toWorkDetail().also {
it?.forEach { it.thumbnail = movieDetails.backdropPath }
},
movieDetails.credits?.toDomainModel(),
PageDomainModel(0, 0),
similar,
PageDomainModel(0, 0),
movieDetails.releaseDate,
movieDetails.overview,
movieDetails.backdropPath,
Pair(movieDetails.isSeries, if(movieDetails.seasons == null) 0 else movieDetails.seasons!!.size)
)
}
data class WorkDetailsDomainWrapper(
val isFavorite: Boolean,
val videos: List<VideoDomainModel>?,
val casts: List<CastDomainModel>?,
val recommended: PageDomainModel<WorkDomainModel>,
val similar: PageDomainModel<WorkDomainModel>,
val reviews: PageDomainModel<ReviewDomainModel>,
val releaseDate: String?,
val overview: String?,
val backDropUrl: String?,
val series:Pair<Boolean?, Int>?
)
}
| 0 | Kotlin | 1 | 4 | 45d661d6b872c13b6a1235bbb9a44c91740d3f9d | 3,366 | blockchain | Apache License 2.0 |
platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/timeline/comment/CommentInputComponentFactory.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.collaboration.ui.codereview.timeline.comment
import com.intellij.collaboration.ui.SingleValueModel
import com.intellij.collaboration.ui.codereview.InlineIconButton
import com.intellij.collaboration.ui.codereview.timeline.comment.CommentInputComponentFactory.CancelActionConfig
import com.intellij.collaboration.ui.codereview.timeline.comment.CommentInputComponentFactory.ScrollOnChangePolicy
import com.intellij.collaboration.ui.codereview.timeline.comment.CommentInputComponentFactory.SubmitActionConfig
import com.intellij.collaboration.ui.codereview.timeline.comment.CommentInputComponentFactory.getEditorTextFieldVerticalOffset
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonShortcuts
import com.intellij.openapi.actionSystem.ShortcutSet
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.AnimatedIcon
import com.intellij.ui.EditorTextField
import com.intellij.util.ui.JBInsets
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.SingleComponentCenteringLayout
import com.intellij.util.ui.UIUtil
import icons.CollaborationToolsIcons
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import java.awt.Dimension
import java.awt.Rectangle
import java.awt.event.*
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JLayeredPane
import javax.swing.JPanel
import javax.swing.border.EmptyBorder
object CommentInputComponentFactory {
val defaultSubmitShortcut: ShortcutSet = CommonShortcuts.CTRL_ENTER
val defaultCancelShortcut: ShortcutSet = CommonShortcuts.ESCAPE
fun create(
model: CommentTextFieldModel,
textField: EditorTextField,
config: Config
): JComponent {
textField.installSubmitAction(model, config.submitConfig)
textField.installCancelAction(config.cancelConfig)
val contentComponent = JPanel(null).apply {
isOpaque = false
layout = MigLayout(
LC()
.gridGap("0", "0")
.insets("0", "0", "0", "0")
.fillX()
)
border = JBUI.Borders.empty()
}
val busyLabel = JLabel(AnimatedIcon.Default())
val submitButton = createSubmitButton(model, config.submitConfig)
val cancelButton = createCancelButton(config.cancelConfig)
updateUiOnModelChanges(contentComponent, model, textField, busyLabel, submitButton)
installScrollIfChangedController(contentComponent, model, config.scrollOnChange)
val textFieldWithOverlay = createTextFieldWithOverlay(textField, submitButton, busyLabel)
contentComponent.add(textFieldWithOverlay, CC().grow().pushX())
cancelButton?.let { contentComponent.add(it, CC().alignY("top")) }
return contentComponent
}
fun getEditorTextFieldVerticalOffset() = if (UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF()) 6 else 4
data class Config(
val scrollOnChange: ScrollOnChangePolicy = ScrollOnChangePolicy.ScrollToField,
val submitConfig: SubmitActionConfig,
val cancelConfig: CancelActionConfig?
)
data class SubmitActionConfig(
val iconConfig: ActionButtonConfig?,
val shortcut: SingleValueModel<ShortcutSet> = SingleValueModel(defaultSubmitShortcut)
)
data class CancelActionConfig(
val iconConfig: ActionButtonConfig?,
val shortcut: ShortcutSet = defaultCancelShortcut,
val action: () -> Unit
)
sealed class ScrollOnChangePolicy {
object DontScroll : ScrollOnChangePolicy()
object ScrollToField : ScrollOnChangePolicy()
class ScrollToComponent(val component: JComponent) : ScrollOnChangePolicy()
}
data class ActionButtonConfig(val name: @NlsContexts.Tooltip String)
}
private fun installScrollIfChangedController(
parent: JComponent,
model: CommentTextFieldModel,
policy: ScrollOnChangePolicy,
) {
if (policy == ScrollOnChangePolicy.DontScroll) {
return
}
fun scroll() {
when (policy) {
ScrollOnChangePolicy.DontScroll -> {
}
is ScrollOnChangePolicy.ScrollToComponent -> {
val componentToScroll = policy.component
parent.scrollRectToVisible(Rectangle(0, 0, componentToScroll.width, componentToScroll.height))
}
ScrollOnChangePolicy.ScrollToField -> {
parent.scrollRectToVisible(Rectangle(0, 0, parent.width, parent.height))
}
}
}
model.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
scroll()
}
})
// previous listener doesn't work properly when text field's size is changed because
// component is not resized at this moment, so we need to handle resizing too
// it also produces such behavior: resize of the ancestor will scroll to the field
parent.addComponentListener(object : ComponentAdapter() {
override fun componentResized(e: ComponentEvent?) {
if (UIUtil.isFocusAncestor(parent)) {
scroll()
}
}
})
}
private fun createSubmitButton(
model: CommentTextFieldModel,
actionConfig: SubmitActionConfig
): InlineIconButton? {
val iconConfig = actionConfig.iconConfig ?: return null
val button = InlineIconButton(
CollaborationToolsIcons.Send, CollaborationToolsIcons.SendHovered,
tooltip = iconConfig.name
).apply {
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
actionListener = ActionListener { model.submitWithCheck() }
}
actionConfig.shortcut.addAndInvokeListener {
button.shortcut = it
}
return button
}
private fun createCancelButton(actionConfig: CancelActionConfig?): InlineIconButton? {
if (actionConfig == null) {
return null
}
val iconConfig = actionConfig.iconConfig ?: return null
return InlineIconButton(
AllIcons.Actions.Close, AllIcons.Actions.CloseHovered,
tooltip = iconConfig.name,
shortcut = actionConfig.shortcut
).apply {
border = JBUI.Borders.empty(getEditorTextFieldVerticalOffset(), 0)
putClientProperty(UIUtil.HIDE_EDITOR_FROM_DATA_CONTEXT_PROPERTY, true)
actionListener = ActionListener { actionConfig.action() }
}
}
private fun EditorTextField.installSubmitAction(
model: CommentTextFieldModel,
submitConfig: SubmitActionConfig
) {
val submitAction = object : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) = model.submitWithCheck()
}
submitConfig.shortcut.addAndInvokeListener {
submitAction.unregisterCustomShortcutSet(this)
submitAction.registerCustomShortcutSet(it, this)
}
}
private fun EditorTextField.installCancelAction(cancelConfig: CancelActionConfig?) {
if (cancelConfig == null) {
return
}
object : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
cancelConfig.action()
}
}.registerCustomShortcutSet(cancelConfig.shortcut, this)
}
private fun updateUiOnModelChanges(
parent: JComponent,
model: CommentTextFieldModel,
textField: EditorTextField,
busyLabel: JComponent,
submitButton: InlineIconButton?
) {
fun update() {
busyLabel.isVisible = model.isBusy
submitButton?.isEnabled = model.isSubmitAllowed()
}
textField.addDocumentListener(object : DocumentListener {
override fun documentChanged(event: DocumentEvent) {
update()
parent.revalidate()
}
})
model.addStateListener(::update)
update()
}
private fun CommentTextFieldModel.isSubmitAllowed(): Boolean = !isBusy && content.text.isNotBlank()
private fun CommentTextFieldModel.submitWithCheck() {
if (isSubmitAllowed()) {
submit()
}
}
/**
* Returns a component with [busyLabel] in center and [button] in bottom-right corner
*/
private fun createTextFieldWithOverlay(textField: EditorTextField, button: JComponent?, busyLabel: JComponent?): JComponent {
if (button != null) {
val bordersListener = object : ComponentAdapter(), HierarchyListener {
override fun componentResized(e: ComponentEvent?) {
val scrollPane = (textField.editor as? EditorEx)?.scrollPane ?: return
val buttonSize = button.size
JBInsets.removeFrom(buttonSize, button.insets)
scrollPane.viewportBorder = JBUI.Borders.emptyRight(buttonSize.width)
scrollPane.viewport.revalidate()
}
override fun hierarchyChanged(e: HierarchyEvent?) {
val scrollPane = (textField.editor as? EditorEx)?.scrollPane ?: return
button.border = EmptyBorder(scrollPane.border.getBorderInsets(scrollPane))
componentResized(null)
}
}
textField.addHierarchyListener(bordersListener)
button.addComponentListener(bordersListener)
}
val layeredPane = object : JLayeredPane() {
override fun getPreferredSize(): Dimension {
return textField.preferredSize
}
override fun doLayout() {
super.doLayout()
textField.setBounds(0, 0, width, height)
if (button != null) {
val preferredButtonSize = button.preferredSize
button.setBounds(width - preferredButtonSize.width, height - preferredButtonSize.height,
preferredButtonSize.width, preferredButtonSize.height)
}
if (busyLabel != null) {
busyLabel.bounds = SingleComponentCenteringLayout.getBoundsForCentered(textField, busyLabel)
}
}
}
layeredPane.add(textField, JLayeredPane.DEFAULT_LAYER, 0)
var index = 1
if (busyLabel != null) {
layeredPane.add(busyLabel, JLayeredPane.POPUP_LAYER, index)
index++
}
if (button != null) {
layeredPane.add(button, JLayeredPane.POPUP_LAYER, index)
}
return layeredPane
} | 191 | null | 4372 | 13,319 | 4d19d247824d8005662f7bd0c03f88ae81d5364b | 9,884 | intellij-community | Apache License 2.0 |
arrow-libs/fx/arrow-fx-coroutines/src/test/kotlin/arrow/fx/coroutines/stream/Counter.kt | clojj | 343,913,289 | true | {"Kotlin": 6274993, "SCSS": 78040, "JavaScript": 77812, "HTML": 21200, "Scala": 8073, "Shell": 2474, "Ruby": 83} | package arrow.fx.coroutines.stream
import arrow.fx.coroutines.Atomic
class Counter private constructor(private val atomic: Atomic<Int>) {
suspend fun increment(): Unit =
atomic.update(Int::inc)
suspend fun decrement(): Unit =
atomic.update(Int::dec)
suspend fun count(): Int =
atomic.get()
companion object {
suspend operator fun invoke(): Counter =
Counter(Atomic(0))
}
}
| 0 | null | 0 | 0 | 5eae605bbaeb2b911f69a5bccf3fa45c42578416 | 411 | arrow | Apache License 2.0 |
src/main/kotlin/no/nav/syfo/consumer/PdlConsumer.kt | navikt | 303,972,532 | false | null | package no.nav.syfo.consumer
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.*
import io.ktor.client.features.json.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import io.ktor.http.*
import kotlinx.coroutines.runBlocking
import no.nav.syfo.CommonEnvironment
import no.nav.syfo.auth.StsConsumer
import no.nav.syfo.consumer.pdl.*
import org.slf4j.LoggerFactory
open class PdlConsumer(env: CommonEnvironment, stsConsumer: StsConsumer) {
private val client: HttpClient
private val stsConsumer: StsConsumer
private val pdlBasepath: String
private val log = LoggerFactory.getLogger("no.nav.syfo.consumer.PdlConsuner")
init {
client = HttpClient(CIO) {
expectSuccess = false
install(JsonFeature) {
serializer = JacksonSerializer {
registerKotlinModule()
registerModule(JavaTimeModule())
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
}
}
}
this.stsConsumer = stsConsumer
pdlBasepath = env.pdlUrl
}
open fun getFnr(aktorId: String): String? {
val response = callPdl(IDENTER_QUERY, aktorId)
return when (response?.status) {
HttpStatusCode.OK -> {
runBlocking { response.receive<PdlIdentResponse>().data?.hentIdenter?.identer?.first()?.ident }
}
HttpStatusCode.NoContent -> {
log.error("Could not get fnr from PDL: No content found in the response body")
null
}
HttpStatusCode.Unauthorized -> {
log.error("Could not get fnr from PDL: Unable to authorize")
null
}
else -> {
log.error("Could not get fnr from PDL: $response")
null
}
}
}
fun isBrukerGradertForInformasjon(aktorId: String): Boolean? {
val response = callPdl(PERSON_QUERY, aktorId)
return when (response?.status) {
HttpStatusCode.OK -> {
runBlocking { response.receive<PdlPersonResponse>().data?.isKode6Eller7() }
}
HttpStatusCode.NoContent -> {
log.error("Could not get adressesperre from PDL: No content found in the response body")
null
}
HttpStatusCode.Unauthorized -> {
log.error("Could not get adressesperre from PDL: Unable to authorize")
null
}
else -> {
log.error("Could not get adressesperre from PDL: $response")
null
}
}
}
fun callPdl(service: String, aktorId: String): HttpResponse? {
return runBlocking {
val stsToken = stsConsumer.getToken()
val bearerTokenString = "Bearer ${stsToken.access_token}"
val graphQuery = this::class.java.getResource("$QUERY_PATH_PREFIX/$service").readText().replace("[\n\r]", "")
val requestBody = PdlRequest(graphQuery, Variables(aktorId))
try {
client.post<HttpResponse>(pdlBasepath) {
headers {
append(TEMA_HEADER, OPPFOLGING_TEMA_HEADERVERDI)
append(HttpHeaders.ContentType, ContentType.Application.Json)
append(HttpHeaders.Authorization, bearerTokenString)
append(NAV_CONSUMER_TOKEN_HEADER, bearerTokenString)
}
body = requestBody
}
} catch (e: Exception) {
log.error("Error while calling PDL ($service): ${e.message}", e)
null
}
}
}
}
class LocalPdlConsumer(env: CommonEnvironment, stsConsumer: StsConsumer): PdlConsumer(env, stsConsumer) {
override fun getFnr(aktorId: String): String {
return aktorId.substring(0,11)
}
}
| 1 | Kotlin | 0 | 0 | 60f1af7bc7582eb1d7531172179b0831581440d7 | 4,210 | esyfovarsel | MIT License |
compiler/testData/codegen/box/functions/bigArity/callFunViaVararg.kt | JetBrains | 3,432,266 | false | null | // !LANGUAGE: +FunctionTypesWithBigArity
// WITH_STDLIB
// TARGET_BACKEND: JVM
// FILE: J.java
// import kotlin.jvm.functions.Arity;
import kotlin.jvm.functions.FunctionN;
import kotlin.Unit;
import java.util.Arrays;
public class J {
// TODO: uncomment arity as soon as Arity is introduced
public static void test(/* @Arity(30) */ FunctionN<Integer> f) {
Object o = new Integer(0);
for (int i = 0; i < 42; i++) {
Object[] args = new Object[i];
Arrays.fill(args, o);
try {
if (f.invoke(args).intValue() != 300 + i) {
throw new AssertionError("Bad return value from function");
}
} catch (IllegalArgumentException e) {
if (i == 30) {
throw new AssertionError(String.format("Call with %d arguments is expected to succeed", i), e);
}
// OK
if (!e.getMessage().contains("30")) {
throw new AssertionError("Exception must specify the expected number of arguments: " + e.getMessage(), e);
}
continue;
} catch (Throwable e) {
throw new AssertionError(
"Incorrect exception (IllegalArgumentException expected): " + e.getClass().getName() + ", i = " + i, e
);
}
if (i != 30) {
throw new AssertionError ("IllegalArgumentException expected, but nothing was thrown, i = " + i);
}
}
}
}
// FILE: K.kt
class Fun : (Int, Int, Int) -> Int,
(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int) -> Int,
(Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int,
Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int, Int) -> Int {
override fun invoke(p00: Int, p01: Int, p02: Int): Int = 303
override fun invoke(
p00: Int, p01: Int, p02: Int, p03: Int, p04: Int, p05: Int, p06: Int, p07: Int, p08: Int, p09: Int,
p10: Int, p11: Int, p12: Int
): Int = 313
override fun invoke(
p00: Int, p01: Int, p02: Int, p03: Int, p04: Int, p05: Int, p06: Int, p07: Int, p08: Int, p09: Int,
p10: Int, p11: Int, p12: Int, p13: Int, p14: Int, p15: Int, p16: Int, p17: Int, p18: Int, p19: Int,
p20: Int, p21: Int, p22: Int, p23: Int, p24: Int, p25: Int, p26: Int, p27: Int, p28: Int, p29: Int
): Int = 330
}
fun box(): String {
@Suppress("DEPRECATION_ERROR")
J.test(Fun() as kotlin.jvm.functions.FunctionN<Int>)
return "OK"
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 2,631 | kotlin | Apache License 2.0 |
app-elgoog/src/main/kotlin/dev/bogdanzurac/marp/app/elgoog/core/feature/FirebaseFeatureManager.kt | bogdanzurac | 606,411,511 | false | null | package dev.bogdanzurac.marp.app.elgoog.core.feature
import com.google.firebase.ktx.Firebase
import com.google.firebase.remoteconfig.FirebaseRemoteConfig
import com.google.firebase.remoteconfig.ktx.remoteConfig
import com.google.firebase.remoteconfig.ktx.remoteConfigSettings
import dev.bogdanzurac.marp.core.feature.Feature
import dev.bogdanzurac.marp.core.feature.FeatureManager
import dev.bogdanzurac.marp.core.feature.KeyFeature
import dev.bogdanzurac.marp.core.logger
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.filter
import org.koin.core.annotation.Singleton
import kotlin.time.Duration.Companion.minutes
@Singleton
class FirebaseFeatureManager : FeatureManager {
private val isReadyState: MutableStateFlow<Boolean> = MutableStateFlow(false)
private val remoteConfig: FirebaseRemoteConfig = Firebase.remoteConfig
init {
val configSettings = remoteConfigSettings {
minimumFetchIntervalInSeconds = 1.minutes.inWholeSeconds
}
remoteConfig.setConfigSettingsAsync(configSettings)
remoteConfig.fetchAndActivate()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val values = remoteConfig.all.mapValues { it.value.asBoolean() }
logger.d("Fetched RemoteConfig feature flags: $values")
} else {
logger.e(
"Error while fetching RemoteConfig feature flags",
task.exception?.cause!!
)
}
isReadyState.tryEmit(true)
}
}
override fun isReady(): Flow<Boolean> = isReadyState.filter { it }
/**
* Check to see if the requested [feature] is enabled.
*/
override fun isEnabled(feature: Feature): Boolean =
if (feature is KeyFeature) remoteConfig.getBoolean(feature.key)
else false
} | 0 | null | 0 | 1 | 9cc815c57d7b3948a5a20f12883dc4dbee7fc4b3 | 1,970 | marp-app-client-android | Apache License 2.0 |
korge-core/src/korlibs/image/color/RGB.kt | korlibs | 80,095,683 | false | null | package korlibs.image.color
import korlibs.memory.extract8
import korlibs.memory.insert8
open class RGB(val rOffset: Int, val gOffset: Int, val bOffset: Int) : ColorFormat24() {
override fun getR(v: Int): Int = v.extract8(rOffset)
override fun getG(v: Int): Int = v.extract8(gOffset)
override fun getB(v: Int): Int = v.extract8(bOffset)
override fun getA(v: Int): Int = 0xFF
override fun pack(r: Int, g: Int, b: Int, a: Int): Int = 0.insert8(r, rOffset).insert8(g, gOffset).insert8(b, bOffset)
companion object : RGB(rOffset = 0, gOffset = 8, bOffset = 16)
}
object BGR : RGB(rOffset = 16, gOffset = 8, bOffset = 0)
| 444 | null | 121 | 2,207 | dc3d2080c6b956d4c06f4bfa90a6c831dbaa983a | 627 | korge | Apache License 2.0 |
openapi-processor-core/src/test/kotlin/io/openapiprocessor/core/converter/OptionsConverterSpec.kt | openapi-processor | 547,758,502 | false | {"Kotlin": 867607, "Groovy": 171700, "Java": 118943, "ANTLR": 2598, "TypeScript": 1166, "Just": 263} | /*
* Copyright 2021 https://github.com/openapi-processor/openapi-processor-core
* PDX-License-Identifier: Apache-2.0
*/
package io.openapiprocessor.core.converter
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.booleans.shouldBeFalse
import io.kotest.matchers.booleans.shouldBeTrue
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import io.openapiprocessor.core.support.Empty
class OptionsConverterSpec: StringSpec({
"produces default options if input options are empty" {
val converter = OptionsConverter()
val options = converter.convertOptions(emptyMap())
options.targetDir shouldBe null
options.clearTargetDir.shouldBeTrue()
options.packageName shouldBe "io.openapiprocessor.generated"
options.beanValidation shouldBe false
options.javadoc shouldBe false
options.modelType shouldBe "default"
options.enumType shouldBe "default"
options.modelNameSuffix shouldBe String.Empty
options.pathPrefix shouldBe false
options.pathPrefixServerIndex shouldBe null
options.formatCode.shouldBeFalse()
options.globalMappings.shouldNotBeNull()
options.endpointMappings.shouldNotBeNull()
options.extensionMappings.shouldNotBeNull()
options.beanValidationValidOnReactive.shouldBeTrue()
options.identifierWordBreakFromDigitToLetter.shouldBeTrue()
}
"should set target dir" {
val converter = OptionsConverter()
val options = converter.convertOptions(mapOf(
"targetDir" to "generated target dir"
))
options.targetDir shouldBe "generated target dir"
}
"should accept deprecated packageName map option" {
val converter = OptionsConverter(true)
val options = converter.convertOptions(mapOf(
"packageName" to "obsolete"
))
options.packageName shouldBe "obsolete"
}
"should accept deprecated beanValidation map option" {
val converter = OptionsConverter(true)
val options = converter.convertOptions(mapOf(
"beanValidation" to true
))
options.beanValidation shouldBe true
}
"should accept deprecated typeMappings map option" {
val converter = OptionsConverter(true)
val options = converter.convertOptions(mapOf(
"typeMappings" to """
openapi-processor-mapping: v2
options:
package-name: generated
""".trimIndent()
))
options.packageName shouldBe "generated"
}
"should read Mapping options (new, v2)" {
val converter = OptionsConverter()
val options = converter.convertOptions(mapOf(
"mapping" to """
openapi-processor-mapping: v7
options:
clear-target-dir: false
package-name: generated
model-name-suffix: Suffix
model-type: record
enum-type: string
bean-validation: true
javadoc: true
format-code: false
compatibility:
bean-validation-valid-on-reactive: false
identifier-word-break-from-digit-to-letter: false
""".trimIndent()
))
options.clearTargetDir.shouldBeFalse()
options.packageName shouldBe "generated"
options.modelNameSuffix shouldBe "Suffix"
options.modelType shouldBe "record"
options.enumType shouldBe "string"
options.beanValidation shouldBe true
options.javadoc shouldBe true
options.formatCode.shouldBeFalse()
options.beanValidationValidOnReactive.shouldBeFalse()
options.identifierWordBreakFromDigitToLetter.shouldBeFalse()
}
data class BeanData(val source: String, val enabled: Boolean, val format: String?)
for (bd in listOf(
BeanData("false", false, null),
BeanData("true", true, "javax"),
BeanData("javax", true, "javax"),
BeanData("jakarta", true, "jakarta")
)) {
"should read bean validation & format: ${bd.source}" {
val converter = OptionsConverter()
val options = converter.convertOptions(mapOf(
"mapping" to """
openapi-processor-mapping: v3
options:
bean-validation: ${bd.source}
""".trimIndent()
))
options.beanValidation shouldBe bd.enabled
options.beanValidationFormat shouldBe bd.format
}
}
data class ServerUrlData(val source: String, val enabled: Boolean, val index: Int?)
for (su in listOf(
ServerUrlData("false", false, null),
ServerUrlData("true", true, 0),
ServerUrlData("0", true, 0),
ServerUrlData("1", true, 1)
)) {
"should read bean server-url: ${su.source}" {
val converter = OptionsConverter()
val options = converter.convertOptions(mapOf(
"mapping" to """
openapi-processor-mapping: v9
options:
package-name: no.warning
server-url: ${su.source}
""".trimIndent()
))
options.pathPrefix shouldBe su.enabled
options.pathPrefixServerIndex shouldBe su.index
}
}
})
| 10 | Kotlin | 3 | 2 | 5e97065608791bbb5846f752f221a0bfa30be92f | 5,517 | openapi-processor-base | Apache License 2.0 |
app/src/main/java/id/ac/undip/ce/student/muhammadrizqi/footballclub/model/Team.kt | muhrizky | 148,885,798 | false | null | package id.ac.undip.ce.student.muhammadrizqi.footballclub.model
import com.google.gson.annotations.SerializedName
data class Team (
@SerializedName("idTeam")
var teamId : String? = null,
@SerializedName("strTeam")
var teamName: String? = null,
@SerializedName("StrTeamBadge")
var teamBadge: String? =null,
@SerializedName("intFormedYear")
var teamFormedYear: String? = null,
@SerializedName("strStadium")
var teamStadium: String? = null,
@SerializedName("strDescriptionEN")
var teamDescription: String? = null
)
| 1 | null | 1 | 1 | ff86b9ab61befd68b567f7cdfdbaf904d82b54f2 | 567 | FootballClub-Latihan | MIT License |
compiler/frontend/src/org/jetbrains/jet/lang/psi/userDataUtil.kt | chashnikov | 14,658,474 | true | {"Java": 14526655, "Kotlin": 6831811, "JavaScript": 897073, "Groovy": 43935, "CSS": 14421, "Shell": 9248} | /*
* Copyright 2010-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jet.lang.psi
import kotlin.properties.ReadWriteProperty
import com.intellij.openapi.util.Key
public class UserDataProperty<T : Any>(val key: Key<T>) : ReadWriteProperty<JetFile, T?> {
override fun get(thisRef: JetFile, desc: kotlin.PropertyMetadata): T? {
return thisRef.getUserData(key)
}
override fun set(thisRef: JetFile, desc: kotlin.PropertyMetadata, value: T?) {
thisRef.putUserData(key, value)
}
} | 1 | Java | 1 | 1 | 88a261234860ff0014e3c2dd8e64072c685d442d | 1,063 | kotlin | Apache License 2.0 |
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/common/ArgsTests.kt | ColleenKeegan | 174,519,919 | false | {"Text": 22, "Ignore List": 25, "YAML": 1, "Markdown": 20, "Gradle": 44, "Shell": 27, "Batchfile": 27, "Java Properties": 17, "Kotlin": 690, "INI": 2, "Java": 4, "SQL": 1, "XML": 5, "HTML": 1, "CSS": 1, "JavaScript": 1, "Swift": 3} | /**
<slate_header>
url: www.slatekit.com
git: www.github.com/code-helix/slatekit
org: www.codehelix.co
author: Kishore Reddy
copyright: 2016 CodeHelix Solutions Inc.
license: refer to website and/or github
about: A Kotlin utility library, tool-kit and server backend.
mantra: Simplicity above all else
</slate_header>
*/
package test.common
/**
* Created by kishorereddy on 5/22/17.
*/
import org.junit.Test
import slatekit.common.args.Args
import slatekit.common.args.ArgsFuncs
import slatekit.results.Try
import slatekit.results.getOrElse
class ArgsTests {
@Test fun `can parse args with defaults2`(): Unit {
println("hello method")
}
@Test fun test_m1(){
`can parse args with defaults2`()
}
@Test fun can_parse_args_with_defaults() {
val result = Args.parse("-env:loc -log:info -region:ny")
ensure(result, true, 3, listOf(
Pair("env" , "loc" ),
Pair("log" , "info"),
Pair("region", "ny" )
))
}
@Test fun can_parse_args_with_custom_prefix_and_separator() {
val result = Args.parse("-env=loc -log=info -region=ny", "-", "=")
ensure(result, true, 3, listOf(
Pair("env" , "loc" ),
Pair("log" , "info"),
Pair("region", "ny" )
))
}
@Test fun can_parse_args_single_quotes() {
val result = Args.parse("-env='loc' -log='info' -region='ny'", "-", "=")
ensure(result, true, 3, listOf(
Pair("env" , "loc" ),
Pair("log" , "info"),
Pair("region", "ny" )
))
}
@Test fun can_parse_args_double_quotes() {
val result = Args.parse("-env=\"loc\" -log=\"info\" -region=\"ny\"", "-", "=")
ensure(result, true, 3, listOf(
Pair("env" , "loc" ),
Pair("log" , "info"),
Pair("region", "ny" )
))
}
@Test fun can_parse_args_with_dots() {
val result = Args.parse("-env.api='loc' -log.level='info' -region.api='ny'", "-", "=")
ensure(result, true, 3, listOf(
Pair("env.api" , "loc" ),
Pair("log.level" , "info"),
Pair("region.api", "ny" )
))
}
@Test fun can_parse_arg_values_with_decimals() {
val result = Args.parse("-env.api='loc' -eg.test=12.34", "-", "=")
ensure(result, true, 2, listOf(
Pair("env.api" , "loc" ),
Pair("eg.test" , "12.34" )
))
}
@Test fun can_parse_arg_values_with_decimals2() {
val result = Args.parse("-env.api='loc' -eg.test=12.34 -log.level='info'", "-", "=")
ensure(result, true, 3, listOf(
Pair("env.api" , "loc" ),
Pair("eg.test" , "12.34" ),
Pair("log.level" , "info")
))
}
@Test fun can_parse_arg_values_with_dots() {
val result = Args.parse("-num=12.34", "-", "=")
ensure(result, true, 1, listOf(
Pair("num" , "12.34" )
))
}
@Test fun can_parse_actions_with_args() {
val result = Args.parse("area.api.action -env.api='loc' -log.level='info' -region.api='ny'", "-", "=", true)
ensure(result, true, 3, listOf(
Pair("env.api" , "loc" ),
Pair("log.level" , "info"),
Pair("region.api", "ny" )
), null, null, listOf("area", "api", "action"))
}
@Test fun can_parse_meta_args() {
val result = Args.parse("area.api.action -env.api='loc' -log.level='info' @api.key='abc123'", "-", "=", true)
ensure(result, true, 2,
listOf(
Pair("env.api" , "loc" ),
Pair("log.level" , "info")
),
listOf(
Pair("api.key" , "abc123" )
),
null,
listOf("area", "api", "action")
)
}
@Test fun can_parse_sys_args() {
val result = Args.parse("area.api.action -env.api='loc' @api.key='abc123' \$format=json", "-", "=", true)
ensure(result, true, 1,
listOf(
Pair("env.api" , "loc" )
),
listOf(
Pair("api.key" , "abc123" )
),
listOf(
Pair("format" , "json" )
),
listOf("area", "api", "action")
)
}
@Test fun can_parse_sys_args_only() {
// app.reg.createSampleUser $command=sample
val result = Args.parse("area.api.action \$format=json", "-", "=", true)
ensure(result, true, 0,
listOf<Pair<String,String>>(),
listOf<Pair<String,String>>(),
listOf(
Pair("format" , "json" )
),
listOf("area", "api", "action")
)
}
// app.users.activate
@Test fun can_parse_actions_without_args() {
val result = Args.parse("area.api.action", "-", "=", true)
ensure(result, true, 0, listOf(), null, null, listOf("area", "api", "action"))
}
@Test fun is_meta_arg_with_help() {
assert( ArgsFuncs.isMetaArg(listOf("help" ), 0, "help", "info") )
assert( ArgsFuncs.isMetaArg(listOf("-help" ), 0, "help", "info") )
assert( ArgsFuncs.isMetaArg(listOf("--help"), 0, "help", "info") )
assert( ArgsFuncs.isMetaArg(listOf("/help" ), 0, "help", "info") )
assert( ArgsFuncs.isMetaArg(listOf("info" ), 0, "help", "info") )
assert( ArgsFuncs.isMetaArg(listOf("-info" ), 0, "help", "info") )
assert( ArgsFuncs.isMetaArg(listOf("--info"), 0, "help", "info") )
assert( ArgsFuncs.isMetaArg(listOf("/info" ), 0, "help", "info") )
assert( !ArgsFuncs.isMetaArg(listOf("/about" ), 0, "help", "info"))
}
@Test fun is_help_on_area() {
assert( ArgsFuncs.isHelp(listOf("app", "?"), 1) )
}
private fun ensure(result: Try<Args>, success:Boolean, size:Int,
expectedNamed:List<Pair<String,String>>,
expectedMeta:List<Pair<String,String>>? = null,
expectedSys:List<Pair<String,String>>? = null,
parts:List<String>? = null) : Unit {
// success / fail
assert( result.success == success )
val args = result.getOrElse { Args.default() }
// size
assert( args.size() == size)
// expected
for(item in expectedNamed){
assert( args.containsKey(item.first))
assert( args.getString(item.first) == item.second)
}
expectedMeta?.let { metaArgs ->
for((first, second) in metaArgs){
assert( args.containsMetaKey(first))
assert( args.getMetaString(first) == second)
}
}
expectedSys?.let { sysArgs ->
for((first, second) in sysArgs){
assert( args.containsSysKey(first))
assert( args.getSysString(first) == second)
}
}
parts?.let { p ->
if(p.isNotEmpty()){
assert(args.actionParts.size == p.size)
for(i in 0 .. p.size - 1){
val part = p[i]
assert( args.getVerb(i) == part)
}
}
}
}
} | 1 | null | 1 | 1 | bd1d55f2191f729149e901be102c22d7c719793d | 7,468 | slatekit | Apache License 2.0 |
backend/api/src/main/kotlin/io/tolgee/api/v2/controllers/suggestion/TranslationSuggestionController.kt | tolgee | 303,766,501 | false | null | package io.tolgee.api.v2.controllers.suggestion
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.tags.Tag
import io.tolgee.api.v2.hateoas.invitation.TranslationMemoryItemModelAssembler
import io.tolgee.constants.Message
import io.tolgee.dtos.request.SuggestRequestDto
import io.tolgee.exceptions.BadRequestException
import io.tolgee.exceptions.NotFoundException
import io.tolgee.hateoas.machineTranslation.SuggestResultModel
import io.tolgee.hateoas.translationMemory.TranslationMemoryItemModel
import io.tolgee.model.enums.Scope
import io.tolgee.model.key.Key
import io.tolgee.model.views.TranslationMemoryItemView
import io.tolgee.security.ProjectHolder
import io.tolgee.security.authentication.AllowApiAccess
import io.tolgee.security.authorization.RequiresProjectPermissions
import io.tolgee.service.LanguageService
import io.tolgee.service.key.KeyService
import io.tolgee.service.security.SecurityService
import io.tolgee.service.translation.TranslationMemoryService
import io.tolgee.util.disableAccelBuffering
import jakarta.validation.Valid
import org.springdoc.core.annotations.ParameterObject
import org.springframework.data.domain.Pageable
import org.springframework.data.web.PagedResourcesAssembler
import org.springframework.hateoas.PagedModel
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
@RestController
@CrossOrigin(origins = ["*"])
@RequestMapping(value = ["/v2/projects/{projectId:[0-9]+}/suggest", "/v2/projects/suggest"])
@Tag(name = "Translation suggestion")
@Suppress("SpringJavaInjectionPointsAutowiringInspection", "MVCPathVariableInspection")
class TranslationSuggestionController(
private val projectHolder: ProjectHolder,
private val languageService: LanguageService,
private val keyService: KeyService,
private val translationMemoryService: TranslationMemoryService,
private val translationMemoryItemModelAssembler: TranslationMemoryItemModelAssembler,
@Suppress("SpringJavaInjectionPointsAutowiringInspection")
private val arraytranslationMemoryItemModelAssembler: PagedResourcesAssembler<TranslationMemoryItemView>,
private val securityService: SecurityService,
private val machineTranslationSuggestionFacade: MachineTranslationSuggestionFacade,
) {
@PostMapping("/machine-translations")
@Operation(summary = "Suggests machine translations from enabled services")
@RequiresProjectPermissions([Scope.TRANSLATIONS_EDIT])
@AllowApiAccess
fun suggestMachineTranslations(
@RequestBody @Valid
dto: SuggestRequestDto,
): SuggestResultModel {
return machineTranslationSuggestionFacade.suggestSync(dto)
}
@PostMapping("/machine-translations-streaming", produces = ["application/x-ndjson"])
@Operation(
summary =
"Suggests machine translations from enabled services (streaming).\n" +
"If an error occurs when any of the services is used," +
" the error information is returned as a part of the result item, while the response has 200 status code.",
)
@RequiresProjectPermissions([Scope.TRANSLATIONS_EDIT])
@AllowApiAccess
fun suggestMachineTranslationsStreaming(
@RequestBody @Valid
dto: SuggestRequestDto,
): ResponseEntity<StreamingResponseBody> {
return ResponseEntity.ok().disableAccelBuffering().body(
machineTranslationSuggestionFacade.suggestStreaming(dto),
)
}
@PostMapping("/translation-memory")
@Operation(
summary =
"Suggests machine translations from translation memory." +
"\n\nThe result is always sorted by similarity, so sorting is not supported.",
)
@RequiresProjectPermissions([Scope.TRANSLATIONS_EDIT])
@AllowApiAccess
fun suggestTranslationMemory(
@RequestBody @Valid
dto: SuggestRequestDto,
@ParameterObject pageable: Pageable,
): PagedModel<TranslationMemoryItemModel> {
val targetLanguage = languageService.get(dto.targetLanguageId, projectHolder.project.id)
securityService.checkLanguageTranslatePermission(projectHolder.project.id, listOf(targetLanguage.id))
val data =
dto.baseText?.let { baseText -> translationMemoryService.suggest(baseText, targetLanguage, pageable) }
?: let {
val keyId = dto.keyId ?: throw BadRequestException(Message.KEY_NOT_FOUND)
val key = keyService.findOptional(keyId).orElseThrow { NotFoundException(Message.KEY_NOT_FOUND) }
key.checkInProject()
translationMemoryService.suggest(key, targetLanguage, pageable)
}
return arraytranslationMemoryItemModelAssembler.toModel(data, translationMemoryItemModelAssembler)
}
private fun Key.checkInProject() {
keyService.checkInProject(this, projectHolder.project.id)
}
}
| 170 | null | 96 | 1,837 | 6e01eec3a19c151a6e0aca49e187e2d0deef3082 | 5,050 | tolgee-platform | Apache License 2.0 |
app/src/main/java/com/realikea/weatherforecast/network/AirQuality.kt | iamrealikea | 678,456,521 | false | {"Kotlin": 106982} | package com.realikea.weatherforecast.network
import com.squareup.moshi.Json
data class AirQuality(
@field:Json(name = "co")
val co: Double,
val no2: Double,
val o3: Double,
val pm10: Double,
val pm2_5: Double,
val so2: Double,
//val usepaindex: Int
) | 0 | Kotlin | 0 | 1 | c39bea4492864f51b791aee2bdba90bc0df32259 | 284 | Weather_Forecast_Application | Apache License 2.0 |
app/src/main/java/com/blinkist/easylibrary/di/DatabaseInjection.kt | dungdung13 | 215,445,852 | true | {"Kotlin": 38853} | package com.blinkist.easylibrary.di
import android.content.Context
import androidx.room.Room
import com.blinkist.easylibrary.data.EasyLibraryDatabase
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module(includes = [DaoModule::class])
object DatabaseModule {
@JvmStatic @Provides @Singleton
fun provideDatabase(context: Context): EasyLibraryDatabase {
return Room.databaseBuilder(context, EasyLibraryDatabase::class.java, "easy-library").build()
}
}
@Module
object DaoModule {
@JvmStatic @Provides
fun provideBookDao(database: EasyLibraryDatabase) = database.bookDao()
}
| 0 | null | 0 | 0 | f3e8c4b6c4f2a8022633490bea80338044b7edd1 | 618 | easy-library | Apache License 2.0 |
core/src/main/java/rs/rocketbyte/wifisilencer/core/usecase/dnd/DndUseCase.kt | izpakla | 584,018,000 | false | null | package rs.rocketbyte.wifisilencer.core.usecase.dnd
interface DndUseCase {
fun isDndPermissionGranted(): Boolean
} | 0 | Kotlin | 0 | 0 | 4d75212f2ee904f1e0e6be7623179dd78351e2e1 | 119 | wifi-silencer | Apache License 2.0 |
threejs_kt/src/main/kotlin/three/TorusGeometry.module_three.kt | mihbor | 525,856,941 | false | null | @file:JsModule("three")
@file:JsNonModule
@file:Suppress("ABSTRACT_MEMBER_NOT_IMPLEMENTED", "VAR_TYPE_MISMATCH_ON_OVERRIDE", "INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "PackageDirectoryMismatch")
package three.js
import kotlin.js.*
external interface `T$31` {
var radius: Number
var tube: Number
var radialSegments: Number
var tubularSegments: Number
var arc: Number
}
open external class TorusGeometry(radius: Number = definedExternally, tube: Number = definedExternally, radialSegments: Number = definedExternally, tubularSegments: Number = definedExternally, arc: Number = definedExternally) : Geometry {
override var type: String
open var parameters: `T$31`
} | 0 | Kotlin | 0 | 0 | cf298738f1ede827308109cdbd06bf28176dce65 | 791 | miniverse | MIT License |
data-processor/src/test/kotlin/at/ac/tuwien/dse/ss18/group05/repository/AccidentRepositoryTest.kt | fuvidani | 128,628,639 | false | null | package at.ac.tuwien.dse.ss18.group05.repository
import at.ac.tuwien.dse.ss18.group05.DataProcessorApplication
import at.ac.tuwien.dse.ss18.group05.TestDataProvider
/* ktlint-disable no-wildcard-imports */
import at.ac.tuwien.dse.ss18.group05.dto.*
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.amqp.rabbit.core.RabbitAdmin
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.test.mock.mockito.MockBean
import org.springframework.data.mongodb.core.MongoTemplate
import org.springframework.test.context.junit4.SpringRunner
/**
* <h4>About this class</h4>
*
* <p>Description</p>
*
* @author <NAME>
* @version 1.0.0
* @since 1.0.0
*/
@RunWith(SpringRunner::class)
@SpringBootTest(value = ["application.yml"], classes = [DataProcessorApplication::class])
class AccidentRepositoryTest {
@Autowired
private lateinit var repository: LiveAccidentRepository
@Autowired
private lateinit var mongoTemplate: MongoTemplate
@Suppress("unused")
@MockBean
private lateinit var rabbitAdmin: RabbitAdmin
@Before
fun setUp() {
mongoTemplate.dropCollection(LiveAccident::class.java)
}
@Test
fun testSaveShouldAddIdAutomatically() {
val newOngoingAccident = TestDataProvider.testLiveAccident()
val savedAccident = repository.save(newOngoingAccident).block()
Assert.assertNotNull(savedAccident)
Assert.assertNotNull(savedAccident?.id)
Assert.assertEquals(newOngoingAccident.vehicleMetaData, savedAccident?.vehicleMetaData)
Assert.assertEquals(newOngoingAccident.location, savedAccident?.location)
Assert.assertEquals(newOngoingAccident.timestampOfAccident, savedAccident?.timestampOfAccident)
}
@Test
fun testSaveThroughVehicleDataRecord() {
val crashDataRecord = TestDataProvider.testVehicleDataRecordCrashTesla()
val savedAccident = repository.save(crashDataRecord.toDefaultLiveAccident()).block()
Assert.assertNotNull(savedAccident)
Assert.assertNotNull(savedAccident?.id)
Assert.assertEquals(crashDataRecord.metaData, savedAccident?.vehicleMetaData)
Assert.assertEquals(crashDataRecord.sensorInformation.location.lon, savedAccident?.location?.x)
Assert.assertEquals(crashDataRecord.sensorInformation.location.lat, savedAccident?.location?.y)
Assert.assertEquals(crashDataRecord.timestamp, savedAccident?.timestampOfAccident)
}
@Test
fun testLiveAccidentLifecycle() {
val crashDataRecord = TestDataProvider.testVehicleDataRecordCrashTesla()
val savedNewAccident = repository.save(crashDataRecord.toDefaultLiveAccident()).block()
Assert.assertNotNull(savedNewAccident)
Assert.assertNotNull(savedNewAccident?.id)
val accidentWithArrival = repository.save(savedNewAccident!!.withServiceArrival(15)).block()
Assert.assertNotNull(accidentWithArrival)
Assert.assertNotNull(accidentWithArrival?.id)
Assert.assertEquals(savedNewAccident.id, accidentWithArrival!!.id)
Assert.assertEquals(savedNewAccident.timestampOfAccident, accidentWithArrival.timestampOfAccident)
Assert.assertEquals(15L, accidentWithArrival.timestampOfServiceArrival)
val accidentWithSiteClearing = repository.save(accidentWithArrival.withSiteClearing(99)).block()
Assert.assertNotNull(accidentWithSiteClearing)
Assert.assertNotNull(accidentWithSiteClearing?.id)
Assert.assertEquals(accidentWithArrival.id, accidentWithSiteClearing!!.id)
Assert.assertEquals(accidentWithArrival.timestampOfAccident, accidentWithSiteClearing.timestampOfAccident)
Assert.assertEquals(
accidentWithArrival.timestampOfServiceArrival,
accidentWithSiteClearing.timestampOfServiceArrival
)
Assert.assertEquals(99L, accidentWithSiteClearing.timestampOfSiteClearing)
}
} | 0 | null | 2 | 2 | 21d0424a6a2f9ce230201a1f960619fdd14059c5 | 4,061 | autonomous-vehicle-data-processing | MIT License |
src/main/kotlin/net/forkk/greenstone/grpl/commands/StringCommands.kt | Forkk | 250,610,539 | false | null | package net.forkk.greenstone.grpl.commands
import net.forkk.greenstone.grpl.Context
import net.forkk.greenstone.grpl.IntVal
import net.forkk.greenstone.grpl.ListVal
import net.forkk.greenstone.grpl.StringVal
import net.forkk.greenstone.grpl.TypeError
import net.forkk.greenstone.grpl.ValueType
val StringCommands = CommandGroup(
"string",
"Commands for manipulating strings",
SliceCmd, FindCmd, RFindCCmd, ConcatCmd
)
object SliceCmd : Command("slice") {
override fun exec(ctx: Context) {
val end = ctx.stack.pop().asIntOrErr()
val start = ctx.stack.pop().asIntOrErr()
val v = ctx.stack.pop()
when (v) {
is StringVal -> ctx.stack.push(StringVal(v.v.substring(start, end)))
is ListVal -> ctx.stack.push(ListVal(v.lst.subList(start, end)))
else -> throw TypeError(v, arrayOf(ValueType.STRING, ValueType.LIST))
}
}
override val help: String
get() = "Pops a string or list, a start index, and an end index, and pushes a sub-string or " +
"sub-list defined by the start and end indices.\n" +
"Example: `\"Hello\" 1 4 slice` pushes \"ello\""
}
object FindCmd : Command("find") {
override fun exec(ctx: Context) {
val find = ctx.stack.pop()
val v = ctx.stack.pop()
when (v) {
is StringVal -> {
val findstr = find.asString()
ctx.stack.push(IntVal(v.v.indexOf(findstr)))
}
is ListVal -> ctx.stack.push(IntVal(v.lst.indexOf(find)))
else -> throw TypeError(v, arrayOf(ValueType.STRING, ValueType.LIST))
}
}
override val help: String
get() = "Pops a string or list, and a pattern string or element to find, and returns the " +
"index of the first occurrence of the given pattern or element in the list or string.\n" +
"Pushes -1 if no match could be found.\n" +
"EXample: `\"Hello hello\" \"ll\" find` pushes `2`"
}
object RFindCCmd : Command("rfind") {
override fun exec(ctx: Context) {
val find = ctx.stack.pop()
val v = ctx.stack.pop()
when (v) {
is StringVal -> {
val findstr = find.asString()
ctx.stack.push(IntVal(v.v.lastIndexOf(findstr)))
}
is ListVal -> ctx.stack.push(IntVal(v.lst.lastIndexOf(find)))
else -> throw TypeError(v, arrayOf(ValueType.STRING, ValueType.LIST))
}
}
override val help: String
get() = "Pops a string or list, and a pattern string or element to find, and returns the " +
"index of the last occurrence of the given pattern or element in the list or string.\n" +
"Pushes -1 if no match could be found.\n" +
"EXample: `\"Hello hello\" \"ll\" find` pushes `8`"
}
object ConcatCmd : Command("concat") {
override fun exec(ctx: Context) {
val b = ctx.stack.pop()
val a = ctx.stack.pop()
when (a) {
is StringVal -> ctx.stack.push(StringVal(a.v + b.asString()))
is ListVal -> ctx.stack.push(ListVal(a.lst + b.asListOrErr()))
else -> throw TypeError(a, arrayOf(ValueType.STRING, ValueType.LIST))
}
}
override val help: String
get() = "Pops two strings or lists and pushes the concatenation of the two.\n" +
"If one is a list and the other a string, or either is some other type, raises a type error."
}
| 1 | Kotlin | 1 | 3 | 6f0eb5483af1586751db1501c32bde845d62663e | 3,528 | Greenstone | MIT License |
src/main/java/io/github/mdsimmo/bomberman/events/BmPlayerWonEvent.kt | mdsimmo | 21,511,109 | false | {"Kotlin": 257371, "Java": 4283} | package io.github.mdsimmo.bomberman.events
import io.github.mdsimmo.bomberman.game.Game
import org.bukkit.entity.Player
import org.bukkit.event.HandlerList
class BmPlayerWonEvent(val game: Game, val player: Player) : BmEvent() {
override fun getHandlers(): HandlerList {
return handlerList
}
companion object {
@JvmStatic
val handlerList = HandlerList()
}
} | 12 | Kotlin | 7 | 3 | 6703100a298c2543098440eded52d7bf12412c39 | 402 | bomberman | The Unlicense |
src/test/kotlin/no/nav/helse/flex/fss/proxy/modiacontext/ModiacontextControllerTest.kt | navikt | 316,526,205 | false | null | package no.nav.helse.flex.fss.proxy.modiacontext
import no.nav.helse.flex.fss.proxy.Application
import no.nav.security.mock.oauth2.MockOAuth2Server
import no.nav.security.mock.oauth2.token.DefaultOAuth2TokenCallback
import no.nav.security.token.support.spring.test.EnableMockOAuth2Server
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.test.web.client.ExpectedCount.once
import org.springframework.test.web.client.MockRestServiceServer
import org.springframework.test.web.client.match.MockRestRequestMatchers
import org.springframework.test.web.client.match.MockRestRequestMatchers.header
import org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo
import org.springframework.test.web.client.response.MockRestResponseCreators
import org.springframework.test.web.servlet.MockMvc
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get
import org.springframework.test.web.servlet.result.MockMvcResultMatchers
import org.springframework.web.client.RestTemplate
import org.springframework.web.context.WebApplicationContext
import java.net.URI
@SpringBootTest(classes = [Application::class], webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@EnableMockOAuth2Server
@AutoConfigureMockMvc
class ModiacontextControllerTest {
@Autowired
private lateinit var webApplicationContext: WebApplicationContext
@Autowired
private lateinit var server: MockOAuth2Server
@Autowired
private lateinit var mockMvc: MockMvc
@Autowired
private lateinit var plainRestTemplate: RestTemplate
private lateinit var mockServer: MockRestServiceServer
@BeforeEach
fun init() {
mockServer = MockRestServiceServer.createServer(plainRestTemplate)
}
@Test
fun `ingen token returnerer 401`() {
mockMvc.perform(
get("/modiacontextholder/api/context/aktivbruker")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(MockMvcResultMatchers.status().isUnauthorized)
.andReturn()
mockServer.verify()
}
@Test
fun `riktig token returnerer 200`() {
val cookie = "KAKEHEADER"
val xauth = "Bearer <PASSWORD>"
mockServer.expect(
once(),
requestTo(URI("http://modiacontexthodler/modiacontextholder/api/context/aktivbruker"))
)
.andExpect(MockRestRequestMatchers.method(HttpMethod.GET))
.andExpect(header("cookie", cookie))
.andExpect(header("authorization", xauth))
.andRespond(
MockRestResponseCreators.withStatus(HttpStatus.OK)
.contentType(MediaType.APPLICATION_JSON)
.body("{\"hei\": 23}")
)
mockMvc.perform(
get("/modiacontextholder/api/context/aktivbruker")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + token())
.header("xauthorization", xauth)
.header("cookie", cookie)
)
.andExpect(MockMvcResultMatchers.status().isOk)
.andReturn()
}
@Test
fun `feil client returnerer 403`() {
mockMvc.perform(
get("/modiacontextholder/api/context/aktivbruker")
.contentType(MediaType.APPLICATION_JSON)
.header("Authorization", "Bearer " + token(clientId = "en-annen-client"))
)
.andExpect(MockMvcResultMatchers.status().isForbidden)
.andReturn()
mockServer.verify()
}
private fun token(
issuerId: String = "aad",
clientId: String = "spinnsyn-frontend-interne-client-id",
subject: String = "Samme det",
audience: List<String> = listOf("flex-fss-proxy")
): String {
return server.issueToken(
issuerId,
clientId,
DefaultOAuth2TokenCallback(
issuerId = issuerId,
subject = subject,
audience = audience,
expiry = 3600
)
).serialize()
}
}
| 7 | Kotlin | 0 | 0 | cf621f446ff4e3f61041cd46b46eceba5523d7e0 | 4,486 | flex-fss-proxy | MIT License |
src/main/kotlin/com/lykke/matching/engine/utils/config/GrpcEndpoints.kt | MyJetWallet | 334,417,928 | true | {"Kotlin": 1903525, "Java": 39278} | package com.lykke.matching.engine.utils.config
data class GrpcEndpoints(
val cashApiServicePort: Int,
val tradingApiServicePort: Int,
val balancesServicePort: Int,
val orderBooksServicePort: Int,
val dictionariesConnection: String,
val outgoingEventsConnections: Set<String>,
val outgoingTrustedClientsEventsConnections: Set<String>,
val publishTimeout: Long,
) | 0 | Kotlin | 1 | 0 | fad1a43743bd7b833bfa4f1490da5e5350b992ff | 395 | MatchingEngine | MIT License |
demo-native/src/main/kotlin/kodein/demo/coffee/ElectricHeater.kt | suclike | 123,946,819 | true | {"Kotlin": 367343, "Java": 15376, "Shell": 723, "HTML": 718} | package kodein.demo.coffee
//import com.github.salomonbrys.kodein.Kodein
//import com.github.salomonbrys.kodein.erased.bind
//import com.github.salomonbrys.kodein.erased.singleton
class ElectricHeater : Heater {
private var heating: Boolean = false
init {
println("<Creating ElectricHeater>")
}
override fun on() {
println("~ ~ ~ heating ~ ~ ~")
this.heating = true
}
override fun off() {
println(". . . cooling . . .")
this.heating = false
}
override val isHot: Boolean get() = heating
}
//val electricHeaterModule = Kodein.Module {
// bind<Heater>() with singleton { ElectricHeater() }
//}
| 0 | Kotlin | 0 | 0 | 734f09ba0e8d80046beec92f29c928b46a4dfd23 | 674 | Kodein | MIT License |
app/src/main/java/fr/free/nrw/commons/explore/depictions/DepictsClient.kt | commons-app | 42,032,884 | false | null | package fr.free.nrw.commons.explore.depictions
import android.annotation.SuppressLint
import fr.free.nrw.commons.mwapi.Binding
import fr.free.nrw.commons.mwapi.SparqlResponse
import fr.free.nrw.commons.upload.depicts.DepictsInterface
import fr.free.nrw.commons.upload.structure.depictions.DepictedItem
import fr.free.nrw.commons.upload.structure.depictions.get
import fr.free.nrw.commons.wikidata.WikidataProperties
import fr.free.nrw.commons.wikidata.model.DataValue
import fr.free.nrw.commons.wikidata.model.DepictSearchItem
import fr.free.nrw.commons.wikidata.model.Entities
import fr.free.nrw.commons.wikidata.model.Statement_partial
import io.reactivex.Single
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/**
* Depicts Client to handle custom calls to Commons Wikibase APIs
*/
@Singleton
class DepictsClient @Inject constructor(private val depictsInterface: DepictsInterface) {
/**
* Search for depictions using the search item
* @return list of depicted items
*/
fun searchForDepictions(query: String?, limit: Int, offset: Int): Single<List<DepictedItem>> {
val language = Locale.getDefault().language
return depictsInterface.searchForDepicts(query, "$limit", language, language, "$offset")
.map { it.search.joinToString("|", transform = DepictSearchItem::id) }
.mapToDepictions()
}
fun getEntities(ids: String): Single<Entities> {
return depictsInterface.getEntities(ids)
}
fun toDepictions(sparqlResponse: Single<SparqlResponse>): Single<List<DepictedItem>> {
return sparqlResponse.map {
it.results.bindings.joinToString("|", transform = Binding::id)
}.mapToDepictions()
}
/**
* Fetches Entities from ids ex. "Q1233|Q546" and converts them into DepictedItem
*/
@SuppressLint("CheckResult")
private fun Single<String>.mapToDepictions() =
flatMap(::getEntities)
.map { entities ->
entities.entities().values.map { entity ->
mapToDepictItem(entity)
}
}
/**
* Convert different entities into DepictedItem
*/
private fun mapToDepictItem(entity: Entities.Entity): DepictedItem {
return if (entity.descriptions().byLanguageOrFirstOrEmpty() == "") {
val instanceOfIDs = entity[WikidataProperties.INSTANCE_OF]
.toIds()
if (instanceOfIDs.isNotEmpty()) {
val entities: Entities = getEntities(instanceOfIDs[0]).blockingGet()
val nameAsDescription = entities.entities().values.first().labels()
.byLanguageOrFirstOrEmpty()
DepictedItem(
entity,
entity.labels().byLanguageOrFirstOrEmpty(),
nameAsDescription
)
} else {
DepictedItem(
entity,
entity.labels().byLanguageOrFirstOrEmpty(),
""
)
}
} else {
DepictedItem(
entity,
entity.labels().byLanguageOrFirstOrEmpty(),
entity.descriptions().byLanguageOrFirstOrEmpty()
)
}
}
/**
* Tries to get Entities.Label by default language from the map.
* If that returns null, Tries to retrieve first element from the map.
* If that still returns null, function returns "".
*/
private fun Map<String, Entities.Label>.byLanguageOrFirstOrEmpty() =
let {
it[Locale.getDefault().language] ?: it.values.firstOrNull() }?.value() ?: ""
/**
* returns list of id ex. "Q2323" from Statement_partial
*/
private fun List<Statement_partial>?.toIds(): List<String> {
return this?.map { it.mainSnak.dataValue }
?.filterIsInstance<DataValue.EntityId>()
?.map { it.value.id }
?: emptyList()
}
}
| 571 | null | 953 | 997 | 93f1e1ec299a78dac8a013ea21414272c1675e7b | 3,987 | apps-android-commons | Apache License 2.0 |
android/racehorse/src/main/java/org/racehorse/AssetLoaderPlugin.kt | smikhalevski | 556,915,160 | false | {"Kotlin": 225363, "TypeScript": 144714, "JavaScript": 1955, "HTML": 23} | package org.racehorse
import android.content.Intent
import android.webkit.WebResourceResponse
import androidx.activity.ComponentActivity
import androidx.annotation.WorkerThread
import androidx.webkit.WebViewAssetLoader
import androidx.webkit.WebViewAssetLoader.PathHandler
import org.greenrobot.eventbus.Subscribe
import org.racehorse.utils.guessIntentAction
import org.racehorse.utils.launchActivity
import org.racehorse.webview.ShouldInterceptRequestEvent
import org.racehorse.webview.ShouldOverrideUrlLoadingEvent
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLConnection
import java.util.TreeMap
/**
* Intercepts requests and serves the responses using an registered asset loaders.
*
* @param activity The activity that starts the external app if no asset loaders can handle the intercepted URL.
*/
open class AssetLoaderPlugin(private val activity: ComponentActivity) {
/**
* If `true` then URLs that cannot be handled by registered asset loaders are opened in an external browser app.
*/
var isUnhandledRequestOpenedInExternalBrowser = true
private val assetLoaders = LinkedHashSet<WebViewAssetLoader>()
/**
* Registers the new asset loader.
*/
fun registerAssetLoader(assetLoader: WebViewAssetLoader) = assetLoaders.add(assetLoader)
/**
* Registers the new asset loader that uses the handler for a given URL.
*/
fun registerAssetLoader(url: String, handler: PathHandler) = registerAssetLoader(URL(url), handler)
/**
* Registers the new asset loader that uses the handler for a given URL.
*/
fun registerAssetLoader(url: URL, handler: PathHandler) {
registerAssetLoader(
WebViewAssetLoader.Builder()
.setHttpAllowed(url.protocol == "http")
.setDomain(url.authority)
.addPathHandler(url.path.ifEmpty { "/" }, handler)
.build()
)
}
/**
* Unregisters previously registered handler.
*/
fun unregisterAssetLoader(assetLoader: WebViewAssetLoader) = assetLoaders.remove(assetLoader)
@Subscribe
open fun onShouldInterceptRequest(event: ShouldInterceptRequestEvent) {
if (event.response == null) {
event.response = assetLoaders.firstNotNullOfOrNull { it.shouldInterceptRequest(event.request.url) }
}
}
@Subscribe
open fun onShouldOverrideUrlLoading(event: ShouldOverrideUrlLoadingEvent) {
val url = event.request.url
if (
isUnhandledRequestOpenedInExternalBrowser &&
assetLoaders.all { it.shouldInterceptRequest(url) == null } &&
event.shouldHandle()
) {
activity.launchActivity(Intent(url.guessIntentAction(), url).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
}
}
}
/**
* The path handler that loads static assets from a given directory.
*
* @param baseDir The directory on the device from which files are served.
* @param indexFileName The name of the index file to look for if handled path is a directory.
*/
open class StaticPathHandler(
private val baseDir: File,
private val indexFileName: String = "index.html"
) : PathHandler {
private val baseDirPath = baseDir.canonicalPath
@WorkerThread
override fun handle(path: String): WebResourceResponse {
var file = File(baseDir, path)
if (file.canonicalPath.startsWith(baseDirPath)) {
if (file.isDirectory) {
file = File(file, indexFileName)
}
if (file.isFile && file.canRead()) {
val mimeType = URLConnection.guessContentTypeFromName(path)
return WebResourceResponse(mimeType, null, FileInputStream(file))
}
}
return WebResourceResponse(null, null, null)
}
}
/**
* Redirects content from the given URL.
*/
open class ProxyPathHandler(private val baseUrl: URL) : PathHandler {
constructor(baseUrl: String) : this(URL(baseUrl))
override fun handle(path: String): WebResourceResponse {
val connection = openConnection(path)
val headers = connection.headerFields
.toMutableMap()
.apply { remove(null) }
.mapValuesTo(TreeMap(String.CASE_INSENSITIVE_ORDER)) { it.value.joinToString("; ") }
headers.remove("Content-Type")
headers.remove("Content-Length")
val mimeType = connection.contentType?.substringBefore(';')
val inputStream = try {
connection.inputStream
} catch (_: IOException) {
null
}
return WebResourceResponse(
mimeType,
connection.contentEncoding,
connection.responseCode,
connection.responseMessage,
headers,
inputStream
)
}
open fun openConnection(path: String): HttpURLConnection {
val connection = URL(baseUrl, path).openConnection() as HttpURLConnection
connection.instanceFollowRedirects = true
connection.connectTimeout = 10_000
return connection
}
}
| 1 | Kotlin | 1 | 3 | c4be3b6e180ebe3ddebdd0482a5c26c6aec298b8 | 5,190 | racehorse | MIT License |
app/src/androidTest/java/com/example/ghostmst/foodtoday/ExampleInstrumentedTest.kt | gitter-badger | 102,723,578 | false | null | package com.example.ghostmst.foodtoday
import android.content.Context
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumentation test, which will execute on an Android device.
*
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
@Throws(Exception::class)
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.example.ghostmst.foodtoday", appContext.getPackageName())
}
}
| 0 | Kotlin | 0 | 0 | 5114476a871b4e4ea4a64753ae8948071ad2af28 | 631 | food-today | MIT License |
src/commonMain/kotlin/io/github/devngho/kisopenapi/requests/response/LiveResponse.kt | devngho | 565,833,597 | false | null | package io.github.devngho.kisopenapi.requests.response
import io.github.devngho.kisopenapi.requests.util.ResultCodeSerializer
import io.github.devngho.kisopenapi.requests.util.YNSerializer
import io.github.devngho.kisopenapi.requests.util.json
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
@Serializable
data class LiveResponse(
val header: LiveResponseHeader?,
val body: LiveResponseBody?,
val output: LiveResponseBodyOutput?
)
@Serializable
data class LiveResponseHeader(
@SerialName("tr_id") val tradeId: String?,
@SerialName("tr_key") val tradeKey: String?,
@SerialName("encrypt") @Serializable(with = YNSerializer::class) val isEncrypted: Boolean?
)
@Serializable
data class LiveResponseBody(
@SerialName("rt_cd") @Serializable(with = ResultCodeSerializer::class) val isOk: Boolean?,
@SerialName("msg_cd") val code: String?,
@SerialName("msg1") val msg: String?,
@SerialName("output") val output: LiveResponseBodyOutput?
)
@Serializable
data class LiveResponseBodyOutput(
@SerialName("iv") val iv: String?,
@SerialName("key") val key: String?,
)
@Serializable
data class LiveCallBody(
val header: LiveCallHeader,
val body: LiveCallBodyBody
) {
companion object {
fun buildCallBody(token: String, consumerType: String, trId: String, trKey: String, trType: String) =
LiveCallBody(
LiveCallHeader(
token,
consumerType,
trType,
"utf-8"
),
LiveCallBodyBody(
LiveCallBodyInput(
trId,
trKey
)
)
).let { json.encodeToString(it) }
}
}
@Serializable
data class LiveCallHeader(
@SerialName("approval_key") val approvalKey: String,
@Suppress("SpellCheckingInspection") @SerialName("custtype") val consumerType: String,
@SerialName("tr_type") val trType: String,
@SerialName("content-type") val contentType: String
)
@Serializable
data class LiveCallBodyBody(
val input: LiveCallBodyInput
)
@Serializable
data class LiveCallBodyInput(
@SerialName("tr_id") val trId: String,
@SerialName("tr_key") val trKey: String
) | 0 | null | 1 | 7 | 9f95e79dcfc53340fcf202a6106876b02eb067e5 | 2,352 | kt_kisopenapi | MIT License |
acornui-core/src/main/kotlin/com/acornui/google/Icons.kt | polyforest | 82,695,679 | false | null | /*
* Copyright 2020 Poly Forest, 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.
*/
@file:Suppress("unused")
package com.acornui.google
import com.acornui.component.ComponentInit
import com.acornui.component.UiComponentImpl
import com.acornui.component.WithNode
import com.acornui.component.span
import com.acornui.component.style.CommonStyleTags
import com.acornui.component.style.CssClass
import com.acornui.component.style.cssClass
import com.acornui.di.Context
import com.acornui.dom.*
import com.acornui.google.IconButtonStyle.iconButton
import com.acornui.google.MaterialIconsCss.materialIconsStyleTag
import com.acornui.properties.afterChange
import com.acornui.skins.CssProps
import org.w3c.dom.HTMLElement
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
/**
* A list of icons provided by Google's material design icon set.
* https://material.io/resources/icons
*/
object Icons {
const val ROTATION_3D = 0xe84d
const val AC_UNIT = 0xeb3b
const val ACCESS_ALARM = 0xe190
const val ACCESS_ALARMS = 0xe191
const val ACCESS_TIME = 0xe192
const val ACCESSIBILITY = 0xe84e
const val ACCESSIBLE = 0xe914
const val ACCOUNT_BALANCE = 0xe84f
const val ACCOUNT_BALANCE_WALLET = 0xe850
const val ACCOUNT_BOX = 0xe851
const val ACCOUNT_CIRCLE = 0xe853
const val ADB = 0xe60e
const val ADD = 0xe145
const val ADD_A_PHOTO = 0xe439
const val ADD_ALARM = 0xe193
const val ADD_ALERT = 0xe003
const val ADD_BOX = 0xe146
const val ADD_CIRCLE = 0xe147
const val ADD_CIRCLE_OUTLINE = 0xe148
const val ADD_LOCATION = 0xe567
const val ADD_SHOPPING_CART = 0xe854
const val ADD_TO_PHOTOS = 0xe39d
const val ADD_TO_QUEUE = 0xe05c
const val ADJUST = 0xe39e
const val AIRLINE_SEAT_FLAT = 0xe630
const val AIRLINE_SEAT_FLAT_ANGLED = 0xe631
const val AIRLINE_SEAT_INDIVIDUAL_SUITE = 0xe632
const val AIRLINE_SEAT_LEGROOM_EXTRA = 0xe633
const val AIRLINE_SEAT_LEGROOM_NORMAL = 0xe634
const val AIRLINE_SEAT_LEGROOM_REDUCED = 0xe635
const val AIRLINE_SEAT_RECLINE_EXTRA = 0xe636
const val AIRLINE_SEAT_RECLINE_NORMAL = 0xe637
const val AIRPLANEMODE_ACTIVE = 0xe195
const val AIRPLANEMODE_INACTIVE = 0xe194
const val AIRPLAY = 0xe055
const val AIRPORT_SHUTTLE = 0xeb3c
const val ALARM = 0xe855
const val ALARM_ADD = 0xe856
const val ALARM_OFF = 0xe857
const val ALARM_ON = 0xe858
const val ALBUM = 0xe019
const val ALL_INCLUSIVE = 0xeb3d
const val ALL_OUT = 0xe90b
const val ANDROID = 0xe859
const val ANNOUNCEMENT = 0xe85a
const val APPS = 0xe5c3
const val ARCHIVE = 0xe149
const val ARROW_BACK = 0xe5c4
const val ARROW_DOWNWARD = 0xe5db
const val ARROW_DROP_DOWN = 0xe5c5
const val ARROW_DROP_DOWN_CIRCLE = 0xe5c6
const val ARROW_DROP_UP = 0xe5c7
const val ARROW_FORWARD = 0xe5c8
const val ARROW_UPWARD = 0xe5d8
const val ART_TRACK = 0xe060
const val ASPECT_RATIO = 0xe85b
const val ASSESSMENT = 0xe85c
const val ASSIGNMENT = 0xe85d
const val ASSIGNMENT_IND = 0xe85e
const val ASSIGNMENT_LATE = 0xe85f
const val ASSIGNMENT_RETURN = 0xe860
const val ASSIGNMENT_RETURNED = 0xe861
const val ASSIGNMENT_TURNED_IN = 0xe862
const val ASSISTANT = 0xe39f
const val ASSISTANT_PHOTO = 0xe3a0
const val ATTACH_FILE = 0xe226
const val ATTACH_MONEY = 0xe227
const val ATTACHMENT = 0xe2bc
const val AUDIOTRACK = 0xe3a1
const val AUTORENEW = 0xe863
const val AV_TIMER = 0xe01b
const val BACKSPACE = 0xe14a
const val BACKUP = 0xe864
const val BATTERY_ALERT = 0xe19c
const val BATTERY_CHARGING_FULL = 0xe1a3
const val BATTERY_FULL = 0xe1a4
const val BATTERY_STD = 0xe1a5
const val BATTERY_UNKNOWN = 0xe1a6
const val BEACH_ACCESS = 0xeb3e
const val BEENHERE = 0xe52d
const val BLOCK = 0xe14b
const val BLUETOOTH = 0xe1a7
const val BLUETOOTH_AUDIO = 0xe60f
const val BLUETOOTH_CONNECTED = 0xe1a8
const val BLUETOOTH_DISABLED = 0xe1a9
const val BLUETOOTH_SEARCHING = 0xe1aa
const val BLUR_CIRCULAR = 0xe3a2
const val BLUR_LINEAR = 0xe3a3
const val BLUR_OFF = 0xe3a4
const val BLUR_ON = 0xe3a5
const val BOOK = 0xe865
const val BOOKMARK = 0xe866
const val BOOKMARK_BORDER = 0xe867
const val BORDER_ALL = 0xe228
const val BORDER_BOTTOM = 0xe229
const val BORDER_CLEAR = 0xe22a
const val BORDER_COLOR = 0xe22b
const val BORDER_HORIZONTAL = 0xe22c
const val BORDER_INNER = 0xe22d
const val BORDER_LEFT = 0xe22e
const val BORDER_OUTER = 0xe22f
const val BORDER_RIGHT = 0xe230
const val BORDER_STYLE = 0xe231
const val BORDER_TOP = 0xe232
const val BORDER_VERTICAL = 0xe233
const val BRANDING_WATERMARK = 0xe06b
const val BRIGHTNESS_1 = 0xe3a6
const val BRIGHTNESS_2 = 0xe3a7
const val BRIGHTNESS_3 = 0xe3a8
const val BRIGHTNESS_4 = 0xe3a9
const val BRIGHTNESS_5 = 0xe3aa
const val BRIGHTNESS_6 = 0xe3ab
const val BRIGHTNESS_7 = 0xe3ac
const val BRIGHTNESS_AUTO = 0xe1ab
const val BRIGHTNESS_HIGH = 0xe1ac
const val BRIGHTNESS_LOW = 0xe1ad
const val BRIGHTNESS_MEDIUM = 0xe1ae
const val BROKEN_IMAGE = 0xe3ad
const val BRUSH = 0xe3ae
const val BUBBLE_CHART = 0xe6dd
const val BUG_REPORT = 0xe868
const val BUILD = 0xe869
const val BURST_MODE = 0xe43c
const val BUSINESS = 0xe0af
const val BUSINESS_CENTER = 0xeb3f
const val CACHED = 0xe86a
const val CAKE = 0xe7e9
const val CALL = 0xe0b0
const val CALL_END = 0xe0b1
const val CALL_MADE = 0xe0b2
const val CALL_MERGE = 0xe0b3
const val CALL_MISSED = 0xe0b4
const val CALL_MISSED_OUTGOING = 0xe0e4
const val CALL_RECEIVED = 0xe0b5
const val CALL_SPLIT = 0xe0b6
const val CALL_TO_ACTION = 0xe06c
const val CAMERA = 0xe3af
const val CAMERA_ALT = 0xe3b0
const val CAMERA_ENHANCE = 0xe8fc
const val CAMERA_FRONT = 0xe3b1
const val CAMERA_REAR = 0xe3b2
const val CAMERA_ROLL = 0xe3b3
const val CANCEL = 0xe5c9
const val CARD_GIFTCARD = 0xe8f6
const val CARD_MEMBERSHIP = 0xe8f7
const val CARD_TRAVEL = 0xe8f8
const val CASINO = 0xeb40
const val CAST = 0xe307
const val CAST_CONNECTED = 0xe308
const val CENTER_FOCUS_STRONG = 0xe3b4
const val CENTER_FOCUS_WEAK = 0xe3b5
const val CHANGE_HISTORY = 0xe86b
const val CHAT = 0xe0b7
const val CHAT_BUBBLE = 0xe0ca
const val CHAT_BUBBLE_OUTLINE = 0xe0cb
const val CHECK = 0xe5ca
const val CHECK_BOX = 0xe834
const val CHECK_BOX_OUTLINE_BLANK = 0xe835
const val CHECK_CIRCLE = 0xe86c
const val CHEVRON_LEFT = 0xe5cb
const val CHEVRON_RIGHT = 0xe5cc
const val CHILD_CARE = 0xeb41
const val CHILD_FRIENDLY = 0xeb42
const val CHROME_READER_MODE = 0xe86d
const val CLASS_ICON = 0xe86e
const val CLEAR = 0xe14c
const val CLEAR_ALL = 0xe0b8
const val CLOSE = 0xe5cd
const val CLOSED_CAPTION = 0xe01c
const val CLOUD = 0xe2bd
const val CLOUD_CIRCLE = 0xe2be
const val CLOUD_DONE = 0xe2bf
const val CLOUD_DOWNLOAD = 0xe2c0
const val CLOUD_OFF = 0xe2c1
const val CLOUD_QUEUE = 0xe2c2
const val CLOUD_UPLOAD = 0xe2c3
const val CODE = 0xe86f
const val COLLECTIONS = 0xe3b6
const val COLLECTIONS_BOOKMARK = 0xe431
const val COLOR_LENS = 0xe3b7
const val COLORIZE = 0xe3b8
const val COMMENT = 0xe0b9
const val COMPARE = 0xe3b9
const val COMPARE_ARROWS = 0xe915
const val COMPUTER = 0xe30a
const val CONFIRMATION_NUMBER = 0xe638
const val CONTACT_MAIL = 0xe0d0
const val CONTACT_PHONE = 0xe0cf
const val CONTACTS = 0xe0ba
const val CONTENT_COPY = 0xe14d
const val CONTENT_CUT = 0xe14e
const val CONTENT_PASTE = 0xe14f
const val CONTROL_POINT = 0xe3ba
const val CONTROL_POINT_DUPLICATE = 0xe3bb
const val COPYRIGHT = 0xe90c
const val CREATE = 0xe150
const val CREATE_NEW_FOLDER = 0xe2cc
const val CREDIT_CARD = 0xe870
const val CROP = 0xe3be
const val CROP_16_9 = 0xe3bc
const val CROP_3_2 = 0xe3bd
const val CROP_5_4 = 0xe3bf
const val CROP_7_5 = 0xe3c0
const val CROP_DIN = 0xe3c1
const val CROP_FREE = 0xe3c2
const val CROP_LANDSCAPE = 0xe3c3
const val CROP_ORIGINAL = 0xe3c4
const val CROP_PORTRAIT = 0xe3c5
const val CROP_ROTATE = 0xe437
const val CROP_SQUARE = 0xe3c6
const val DASHBOARD = 0xe871
const val DATA_USAGE = 0xe1af
const val DATE_RANGE = 0xe916
const val DEHAZE = 0xe3c7
const val DELETE = 0xe872
const val DELETE_FOREVER = 0xe92b
const val DELETE_SWEEP = 0xe16c
const val DESCRIPTION = 0xe873
const val DESKTOP_MAC = 0xe30b
const val DESKTOP_WINDOWS = 0xe30c
const val DETAILS = 0xe3c8
const val DEVELOPER_BOARD = 0xe30d
const val DEVELOPER_MODE = 0xe1b0
const val DEVICE_HUB = 0xe335
const val DEVICES = 0xe1b1
const val DEVICES_OTHER = 0xe337
const val DIALER_SIP = 0xe0bb
const val DIALPAD = 0xe0bc
const val DIRECTIONS = 0xe52e
const val DIRECTIONS_BIKE = 0xe52f
const val DIRECTIONS_BOAT = 0xe532
const val DIRECTIONS_BUS = 0xe530
const val DIRECTIONS_CAR = 0xe531
const val DIRECTIONS_RAILWAY = 0xe534
const val DIRECTIONS_RUN = 0xe566
const val DIRECTIONS_SUBWAY = 0xe533
const val DIRECTIONS_TRANSIT = 0xe535
const val DIRECTIONS_WALK = 0xe536
const val DISC_FULL = 0xe610
const val DNS = 0xe875
const val DO_NOT_DISTURB = 0xe612
const val DO_NOT_DISTURB_ALT = 0xe611
const val DO_NOT_DISTURB_OFF = 0xe643
const val DO_NOT_DISTURB_ON = 0xe644
const val DOCK = 0xe30e
const val DOMAIN = 0xe7ee
const val DONE = 0xe876
const val DONE_ALL = 0xe877
const val DONUT_LARGE = 0xe917
const val DONUT_SMALL = 0xe918
const val DRAFTS = 0xe151
const val DRAG_HANDLE = 0xe25d
const val DRIVE_ETA = 0xe613
const val DVR = 0xe1b2
const val EDIT = 0xe3c9
const val EDIT_LOCATION = 0xe568
const val EJECT = 0xe8fb
const val EMAIL = 0xe0be
const val ENHANCED_ENCRYPTION = 0xe63f
const val EQUALIZER = 0xe01d
const val ERROR = 0xe000
const val ERROR_OUTLINE = 0xe001
const val EURO_SYMBOL = 0xe926
const val EV_STATION = 0xe56d
const val EVENT = 0xe878
const val EVENT_AVAILABLE = 0xe614
const val EVENT_BUSY = 0xe615
const val EVENT_NOTE = 0xe616
const val EVENT_SEAT = 0xe903
const val EXIT_TO_APP = 0xe879
const val EXPAND_LESS = 0xe5ce
const val EXPAND_MORE = 0xe5cf
const val EXPLICIT = 0xe01e
const val EXPLORE = 0xe87a
const val EXPOSURE = 0xe3ca
const val EXPOSURE_NEG_1 = 0xe3cb
const val EXPOSURE_NEG_2 = 0xe3cc
const val EXPOSURE_PLUS_1 = 0xe3cd
const val EXPOSURE_PLUS_2 = 0xe3ce
const val EXPOSURE_ZERO = 0xe3cf
const val EXTENSION = 0xe87b
const val FACE = 0xe87c
const val FAST_FORWARD = 0xe01f
const val FAST_REWIND = 0xe020
const val FAVORITE = 0xe87d
const val FAVORITE_BORDER = 0xe87e
const val FEATURED_PLAY_LIST = 0xe06d
const val FEATURED_VIDEO = 0xe06e
const val FEEDBACK = 0xe87f
const val FIBER_DVR = 0xe05d
const val FIBER_MANUAL_RECORD = 0xe061
const val FIBER_NEW = 0xe05e
const val FIBER_PIN = 0xe06a
const val FIBER_SMART_RECORD = 0xe062
const val FILE_DOWNLOAD = 0xe2c4
const val FILE_UPLOAD = 0xe2c6
const val FILTER = 0xe3d3
const val FILTER_1 = 0xe3d0
const val FILTER_2 = 0xe3d1
const val FILTER_3 = 0xe3d2
const val FILTER_4 = 0xe3d4
const val FILTER_5 = 0xe3d5
const val FILTER_6 = 0xe3d6
const val FILTER_7 = 0xe3d7
const val FILTER_8 = 0xe3d8
const val FILTER_9 = 0xe3d9
const val FILTER_9_PLUS = 0xe3da
const val FILTER_B_AND_W = 0xe3db
const val FILTER_CENTER_FOCUS = 0xe3dc
const val FILTER_DRAMA = 0xe3dd
const val FILTER_FRAMES = 0xe3de
const val FILTER_HDR = 0xe3df
const val FILTER_LIST = 0xe152
const val FILTER_NONE = 0xe3e0
const val FILTER_TILT_SHIFT = 0xe3e2
const val FILTER_VINTAGE = 0xe3e3
const val FIND_IN_PAGE = 0xe880
const val FIND_REPLACE = 0xe881
const val FINGERPRINT = 0xe90d
const val FIRST_PAGE = 0xe5dc
const val FITNESS_CENTER = 0xeb43
const val FLAG = 0xe153
const val FLARE = 0xe3e4
const val FLASH_AUTO = 0xe3e5
const val FLASH_OFF = 0xe3e6
const val FLASH_ON = 0xe3e7
const val FLIGHT = 0xe539
const val FLIGHT_LAND = 0xe904
const val FLIGHT_TAKEOFF = 0xe905
const val FLIP = 0xe3e8
const val FLIP_TO_BACK = 0xe882
const val FLIP_TO_FRONT = 0xe883
const val FOLDER = 0xe2c7
const val FOLDER_OPEN = 0xe2c8
const val FOLDER_SHARED = 0xe2c9
const val FOLDER_SPECIAL = 0xe617
const val FONT_DOWNLOAD = 0xe167
const val FORMAT_ALIGN_CENTER = 0xe234
const val FORMAT_ALIGN_JUSTIFY = 0xe235
const val FORMAT_ALIGN_LEFT = 0xe236
const val FORMAT_ALIGN_RIGHT = 0xe237
const val FORMAT_BOLD = 0xe238
const val FORMAT_CLEAR = 0xe239
const val FORMAT_COLOR_FILL = 0xe23a
const val FORMAT_COLOR_RESET = 0xe23b
const val FORMAT_COLOR_TEXT = 0xe23c
const val FORMAT_INDENT_DECREASE = 0xe23d
const val FORMAT_INDENT_INCREASE = 0xe23e
const val FORMAT_ITALIC = 0xe23f
const val FORMAT_LINE_SPACING = 0xe240
const val FORMAT_LIST_BULLETED = 0xe241
const val FORMAT_LIST_NUMBERED = 0xe242
const val FORMAT_PAINT = 0xe243
const val FORMAT_QUOTE = 0xe244
const val FORMAT_SHAPES = 0xe25e
const val FORMAT_SIZE = 0xe245
const val FORMAT_STRIKETHROUGH = 0xe246
const val FORMAT_TEXTDIRECTION_L_TO_R = 0xe247
const val FORMAT_TEXTDIRECTION_R_TO_L = 0xe248
const val FORMAT_UNDERLINED = 0xe249
const val FORUM = 0xe0bf
const val FORWARD = 0xe154
const val FORWARD_10 = 0xe056
const val FORWARD_30 = 0xe057
const val FORWARD_5 = 0xe058
const val FREE_BREAKFAST = 0xeb44
const val FULLSCREEN = 0xe5d0
const val FULLSCREEN_EXIT = 0xe5d1
const val FUNCTIONS = 0xe24a
const val G_TRANSLATE = 0xe927
const val GAMEPAD = 0xe30f
const val GAMES = 0xe021
const val GAVEL = 0xe90e
const val GESTURE = 0xe155
const val GET_APP = 0xe884
const val GIF = 0xe908
const val GOLF_COURSE = 0xeb45
const val GPS_FIXED = 0xe1b3
const val GPS_NOT_FIXED = 0xe1b4
const val GPS_OFF = 0xe1b5
const val GRADE = 0xe885
const val GRADIENT = 0xe3e9
const val GRAIN = 0xe3ea
const val GRAPHIC_EQ = 0xe1b8
const val GRID_OFF = 0xe3eb
const val GRID_ON = 0xe3ec
const val GROUP = 0xe7ef
const val GROUP_ADD = 0xe7f0
const val GROUP_WORK = 0xe886
const val HD = 0xe052
const val HDR_OFF = 0xe3ed
const val HDR_ON = 0xe3ee
const val HDR_STRONG = 0xe3f1
const val HDR_WEAK = 0xe3f2
const val HEADSET = 0xe310
const val HEADSET_MIC = 0xe311
const val HEALING = 0xe3f3
const val HEARING = 0xe023
const val HELP = 0xe887
const val HELP_OUTLINE = 0xe8fd
const val HIGH_QUALITY = 0xe024
const val HIGHLIGHT = 0xe25f
const val HIGHLIGHT_OFF = 0xe888
const val HISTORY = 0xe889
const val HOME = 0xe88a
const val HOT_TUB = 0xeb46
const val HOTEL = 0xe53a
const val HOURGLASS_EMPTY = 0xe88b
const val HOURGLASS_FULL = 0xe88c
const val HTTP = 0xe902
const val HTTPS = 0xe88d
const val IMAGE = 0xe3f4
const val IMAGE_ASPECT_RATIO = 0xe3f5
const val IMPORT_CONTACTS = 0xe0e0
const val IMPORT_EXPORT = 0xe0c3
const val IMPORTANT_DEVICES = 0xe912
const val INBOX = 0xe156
const val INDETERMINATE_CHECK_BOX = 0xe909
const val INFO = 0xe88e
const val INFO_OUTLINE = 0xe88f
const val INPUT = 0xe890
const val INSERT_CHART = 0xe24b
const val INSERT_COMMENT = 0xe24c
const val INSERT_DRIVE_FILE = 0xe24d
const val INSERT_EMOTICON = 0xe24e
const val INSERT_INVITATION = 0xe24f
const val INSERT_LINK = 0xe250
const val INSERT_PHOTO = 0xe251
const val INVERT_COLORS = 0xe891
const val INVERT_COLORS_OFF = 0xe0c4
const val ISO = 0xe3f6
const val KEYBOARD = 0xe312
const val KEYBOARD_ARROW_DOWN = 0xe313
const val KEYBOARD_ARROW_LEFT = 0xe314
const val KEYBOARD_ARROW_RIGHT = 0xe315
const val KEYBOARD_ARROW_UP = 0xe316
const val KEYBOARD_BACKSPACE = 0xe317
const val KEYBOARD_CAPSLOCK = 0xe318
const val KEYBOARD_HIDE = 0xe31a
const val KEYBOARD_RETURN = 0xe31b
const val KEYBOARD_TAB = 0xe31c
const val KEYBOARD_VOICE = 0xe31d
const val KITCHEN = 0xeb47
const val LABEL = 0xe892
const val LABEL_OUTLINE = 0xe893
const val LANDSCAPE = 0xe3f7
const val LANGUAGE = 0xe894
const val LAPTOP = 0xe31e
const val LAPTOP_CHROMEBOOK = 0xe31f
const val LAPTOP_MAC = 0xe320
const val LAPTOP_WINDOWS = 0xe321
const val LAST_PAGE = 0xe5dd
const val LAUNCH = 0xe895
const val LAYERS = 0xe53b
const val LAYERS_CLEAR = 0xe53c
const val LEAK_ADD = 0xe3f8
const val LEAK_REMOVE = 0xe3f9
const val LENS = 0xe3fa
const val LIBRARY_ADD = 0xe02e
const val LIBRARY_BOOKS = 0xe02f
const val LIBRARY_MUSIC = 0xe030
const val LIGHTBULB_OUTLINE = 0xe90f
const val LINE_STYLE = 0xe919
const val LINE_WEIGHT = 0xe91a
const val LINEAR_SCALE = 0xe260
const val LINK = 0xe157
const val LINKED_CAMERA = 0xe438
const val LIST = 0xe896
const val LIVE_HELP = 0xe0c6
const val LIVE_TV = 0xe639
const val LOCAL_ACTIVITY = 0xe53f
const val LOCAL_AIRPORT = 0xe53d
const val LOCAL_ATM = 0xe53e
const val LOCAL_BAR = 0xe540
const val LOCAL_CAFE = 0xe541
const val LOCAL_CAR_WASH = 0xe542
const val LOCAL_CONVENIENCE_STORE = 0xe543
const val LOCAL_DINING = 0xe556
const val LOCAL_DRINK = 0xe544
const val LOCAL_FLORIST = 0xe545
const val LOCAL_GAS_STATION = 0xe546
const val LOCAL_GROCERY_STORE = 0xe547
const val LOCAL_HOSPITAL = 0xe548
const val LOCAL_HOTEL = 0xe549
const val LOCAL_LAUNDRY_SERVICE = 0xe54a
const val LOCAL_LIBRARY = 0xe54b
const val LOCAL_MALL = 0xe54c
const val LOCAL_MOVIES = 0xe54d
const val LOCAL_OFFER = 0xe54e
const val LOCAL_PARKING = 0xe54f
const val LOCAL_PHARMACY = 0xe550
const val LOCAL_PHONE = 0xe551
const val LOCAL_PIZZA = 0xe552
const val LOCAL_PLAY = 0xe553
const val LOCAL_POST_OFFICE = 0xe554
const val LOCAL_PRINTSHOP = 0xe555
const val LOCAL_SEE = 0xe557
const val LOCAL_SHIPPING = 0xe558
const val LOCAL_TAXI = 0xe559
const val LOCATION_CITY = 0xe7f1
const val LOCATION_DISABLED = 0xe1b6
const val LOCATION_OFF = 0xe0c7
const val LOCATION_ON = 0xe0c8
const val LOCATION_SEARCHING = 0xe1b7
const val LOCK = 0xe897
const val LOCK_OPEN = 0xe898
const val LOCK_OUTLINE = 0xe899
const val LOOKS = 0xe3fc
const val LOOKS_3 = 0xe3fb
const val LOOKS_4 = 0xe3fd
const val LOOKS_5 = 0xe3fe
const val LOOKS_6 = 0xe3ff
const val LOOKS_ONE = 0xe400
const val LOOKS_TWO = 0xe401
const val LOOP = 0xe028
const val LOUPE = 0xe402
const val LOW_PRIORITY = 0xe16d
const val LOYALTY = 0xe89a
const val MAIL = 0xe158
const val MAIL_OUTLINE = 0xe0e1
const val MAP = 0xe55b
const val MARKUNREAD = 0xe159
const val MARKUNREAD_MAILBOX = 0xe89b
const val MEMORY = 0xe322
const val MENU = 0xe5d2
const val MERGE_TYPE = 0xe252
const val MESSAGE = 0xe0c9
const val MIC = 0xe029
const val MIC_NONE = 0xe02a
const val MIC_OFF = 0xe02b
const val MMS = 0xe618
const val MODE_COMMENT = 0xe253
const val MODE_EDIT = 0xe254
const val MONETIZATION_ON = 0xe263
const val MONEY_OFF = 0xe25c
const val MONOCHROME_PHOTOS = 0xe403
const val MOOD = 0xe7f2
const val MOOD_BAD = 0xe7f3
const val MORE = 0xe619
const val MORE_HORIZ = 0xe5d3
const val MORE_VERT = 0xe5d4
const val MOTORCYCLE = 0xe91b
const val MOUSE = 0xe323
const val MOVE_TO_INBOX = 0xe168
const val MOVIE = 0xe02c
const val MOVIE_CREATION = 0xe404
const val MOVIE_FILTER = 0xe43a
const val MULTILINE_CHART = 0xe6df
const val MUSIC_NOTE = 0xe405
const val MUSIC_VIDEO = 0xe063
const val MY_LOCATION = 0xe55c
const val NATURE = 0xe406
const val NATURE_PEOPLE = 0xe407
const val NAVIGATE_BEFORE = 0xe408
const val NAVIGATE_NEXT = 0xe409
const val NAVIGATION = 0xe55d
const val NEAR_ME = 0xe569
const val NETWORK_CELL = 0xe1b9
const val NETWORK_CHECK = 0xe640
const val NETWORK_LOCKED = 0xe61a
const val NETWORK_WIFI = 0xe1ba
const val NEW_RELEASES = 0xe031
const val NEXT_WEEK = 0xe16a
const val NFC = 0xe1bb
const val NO_ENCRYPTION = 0xe641
const val NO_SIM = 0xe0cc
const val NOT_INTERESTED = 0xe033
const val NOTE = 0xe06f
const val NOTE_ADD = 0xe89c
const val NOTIFICATIONS = 0xe7f4
const val NOTIFICATIONS_ACTIVE = 0xe7f7
const val NOTIFICATIONS_NONE = 0xe7f5
const val NOTIFICATIONS_OFF = 0xe7f6
const val NOTIFICATIONS_PAUSED = 0xe7f8
const val OFFLINE_PIN = 0xe90a
const val ONDEMAND_VIDEO = 0xe63a
const val OPACITY = 0xe91c
const val OPEN_IN_BROWSER = 0xe89d
const val OPEN_IN_NEW = 0xe89e
const val OPEN_WITH = 0xe89f
const val PAGES = 0xe7f9
const val PAGEVIEW = 0xe8a0
const val PALETTE = 0xe40a
const val PAN_TOOL = 0xe925
const val PANORAMA = 0xe40b
const val PANORAMA_FISH_EYE = 0xe40c
const val PANORAMA_HORIZONTAL = 0xe40d
const val PANORAMA_VERTICAL = 0xe40e
const val PANORAMA_WIDE_ANGLE = 0xe40f
const val PARTY_MODE = 0xe7fa
const val PAUSE = 0xe034
const val PAUSE_CIRCLE_FILLED = 0xe035
const val PAUSE_CIRCLE_OUTLINE = 0xe036
const val PAYMENT = 0xe8a1
const val PEOPLE = 0xe7fb
const val PEOPLE_OUTLINE = 0xe7fc
const val PERM_CAMERA_MIC = 0xe8a2
const val PERM_CONTACT_CALENDAR = 0xe8a3
const val PERM_DATA_SETTING = 0xe8a4
const val PERM_DEVICE_INFORMATION = 0xe8a5
const val PERM_IDENTITY = 0xe8a6
const val PERM_MEDIA = 0xe8a7
const val PERM_PHONE_MSG = 0xe8a8
const val PERM_SCAN_WIFI = 0xe8a9
const val PERSON = 0xe7fd
const val PERSON_ADD = 0xe7fe
const val PERSON_OUTLINE = 0xe7ff
const val PERSON_PIN = 0xe55a
const val PERSON_PIN_CIRCLE = 0xe56a
const val PERSONAL_VIDEO = 0xe63b
const val PETS = 0xe91d
const val PHONE = 0xe0cd
const val PHONE_ANDROID = 0xe324
const val PHONE_BLUETOOTH_SPEAKER = 0xe61b
const val PHONE_FORWARDED = 0xe61c
const val PHONE_IN_TALK = 0xe61d
const val PHONE_IPHONE = 0xe325
const val PHONE_LOCKED = 0xe61e
const val PHONE_MISSED = 0xe61f
const val PHONE_PAUSED = 0xe620
const val PHONELINK = 0xe326
const val PHONELINK_ERASE = 0xe0db
const val PHONELINK_LOCK = 0xe0dc
const val PHONELINK_OFF = 0xe327
const val PHONELINK_RING = 0xe0dd
const val PHONELINK_SETUP = 0xe0de
const val PHOTO = 0xe410
const val PHOTO_ALBUM = 0xe411
const val PHOTO_CAMERA = 0xe412
const val PHOTO_FILTER = 0xe43b
const val PHOTO_LIBRARY = 0xe413
const val PHOTO_SIZE_SELECT_ACTUAL = 0xe432
const val PHOTO_SIZE_SELECT_LARGE = 0xe433
const val PHOTO_SIZE_SELECT_SMALL = 0xe434
const val PICTURE_AS_PDF = 0xe415
const val PICTURE_IN_PICTURE = 0xe8aa
const val PICTURE_IN_PICTURE_ALT = 0xe911
const val PIE_CHART = 0xe6c4
const val PIE_CHART_OUTLINED = 0xe6c5
const val PIN_DROP = 0xe55e
const val PLACE = 0xe55f
const val PLAY_ARROW = 0xe037
const val PLAY_CIRCLE_FILLED = 0xe038
const val PLAY_CIRCLE_OUTLINE = 0xe039
const val PLAY_FOR_WORK = 0xe906
const val PLAYLIST_ADD = 0xe03b
const val PLAYLIST_ADD_CHECK = 0xe065
const val PLAYLIST_PLAY = 0xe05f
const val PLUS_ONE = 0xe800
const val POLL = 0xe801
const val POLYMER = 0xe8ab
const val POOL = 0xeb48
const val PORTABLE_WIFI_OFF = 0xe0ce
const val PORTRAIT = 0xe416
const val POWER = 0xe63c
const val POWER_INPUT = 0xe336
const val POWER_SETTINGS_NEW = 0xe8ac
const val PREGNANT_WOMAN = 0xe91e
const val PRESENT_TO_ALL = 0xe0df
const val PRINT = 0xe8ad
const val PRIORITY_HIGH = 0xe645
const val PUBLIC = 0xe80b
const val PUBLISH = 0xe255
const val QUERY_BUILDER = 0xe8ae
const val QUESTION_ANSWER = 0xe8af
const val QUEUE = 0xe03c
const val QUEUE_MUSIC = 0xe03d
const val QUEUE_PLAY_NEXT = 0xe066
const val RADIO = 0xe03e
const val RADIO_BUTTON_CHECKED = 0xe837
const val RADIO_BUTTON_UNCHECKED = 0xe836
const val RATE_REVIEW = 0xe560
const val RECEIPT = 0xe8b0
const val RECENT_ACTORS = 0xe03f
const val RECORD_VOICE_OVER = 0xe91f
const val REDEEM = 0xe8b1
const val REDO = 0xe15a
const val REFRESH = 0xe5d5
const val REMOVE = 0xe15b
const val REMOVE_CIRCLE = 0xe15c
const val REMOVE_CIRCLE_OUTLINE = 0xe15d
const val REMOVE_FROM_QUEUE = 0xe067
const val REMOVE_RED_EYE = 0xe417
const val REMOVE_SHOPPING_CART = 0xe928
const val REORDER = 0xe8fe
const val REPEAT = 0xe040
const val REPEAT_ONE = 0xe041
const val REPLAY = 0xe042
const val REPLAY_10 = 0xe059
const val REPLAY_30 = 0xe05a
const val REPLAY_5 = 0xe05b
const val REPLY = 0xe15e
const val REPLY_ALL = 0xe15f
const val REPORT = 0xe160
const val REPORT_PROBLEM = 0xe8b2
const val RESTAURANT = 0xe56c
const val RESTAURANT_MENU = 0xe561
const val RESTORE = 0xe8b3
const val RESTORE_PAGE = 0xe929
const val RING_VOLUME = 0xe0d1
const val ROOM = 0xe8b4
const val ROOM_SERVICE = 0xeb49
const val ROTATE_90_DEGREES_CCW = 0xe418
const val ROTATE_LEFT = 0xe419
const val ROTATE_RIGHT = 0xe41a
const val ROUNDED_CORNER = 0xe920
const val ROUTER = 0xe328
const val ROWING = 0xe921
const val RSS_FEED = 0xe0e5
const val RV_HOOKUP = 0xe642
const val SATELLITE = 0xe562
const val SAVE = 0xe161
const val SCANNER = 0xe329
const val SCHEDULE = 0xe8b5
const val SCHOOL = 0xe80c
const val SCREEN_LOCK_LANDSCAPE = 0xe1be
const val SCREEN_LOCK_PORTRAIT = 0xe1bf
const val SCREEN_LOCK_ROTATION = 0xe1c0
const val SCREEN_ROTATION = 0xe1c1
const val SCREEN_SHARE = 0xe0e2
const val SD_CARD = 0xe623
const val SD_STORAGE = 0xe1c2
const val SEARCH = 0xe8b6
const val SECURITY = 0xe32a
const val SELECT_ALL = 0xe162
const val SEND = 0xe163
const val SENTIMENT_DISSATISFIED = 0xe811
const val SENTIMENT_NEUTRAL = 0xe812
const val SENTIMENT_SATISFIED = 0xe813
const val SENTIMENT_VERY_DISSATISFIED = 0xe814
const val SENTIMENT_VERY_SATISFIED = 0xe815
const val SETTINGS = 0xe8b8
const val SETTINGS_APPLICATIONS = 0xe8b9
const val SETTINGS_BACKUP_RESTORE = 0xe8ba
const val SETTINGS_BLUETOOTH = 0xe8bb
const val SETTINGS_BRIGHTNESS = 0xe8bd
const val SETTINGS_CELL = 0xe8bc
const val SETTINGS_ETHERNET = 0xe8be
const val SETTINGS_INPUT_ANTENNA = 0xe8bf
const val SETTINGS_INPUT_COMPONENT = 0xe8c0
const val SETTINGS_INPUT_COMPOSITE = 0xe8c1
const val SETTINGS_INPUT_HDMI = 0xe8c2
const val SETTINGS_INPUT_SVIDEO = 0xe8c3
const val SETTINGS_OVERSCAN = 0xe8c4
const val SETTINGS_PHONE = 0xe8c5
const val SETTINGS_POWER = 0xe8c6
const val SETTINGS_REMOTE = 0xe8c7
const val SETTINGS_SYSTEM_DAYDREAM = 0xe1c3
const val SETTINGS_VOICE = 0xe8c8
const val SHARE = 0xe80d
const val SHOP = 0xe8c9
const val SHOP_TWO = 0xe8ca
const val SHOPPING_BASKET = 0xe8cb
const val SHOPPING_CART = 0xe8cc
const val SHORT_TEXT = 0xe261
const val SHOW_CHART = 0xe6e1
const val SHUFFLE = 0xe043
const val SIGNAL_CELLULAR_4_BAR = 0xe1c8
const val SIGNAL_CELLULAR_CONNECTED_NO_INTERNET_4_BAR = 0xe1cd
const val SIGNAL_CELLULAR_NO_SIM = 0xe1ce
const val SIGNAL_CELLULAR_NULL = 0xe1cf
const val SIGNAL_CELLULAR_OFF = 0xe1d0
const val SIGNAL_WIFI_4_BAR = 0xe1d8
const val SIGNAL_WIFI_4_BAR_LOCK = 0xe1d9
const val SIGNAL_WIFI_OFF = 0xe1da
const val SIM_CARD = 0xe32b
const val SIM_CARD_ALERT = 0xe624
const val SKIP_NEXT = 0xe044
const val SKIP_PREVIOUS = 0xe045
const val SLIDESHOW = 0xe41b
const val SLOW_MOTION_VIDEO = 0xe068
const val SMARTPHONE = 0xe32c
const val SMOKE_FREE = 0xeb4a
const val SMOKING_ROOMS = 0xeb4b
const val SMS = 0xe625
const val SMS_FAILED = 0xe626
const val SNOOZE = 0xe046
const val SORT = 0xe164
const val SORT_BY_ALPHA = 0xe053
const val SPA = 0xeb4c
const val SPACE_BAR = 0xe256
const val SPEAKER = 0xe32d
const val SPEAKER_GROUP = 0xe32e
const val SPEAKER_NOTES = 0xe8cd
const val SPEAKER_NOTES_OFF = 0xe92a
const val SPEAKER_PHONE = 0xe0d2
const val SPELLCHECK = 0xe8ce
const val STAR = 0xe838
const val STAR_BORDER = 0xe83a
const val STAR_HALF = 0xe839
const val STARS = 0xe8d0
const val STAY_CURRENT_LANDSCAPE = 0xe0d3
const val STAY_CURRENT_PORTRAIT = 0xe0d4
const val STAY_PRIMARY_LANDSCAPE = 0xe0d5
const val STAY_PRIMARY_PORTRAIT = 0xe0d6
const val STOP = 0xe047
const val STOP_SCREEN_SHARE = 0xe0e3
const val STORAGE = 0xe1db
const val STORE = 0xe8d1
const val STORE_MALL_DIRECTORY = 0xe563
const val STRAIGHTEN = 0xe41c
const val STREETVIEW = 0xe56e
const val STRIKETHROUGH_S = 0xe257
const val STYLE = 0xe41d
const val SUBDIRECTORY_ARROW_LEFT = 0xe5d9
const val SUBDIRECTORY_ARROW_RIGHT = 0xe5da
const val SUBJECT = 0xe8d2
const val SUBSCRIPTIONS = 0xe064
const val SUBTITLES = 0xe048
const val SUBWAY = 0xe56f
const val SUPERVISOR_ACCOUNT = 0xe8d3
const val SURROUND_SOUND = 0xe049
const val SWAP_CALLS = 0xe0d7
const val SWAP_HORIZ = 0xe8d4
const val SWAP_VERT = 0xe8d5
const val SWAP_VERTICAL_CIRCLE = 0xe8d6
const val SWITCH_CAMERA = 0xe41e
const val SWITCH_VIDEO = 0xe41f
const val SYNC = 0xe627
const val SYNC_DISABLED = 0xe628
const val SYNC_PROBLEM = 0xe629
const val SYSTEM_UPDATE = 0xe62a
const val SYSTEM_UPDATE_ALT = 0xe8d7
const val TAB = 0xe8d8
const val TAB_UNSELECTED = 0xe8d9
const val TABLET = 0xe32f
const val TABLET_ANDROID = 0xe330
const val TABLET_MAC = 0xe331
const val TAG_FACES = 0xe420
const val TAP_AND_PLAY = 0xe62b
const val TERRAIN = 0xe564
const val TEXT_FIELDS = 0xe262
const val TEXT_FORMAT = 0xe165
const val TEXTSMS = 0xe0d8
const val TEXTURE = 0xe421
const val THEATERS = 0xe8da
const val THUMB_DOWN = 0xe8db
const val THUMB_UP = 0xe8dc
const val THUMBS_UP_DOWN = 0xe8dd
const val TIME_TO_LEAVE = 0xe62c
const val TIMELAPSE = 0xe422
const val TIMELINE = 0xe922
const val TIMER = 0xe425
const val TIMER_10 = 0xe423
const val TIMER_3 = 0xe424
const val TIMER_OFF = 0xe426
const val TITLE = 0xe264
const val TOC = 0xe8de
const val TODAY = 0xe8df
const val TOLL = 0xe8e0
const val TONALITY = 0xe427
const val TOUCH_APP = 0xe913
const val TOYS = 0xe332
const val TRACK_CHANGES = 0xe8e1
const val TRAFFIC = 0xe565
const val TRAIN = 0xe570
const val TRAM = 0xe571
const val TRANSFER_WITHIN_A_STATION = 0xe572
const val TRANSFORM = 0xe428
const val TRANSLATE = 0xe8e2
const val TRENDING_DOWN = 0xe8e3
const val TRENDING_FLAT = 0xe8e4
const val TRENDING_UP = 0xe8e5
const val TUNE = 0xe429
const val TURNED_IN = 0xe8e6
const val TURNED_IN_NOT = 0xe8e7
const val TV = 0xe333
const val UNARCHIVE = 0xe169
const val UNDO = 0xe166
const val UNFOLD_LESS = 0xe5d6
const val UNFOLD_MORE = 0xe5d7
const val UPDATE = 0xe923
const val USB = 0xe1e0
const val VERIFIED_USER = 0xe8e8
const val VERTICAL_ALIGN_BOTTOM = 0xe258
const val VERTICAL_ALIGN_CENTER = 0xe259
const val VERTICAL_ALIGN_TOP = 0xe25a
const val VIBRATION = 0xe62d
const val VIDEO_CALL = 0xe070
const val VIDEO_LABEL = 0xe071
const val VIDEO_LIBRARY = 0xe04a
const val VIDEOCAM = 0xe04b
const val VIDEOCAM_OFF = 0xe04c
const val VIDEOGAME_ASSET = 0xe338
const val VIEW_AGENDA = 0xe8e9
const val VIEW_ARRAY = 0xe8ea
const val VIEW_CAROUSEL = 0xe8eb
const val VIEW_COLUMN = 0xe8ec
const val VIEW_COMFY = 0xe42a
const val VIEW_COMPACT = 0xe42b
const val VIEW_DAY = 0xe8ed
const val VIEW_HEADLINE = 0xe8ee
const val VIEW_LIST = 0xe8ef
const val VIEW_MODULE = 0xe8f0
const val VIEW_QUILT = 0xe8f1
const val VIEW_STREAM = 0xe8f2
const val VIEW_WEEK = 0xe8f3
const val VIGNETTE = 0xe435
const val VISIBILITY = 0xe8f4
const val VISIBILITY_OFF = 0xe8f5
const val VOICE_CHAT = 0xe62e
const val VOICEMAIL = 0xe0d9
const val VOLUME_DOWN = 0xe04d
const val VOLUME_MUTE = 0xe04e
const val VOLUME_OFF = 0xe04f
const val VOLUME_UP = 0xe050
const val VPN_KEY = 0xe0da
const val VPN_LOCK = 0xe62f
const val WALLPAPER = 0xe1bc
const val WARNING = 0xe002
const val WATCH = 0xe334
const val WATCH_LATER = 0xe924
const val WB_AUTO = 0xe42c
const val WB_CLOUDY = 0xe42d
const val WB_INCANDESCENT = 0xe42e
const val WB_IRIDESCENT = 0xe436
const val WB_SUNNY = 0xe430
const val WC = 0xe63d
const val WEB = 0xe051
const val WEB_ASSET = 0xe069
const val WEEKEND = 0xe16b
const val WHATSHOT = 0xe80e
const val WIDGETS = 0xe1bd
const val WIFI = 0xe63e
const val WIFI_LOCK = 0xe1e1
const val WIFI_TETHERING = 0xe1e2
const val WORK = 0xe8f9
const val WRAP_TEXT = 0xe25b
const val YOUTUBE_SEARCHED_FOR = 0xe8fa
const val ZOOM_IN = 0xe8ff
const val ZOOM_OUT = 0xe900
const val ZOOM_OUT_MAP = 0xe56b
}
inline fun Context.icon(codePoint: Int, init: ComponentInit<UiComponentImpl<HTMLElement>> = {}): UiComponentImpl<HTMLElement> {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return component("i") {
addClass(materialIconsStyleTag)
dom.innerText = codePoint.toChar().toString()
init()
}
}
object MaterialIconsCss {
init {
head.add(linkElement("https://fonts.googleapis.com/icon?family=Material+Icons", rel = "stylesheet"))
}
val materialIconsStyleTag = CssClass("material-icons")
}
class IconButton(owner: Context) : A(owner) {
val iconComponent = addChild(icon(0))
val labelComponent = addChild(span {
addClass(IconButtonStyle.label)
})
var icon: Int = 0
set(value) {
field = value
iconComponent.label = value.toChar().toString()
}
override var label: String
get() = labelComponent.label
set(value) {
labelComponent.label = value
labelComponent.style.display = if (value.isEmpty()) "none" else "inline-block"
}
var disabled: Boolean by afterChange(false) {
toggleClass(CommonStyleTags.disabled)
}
init {
addClass(iconButton)
tabIndex = 0
}
override fun onElementAdded(oldIndex: Int, newIndex: Int, element: WithNode) {
labelComponent.addElement(newIndex, element)
}
override fun onElementRemoved(index: Int, element: WithNode) {
labelComponent.removeElement(element)
}
}
object IconButtonStyle {
val iconButton by cssClass()
val label by cssClass()
init {
addStyleToHead("""
$iconButton {
display: flex;
align-items: center;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
$label {
margin-left: ${CssProps.gap.v};
display: none;
}
$iconButton${CommonStyleTags.disabled} {
color: ${CssProps.toggledInnerDisabled.v};
pointer-events: none;
}
""")
}
}
inline fun Context.iconButton(codePoint: Int, label: String = "", init: ComponentInit<IconButton> = {}): IconButton {
contract { callsInPlace(init, InvocationKind.EXACTLY_ONCE) }
return IconButton(this).apply {
icon = codePoint
this.label = label
init()
}
}
| 3 | Kotlin | 0 | 1 | 87e0d951b75f4c4220147ff729ed199ec0a54e10 | 33,773 | acornui | Apache License 2.0 |
src/main/java/io/github/hotlava03/baclava/bot/listeners/tictactoe/TicTacToeListener.kt | HotLava03 | 179,969,541 | false | null | package io.github.hotlava03.baclava.bot.listeners.tictactoe
import net.dv8tion.jda.api.events.interaction.ButtonClickEvent
import net.dv8tion.jda.api.hooks.ListenerAdapter
import java.util.concurrent.TimeUnit
class TicTacToeListener : ListenerAdapter() {
override fun onButtonClick(e: ButtonClickEvent) {
if (!e.componentId.startsWith("ttt")) return
else if (e.member == null) return
val splitId = e.componentId.split("::")[0].split(":")
val players = splitId[0].split(":")
val coords = splitId[1].split(":")
val pair = players[0] to players[1]
// Check if a game exists.
if (!TicTacToePlayers[pair]) {
return e.reply("This isn't your game, ${e.member!!.asMention}")
.queue { it.deleteOriginal().queueAfter(5, TimeUnit.SECONDS) }
}
}
} | 0 | Kotlin | 0 | 1 | ed3365a59ca567afe6decd8968051ec0240328fc | 850 | baclava | Apache License 2.0 |
kotlin/basic-script-hello-world/Main.kt | TWiStErRob | 175,983,199 | false | null | import java.io.File
import kotlin.script.experimental.annotations.KotlinScript
import kotlin.script.experimental.api.EvaluationResult
import kotlin.script.experimental.api.ResultWithDiagnostics
import kotlin.script.experimental.api.ScriptDiagnostic
import kotlin.script.experimental.host.toScriptSource
import kotlin.script.experimental.jvmhost.BasicJvmScriptingHost
import kotlin.script.experimental.jvmhost.createJvmCompilationConfigurationFromTemplate
import kotlin.script.experimental.jvm.dependenciesFromCurrentContext
import kotlin.script.experimental.jvm.jvm
fun main(args: Array<String>) {
println("Hello World!")
// Try adding program arguments via Run/Debug configuration.
// Learn more about running applications: https://www.jetbrains.com/help/idea/running-applications.html.
println("Program arguments: ${args.joinToString()}")
if (args.isEmpty()) {
val file = File("default.simplescript.kts")
println(file.absolutePath)
val results = evalFile(file)
results.reports.forEach {
if (it.severity > ScriptDiagnostic.Severity.DEBUG) {
val ex = it.exception
println(" : ${it.message}" + if (ex == null) "" else "\n${ex.stackTraceToString()}")
}
}
}
}
@KotlinScript(fileExtension = "simplescript.kts")
abstract class SimpleScript
fun evalFile(scriptFile: File): ResultWithDiagnostics<EvaluationResult> {
val compilationConfiguration = createJvmCompilationConfigurationFromTemplate<SimpleScript> {
jvm {
// configure dependencies for compilation, they should contain at least the script base class and
// its dependencies
// variant 1: try to extract current classpath and take only a path to the specified "script.jar"
// dependenciesFromCurrentContext(
// "script" /* script library jar name (exact or without a version) */
// )
// variant 2: try to extract current classpath and use it for the compilation without filtering
dependenciesFromCurrentContext(wholeClasspath = true)
// variant 3: try to extract a classpath from a particular classloader (or Thread.contextClassLoader by default)
// filtering as in the variat 1 is supported too
// dependenciesFromClassloader(classLoader = SimpleScript::class.java.classLoader, wholeClasspath = true)
// variant 4: explicit classpath
// updateClasspath(listOf(File("/path/to/jar")))
}
}
return BasicJvmScriptingHost().eval(scriptFile.toScriptSource(), compilationConfiguration, null)
}
| 0 | Kotlin | 3 | 0 | 8179d79b75fa1a87b1b73a3b05ceade098bf4768 | 2,652 | repros | The Unlicense |
example/src/main/java/com/freeletics/statelayout/MainActivity.kt | freeletics | 262,744,080 | false | null | package com.freeletics.statelayout
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.transition.Transition
import android.view.View
import android.widget.TextView
import androidx.transition.TransitionInflater
class MainActivity : AppCompatActivity() {
private lateinit var stateLayout: StateLayout
private val loadingState = ViewState.create(R.layout.view_state_loading)
private val contentState = BindableContent("Content ready")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
stateLayout = findViewById(R.id.state_layout)
stateLayout.showState(loadingState)
Handler().postDelayed({
val transition = TransitionInflater.from(this).inflateTransition(android.R.transition.slide_left)
transition.duration = 200
stateLayout.showState(contentState, transition)
}, 2000)
}
private inner class BindableContent(
val text: String
) : ViewState.Inflatable(R.layout.view_state_content) {
override fun onBindView(view: View) {
super.onBindView(view)
val textView = view.findViewById<TextView>(R.id.text)
textView.text = text
}
}
}
| 0 | Kotlin | 1 | 7 | 03395f9a132f2f98834f42f19f7d67370197b6cc | 1,347 | StateLayout | Apache License 2.0 |
app/src/main/java/com/vishalag53/pokedex/splashScreen/SplashScreenActivity.kt | vishalag53 | 659,343,908 | false | null | package com.vishalag53.pokedex.splashScreen
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.animation.AnimationUtils
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import com.vishalag53.pokedex.databinding.ActivitySplashScreenBinding
import com.vishalag53.pokedex.MainActivity
import com.vishalag53.pokedex.R
class SplashScreenActivity : AppCompatActivity() {
private lateinit var binding: ActivitySplashScreenBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_splash_screen)
}
} | 0 | Kotlin | 0 | 0 | 4389a73c474363be86666f2af9e961d2dd78a12b | 844 | Pokedex | Apache License 2.0 |
core/src/main/kotlin/com/demo/dynamopoc/core/book/BookRepository.kt | jorgejcabrera | 287,841,868 | false | null | package com.demo.dynamopoc.core.book
import java.util.*
interface BookRepository {
fun findAll(): List<Book>
fun findAllByCategoryAndPriceGreaterThan(category: Category, price: Double): List<Book>
fun findAllByCreatedDateBefore(date: Date): List<Book>
fun save(book: Book)
fun findAllByCategory(category: Category): List<Book>
fun findAllByPriceGreaterThan(price: Double): List<Book>
fun findAllByRatingGreaterThan(rating: Int): List<Book>
fun findAllByCategoryAndCreatedDateAfter(category: Category, date: Date): List<Book>
} | 0 | Kotlin | 0 | 1 | 68660741a6c2e0518e41d2a3c8e3ec073a86e757 | 560 | dynamo-poc | MIT License |
infrastructure/rsocket-api/src/main/kotlin/io/timemates/backend/rsocket/internal/AuthorizationMetadata.kt | timemates | 575,534,781 | false | {"Kotlin": 441365, "Dockerfile": 859} | package io.timemates.backend.rsocket.internal
import io.ktor.utils.io.core.*
import io.ktor.utils.io.core.internal.*
import io.ktor.utils.io.pool.*
import io.rsocket.kotlin.ExperimentalMetadataApi
import io.rsocket.kotlin.core.MimeType
import io.rsocket.kotlin.core.WellKnownMimeType
import io.rsocket.kotlin.metadata.Metadata
import io.rsocket.kotlin.metadata.MetadataReader
@ExperimentalMetadataApi
fun AuthorizationMetadata(vararg tags: String): AuthorizationMetadata = AuthorizationMetadata(tags.toList())
@ExperimentalMetadataApi
class AuthorizationMetadata(val tags: List<String>) : Metadata {
init {
tags.forEach {
require(it.length in 1..255) { "Tag length must be in range 1..255 but was '${it.length}'" }
}
}
override val mimeType: MimeType get() = Reader.mimeType
override fun BytePacketBuilder.writeSelf() {
tags.forEach {
val bytes = it.encodeToByteArray()
writeByte(bytes.size.toByte())
writeFully(bytes)
}
}
override fun close(): Unit = Unit
companion object Reader : MetadataReader<AuthorizationMetadata> {
override val mimeType: MimeType get() = WellKnownMimeType.MessageRSocketRouting
override fun ByteReadPacket.read(pool: ObjectPool<ChunkBuffer>): AuthorizationMetadata {
val list = mutableListOf<String>()
while (isNotEmpty) {
val length = readByte().toInt() and 0xFF
list.add(readTextExactBytes(length))
}
return AuthorizationMetadata(list.toList())
}
}
}
| 17 | Kotlin | 0 | 8 | ba66b305eebf276c6f72131a2500c7f47cc5d7e3 | 1,601 | backend | MIT License |
commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/FileConflictDialog.kt | Zxc-40 | 120,768,753 | true | {"Kotlin": 286154} | package com.simplemobiletools.commons.dialogs
import android.app.Activity
import android.support.v7.app.AlertDialog
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.R.id.conflict_dialog_radio_merge
import com.simplemobiletools.commons.R.id.conflict_dialog_radio_skip
import com.simplemobiletools.commons.extensions.baseConfig
import com.simplemobiletools.commons.extensions.beVisibleIf
import com.simplemobiletools.commons.extensions.setupDialogStuff
import com.simplemobiletools.commons.helpers.CONFLICT_MERGE
import com.simplemobiletools.commons.helpers.CONFLICT_OVERWRITE
import com.simplemobiletools.commons.helpers.CONFLICT_SKIP
import kotlinx.android.synthetic.main.dialog_file_conflict.view.*
import java.io.File
class FileConflictDialog(val activity: Activity, val file: File, val callback: (resolution: Int, applyForAll: Boolean) -> Unit) {
val view = activity.layoutInflater.inflate(R.layout.dialog_file_conflict, null)!!
init {
view.apply {
val stringBase = if (file.isDirectory) R.string.folder_already_exists else R.string.file_already_exists
conflict_dialog_title.text = String.format(activity.getString(stringBase), file.name)
conflict_dialog_apply_to_all.isChecked = activity.baseConfig.lastConflictApplyToAll
conflict_dialog_radio_merge.beVisibleIf(file.isDirectory)
val resolutionButton = when (activity.baseConfig.lastConflictResolution) {
CONFLICT_OVERWRITE -> conflict_dialog_radio_overwrite
CONFLICT_MERGE -> conflict_dialog_radio_merge
else -> conflict_dialog_radio_skip
}
resolutionButton.isChecked = true
}
AlertDialog.Builder(activity)
.setPositiveButton(R.string.ok, { dialog, which -> dialogConfirmed() })
.setNegativeButton(R.string.cancel, null)
.create().apply {
activity.setupDialogStuff(view, this)
}
}
private fun dialogConfirmed() {
val resolution = when (view.conflict_dialog_radio_group.checkedRadioButtonId) {
conflict_dialog_radio_skip -> CONFLICT_SKIP
conflict_dialog_radio_merge -> CONFLICT_MERGE
else -> CONFLICT_OVERWRITE
}
val applyToAll = view.conflict_dialog_apply_to_all.isChecked
activity.baseConfig.apply {
lastConflictApplyToAll = applyToAll
lastConflictResolution = resolution
}
callback(resolution, applyToAll)
}
}
| 0 | Kotlin | 0 | 0 | 197ffd66060924f9cbbaeff12adf2e81e0c093dd | 2,554 | Simple-Commons | Apache License 2.0 |
src/main/kotlin/dev/rvbsm/fsit/event/ServerStoppingListener.kt | rvbsm | 611,853,270 | false | {"Kotlin": 93738, "Java": 20363} | package dev.rvbsm.fsit.event
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents
val ServerStoppingListener = ServerLifecycleEvents.ServerStopping { server ->
RidingServerStoppingEvent.onServerStopping(server)
}
| 2 | Kotlin | 2 | 9 | e67762263d45cd74dbc592c00c65b8bd5a3a8fa4 | 238 | fsit | MIT License |
src/main/kotlin/me/melijn/melijnbot/commands/games/PokerCommand.kt | ToxicMushroom | 107,187,088 | false | null | package me.melijn.melijnbot.commands.games
import me.melijn.melijnbot.internals.command.AbstractCommand
import me.melijn.melijnbot.internals.command.CommandCategory
import me.melijn.melijnbot.internals.command.ICommandContext
import me.melijn.melijnbot.internals.embed.Embedder
import me.melijn.melijnbot.internals.utils.getBalanceNMessage
import me.melijn.melijnbot.internals.utils.message.sendEmbedRsp
import me.melijn.melijnbot.internals.utils.message.sendEmbedRspAwaitEL
import me.melijn.melijnbot.internals.utils.message.sendSyntax
import me.melijn.melijnbot.internals.utils.withVariable
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import kotlin.random.Random
class PokerCommand : AbstractCommand("command.poker") {
init {
id = 218
name = "poker"
cooldown = 4000
commandCategory = CommandCategory.GAME
}
companion object {
val ongoingPoker = mutableListOf<PokerGame>()
}
data class PokerGame(
val userId: Long,
val bet: Long,
val firstHand: String,
val channelId: Long,
val msgId: Long,
val moment: Long,
var reactions: List<Int>
)
private val ranks = listOf("2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "R", "A")
private val types = listOf('♠', '♣', '♥', '♦')
override suspend fun execute(context: ICommandContext) {
if (context.args.isEmpty()) {
sendSyntax(context)
return
}
val balanceWrapper = context.daoManager.balanceWrapper
val amount = getBalanceNMessage(context, 0) ?: return
context.initCooldown()
balanceWrapper.removeBalance(context.authorId, amount)
try {
val allCards = mutableListOf<String>()
for (type in types) {
for (rank in ranks) {
allCards.add("$rank$type")
}
}
val eb = Embedder(context)
var hand = ""
for (i in 0 until 5) {
val cardPosition = Random.nextInt(allCards.size)
val card = allCards[cardPosition]
allCards.removeAt(cardPosition)
hand += "$card, "
}
hand.removeSuffix(", ")
eb.addField(
context.getTranslation("$root.title1").withVariable(
"user",
context.member.effectiveName
), hand, false
)
eb.addField(
context.getTranslation("$root.actions"),
context.getTranslation(
"$root.actionsvalue"
).withVariable("prefix", context.usedPrefix),
false
)
eb.setFooter(
context.getTranslation(
"$root.helpfooter"
)
)
val msg = sendEmbedRspAwaitEL(context, eb.build()).first()
msg.addReaction("1️⃣").queue()
msg.addReaction("2️⃣").queue()
msg.addReaction("3️⃣").queue()
msg.addReaction("4️⃣").queue()
msg.addReaction("5️⃣").queue()
ongoingPoker.add(
PokerGame(
context.authorId,
amount,
hand,
msg.channel.idLong,
msg.idLong,
System.currentTimeMillis(),
emptyList()
)
)
context.container.eventWaiter.waitFor(MessageReceivedEvent::class.java, { event ->
event.message.contentRaw == "${context.prefix}draw" &&
ongoingPoker.any { it.userId == event.author.idLong && it.channelId == event.channel.idLong }
}, func@{ event ->
val pokerGame = ongoingPoker.first { it.userId == event.author.idLong }
val lockedCards = pokerGame.firstHand.split(", ").withIndex().filter {
pokerGame.reactions.contains(it.index + 1)
}
val nexCardPool = mutableListOf<String>()
for (type in types) {
for (rank in ranks) {
if (!lockedCards.map { it.value }.contains("$rank$type")) {
nexCardPool.add("$rank$type")
}
}
}
val finalCards = mutableListOf<String>()
for (i in 0 until 5) {
if (lockedCards.any { it.index == i }) {
finalCards.add(lockedCards.first { it.index == i }.value)
} else {
val cardPosition = Random.nextInt(allCards.size)
val card = allCards[cardPosition]
allCards.removeAt(cardPosition)
finalCards.add(card)
}
}
val ebb = Embedder(context)
.setTitle(context.getTranslation("$root.finalhandtitle"))
.setDescription(finalCards.joinToString(", "))
sendEmbedRsp(context, ebb.build())
val pokerHand = findPokerHand(finalCards)
val bal = if (pokerHand != null) {
balanceWrapper.addBalanceAndGet(context.authorId, (pokerGame.bet * pokerHand.multiplier).toLong())
} else {
balanceWrapper.getBalance(context.authorId)
}
if (pokerHand != null) {
val ebb1 = Embedder(context)
.addField(
pokerHand.name,
context.getTranslation("$root.won")
.withVariable("amount", pokerGame.bet * pokerHand.multiplier),
false
)
.addField(
context.getTranslation("$root.mel"),
context.getTranslation("$root.newbalance")
.withVariable("amount", bal),
false
)
sendEmbedRsp(context, ebb1.build())
} else {
val ebb1 = Embedder(context)
.addField(
context.getTranslation("$root.losttitle"),
context.getTranslation("$root.lost")
.withVariable("amount", pokerGame.bet),
false
)
.addField(
context.getTranslation("$root.mel"),
context.getTranslation("$root.newbalance")
.withVariable("amount", bal),
false
)
sendEmbedRsp(context, ebb1.build())
}
ongoingPoker.removeIf { it.userId == context.authorId }
}, {
ongoingPoker.removeIf { it.userId == context.authorId }
}, 120)
} catch (t: Throwable) {
balanceWrapper.addBalance(context.authorId, amount)
}
}
private fun findPokerHand(finalCards: MutableList<String>): PokerHand? {
// Royal flush
val ctypes = finalCards.map { it.last() }
val cranks = finalCards.map { it.dropLast(1) }
val ranksOccurrenceMap = mutableMapOf<Int, Int>()
for (card in finalCards) {
val r = card.dropLast(1)
ranksOccurrenceMap[ranks.indexOf(r)] = (ranksOccurrenceMap[ranks.indexOf(r)] ?: 0) + 1
}
val type1 = ctypes[0]
val positions = cranks.map { ranks.indexOf(it) }.sorted()
var flush = false
if (ctypes.all { it == type1 }) { // flush check (all same type)
if (
cranks.contains("A") &&
cranks.contains("K") &&
cranks.contains("Q") &&
cranks.contains("J") &&
cranks.contains("10")
) { // Royal flush check
return PokerHand("Royal Flush", 100f)
}
var lastRank = positions[0]
var indices = 1 until 5
if (lastRank == 0 && positions[4] == 12) { // if lastRank card is 2 and hand contains 1 then we can use A as a 1
lastRank = positions[4]
indices = 0 until 4
}
var straightFlush = true
for (i in indices) {
if (i == (lastRank + 1)) {
lastRank = positions[i]
} else {
straightFlush = false
}
}
if (straightFlush) {
return PokerHand("Straight Flush", 50f)
}
flush = true
}
if (ranksOccurrenceMap.size <= 2) {
if (ranksOccurrenceMap.values.sorted()[0] == 4) { // 4 of a kind
return PokerHand("Four of a Kind", 7f)
} else if (ranksOccurrenceMap.values.sorted()[0] == 3) { // Full house
return PokerHand("Full House", 5f)
}
}
if (flush) {
return PokerHand("Flush", 4f)
}
// Straight check
var lastRank = positions[0]
var indices = 1 until 5
if (lastRank == 0 && positions[4] == 12) { // if lastRank card is 2 and hand contains 1 then we can use A as a 1
lastRank = positions[4]
indices = 0 until 4
}
var straight = true
for (i in indices) {
if (i == (lastRank + 1)) {
lastRank = positions[i]
} else {
straight = false
}
}
if (straight) {
return PokerHand("Straight", 50f)
}
if (ranksOccurrenceMap.size == 3 && ranksOccurrenceMap.values.sorted()[0] == 2 && ranksOccurrenceMap.values.sorted()[1] == 2) { // Two Pair
return PokerHand("Two Pair", 2f)
}
return null
}
data class PokerHand(
val name: String,
val multiplier: Float
)
}
| 5 | null | 22 | 80 | 01107bbaad0e343d770b1e4124a5a9873b1bb5bd | 10,312 | Melijn | MIT License |
app/src/main/java/com/pandulapeter/beagle/appDemo/feature/main/examples/simpleSetup/list/SimpleSetupAdapter.kt | pandulapeter | 209,092,048 | false | {"Kotlin": 849080, "Ruby": 497} | package com.pandulapeter.beagle.appDemo.feature.main.examples.simpleSetup.list
import android.view.ViewGroup
import com.pandulapeter.beagle.appDemo.R
import com.pandulapeter.beagle.appDemo.feature.shared.list.BaseAdapter
import com.pandulapeter.beagle.appDemo.feature.shared.list.BaseViewHolder
import com.pandulapeter.beagle.appDemo.feature.shared.list.SectionHeaderViewHolder
import kotlinx.coroutines.CoroutineScope
class SimpleSetupAdapter(
scope: CoroutineScope,
onSectionHeaderSelected: (SectionHeaderViewHolder.UiModel) -> Unit
) : BaseAdapter<SimpleSetupListItem>(scope, onSectionHeaderSelected) {
override fun getItemViewType(position: Int) = when (getItem(position)) {
is LoadingIndicatorViewHolder.UiModel -> R.layout.item_simple_setup_loading_indicator
else -> super.getItemViewType(position)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BaseViewHolder<*, *> = when (viewType) {
R.layout.item_simple_setup_loading_indicator -> LoadingIndicatorViewHolder.create(parent)
else -> super.onCreateViewHolder(parent, viewType)
}
override fun onBindViewHolder(holder: BaseViewHolder<*, *>, position: Int) = when (holder) {
is LoadingIndicatorViewHolder -> holder.bind(getItem(position) as LoadingIndicatorViewHolder.UiModel)
else -> super.onBindViewHolder(holder, position)
}
} | 15 | Kotlin | 27 | 491 | edc654e4bd75bf9519c476c67a9b77d600e3ce9e | 1,390 | beagle | Apache License 2.0 |
app/common/src/commonMain/kotlin/com/denchic45/studiversity/data/db/local/DbHelper.kt | denchic45 | 435,895,363 | false | null | package com.denchic45.studiversity.data.db.local
import app.cash.sqldelight.ColumnAdapter
import app.cash.sqldelight.EnumColumnAdapter
import app.cash.sqldelight.Transacter
import app.cash.sqldelight.adapter.primitive.IntColumnAdapter
import app.cash.sqldelight.db.SqlDriver
import com.denchic45.studiversity.AppDatabase
import com.denchic45.studiversity.AttachmentEntity
import com.denchic45.studiversity.CourseContentEntity
import com.denchic45.studiversity.EventEntity
import com.denchic45.studiversity.SectionEntity
import com.denchic45.studiversity.StudyGroupEntity
import com.denchic45.studiversity.SubmissionEntity
import com.denchic45.studiversity.UserEntity
import com.denchic45.studiversity.data.mapper.ListMapper
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.time.LocalDate
import java.time.format.DateTimeFormatter
class ListColumnAdapter : ColumnAdapter<List<String>, String> {
override fun decode(databaseValue: String): List<String> {
return ListMapper.tolList(databaseValue)
}
override fun encode(value: List<String>): String {
return ListMapper.fromList(value)
}
}
class LocalDateColumnAdapter : ColumnAdapter<LocalDate, String> {
override fun decode(databaseValue: String): LocalDate {
return LocalDate.parse(databaseValue)
}
override fun encode(value: LocalDate): String {
return value.format(DateTimeFormatter.ISO_LOCAL_DATE)
}
}
class DbHelper(val driver: SqlDriver) {
val database = AppDatabase(
driver = driver,
courseContentEntityAdapter = CourseContentEntity.Adapter(
attachmentsAdapter = ListColumnAdapter()
),
submissionEntityAdapter = SubmissionEntity.Adapter(
attachmentsAdapter = ListColumnAdapter()
),
eventEntityAdapter = EventEntity.Adapter(
teacher_idsAdapter = ListColumnAdapter(),
positionAdapter = IntColumnAdapter
),
userEntityAdapter = UserEntity.Adapter(
EnumColumnAdapter()
),
studyGroupEntityAdapter = StudyGroupEntity.Adapter(
LocalDateColumnAdapter(),
LocalDateColumnAdapter()
),
attachmentEntityAdapter = AttachmentEntity.Adapter(
EnumColumnAdapter()
),
sectionEntityAdapter = SectionEntity.Adapter(
orderAdapter = IntColumnAdapter
)
)
private var version: Int
get() {
val sqlCursor = driver.executeQuery(
identifier = null,
sql = "PRAGMA user_version;",
mapper = { it.getLong(0)!!.toInt() },
parameters = 0,
binders = null
)
return sqlCursor.value
}
private set(version) {
driver.execute(null, String.format("PRAGMA user_version = %d;", version), 0, null)
}
}
suspend fun Transacter.suspendedTransaction(
block: suspend () -> Unit
) = withContext(Dispatchers.IO) {
transaction {
launch {
block()
}
}
}
suspend fun <T> Transacter.suspendedTransactionWithResult(block: suspend () -> T): T =
withContext(Dispatchers.IO) {
val result: Deferred<T> = transactionWithResult {
async {
block()
}
}
result.await()
} | 0 | null | 0 | 7 | 9d1744ffd9e1652e93af711951e924b739e96dcc | 3,478 | Studiversity | Apache License 2.0 |
game/src/commonMain/kotlin/com/lehaine/game/component/DebugSpriteComponent.kt | anthony-tarantini | 832,768,665 | false | {"Kotlin": 62248, "Shell": 1686, "HTML": 348} | package com.lehaine.game.component
import com.github.quillraven.fleks.Component
import com.github.quillraven.fleks.ComponentType
import com.lehaine.littlekt.graphics.Color
/**
* @author <NAME>
* @date 3/15/2023
*/
class DebugSpriteComponent : Component<DebugSpriteComponent> {
override fun type() = DebugSpriteComponent
companion object : ComponentType<DebugSpriteComponent>()
} | 0 | Kotlin | 0 | 0 | 954160f073400e212e0d728fb7ded592eb2163af | 392 | littleky | MIT License |
src/main/kotlin/BuiltInProperties.kt | pongasoft | 312,870,302 | false | null | /*
* Copyright (c) 2020 pongasoft
*
* 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.
*
* @author <NAME>
*/
/**
* A built in property is provided by Reason and as result does not have a representation in the motherboard */
open class REBuiltInProperty(name: String) : REProperty(name) {
/**
* @return the definition of the property defined in the `motherboard_def.lua` file */
override fun motherboard(): String = ""
// textResources
override fun textResources() = emptyMap<String, String>()
}
/**
* Device name widget (built-in) represented by a tape */
class REDeviceNameWidget(
panel: Panel,
prop: REProperty,
offsetX: Int,
offsetY: Int,
imageResource: ImageResource
) : REPropertyWidget(panel, prop, offsetX, offsetY, imageResource) {
// hdgui2D
override fun hdgui2D(): String {
return """-- device name / tape
${panel}_widgets[#${panel}_widgets + 1] = jbox.device_name {
graphics = {
node = "$nodeName",
}
}"""
}
}
/**
* Placeholder property to reserve space in the back panel */
class REPlaceholderProperty(
name: String,
offsetX: Int,
offsetY: Int,
imageResource: ImageResource
) : REBuiltInProperty(name) {
init {
addWidget(REPlaceholderWidget(this, offsetX, offsetY, imageResource))
}
}
/**
* Placeholder (built-in) represented by a transparent image (so will not render). */
class REPlaceholderWidget(
prop: REPlaceholderProperty,
offsetX: Int,
offsetY: Int,
imageResource: ImageResource
) : REPropertyWidget(Panel.back, prop, offsetX, offsetY, imageResource) {
// hdgui2D
override fun hdgui2D(): String {
return """-- placeholder
${panel}_widgets[#${panel}_widgets + 1] = jbox.placeholder {
graphics = {
node = "$nodeName",
}
}"""
}
}
| 0 | Kotlin | 0 | 3 | e47a7f12d758ca004863e042a40e08ca314cbc46 | 2,308 | re-quickstart | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.