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
kotlin-gradle-extensions/src/main/kotlin/com/rickbusarow/kgx/kgp.kt
rickbusarow
684,172,148
false
{"Kotlin": 314329, "Shell": 4127}
/* * Copyright (C) 2024 <NAME> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.rickbusarow.kgx import com.rickbusarow.kgx.internal.ElementInfoAction import com.rickbusarow.kgx.internal.ElementInfoAction.ElementValue import com.rickbusarow.kgx.internal.InternalGradleApiAccess import com.rickbusarow.kgx.internal.whenElementKnown import org.gradle.api.Action import org.gradle.api.Project import org.jetbrains.kotlin.gradle.dsl.JvmTarget import org.jetbrains.kotlin.gradle.dsl.KotlinJvmProjectExtension import org.jetbrains.kotlin.gradle.dsl.KotlinMultiplatformExtension import org.jetbrains.kotlin.gradle.dsl.KotlinProjectExtension import org.jetbrains.kotlin.gradle.dsl.KotlinSingleTargetExtension import org.jetbrains.kotlin.gradle.dsl.kotlinExtension import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet import org.jetbrains.kotlin.gradle.plugin.KotlinTarget /** * Converts the integer value of a Java version to the Gradle DSL version of [JvmTarget]. * * Note this is different from the Kotlin compiler's * type at `org.jetbrains.kotlin.config.JvmTarget`. * * @since 0.1.9 * @throws NullPointerException if KGP doesn't have an enum defined for the provided [targetInt]. */ public fun JvmTarget.Companion.fromInt(targetInt: Int): JvmTarget { @Suppress("MagicNumber") return when (targetInt) { 8 -> JvmTarget.fromTarget("1.8") else -> JvmTarget.fromTarget("$targetInt") } } /** * Converts the [JvmTarget] to its integer version number * * @since 0.1.9 */ public fun JvmTarget.toInt(): Int = target.substringAfterLast('.').toInt() /** * Applies the provided [ElementInfoAction] to a Kotlin target when * it gets registered. This function caters to both single target and * multiplatform Kotlin projects by delegating to the appropriate extension. * * For single-target projects, the action is directly applied to the target. For * multiplatform projects, the action is handed off to the [KotlinMultiplatformExtension]. * * @param configurationAction The action to apply to the Kotlin target upon registration. * @receiver [KotlinProjectExtension] The Kotlin project extension, * which could be a single-target or multiplatform extension. * @since 0.1.5 */ @InternalGradleApiAccess public fun KotlinProjectExtension.onTargetRegistered( configurationAction: ElementInfoAction<KotlinTarget> ) { when (val extension = this) { is KotlinSingleTargetExtension<*> -> { extension.target.let { target -> configurationAction.invoke( elementName = target.name, elementType = target::class.java, elementValue = ElementValue(target) ) } } is KotlinMultiplatformExtension -> { extension.onTargetRegistered(configurationAction = configurationAction) } } } /** * Applies the provided [ElementInfoAction] to a Kotlin target when it gets registered * within a multiplatform project. This function leverages the [whenElementKnown] * extension to avoid triggering the target's creation or configuration prematurely. * * @param configurationAction The action to apply to the Kotlin target upon registration. * @receiver [KotlinMultiplatformExtension] The Kotlin multiplatform project extension. * @since 0.1.5 */ @InternalGradleApiAccess public fun KotlinMultiplatformExtension.onTargetRegistered( configurationAction: ElementInfoAction<KotlinTarget> ) { targets.whenElementKnown { configurationAction.execute(it) } } /** * shorthand for `extensions.getByName("kotlin") as KotlinProjectExtension` * * @since 0.1.12 */ public val Project.kotlinExtensionOrNull: KotlinProjectExtension? get() = extensions.findByName("kotlin") as? KotlinProjectExtension /** * shorthand for `extensions.getByName("kotlin") as KotlinJvmProjectExtension` * * @since 0.1.12 */ public val Project.kotlinJvmExtension: KotlinJvmProjectExtension get() = kotlinExtension as KotlinJvmProjectExtension /** * shorthand for `extensions.findByName("kotlin") as? KotlinJvmProjectExtension` * * @since 0.1.12 */ public val Project.kotlinJvmExtensionOrNull: KotlinJvmProjectExtension? get() = kotlinExtensionOrNull as? KotlinJvmProjectExtension /** * Only executes [action] if the project has the kotlin plugin applied. * * Shorthand for: * ``` * plugins.withId("org.jetbrains.kotlin.jvm") { * extensions.configure<KotlinJvmProjectExtension>("kotlin") { * // ... * } * } * ``` * * @since 0.1.12 */ public fun Project.kotlinJvmExtensionSafe(action: Action<KotlinJvmProjectExtension>) { plugins.withKotlinJvmPlugin { action.execute(kotlinJvmExtension) } } /** [org.gradle.api.tasks.SourceSet] */ public typealias JavaSourceSet = org.gradle.api.tasks.SourceSet /** Shorthand for `target.kotlinExtension.sourceSets.getByName(name)` */ public fun JavaSourceSet.kotlinSourceSet(target: Project): KotlinSourceSet { return target.kotlinExtension.sourceSets.getByName(name) } /** Shorthand for `target.kotlinExtensionOrNull?.sourceSets?.findByName(name)` */ public fun JavaSourceSet.kotlinSourceSetOrNull(target: Project): KotlinSourceSet? { return target.kotlinExtensionOrNull?.sourceSets?.findByName(name) } /** Shorthand for `target.javaExtension.sourceSets.getByName(name)` */ public fun KotlinSourceSet.javaSourceSet(target: Project): JavaSourceSet { return target.javaExtension.sourceSets.getByName(name) } /** Shorthand for `target.javaExtension.sourceSets.findByName(name)` */ public fun KotlinSourceSet.javaSourceSetOrNull(target: Project): JavaSourceSet? { return target.javaExtensionOrNull?.sourceSets?.findByName(name) }
12
Kotlin
0
6
f7fdf973ef95828c19810d9f311575d8d77133db
6,102
kotlin-gradle-extensions
Apache License 2.0
app/src/main/java/com/example/notifyme/MainActivity.kt
Scottchiang90
310,649,943
false
null
package com.example.notifyme import android.app.AlarmManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.net.Uri import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.method.ScrollingMovementMethod import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.ProgressBar import android.widget.Switch import android.widget.TextView import android.widget.Toast import androidx.lifecycle.Lifecycle import androidx.lifecycle.OnLifecycleEvent import java.util.* class MainActivity : AppCompatActivity() { private var alarmMgr: AlarmManager? = null private lateinit var alarmIntent: PendingIntent override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val tv = findViewById<TextView>(R.id.textView) tv.movementMethod = ScrollingMovementMethod() tv.setTextIsSelectable(true) initNotificationSwitch() searchOnLocations(tv) } override fun onCreateOptionsMenu(menu: Menu?): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true } private fun initNotificationSwitch(){ // get state from shared preference val sharedPref = this.getSharedPreferences(getString(R.string.shared_pref), Context.MODE_PRIVATE) ?: return val notificationState = sharedPref.getBoolean(getString(R.string.notification_state), false) val switch = findViewById<Switch>(R.id.switch_notification) switch.isChecked = notificationState switch.setOnCheckedChangeListener { view, isChecked -> if (isChecked) { // The switch is On startNotifications(view) } else { // The switch is Off stopNotifications (view) } // save to shared preference with (sharedPref.edit()) { putBoolean(getString(R.string.notification_state), isChecked) apply() } } } fun startNotifications (view: View) { alarmMgr = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmIntent = Intent(this, AlarmReceiver::class.java).let { intent -> PendingIntent.getBroadcast(this, 0, intent, 0) } // Set the alarm to start at approximately 8:00 a.m. val calendar: Calendar = Calendar.getInstance().apply { timeInMillis = System.currentTimeMillis() set(Calendar.HOUR_OF_DAY, 8) } //With setInexactRepeating(), you have to use one of the AlarmManager interval // constants--in this case, AlarmManager.INTERVAL_DAY. alarmMgr?.setInexactRepeating( AlarmManager.RTC_WAKEUP, calendar.timeInMillis, AlarmManager.INTERVAL_HALF_HOUR, alarmIntent ) } fun stopNotifications (view: View) { alarmMgr = this.getSystemService(Context.ALARM_SERVICE) as AlarmManager alarmIntent = Intent(this, AlarmReceiver::class.java).let { intent -> PendingIntent.getBroadcast(this, 0, intent, 0) } alarmMgr?.cancel(alarmIntent) } fun goToSettings (mi: MenuItem) { val intent = Intent(this, LocationList::class.java) startActivity(intent) } fun showVersion (mi: MenuItem) { Toast.makeText(this, "${getString(R.string.app_name)} ${getString(R.string.version)} ${getString(R.string.version_number)}", Toast.LENGTH_SHORT).show() } fun openMap (view: View) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.url_to_gym)))) } /** Called when the user taps the Search button */ fun searchOnLocations(view: View) { val textView = findViewById<TextView>(R.id.textView) textView.visibility = View.INVISIBLE val progressBar = findViewById<ProgressBar>(R.id.progressBar) progressBar.visibility = View.VISIBLE RequestHandler(context = this, textView=textView, progressBar=progressBar).searchOnLocations() } }
0
Kotlin
0
0
832638eb4ea3ca323fbd6bbbc0a36a2339f3e8fe
4,335
NotifyMe
MIT License
src/commonMain/kotlin/common/helpers/PathBuilder.kt
Rinat-Suleimanov
649,406,285
false
null
package common.helpers abstract class PathBuilder(val parent: PathBuilder? = null, val relativePath: String) { fun Path(relPath: String) = object: PathBuilder(this, relPath) { } override fun toString(): String { val sb = StringBuilder() if (parent != null) { sb.append(parent) } sb.append(relativePath) return sb.toString().replace("/+".toRegex(), "/") } }
0
Kotlin
0
0
376a0c95f0caea87075d119095a0eaae0c9e39ee
427
game-assets
Apache License 2.0
app/src/main/java/project/dheeraj/showtime/ui/SplashScreenActivity.kt
akp2609
551,974,640
false
{"Kotlin": 87659}
package project.dheeraj.showtime.ui import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch import project.dheeraj.showtime.R import project.dheeraj.showtime.ui.main.MainActivity class SplashScreenActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_splash_screen) GlobalScope.launch(Dispatchers.IO) { delay(2500) MainActivity.start(this@SplashScreenActivity) finish() } } }
0
Kotlin
0
0
e932433dfb15cb44b657fa14964ac9acfbc37109
713
ShowTime
MIT License
app/src/main/java/de/stefanmedack/ccctv/ui/details/VideoDetailsFragment.kt
cfirmo33
98,419,053
true
{"Kotlin": 94946}
/* * Copyright (C) 2017 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 de.stefanmedack.ccctv.ui.details import android.content.Intent import android.graphics.Bitmap import android.os.Bundle import android.support.v17.leanback.app.DetailsFragment import android.support.v17.leanback.app.DetailsFragmentBackgroundController import android.support.v17.leanback.widget.* import android.support.v4.content.ContextCompat import android.util.Log import android.widget.Toast import com.bumptech.glide.Glide import com.bumptech.glide.load.resource.drawable.GlideDrawable import com.bumptech.glide.request.animation.GlideAnimation import com.bumptech.glide.request.target.SimpleTarget import de.stefanmedack.ccctv.C3TVApp import de.stefanmedack.ccctv.R import de.stefanmedack.ccctv.ui.main.MainActivity import de.stefanmedack.ccctv.ui.playback.ExoPlayerActivity import de.stefanmedack.ccctv.util.EVENT import de.stefanmedack.ccctv.util.applySchedulers import info.metadude.kotlin.library.c3media.RxC3MediaService import info.metadude.kotlin.library.c3media.models.Event import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.subscribeBy import javax.inject.Inject /** * A wrapper fragment for leanback details screens. * It shows a detailed view of video and its metadata plus related videos. */ class VideoDetailsFragment : DetailsFragment() { private val TAG = "VideoDetailsFragment" private val ACTION_WATCH = 1L @Inject lateinit var c3MediaService: RxC3MediaService private var mSelectedEvent: Event? = null private lateinit var mDetailsBackground: DetailsFragmentBackgroundController private lateinit var mPresenterSelector: ClassPresenterSelector private lateinit var mAdapter: ArrayObjectAdapter // TODO move into BaseFragment lateinit var mDisposables: CompositeDisposable var mFullEvent: Event? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) C3TVApp.graph.inject(this) mDetailsBackground = DetailsFragmentBackgroundController(this) mSelectedEvent = activity.intent.getParcelableExtra<Event>(EVENT) val selectedId = mSelectedEvent?.url?.substringAfterLast('/')?.toInt() if (mSelectedEvent != null && selectedId != null) { mPresenterSelector = ClassPresenterSelector() mAdapter = ArrayObjectAdapter(mPresenterSelector) setupDetailsOverviewRow() setupDetailsOverviewRowPresenter() adapter = mAdapter initializeBackground(mSelectedEvent) loadEventDetailAsync(selectedId) } else { val intent = Intent(activity, MainActivity::class.java) startActivity(intent) } } override fun onDestroy() { mDisposables.clear() super.onDestroy() } private fun initializeBackground(event: Event?) { mDetailsBackground.enableParallax() Glide.with(activity) .load(event?.posterUrl) .asBitmap() .centerCrop() .error(R.drawable.default_background) .into<SimpleTarget<Bitmap>>(object : SimpleTarget<Bitmap>() { override fun onResourceReady(bitmap: Bitmap, glideAnimation: GlideAnimation<in Bitmap>) { mDetailsBackground.coverBitmap = bitmap mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size()) } }) } private fun setupDetailsOverviewRow() { Log.d(TAG, "doInBackground: " + mSelectedEvent?.toString()) val row = DetailsOverviewRow(mSelectedEvent) row.imageDrawable = ContextCompat.getDrawable(activity, R.drawable.default_background) Glide.with(activity) .load(mSelectedEvent?.thumbUrl) .centerCrop() .error(R.drawable.default_background) .into<SimpleTarget<GlideDrawable>>(object : SimpleTarget<GlideDrawable>( resources.getDimensionPixelSize(R.dimen.card_width), resources.getDimensionPixelSize(R.dimen.card_height)) { override fun onResourceReady(resource: GlideDrawable, glideAnimation: GlideAnimation<in GlideDrawable>) { Log.d(TAG, "details overview card image url ready: " + resource) row.imageDrawable = resource mAdapter.notifyArrayItemRangeChanged(0, mAdapter.size()) } }) val actionAdapter = ArrayObjectAdapter() actionAdapter.add( Action( ACTION_WATCH, resources.getString(R.string.watch_event))) row.actionsAdapter = actionAdapter mAdapter.add(row) } private fun setupDetailsOverviewRowPresenter() { // Set detail background. val detailsPresenter = FullWidthDetailsOverviewRowPresenter(DetailsDescriptionPresenter()) detailsPresenter.backgroundColor = ContextCompat.getColor(activity, R.color.selected_background) // Hook up transition element. val sharedElementHelper = FullWidthDetailsOverviewSharedElementHelper() sharedElementHelper.setSharedElementEnterTransition( activity, DetailsActivity.SHARED_ELEMENT_NAME) detailsPresenter.setListener(sharedElementHelper) detailsPresenter.isParticipatingEntranceTransition = true detailsPresenter.onActionClickedListener = OnActionClickedListener { action -> // TODO needs better async loading if (action.id == ACTION_WATCH && mFullEvent != null) { val intent = Intent(activity, ExoPlayerActivity::class.java) intent.putExtra(EVENT, mFullEvent) startActivity(intent) } else { Toast.makeText(activity, action.toString(), Toast.LENGTH_SHORT).show() } } mPresenterSelector.addClassPresenter(DetailsOverviewRow::class.java, detailsPresenter) } // ********************************************* // TODO encapsulate (MVP/MVVM/MVI) // ********************************************* private fun loadEventDetailAsync(eventId: Int) { val loadConferencesSingle = c3MediaService.getEvent(eventId) .applySchedulers() mDisposables = CompositeDisposable() mDisposables.add(loadConferencesSingle .subscribeBy(// named arguments for lambda Subscribers onSuccess = { setFullEvent(it) }, // TODO proper error handling onError = { it.printStackTrace() } )) } private fun setFullEvent(event: Event) { mFullEvent = event } }
0
Kotlin
0
0
2f00a7c36b61972a3aa6c866dbeffe9c3b0e1a4b
7,532
cccTV
Apache License 2.0
base/src/main/java/com/fastaac/base/pagestate/EmptyCallback.kt
Borninthesun
266,958,012
true
{"Kotlin": 24456}
package com.fastaac.base.pagestate import com.fastaac.base.R import com.kingja.loadsir.callback.Callback /** * author : wutao * e-mail : 670831931@qq.com * time : 2019/05/17 * desc : * version: 1.0 */ class EmptyCallback : Callback() { override fun onCreateView(): Int { return R.layout.layout_empty } }
0
null
0
0
c5320b278adfb1cd0186857e934b7200d6722231
331
FastAAC
Apache License 2.0
src/main/kotlin/com/zenasoft/ami/controller/model/InfoExtractorRequest.kt
czyczk
695,836,956
false
{"Kotlin": 73106}
package com.zenasoft.ami.controller.model import kotlinx.serialization.Serializable @Serializable class InfoExtractorRequest { lateinit var url: String lateinit var query: String }
0
Kotlin
0
1
d63ba96858cdc27dea1e9fd49baa5cb0a086fb04
193
auto-music-info-server
Apache License 2.0
app/src/main/java/com/example/graduation/base/ParentDialogFragment.kt
PanicLess-2023
628,118,517
false
null
package com.example.graduation.base import android.content.DialogInterface import android.os.Bundle import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.DialogFragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentTransaction import androidx.viewbinding.ViewBinding import java.lang.reflect.ParameterizedType abstract class ParentDialogFragment<out VB : ViewBinding>(layoutId: Int) : DialogFragment(layoutId) { private var _binding: ViewBinding? = null abstract val bindingInflater: (LayoutInflater) -> VB protected abstract val cancellable: Boolean protected abstract fun initializeComponents(view: View) protected abstract val listener: DialogInterface.OnCancelListener? protected abstract val dismiss: DialogInterface.OnDismissListener? protected val binding: VB get() = _binding as VB override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { dialog?.requestWindowFeature(Window.FEATURE_NO_TITLE) dialog?.window!!.setLayout( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) dialog?.window!!.setBackgroundDrawable( ResourcesCompat.getDrawable( this.resources, android.R.color.transparent, null ) ) dialog?.window!!.setGravity(Gravity.CENTER) isCancelable = false val type = javaClass.genericSuperclass val clazz = (type as ParameterizedType).actualTypeArguments[0] as Class<VB> val method = clazz.getMethod( "inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java ) _binding = method.invoke(null, layoutInflater, container, false) as VB return _binding!!.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initializeComponents(view) } override fun onDestroyView() { _binding = null super.onDestroyView() } override fun onDestroy() { _binding = null super.onDestroy() } override fun onDismiss(dialog: DialogInterface) { val fragmentManager: FragmentManager = childFragmentManager val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction() if (fragmentManager.backStackEntryCount > 0) fragmentManager.popBackStack() fragmentTransaction.commit() _binding = null super.onDismiss(dialog) } }
0
Kotlin
0
0
c6c8e69421f441e48b5869e98dea804ffe31183a
2,969
Panicless
MIT License
feature/auth/src/androidMain/kotlin/org/michaelbel/movies/auth/AuthNavigation.kt
michaelbel
115,437,864
false
{"Kotlin": 789552, "Java": 9757, "Swift": 342, "Shell": 235}
package org.michaelbel.movies.auth import androidx.compose.ui.window.DialogProperties import androidx.navigation.NavController import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.dialog import org.michaelbel.movies.auth.ui.AuthRoute fun NavController.navigateToAuth() { navigate(AuthDestination.route) } fun NavGraphBuilder.authGraph( navigateBack: () -> Unit ) { dialog( route = AuthDestination.route, dialogProperties = DialogProperties( usePlatformDefaultWidth = false ) ) { AuthRoute( onBackClick = navigateBack ) } }
11
Kotlin
34
225
dbe7a15efd0394207ef90b267ae4316dcd3cb58c
634
movies
Apache License 2.0
gd-map-compose/src/main/java/com/melody/map/gd_compose/adapter/ComposeInfoWindowAdapter.kt
TheMelody
543,049,561
false
{"Kotlin": 1503767}
// MIT License // // Copyright (c) 2022 被风吹过的夏天 // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. package com.melody.map.gd_compose.adapter import android.content.Context import android.graphics.Color import android.view.Gravity import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.LinearLayout import android.widget.Space import android.widget.TextView import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionContext import androidx.compose.ui.platform.ComposeView import com.amap.api.maps.AMap import com.amap.api.maps.model.Marker import com.melody.map.gd_compose.overlay.MarkerNode internal class ComposeInfoWindowAdapter( private val mapContext: Context, private val markerNodeFinder: (Marker) -> MarkerNode? ) : AMap.InfoWindowAdapter { override fun getInfoContents(marker: Marker): View? { // https://lbs.amap.com/api/android-sdk/guide/draw-on-map/draw-marker // 当实现此方法并返回有效值时(返回值不为空,则视为有效),SDK 将不会使用默认的样式,而采用此方法返回的样式 val markerNode = markerNodeFinder(marker) ?: return Space(mapContext) val infoContent = markerNode.infoContent if (infoContent == null) { // 这里返回null,是处理getInfoWindow这2个方法谁返回视图的并显示冲突的问题 if(markerNode.infoWindow == null){ // 由于上面返回了一个SpaceView,这里返回一个,啥都没有设置的默认视图内容 return getDefaultInfoContent(marker, mapContext) } return null } return applyAndRemove(false ,markerNode.compositionContext) { infoContent(marker) } } override fun getInfoWindow(marker: Marker): View? { // https://lbs.amap.com/api/android-sdk/guide/draw-on-map/draw-marker // 当实现此方法并返回有效值时(返回值不为空,则视为有效),SDK 将不会使用默认的样式,而采用此方法返回的样式 val markerNode = markerNodeFinder(marker) ?: return Space(mapContext) val infoWindow = markerNode.infoWindow if (infoWindow == null) { // 这里返回null,是处理getInfoContents这2个方法谁返回视图的并显示冲突的问题 return null } return applyAndRemove(true,markerNode.compositionContext) { infoWindow(marker) } } /** * 这算是高德地图给开发者的bug,不太灵活,增加这个方法是为了给[com.melody.map.gd_compose.overlay.Marker]这个组合项使用的 * 返回一个默认的InfoContent视图,保证[com.melody.map.gd_compose.overlay.Marker]能正常弹出信息窗 */ private fun getDefaultInfoContent(marker: Marker,context: Context): View { return LinearLayout(context).apply { layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT) orientation = LinearLayout.VERTICAL addView(getDefaultInfoTextView(context,marker.title)) if(!marker.snippet.isNullOrBlank()){ addView(getDefaultInfoTextView(context,marker.snippet)) } } } private fun getDefaultInfoTextView(context: Context,content: String) : TextView { return TextView(context).apply { gravity = Gravity.CENTER_HORIZONTAL isSingleLine = true setTextColor(Color.BLACK) text = content } } private fun applyAndRemove( fromInfoWindow: Boolean, parentContext: CompositionContext, content: @Composable () -> Unit ): ViewGroup { return FrameLayout(mapContext).apply { layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT ) if(fromInfoWindow) { // 去除地图默认气泡背景, 如果是InfoContent,则只定制内容,不修改窗口背景和样式 setBackgroundColor(Color.TRANSPARENT) } addView( ComposeView(mapContext).apply { setParentCompositionContext(parentContext) setContent { content.invoke() } } ) } } }
2
Kotlin
5
60
8a867728136bdb97f156ce57381437864c196382
5,001
OmniMap-Compose
MIT License
src/test/java/no/nav/fo/veilarbregistrering/bruker/krr/KrrClientTest.kt
navikt
131,013,336
false
null
package no.nav.fo.veilarbregistrering.bruker.krr import no.nav.fo.veilarbregistrering.FileToJson.toJson import org.assertj.core.api.Assertions.* import org.junit.jupiter.api.Assertions.assertThrows import org.junit.jupiter.api.Test import java.lang.RuntimeException import kotlin.test.assertNotNull class KrrClientTest { @Test fun `skal mappe kontaktinfo med mobiltelefonnummer med ny jsonparser`() { val json = toJson(OK_JSON) val kontaktinfoDto = KrrClient.parse(json) assertNotNull(kontaktinfoDto) assertThat(kontaktinfoDto.mobiltelefonnummer).isEqualTo("11111111") } @Test fun `skal mappe feil til runtimeException`() { val json = toJson(FEIL_JSON) val runtimeException = assertThrows( RuntimeException::class.java ) { KrrClient.parse(json) } assertThat(runtimeException.message) .isEqualTo("Henting av kontaktinfo fra KRR feilet: fant ikke person") } companion object { private const val OK_JSON = "/krr/hentKontaktinformasjonOk.json" private const val FEIL_JSON = "/krr/hentKontaktinformasjonError.json" } }
13
Kotlin
4
4
a103f2b269a494d99f5f61fbc5b8505221c8f1f0
1,155
veilarbregistrering
MIT License
src/maia/ml/dataset/primitive/error/UnsupportedRepresentationError.kt
waikato-maia
387,326,639
false
null
package maia.ml.dataset.primitive.error import maia.ml.dataset.type.DataRepresentation /** * TODO */ class UnsupportedRepresentationError( representation: DataRepresentation<*, *, *> ): Exception( "Primitive datasets don't support the $representation representational type" )
0
Kotlin
0
0
b1faa44a06ce10fe4a73d42885966607649b2134
288
maia-primitive
Apache License 2.0
save-demo/src/main/kotlin/com/saveourtool/save/demo/runners/command/CommandBuilder.kt
saveourtool
300,279,336
false
{"Kotlin": 3416213, "SCSS": 86430, "JavaScript": 9061, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366}
package com.saveourtool.save.demo.runners.command import org.apache.commons.text.StringSubstitutor import org.springframework.stereotype.Component /** * Component to build a command line */ @Component class CommandBuilder { /** * @param templateCommand * @param commandContext * @return command line built by provided values */ fun build(templateCommand: String, commandContext: CommandContext): String = StringSubstitutor.replace(templateCommand, commandContext.toMap()) private fun CommandContext.toMap(): Map<String, String> = buildMap { put("testPath", testPath.toString()) put("outputPath", outputPath.toString()) tools.map { (key, value) -> put("tools.$key", value.toString()) } configPath?.let { put("configPath", it.toString()) } } }
198
Kotlin
3
38
7501e3ebe799cb0471d9b2e66df7e5089cba199b
867
save-cloud
MIT License
tasks/src/jvmMain/kotlin/app/tivi/tasks/TasksPlatformComponent.kt
ra0926
646,050,051
false
null
/* * Copyright 2023 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.tivi.tasks import app.tivi.inject.ApplicationScope import me.tatarka.inject.annotations.Provides actual interface TasksPlatformComponent { @ApplicationScope @Provides fun provideShowTasks(): ShowTasks = EmptyShowTasks } object EmptyShowTasks : ShowTasks { override fun syncLibraryShows(deferUntilIdle: Boolean) { } override fun setupNightSyncs() { } }
0
Kotlin
0
4
e780a4c48545d5198290e4f79e5b0fda28f30d40
991
CelebrationMessage
Apache License 2.0
Retail-app/android/app/src/main/java/com/wekanmdb/storeinventory/model/product/Products.kt
realm
422,284,529
false
{"Kotlin": 966534, "Swift": 867269, "Objective-C": 232478, "TypeScript": 75527, "JavaScript": 32651, "HTML": 2365, "Ruby": 2276, "Less": 31}
package com.wekanmdb.storeinventory.model.product import io.realm.RealmObject import io.realm.annotations.PrimaryKey import org.bson.types.ObjectId open class Products( @PrimaryKey var _id: ObjectId = ObjectId(), var _partition: String = "", var description: String? = null, var brand: String? = null, var detail: String? = null, var image: String = "", var name: String = "", var price: Double = 0.0, var sku: Int = 0, var totalQuantity: Long = 0 ): RealmObject()
0
Kotlin
1
8
e57077e2c26a75db4e80dd40909f12dca4a431e0
548
realm-sync-demos
Apache License 2.0
src/main/kotlin/com/yangga/kopringrestapiboilerplate/common/error/exception/ApiException.kt
yangga
692,578,157
false
{"Kotlin": 63382, "Shell": 273}
package com.yangga.kopringrestapiboilerplate.common.error.exception import com.yangga.kopringrestapiboilerplate.common.error.enums.ErrorCode open class ApiException(val code: ErrorCode, message: String?, val data: Any?) : Throwable(message) { companion object { fun of(code: ErrorCode, message: String? = null, data: Any? = null): ApiException { return ApiException(code, message, data) } } override fun toString(): String { return "ApiException(code=$code, message=$message, data=$data)" } }
0
Kotlin
0
0
52f95908f0da71c33b05f1a27362d2c519c9cb14
550
kopring-restapi-boilerplate
MIT License
src/main/kotlin/io/imulab/connect/Request.kt
imulab
181,234,721
false
null
package io.imulab.connect import io.imulab.connect.client.Client import io.imulab.connect.client.GrantType import io.imulab.connect.client.NothingClient import io.imulab.connect.client.ResponseType import java.time.LocalDateTime import java.util.* /** * Common interface for authorize request and token request. */ interface Request { /** * The unique identifier for this request */ val id: String /** * The request time. */ val requestedAt: LocalDateTime /** * The client associated with this request. */ val client: Client /** * The requested redirect_uri for this request. */ val redirectUri: String /** * The requested scopes for this request. */ val scopes: Set<String> /** * The long living session information associated with this request. */ val session: Session /** * Reference to unparsed values for this request. */ val rawValues: Map<String, String> } /** * Interface for Open ID Connect 1.0 authorize request */ interface AuthorizeRequest : Request { /** * The requested response types. */ val responseTypes: Set<ResponseType> /** * The state parameter */ val state: String /** * The requested response mode. Default to [ResponseMode.QUERY]. */ val responseMode: ResponseMode /** * The nonce of the request. Sufficient entropy is recommended. */ val nonce: String /** * The display parameter value. */ val display: Display /** * The requested prompt parameters. */ val prompt: Set<Prompt> /** * The request max_age, default to 0. */ val maxAge: Long /** * The preferred list of locales for UI display. */ val uiLocales: List<String> /** * The id_token_hint parameter. This can be used as a hint for authentication when prompt=none */ val idTokenHint: String /** * The login_hint parameter. */ val loginHint: String /** * A list of preferred authentication class reference values. */ val acrValues: List<String> /** * A list of preferred locales for the claims */ val claimsLocales: List<String> /** * Requested claims. * * Given the dynamic nature of claims, it is modelled use string based maps. */ val claims: Map<String, Any> /** * The raw request parameter */ val request: String /** * The request_uri parameter */ val requestUri: String /** * The registration parameter for dynamic client registration. */ val registration: String /** * Mark the given [responseType] as handled. */ fun markResponseTypeAsHandled(responseType: ResponseType) /** * Returns true if the given [responseType] has been marked handled by calling [markResponseTypeAsHandled]. */ fun isResponseTypeHandled(responseType: ResponseType): Boolean /** * Returns true if all response types have been handled. */ fun hasAllResponseTypesBeenHandled(): Boolean = responseTypes.all { isResponseTypeHandled(it) } /** * Merge the [other] authorize request with this one. * * When [hard] is true, values from this request will be forcefully replaced provided that values from [other] is * not null or empty * * When [hard] is false, values from this request will only be replaced when they are null or empty. * * This method should not touch system generated values such as id, request time, session, etc. */ fun mergeWith(other: AuthorizeRequest, hard: Boolean = true) } /** * Interface for a token request. */ interface TokenRequest : Request { /** * The requested grant types. */ val grantTypes: Set<GrantType> /** * The authorization code, if grant_type=authorization_code */ val code: String /** * The refresh token, if grant_type=refresh_token */ val refreshToken: String /** * Merge with another [TokenRequest]. Replace value only when self is empty or nil and [other] is not. */ fun mergeWith(other: TokenRequest, hard: Boolean = true) } /** * Interface for a session. */ interface Session { /** * The session user subject identifier. */ var subject: String /** * The session user subject identifier after the pseudonymous subject value calculation. */ var obfuscatedSubject: String /** * Id of the client that started the session. */ var clientId: String /** * Id of the request that saved this session. */ var savedByRequestId: String /** * The determined redirect_uri to be used for this request. This is not necessarily the same with * requested redirect_uri. */ var finalRedirectUri: String /** * The in-effect authorization code associated with this session. */ var liveAuthorizationCode: String /** * The in-effect access token associated with this session. */ var liveAccessToken: String /** * The in-effect refresh token associated with this ession. */ var liveRefreshToken: String /** * The scopes granted by the user. */ val grantedScopes: MutableSet<String> /** * The claims to be included in access tokens. */ val accessClaims: MutableMap<String, Any> /** * The claims to be included in id tokens. */ val idClaims: MutableMap<String, Any> /** * The authentication time */ val authTime: LocalDateTime? /** * The authentication class references satisfied by the authentication. */ val acrValues: MutableList<String> /** * The nonce value to be included in the id token. */ var nonce: String /** * Replace this session with the [other] session. Keep existing values if the values from [other] is nil or empty. */ fun replacedWith(other: Session) /** * Convenience method to test if refresh token should be generated */ fun authorizedRefreshToken(): Boolean = grantedScopes.contains(OFFLINE_ACCESS) /** * Convenience method to test if id token should be generated */ fun authorizeIdToken(): Boolean = grantedScopes.contains(OPEN_ID) } /** * Default implementation of [AuthorizeRequest]. */ class ConnectAuthorizeRequest( override var id: String = UUID.randomUUID().toString(), override var requestedAt: LocalDateTime = LocalDateTime.now(), override var client: Client = NothingClient(), override var redirectUri: String = "", override val scopes: MutableSet<String> = mutableSetOf(), override var session: Session = ConnectSession(), override var rawValues: Map<String, String> = emptyMap(), override val responseTypes: MutableSet<ResponseType> = mutableSetOf(), override var state: String = "", override var responseMode: ResponseMode = ResponseMode.QUERY, override var nonce: String = "", override var display: Display = Display.PAGE, override val prompt: MutableSet<Prompt> = mutableSetOf(), override var maxAge: Long = 0, override val uiLocales: MutableList<String> = mutableListOf(), override var idTokenHint: String = "", override var loginHint: String = "", override val acrValues: MutableList<String> = mutableListOf(), override val claimsLocales: MutableList<String> = mutableListOf(), override var claims: MutableMap<String, Any> = mutableMapOf(), override var request: String = "", override var requestUri: String = "", override var registration: String = "", private val _handled: MutableSet<ResponseType> = mutableSetOf() ) : AuthorizeRequest { override fun markResponseTypeAsHandled(responseType: ResponseType) { _handled.add(responseType) } override fun isResponseTypeHandled(responseType: ResponseType): Boolean = _handled.contains(responseType) override fun mergeWith(other: AuthorizeRequest, hard: Boolean) { if ((hard && other.client !is NothingClient) || this.client is NothingClient) this.client = other.client if ((hard && other.redirectUri.isNotEmpty()) || this.redirectUri.isEmpty()) this.redirectUri = other.redirectUri if ((hard && other.scopes.isNotEmpty()) || this.scopes.isEmpty()) { this.scopes.clear() this.scopes.addAll(other.scopes) } if ((hard && other.rawValues.isNotEmpty()) || this.rawValues.isEmpty()) this.rawValues = other.rawValues if ((hard && other.responseTypes.isNotEmpty()) || this.responseTypes.isEmpty()) { this.responseTypes.clear() this.responseTypes.addAll(other.responseTypes) } if ((hard && other.state.isNotEmpty()) || this.state.isEmpty()) this.state = other.state if ((hard && other.responseMode != ResponseMode.QUERY) || this.responseMode == ResponseMode.QUERY) this.responseMode = other.responseMode if ((hard && other.nonce.isNotEmpty()) || this.nonce.isEmpty()) this.nonce = other.nonce if ((hard && other.display != Display.PAGE) || this.display == Display.PAGE) this.display = other.display if ((hard && other.prompt.isNotEmpty()) || this.prompt.isEmpty()) { this.prompt.clear() this.prompt.addAll(other.prompt) } if ((hard && other.maxAge > 0) || this.maxAge == 0L) this.maxAge = other.maxAge if ((hard && other.uiLocales.isNotEmpty()) || this.uiLocales.isEmpty()) { this.uiLocales.clear() this.uiLocales.addAll(other.uiLocales) } if ((hard || other.idTokenHint.isNotEmpty()) || this.idTokenHint.isEmpty()) this.idTokenHint = other.idTokenHint if ((hard || other.loginHint.isNotEmpty()) || this.loginHint.isEmpty()) this.loginHint = other.loginHint if ((hard || other.acrValues.isNotEmpty()) || this.acrValues.isEmpty()) { this.acrValues.clear() this.acrValues.addAll(other.acrValues) } if ((hard || other.claimsLocales.isNotEmpty()) || this.claimsLocales.isEmpty()) { this.claimsLocales.clear() this.claimsLocales.addAll(other.claimsLocales) } if ((hard || other.claims.isNotEmpty()) || this.claims.isEmpty()) { this.claims.clear() this.claims.putAll(other.claims) } if ((hard || other.request.isNotEmpty()) || this.request.isEmpty()) this.request = other.request if ((hard || other.requestUri.isNotEmpty()) || this.requestUri.isEmpty()) this.requestUri = other.requestUri if ((hard || other.registration.isNotEmpty()) || this.registration.isEmpty()) this.registration = other.registration } } /** * Baked-in authorize request with default values. This is used to be merged with the authorize request parsed from * HTTP parameters, right before continue merging the one resolved from request parameters. */ val DefaultAuthorizeRequestValues = ConnectAuthorizeRequest( id = "", responseMode = ResponseMode.QUERY, display = Display.PAGE ) /** * Default implementation of [TokenRequest]. */ class ConnectTokenRequest( override var id: String = UUID.randomUUID().toString(), override var requestedAt: LocalDateTime = LocalDateTime.now(), override var client: Client = NothingClient(), override var redirectUri: String = "", override val scopes: MutableSet<String> = mutableSetOf(), override var session: Session = ConnectSession(), override var rawValues: Map<String, String> = emptyMap(), override val grantTypes: MutableSet<GrantType> = mutableSetOf(), override var code: String = "", override var refreshToken: String = "" ): TokenRequest { override fun mergeWith(other: TokenRequest, hard: Boolean) { if ((hard && other.client !is NothingClient) || this.client is NothingClient) this.client = other.client if ((hard && other.redirectUri.isNotEmpty()) || this.redirectUri.isEmpty()) this.redirectUri = other.redirectUri if ((hard && other.scopes.isNotEmpty()) || this.scopes.isEmpty()) { this.scopes.clear() this.scopes.addAll(other.scopes) } if ((hard && other.rawValues.isNotEmpty()) || this.rawValues.isEmpty()) this.rawValues = other.rawValues if ((hard && other.grantTypes.isNotEmpty()) || this.grantTypes.isEmpty()) { this.grantTypes.clear() this.grantTypes.addAll(other.grantTypes) } if ((hard && other.code.isNotEmpty()) || this.code.isEmpty()) code = other.code if ((hard && other.refreshToken.isNotEmpty()) || this.refreshToken.isEmpty()) refreshToken = other.refreshToken } } /** * Default implementation of [Session]. */ class ConnectSession( override var subject: String = "", override var obfuscatedSubject: String = "", override var clientId: String = "", override var savedByRequestId: String = "", override var finalRedirectUri: String = "", override var liveAuthorizationCode: String = "", override var liveAccessToken: String = "", override var liveRefreshToken: String = "", override val grantedScopes: MutableSet<String> = mutableSetOf(), override var accessClaims: MutableMap<String, Any> = mutableMapOf(), override var idClaims: MutableMap<String, Any> = mutableMapOf(), override var authTime: LocalDateTime? = null, override val acrValues: MutableList<String> = mutableListOf(), override var nonce: String = "" ) : Session { override fun replacedWith(other: Session) { if (other.subject.isNotEmpty()) this.subject = other.subject if (other.obfuscatedSubject.isNotEmpty()) this.obfuscatedSubject = other.obfuscatedSubject if (other.clientId.isNotEmpty()) this.clientId = other.clientId if (other.savedByRequestId.isNotEmpty()) this.savedByRequestId = other.savedByRequestId if (other.finalRedirectUri.isNotEmpty()) this.finalRedirectUri = other.finalRedirectUri if (other.liveAuthorizationCode.isNotEmpty()) this.liveAuthorizationCode = other.liveAuthorizationCode if (other.liveAccessToken.isNotEmpty()) this.liveAccessToken = other.liveAccessToken if (other.liveRefreshToken.isNotEmpty()) this.liveRefreshToken = other.liveRefreshToken if (other.grantedScopes.isNotEmpty()) { this.grantedScopes.clear() this.grantedScopes.addAll(other.grantedScopes) } if (other.accessClaims.isNotEmpty()) this.accessClaims = other.accessClaims if (other.idClaims.isNotEmpty()) this.idClaims = other.idClaims if (other.authTime != null) this.authTime = other.authTime if (other.acrValues.isNotEmpty()) { this.acrValues.clear() this.acrValues.addAll(other.acrValues) } if (other.nonce.isNotEmpty()) this.nonce = other.nonce } } enum class ResponseMode(val value: String) { QUERY("query"), FRAGMENT("fragment"); companion object { @JvmStatic fun parse(value: String): ResponseMode = values().find { it.value == value } ?: throw Errors.invalidRequest("'$value' is not a valid response mode.") } } enum class Display(val value: String) { PAGE("page"), POPUP("popup"), TOUCH("touch"), WAP("wap"); companion object { @JvmStatic fun parse(value: String): Display = values().find { it.value == value } ?: throw Errors.invalidRequest("'$value' is not a valid display.") } } enum class Prompt(val value: String) { NONE("none"), LOGIN("login"), CONSENT("consent"), SELECT_ACCOUNT("select_account"); companion object { @JvmStatic fun parse(value: String): Prompt = values().find { it.value == value } ?: throw Errors.invalidRequest("'$value' is not a valid prompt.") } }
1
Kotlin
0
0
8983abc537212b822abe6565cc92f0a4f3678b81
16,361
connect-sdk
MIT License
comvvmhelper/src/main/java/com/kk/android/comvvmhelper/extension/ActivityExtensions.kt
chenlong0525
309,290,111
true
{"Kotlin": 132728}
package com.kk.android.comvvmhelper.extension import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.fragment.app.FragmentActivity /** * @author kuky. * @description */ fun FragmentActivity.normalWindow() { window?.decorView?.systemUiVisibility = 0 } fun FragmentActivity.hideStatusBar() { window?.decorView?.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_FULLSCREEN actionBar?.hide() } fun FragmentActivity.hideNavigationBar() { window?.decorView?.systemUiVisibility = ( View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE) } fun FragmentActivity.normalFullScreen() { window?.decorView?.systemUiVisibility = ( View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) actionBar?.hide() } fun FragmentActivity.stickFullScreen() { window?.decorView?.systemUiVisibility = ( View.SYSTEM_UI_FLAG_IMMERSIVE or View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN) actionBar?.hide() } fun AppCompatActivity.replaceActionBar(toolbar: Toolbar) { setSupportActionBar(toolbar) supportActionBar?.apply { setDisplayHomeAsUpEnabled(true) setDisplayShowTitleEnabled(true) } }
0
null
0
0
0c545b11bb8ffb15d17616855f1846a8969b804f
1,891
CoMvvmHelper
MIT License
common-jvm/src/main/java/org/ergoplatform/utils/UiUtils.kt
ergoplatform
376,102,125
false
null
package org.ergoplatform.utils import org.ergoplatform.TokenAmount import org.ergoplatform.WalletStateSyncManager import org.ergoplatform.uilogic.STRING_FORMAT_FIAT import org.ergoplatform.uilogic.STRING_LABEL_ERG_AMOUNT import org.ergoplatform.uilogic.StringProvider import java.math.BigDecimal import java.math.RoundingMode import java.text.DecimalFormat import java.text.DecimalFormatSymbols import java.util.* import kotlin.math.ln import kotlin.math.pow fun inputTextToDouble(amountStr: String?): Double { try { return if (amountStr.isNullOrEmpty()) 0.0 else amountStr.toDouble() } catch (t: Throwable) { return 0.0 } } fun formatTokenPriceToString( balanceAmount: TokenAmount, pricePerErg: BigDecimal, walletSyncManager: WalletStateSyncManager, text: StringProvider ): String { val ergValue = balanceAmount.toErgoValue(pricePerErg) return if (walletSyncManager.fiatCurrency.isNotEmpty()) { formatFiatToString( ergValue.toDouble() * walletSyncManager.fiatValue.value, walletSyncManager.fiatCurrency, text ) } else { text.getString(STRING_LABEL_ERG_AMOUNT, ergValue.toStringRoundToDecimals()) } } /** * fiat is formatted according to users locale, because it is his local currency */ fun formatFiatToString(amount: Double, currency: String, text: StringProvider): String { return DecimalFormat(text.getString(STRING_FORMAT_FIAT)).format(amount) + " " + currency.uppercase(Locale.getDefault()) } fun formatDoubleWithPrettyReduction(amount: Double): String { val suffixChars = "KMGTPE" val formatter = DecimalFormat("###.#", DecimalFormatSymbols(Locale.US)) formatter.roundingMode = RoundingMode.DOWN return if (amount < 1000.0) formatter.format(amount) else { val exp = (ln(amount) / ln(1000.0)).toInt() formatter.format(amount / 1000.0.pow(exp.toDouble())) + suffixChars[exp - 1] } } fun ByteArray.toHex(): String = joinToString(separator = "") { eachByte -> "%02x".format(eachByte) } fun Throwable.getMessageOrName(): String = message ?: javaClass.name
20
null
35
94
b5f6e5176cf780a7437eb3c8447820bd9409c8ac
2,132
ergo-wallet-app
Apache License 2.0
app/src/main/java/co/tami/basketball/team/data/source/LoginDataSourceImpl.kt
Hydratant
747,542,242
false
{"Kotlin": 21076}
package co.tami.basketball.team.data import com.google.firebase.auth.AuthResult import com.google.firebase.auth.FirebaseAuth import com.google.firebase.auth.FirebaseUser import kotlinx.coroutines.CancellableContinuation import kotlinx.coroutines.suspendCancellableCoroutine import timber.log.Timber import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException class LoginDataSourceImpl( private val firebaseAuth: FirebaseAuth ) : LoginDataSource { override suspend fun login( email: String, password: String ): UserData = suspendCancellableCoroutine { continuation: CancellableContinuation<UserData> -> firebaseAuth.signInWithEmailAndPassword(email, password) .addOnSuccessListener { authResult: AuthResult -> authResult.user?.let { firebaseUser: FirebaseUser -> Timber.i("FirebaseAuth Login Success : ${firebaseUser.uid}") continuation.resume(firebaseUser.toUserData()) } ?: continuation.resumeWithException(Exception("login User is Null")) }.addOnFailureListener { exception: Exception -> Timber.e("loginError : ${exception.message}") continuation.resumeWithException(exception) } } }
2
Kotlin
0
0
208427a81756a91f634b6440c00a35f791d0d83a
1,285
team
Apache License 2.0
service/src/main/kotlin/io/provenance/explorer/grpc/v1/MarkerGrpcClient.kt
provenance-io
332,035,574
false
null
package io.provenance.explorer.grpc.v1 import io.grpc.ManagedChannelBuilder import io.provenance.explorer.config.interceptor.GrpcLoggingInterceptor import io.provenance.explorer.grpc.extensions.getPagination import io.provenance.explorer.grpc.extensions.toMarker import io.provenance.marker.v1.Balance import io.provenance.marker.v1.MarkerAccount import io.provenance.marker.v1.QueryGrpcKt import io.provenance.marker.v1.QueryHoldingResponse import io.provenance.marker.v1.queryHoldingRequest import io.provenance.marker.v1.queryMarkerRequest import kotlinx.coroutines.sync.Semaphore import kotlinx.coroutines.sync.withPermit import org.springframework.stereotype.Component import java.net.URI import java.util.concurrent.TimeUnit import io.provenance.marker.v1.QueryParamsRequest as MarkerRequest @Component class MarkerGrpcClient(channelUri: URI, private val semaphore: Semaphore) { private val markerClient: QueryGrpcKt.QueryCoroutineStub private val markerClientFuture: QueryGrpcKt.QueryCoroutineStub init { val channel = ManagedChannelBuilder.forAddress(channelUri.host, channelUri.port) .also { if (channelUri.scheme == "grpcs") { it.useTransportSecurity() } else { it.usePlaintext() } } .idleTimeout(5, TimeUnit.MINUTES) .keepAliveTime(60, TimeUnit.SECONDS) .keepAliveTimeout(20, TimeUnit.SECONDS) .intercept(GrpcLoggingInterceptor()) .build() markerClient = QueryGrpcKt.QueryCoroutineStub(channel) markerClientFuture = QueryGrpcKt.QueryCoroutineStub(channel) } suspend fun getMarkerDetail(id: String): MarkerAccount? = semaphore.withPermit { try { markerClient.marker(queryMarkerRequest { this.id = id }).marker.toMarker() } catch (e: Exception) { null } } suspend fun getMarkerHolders(denom: String, offset: Int, count: Int): QueryHoldingResponse = semaphore.withPermit { markerClient.holding( queryHoldingRequest { this.id = denom this.pagination = getPagination(offset, count) } ) } suspend fun getMarkerHoldersCount(denom: String): QueryHoldingResponse = semaphore.withPermit { markerClient.holding( queryHoldingRequest { this.id = denom this.pagination = getPagination(0, 1) } ) } suspend fun getMarkerParams() = markerClient.params(MarkerRequest.newBuilder().build()) suspend fun getAllMarkerHolders(denom: String): MutableList<Balance> { var offset = 0 val count = 100 val results = getMarkerHolders(denom, offset, count) val total = results.pagination?.total ?: results.balancesCount.toLong() val holders = results.balancesList.toMutableList() while (holders.count() < total) { offset += count getMarkerHolders(denom, offset, count).let { holders.addAll(it.balancesList) } } return holders } }
16
null
2
4
f90c3b406561965b8ce08359d703a9ad5a54a928
3,316
explorer-service
Apache License 2.0
src/main/kotlin/gg/scala/aware/conversation/ConversationContinuation.kt
GrowlyX
467,297,067
false
{"Kotlin": 36771}
package gg.scala.aware.conversation /** * Continuation context * for a conversation. * * @author GrowlyX * @since 3/9/2022 */ enum class ConversationContinuation { CONTINUE, END }
0
Kotlin
1
8
c41894537db8f7a56f80060150405f5da806fe26
191
aware
MIT License
vico/core/src/main/java/com/patrykandpatrick/vico/core/common/MutableMeasuringContext.kt
patrykandpatrick
338,848,755
false
{"Kotlin": 680666, "CSS": 166}
/* * Copyright 2024 by Patryk Goworowski and Patrick Michalik. * * 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.patrykandpatrick.vico.core.common import android.graphics.RectF import androidx.annotation.RestrictTo import com.patrykandpatrick.vico.core.common.data.CacheStore /** A [MeasuringContext] implementation that facilitates the mutation of some of its properties. */ public open class MutableMeasuringContext( override val canvasBounds: RectF, override var density: Float, override var isLtr: Boolean, @get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) public var spToPx: (Float) -> Float, ) : MeasuringContext { override val cacheStore: CacheStore = CacheStore() override fun spToPx(sp: Float): Float = spToPx.invoke(sp) }
12
Kotlin
130
2,132
7066e4bf88cdd1e4c57e1ab03d10354e5f640928
1,271
vico
Apache License 2.0
demo/desktop/src/jvmMain/kotlin/main.kt
Qawaz
605,951,742
false
null
import androidx.compose.material.MaterialTheme import androidx.compose.ui.window.Window import androidx.compose.ui.window.application import com.wakaztahir.common.DisplayWebView fun main() = application { Window(onCloseRequest = ::exitApplication) { MaterialTheme { DisplayWebView() } } }
0
Kotlin
0
0
46568363ff182771c31ee7e8ffb9de7684028af1
326
webview-compose
MIT License
src/main/kotlin/com/vladonemo/tools/dependencycollector/input/maven/MavenDependency.kt
vladonemo
326,962,329
false
null
package com.vladonemo.tools.dependencycollector.input.maven import com.vladonemo.tools.dependencycollector.input.Dependency class MavenDependency() : Dependency() { lateinit var scope: String companion object { infix fun fromString(id: String): MavenDependency { val splits = id.trimStart('"').trimEnd('"').split(':') return MavenDependency().apply { name = "${splits[0]}:${splits[1]}" version = splits[3] scope = splits[4] } } } }
0
Kotlin
1
1
cb2c3063916d2f4e1146ee34b869d57fb7db1730
550
dependency-list
MIT License
ZMain/ImkGithubApp/src/main/java/net/imknown/imkgithub/mvp/BaseMvpPresenterActivity.kt
imknown
98,404,658
false
null
package net.imknown.imkgithub.mvp import android.widget.Toast import net.imknown.imkgithub.global.BaseActivity import javax.inject.Inject abstract class BaseMvpPresenterActivity<MvpView : IMvpView, MvpPresenter : IMvpPresenter<MvpView>> : BaseActivity(), IMvpView { @Inject protected lateinit var mPresenter: MvpPresenter override fun showMessage(@MessageTypeDef messageType: Int, message: String) { if (messageType == MessageType.Toast) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } } override fun onDestroy() { mPresenter.detachView() super.onDestroy() } }
0
Kotlin
0
3
4c6b88eaf7b3cc3cfb68bed6a952a284fdae1ac0
656
ImkGithub
Apache License 2.0
data/core/src/main/java/com/gnoemes/shimori/data/core/entities/titles/ranobe/RanobeWithTrack.kt
gnoemes
213,210,354
false
{"Kotlin": 788446, "Shell": 2974}
package com.gnoemes.shimori.data.core.entities.titles.ranobe import com.gnoemes.shimori.data.core.entities.PaginatedEntity import com.gnoemes.shimori.data.core.entities.TitleWithTrack import com.gnoemes.shimori.data.core.entities.track.Track import com.gnoemes.shimori.data.core.entities.track.TrackTargetType @kotlinx.serialization.Serializable data class RanobeWithTrack( override val entity: Ranobe, override val track: Track?, override val pinned: Boolean ) : TitleWithTrack<Ranobe>, PaginatedEntity { override val id: Long = entity.id override val type: TrackTargetType = entity.type }
0
Kotlin
1
31
7bf5caccb92d3c789ecd3f1c8a6d3a7eeb4d408b
612
Shimori
Apache License 2.0
test-common/src/main/kotlin/ArrowTestEx.kt
navikt
227,366,088
false
{"Kotlin": 9808901, "Shell": 4388, "TSQL": 1233, "Dockerfile": 1209}
package no.nav.su.se.bakover.test import arrow.core.Either import arrow.core.getOrElse import io.kotest.assertions.fail import org.checkerframework.checker.units.qual.C fun <A, B> Either<A, B>.getOrFail(msg: String): B { return getOrElse { fail("Message: $msg, Error: $it") } } fun <A, B> Either<A, B>.getOrFail(): B { return getOrElse { fail("""$it""") } } inline fun <reified C> Either<Any?, Any?>.getOrFailAsType(): C { return getOrElse { fail("""$it""") }.let { it as C } }
2
Kotlin
1
1
1fad47d00b8bf746c7770652fdbb21b91ab0766e
494
su-se-bakover
MIT License
packages/core/src/main/java/com/openmobilehub/android/maps/core/utils/location/ContinuousLocationService.kt
openmobilehub
742,498,878
false
{"Kotlin": 1027038, "Java": 38535, "Shell": 1124}
package com.openmobilehub.android.maps.core.utils.location import android.Manifest import android.location.Location import android.location.LocationListener import android.location.LocationManager import androidx.annotation.RequiresPermission import com.openmobilehub.android.maps.core.presentation.models.OmhCoordinate import com.openmobilehub.android.maps.core.presentation.models.OmhMapException import com.openmobilehub.android.maps.core.presentation.models.OmhMapStatusCodes class ContinuousLocationService( private val locationManager: LocationManager, private val providers: List<String>, ) { private var locationListener: LocationListener? = null private var currentBestLocation: Location? = null @SuppressWarnings("TooGenericExceptionCaught", "LongMethod") @RequiresPermission(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION]) fun startLocationUpdates( onLocationUpdateSuccess: (OmhCoordinate) -> Unit, onLocationUpdateFailure: (Exception) -> Unit ) { // Get the last location first to improve UX val lastLocations = providers.map { provider -> locationManager.getLastKnownLocation(provider) } val bestLocation = LocationUtil.getMostAccurateLocation(lastLocations) if (bestLocation != null) { currentBestLocation = bestLocation onLocationUpdateSuccess( OmhCoordinate( bestLocation.latitude, bestLocation.longitude ) ) } locationListener = LocationListener { location: Location? -> if (location != null) { val moreAccurateLocation = LocationUtil.getMoreAccurateLocation(location, currentBestLocation) if (moreAccurateLocation == location) { currentBestLocation = location onLocationUpdateSuccess( OmhCoordinate( location.latitude, location.longitude ) ) } } else { onLocationUpdateFailure( OmhMapException.NullLocation( IllegalStateException( OmhMapStatusCodes.getStatusCodeString( OmhMapStatusCodes.NULL_LOCATION ) ) ) ) } } try { providers.forEach { provider -> locationManager.requestLocationUpdates( provider, 0L, 0f, locationListener!! ) } } catch (exception: IllegalArgumentException) { onLocationUpdateFailure( OmhMapException.ApiException( OmhMapStatusCodes.NULL_LISTENER, exception ) ) } catch (exception: RuntimeException) { onLocationUpdateFailure( OmhMapException.ApiException( OmhMapStatusCodes.INVALID_LOOPER, exception ) ) } catch (exception: SecurityException) { onLocationUpdateFailure(OmhMapException.PermissionError(exception)) } catch (exception: OmhMapException.ApiException) { onLocationUpdateFailure(exception) } } @RequiresPermission(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION]) fun stopLocationUpdates() { currentBestLocation = null if (locationListener != null) { locationManager.removeUpdates(locationListener!!) } } }
0
Kotlin
0
1
922578f1166e8e49de891107848287df8be96787
4,020
android-omh-maps
Apache License 2.0
app/src/main/java/vn/loitp/app/activity/demo/fragmentflow/FrmFlow1.kt
tplloi
126,578,283
false
null
package vn.loitp.app.activity.demo.fragmentflow import android.os.Bundle import android.view.View import com.annotation.LogTag import kotlinx.android.synthetic.main.frm_demo_flow_1.* import vn.loitp.app.R @LogTag("FrmFlow1") class FrmFlow1 : FrmFlowBase() { override fun setLayoutResourceId(): Int { return R.layout.frm_demo_flow_1 } override fun onBackClick(): Boolean { print("onBackClick") popThisFragment() return true } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) print("onViewCreated") bt.setOnClickListener { (activity as FragmentFlowActivity).showFragment(FrmFlow2()) } } override fun onFragmentResume() { super.onFragmentResume() print("onFragmentResume") } fun print(msg: String) { (activity as FragmentFlowActivity).print("FrmFlow1: $msg") } }
0
Kotlin
0
6
4fe4c945e89819d77aaf6cb76f1de6bbff7868a5
974
basemaster
Apache License 2.0
application/src/main/kotlin/dev/hypest/pis/restaurants/adapter/out/event/OrderRejectedEventProducer.kt
PIS22Z
557,250,063
false
{"Kotlin": 118874, "Groovy": 79090, "Dockerfile": 145}
package dev.hypest.pis.restaurants.adapter.out.event import dev.hypest.pis.common.eventaggregator.DomainEvent import dev.hypest.pis.common.eventaggregator.EventProducer import dev.hypest.pis.configuration.RabbitmqConfig.Companion.ORDER_REJECTED import io.micronaut.rabbitmq.annotation.Binding import io.micronaut.rabbitmq.annotation.RabbitClient @RabbitClient interface OrderRejectedEventProducer : EventProducer { @Binding(ORDER_REJECTED) override fun produce(event: DomainEvent) }
0
Kotlin
0
0
a5eab87108f49a6355362682b94b7c49d5dd421b
495
backend
MIT License
vclib-openid/src/commonMain/kotlin/at/asitplus/wallet/lib/oidc/AuthenticationRequest.kt
a-sit-plus
602,578,639
false
null
package at.asitplus.wallet.lib.oidc import at.asitplus.wallet.lib.oidvci.decodeFromUrlQuery import at.asitplus.wallet.lib.oidvci.encodeToParameters import io.ktor.http.URLBuilder import io.ktor.http.Url import io.ktor.util.flattenEntries /** * Container for a OIDC Authentication Request */ data class AuthenticationRequest( val url: String, val params: AuthenticationRequestParameters, ) { fun toUrl(): String { val urlBuilder = URLBuilder(url) params.encodeToParameters().forEach { urlBuilder.parameters.append(it.key, it.value) } return urlBuilder.buildString() } companion object { /** * Expects [AuthenticationRequestParameters] as the parameters of the URL in [it], * e.g. `https://example.com?response_type=..." */ fun parseUrl(it: String): AuthenticationRequest? { val url = kotlin.runCatching { Url(it) }.getOrNull() ?: return null val params: AuthenticationRequestParameters = url.parameters.flattenEntries().toMap().decodeFromUrlQuery() return AuthenticationRequest( url = "${url.protocol}://${url.host}${url.encodedPath}", params = params ) } } }
2
Kotlin
0
2
4c445138f0921740777467c90ec35acad351c791
1,260
kmm-vc-library
Apache License 2.0
src/main/kotlin/com/imoonday/skill/DoubleJumpSkill.kt
iMoonDay
759,188,611
false
{"Kotlin": 382822, "Java": 57048}
package com.imoonday.skill import com.imoonday.util.SkillType import com.imoonday.util.UseResult import com.imoonday.util.send import com.imoonday.util.spawnParticles import net.minecraft.network.packet.s2c.play.EntityVelocityUpdateS2CPacket import net.minecraft.particle.ParticleTypes import net.minecraft.server.network.ServerPlayerEntity class DoubleJumpSkill : Skill( id = "double_jump", types = listOf(SkillType.MOVEMENT), cooldown = 3, rarity = Rarity.UNCOMMON ) { override fun use(user: ServerPlayerEntity): UseResult { user.run { stopFallFlying() jump() velocityDirty = true velocity = velocity.multiply(1.0, 1.35, 1.0) send(EntityVelocityUpdateS2CPacket(this)) user.spawnParticles( ParticleTypes.CLOUD, pos, 10, 0.5, 0.0, 0.5, 0.1 ) } return UseResult.success() } }
0
Kotlin
0
0
bdccadd1cdfaeaf551ce38cb82b5ec536eff30f9
1,021
AdvancedSkills
Creative Commons Zero v1.0 Universal
backend/src/main/kotlin/ntnu/idatt2105/core/exception/handler/MethodArgumentInvalidHandler.kt
olros
366,615,349
false
null
package ntnu.idatt2105.core.exception.handler import ntnu.idatt2105.core.response.ResponseError import org.springframework.core.annotation.Order import org.springframework.http.HttpStatus import org.springframework.web.bind.MethodArgumentNotValidException import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.ResponseStatus import org.springframework.web.bind.annotation.RestControllerAdvice @Order(1) @RestControllerAdvice class MethodArgumentInvalidHandler { /** * Return response validation error with the the errors mapped * and appropriate error message */ @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(MethodArgumentNotValidException::class) fun handleValidationExceptions(exception: MethodArgumentNotValidException): ResponseError? { val fieldErrorMessages = getFieldErrors(exception) val globalErrorMessages: MutableMap<String, Any?> = getGlobalErrors(exception) val message = getMessage(exception) includeFieldErrors(fieldErrorMessages, globalErrorMessages) return ResponseError.validationError(message, globalErrorMessages) } /** * Return map of field to field error messages */ private fun getFieldErrors(exception: MethodArgumentNotValidException): Map<String, String?> = exception.bindingResult .fieldErrors .map { it.field to it.defaultMessage } .toMap() private fun getGlobalErrors(exception: MethodArgumentNotValidException): MutableMap<String, Any?> = exception.globalErrors .map { it.code.toString() to it.defaultMessage } .toMap() .toMutableMap() /** * Return appropriate message from the exception. * * If it has global errors use the first message, if not use the first field message if present. * Defaults to a generic message. */ private fun getMessage( exception: MethodArgumentNotValidException, ) = when { exception.globalErrors.isNotEmpty() -> exception.globalErrors[0].defaultMessage.toString() exception.fieldErrors.isNotEmpty() -> exception.fieldErrors[0].defaultMessage.toString() else -> "One or more arguments are invalid" } /** * Add field errors map to the global map if present. */ private fun includeFieldErrors( fieldErrorMessages: Map<String, String?>, globalErrorMessages: MutableMap<String, Any?> ) { if (fieldErrorMessages.isNotEmpty()) globalErrorMessages["fields"] = fieldErrorMessages } }
0
Kotlin
3
2
a2fa5bbca5a9db67f12733301b952807d66e673f
2,649
Rombestilling
MIT License
app/src/main/java/com/concordium/wallet/ui/airdrop/AirdropActivity.kt
Concordium
750,205,274
false
{"Kotlin": 1674268, "Java": 68714, "HTML": 53707, "CSS": 256}
package com.concordium.wallet.ui.airdrop import android.content.Intent import android.net.Uri import android.os.Bundle import android.text.* import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.util.Base64 import android.view.View import android.widget.TextView import android.widget.Toast import androidx.constraintlayout.widget.ConstraintLayout import androidx.core.text.bold import androidx.core.text.underline import androidx.core.view.children import androidx.lifecycle.ViewModelProvider import com.bumptech.glide.Glide import com.concordium.wallet.Constants import com.concordium.wallet.R import com.concordium.wallet.data.room.Account import com.concordium.wallet.data.util.CurrencyUtil.formatGTU import com.concordium.wallet.databinding.ActivityAirdropBinding import com.concordium.wallet.extension.collectWhenStarted import com.concordium.wallet.ui.base.BaseActivity import com.google.gson.Gson import com.google.gson.annotations.SerializedName import timber.log.Timber // { // "api_url": "https://stage.spaceseven.cloud/api/v2/airdrop/register-wallet", // "airdrop_id": "3446112874593", // "airdrop_name": "MasterChef", // "marketplace_name": "Spaceseven", // "marketplace_url": "https://stage.spaceseven.cloud", // "marketplace_icon": " https://weeny.link/1KRq431" // } data class AirDropPayload( @SerializedName("api_url") val apiUrl: String, @SerializedName("airdrop_id") val airdropId: Long, @SerializedName("airdrop_name") val airdropName: String, @SerializedName("marketplace_name") val marketplaceName: String, @SerializedName("marketplace_url") val marketplaceUrl: String, @SerializedName("marketplace_icon") val marketplaceIcon: String ) { override fun toString(): String { return "AirDropPayload(apiUrl='$apiUrl', airdropId='$airdropId', airdropName='$airdropName', marketplaceName='$marketplaceName', marketplaceUrl='$marketplaceUrl', marketplaceIcon='$marketplaceIcon')" } } class AirdropActivity : BaseActivity() { private lateinit var viewModel: AirDropViewModel private var binding: ActivityAirdropBinding? = null private var selectedAccount: Account? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityAirdropBinding.inflate(layoutInflater) setContentView(binding?.root) val airDropPayload = intent?.getStringExtra(Constants.Extras.EXTRA_AIR_DROP_PAYLOAD) if (airDropPayload == null) { finish() return } println(">>>>>>>>>>>>>>>>>>> ") val payloadJson = try { String(Base64.decode(airDropPayload.replace("airdrop://", ""), Base64.DEFAULT)).trim() } catch (ex: Exception) { showErrorMessage("Malformed airdrop data") finish() return } val payload = try { Gson().fromJson(payloadJson, AirDropPayload::class.java) } catch (ex: Exception) { Timber.e("Unable parse jsom from QR. Exception: ${ex.message}") finish() return } println(payload) initUi(payload) initViewModel(payload) } private fun initUi(payload: AirDropPayload) { binding?.shopName?.text = payload.marketplaceName binding?.shopDesc?.text = payload.airdropName binding?.btnCancel?.setOnClickListener { finish() } binding?.toolbarLayout?.toolbarTitle?.text = "AirDrop" binding?.toolbarLayout?.toolbarCloseBtn?.visibility = View.VISIBLE binding?.toolbarLayout?.toolbarCloseBtn?.setOnClickListener { finish() } binding?.btnConnect?.setOnClickListener { viewModel.processAction(AirDropAction.GetWallets) } binding?.btnContinue?.setOnClickListener { finish() } // binding?.descBody?.text = getString(R.string.airdrop_connect_description, payload.marketplaceName, payload.airdropName) binding?.descBody?.text = getSpannableDescription(payload.marketplaceName, payload.airdropName, payload.marketplaceUrl) binding?.descBody?.movementMethod = LinkMovementMethod.getInstance() binding?.shopLogo?.let { Glide.with(applicationContext).load(payload.marketplaceIcon).into(it) } } private fun getSpannableDescription(marketplaceName: String, airdropName: String, marketplaceUrl: String): Spannable { // val txt = "Please confirm registration to AirDrop campaign at $marketplaceName $airdropName" val sb = SpannableStringBuilder() .append("Please confirm registration to AirDrop campaign at ") .bold { underline { append(marketplaceName) } } .append(" $airdropName") val clickable = object : ClickableSpan() { override fun onClick(p0: View) { startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(marketplaceUrl))) } } sb.setSpan(clickable, 51, 51 + marketplaceName.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) return sb } private fun initViewModel(payload: AirDropPayload) { viewModel = ViewModelProvider( this, ViewModelProvider.AndroidViewModelFactory.getInstance(application) )[AirDropViewModel::class.java] viewModel.processAction(AirDropAction.Init(payload.airdropId.toLong(), payload.apiUrl)) viewModel.viewState.collectWhenStarted(this, ::processViewState) viewModel.onWalletReady().observe(this) { event -> event.contentOrNullIfUsed?.let { showWallets(it) } } viewModel.onError().observe(this) { event -> event.contentOrNullIfUsed?.let { Toast.makeText(applicationContext, it, Toast.LENGTH_SHORT).show() // showErrorMessage(it) finish() } } viewModel.doRegistrationResponse().observe(this) { event -> event.contentOrNullIfUsed?.let { binding?.btnContinue?.visibility = View.VISIBLE binding?.btnConnect?.visibility = View.GONE binding?.btnCancel?.visibility = View.GONE binding?.descTitle?.visibility = View.GONE binding?.descBody?.visibility = View.GONE binding?.accountsPool?.removeAllViews() binding?.accountsPool?.visibility = View.GONE binding?.regResult?.visibility = View.VISIBLE binding?.regResult?.text = it.message } } } private fun processViewState(state: AirDropState) { when (state) { AirDropState.ConnectConfirm -> {} AirDropState.SelectWallet -> { binding?.descTitle?.text = "Select wallet" binding?.descBody?.visibility = View.GONE binding?.btnConnect?.text = "Select" binding?.btnConnect?.setOnClickListener { if (selectedAccount != null) { viewModel.processAction(AirDropAction.SendRegistration(selectedAccount!!)) } else { showErrorMessage("No wallet selected") } } } AirDropState.ShowResult -> {} } } private fun showErrorMessage(string: String) { binding?.toastLayoutTopError?.let { popup.showSnackbarError(it, string) } } private fun showWallets(wallets: List<Account>) { binding?.accountsPool?.removeAllViews() wallets.forEach { acc -> val v = layoutInflater.inflate(R.layout.account_info_row, null) v.findViewById<TextView>(R.id.accAddress).text = getString(R.string.acc_address_placeholder, acc.name, acc.address) val balance = formatGTU(acc.totalUnshieldedBalance) v.findViewById<TextView>(R.id.accBalance).text = getString(R.string.acc_balance_placeholder, balance) binding?.accountsPool?.addView(v) v.setOnClickListener { clearAccSelection() selectedAccount = acc v.findViewById<ConstraintLayout>(R.id.accRoot).background = resources.getDrawable(R.drawable.btn_round_outline_bg_active) } } } private fun clearAccSelection() { binding?.accountsPool?.children?.forEach { it.findViewById<ConstraintLayout>(R.id.accRoot).background = resources.getDrawable(R.drawable.btn_round_outline_bg) } } }
20
Kotlin
0
1
8f6c0019e2edf22900fbe480b3fa39996fefa2dc
8,763
cryptox-android
Apache License 2.0
tgbotapi.core/src/commonMain/kotlin/dev/inmo/tgbotapi/requests/send/abstracts/ReplyingMarkupSendMessageRequest.kt
InsanusMokrassar
163,152,024
false
null
package dev.inmo.tgbotapi.requests.send.abstracts import dev.inmo.tgbotapi.CommonAbstracts.types.ReplyMarkup interface ReplyingMarkupSendMessageRequest<T: Any>: SendMessageRequest<T>, ReplyMarkup
9
Kotlin
10
99
8206aefbb661db936d4078a8ef7cc9cecb5384e4
197
TelegramBotAPI
Apache License 2.0
src/main/kotlin/com/blog/configurationproperties/ConfigurationPropertiesApplication.kt
BalazsAtWork
160,158,772
false
null
package com.blog.configurationproperties import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class ConfigurationPropertiesApplication fun main(args: Array<String>) { runApplication<ConfigurationPropertiesApplication>(*args) }
0
Kotlin
0
0
673a8f834ce67afd9fb62cb6d10031bda91a5efb
319
blog-springboot-confprop-cglibproxy-kotlin
Apache License 2.0
presentation/src/main/java/com/easycashwallet/tasks/ec/config/PresentationModule.kt
ibrahimelgales
725,755,251
false
{"Kotlin": 80151}
package com.easycashwallet.tasks.ec.config import com.easycashwallet.tasks.ec.di.ManagersModule import com.easycashwallet.tasks.ec.di.MappersModule import com.easycashwallet.tasks.ec.di.ViewModelsModule import com.easycashwallet.tasks.utils.extention.lazyModule import org.koin.dsl.module val PresentationModule by lazyModule { includes(ViewModelsModule, ManagersModule, MappersModule) }
0
Kotlin
0
0
56fc753814377c998263617c039493e450fb2b18
393
EC
Apache License 2.0
stream-chat-android-ui-components/src/main/kotlin/io/getstream/chat/android/ui/feature/messages/composer/attachment/picker/factory/system/internal/AttachmentsPickerSystemFragment.kt
GetStream
177,873,527
false
{"Kotlin": 8578375, "MDX": 2150736, "Java": 271477, "JavaScript": 6737, "Shell": 5229}
/* * Copyright (c) 2014-2024 Stream.io Inc. All rights reserved. * * Licensed under the Stream License; * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://github.com/GetStream/stream-chat-android/blob/main/LICENSE * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.getstream.chat.android.ui.feature.messages.composer.attachment.picker.factory.system.internal import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.PickVisualMediaRequest import androidx.activity.result.contract.ActivityResultContracts import androidx.fragment.app.Fragment import io.getstream.chat.android.models.PollConfig import io.getstream.chat.android.ui.common.contract.internal.CaptureMediaContract import io.getstream.chat.android.ui.common.helper.internal.AttachmentFilter import io.getstream.chat.android.ui.common.helper.internal.StorageHelper import io.getstream.chat.android.ui.common.state.messages.composer.AttachmentMetaData import io.getstream.chat.android.ui.databinding.StreamUiFragmentAttachmentSystemPickerBinding import io.getstream.chat.android.ui.feature.messages.composer.attachment.picker.AttachmentsPickerDialogStyle import io.getstream.chat.android.ui.feature.messages.composer.attachment.picker.factory.AttachmentsPickerTabListener import io.getstream.chat.android.ui.feature.messages.composer.attachment.picker.factory.camera.internal.CameraAttachmentFragment.Companion.mode import io.getstream.chat.android.ui.feature.messages.composer.attachment.picker.factory.camera.internal.CameraAttachmentFragment.LauncherRequestsKeys import io.getstream.chat.android.ui.feature.messages.composer.attachment.picker.poll.CreatePollDialogFragment import io.getstream.chat.android.ui.utils.extensions.getFragmentManager import io.getstream.chat.android.ui.utils.extensions.streamThemeInflater import java.io.File internal class AttachmentsPickerSystemFragment : Fragment() { private lateinit var config: AttachmentsPickerSystemConfig private var _binding: StreamUiFragmentAttachmentSystemPickerBinding? = null private val binding get() = _binding!! private lateinit var style: AttachmentsPickerDialogStyle /** * A listener invoked when attachments are selected in the attachment tab. */ private var attachmentsPickerTabListener: AttachmentsPickerTabListener? = null private val storageHelper = StorageHelper() private val attachmentFilter = AttachmentFilter() private val filePickerLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result -> val uri = result.data?.data if (uri != null) { val attachmentMetaData = storageHelper.getAttachmentsFromUriList(requireContext(), listOf(uri)) attachmentsPickerTabListener?.onSelectedAttachmentsChanged(attachmentMetaData) } attachmentsPickerTabListener?.onSelectedAttachmentsSubmitted() } private val imagePickerLauncher = registerForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri: Uri? -> if (uri != null) { val attachmentMetaData = storageHelper.getAttachmentsFromUriList(requireContext(), listOf(uri)) attachmentsPickerTabListener?.onSelectedAttachmentsChanged(attachmentMetaData) } attachmentsPickerTabListener?.onSelectedAttachmentsSubmitted() } private var captureMedia: ActivityResultLauncher<Unit>? = null override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { _binding = StreamUiFragmentAttachmentSystemPickerBinding.inflate( requireContext().streamThemeInflater, container, false, ) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupViews() } private fun setupViews() { // Adjust visibility of the tabs based on the enabled flags if (!config.fileAttachmentsTabEnabled) { binding.buttonFiles.visibility = View.GONE binding.textFiles.visibility = View.GONE } if (!config.mediaAttachmentsTabEnabled) { binding.buttonMedia.visibility = View.GONE binding.textMedia.visibility = View.GONE } if (!config.cameraAttachmentsTabEnabled) { binding.buttonCapture.visibility = View.GONE binding.textCapture.visibility = View.GONE } if (!config.pollAttachmentsTabEnabled) { binding.buttonPolls.visibility = View.GONE binding.textPoll.visibility = View.GONE } // Setup listeners and actions binding.buttonFiles.setOnClickListener { val supportedMimeTypes = attachmentFilter.getSupportedMimeTypes() val filePickerIntent = Intent(Intent.ACTION_GET_CONTENT).apply { type = "*/*" // General type to include multiple types putExtra(Intent.EXTRA_MIME_TYPES, attachmentFilter.getSupportedMimeTypes().toTypedArray()) addCategory(Intent.CATEGORY_OPENABLE) } filePickerLauncher.launch(filePickerIntent) } binding.buttonMedia.setOnClickListener { imagePickerLauncher.launch( PickVisualMediaRequest( mediaType = ActivityResultContracts.PickVisualMedia.ImageAndVideo, ), ) } captureMedia = activity?.activityResultRegistry ?.register( LauncherRequestsKeys.CAPTURE_MEDIA, CaptureMediaContract(style.pickerMediaMode.mode), ) { file: File? -> val result: List<AttachmentMetaData> = if (file == null) { emptyList() } else { listOf(AttachmentMetaData(requireContext(), file)) } attachmentsPickerTabListener?.onSelectedAttachmentsChanged(result) attachmentsPickerTabListener?.onSelectedAttachmentsSubmitted() } captureMedia?.let { binding.buttonCapture.setOnClickListener { captureMedia?.launch(Unit) } } binding.buttonPolls.setOnClickListener { context.getFragmentManager()?.let { CreatePollDialogFragment.newInstance(object : CreatePollDialogFragment.CreatePollDialogListener { override fun onCreatePoll(pollConfig: PollConfig) { attachmentsPickerTabListener?.onPollSubmitted(pollConfig) } override fun onDismiss() { attachmentsPickerTabListener?.onPollSubmitted(null) } }) .show(it, CreatePollDialogFragment.TAG) } } } /** * Sets the listener invoked when attachments are selected in the attachment tab. * * @param attachmentsPickerTabListener The listener invoked when attachments are selected in the tab. */ fun setAttachmentsPickerTabListener(attachmentsPickerTabListener: AttachmentsPickerTabListener) { this.attachmentsPickerTabListener = attachmentsPickerTabListener } /** * Set the style. * * @param style Style for the dialog. */ fun setStyle(style: AttachmentsPickerDialogStyle) { this.style = style } companion object { fun newInstance( style: AttachmentsPickerDialogStyle, attachmentsPickerTabListener: AttachmentsPickerTabListener, config: AttachmentsPickerSystemConfig, ): Fragment = AttachmentsPickerSystemFragment().apply { this.style = style this.attachmentsPickerTabListener = attachmentsPickerTabListener this.config = config } } } internal data class AttachmentsPickerSystemConfig( val mediaAttachmentsTabEnabled: Boolean, val fileAttachmentsTabEnabled: Boolean, val cameraAttachmentsTabEnabled: Boolean, val pollAttachmentsTabEnabled: Boolean, )
28
Kotlin
273
1,451
8e46f46a68810d8086c48a88f0fff29faa2629eb
8,782
stream-chat-android
FSF All Permissive License
src/main/kotlin/no/nav/syfo/dinesykmeldte/model/Pasient.kt
navikt
322,575,632
false
{"Kotlin": 108227, "Dockerfile": 277}
package no.nav.syfo.dinesykmeldte.model data class Pasient( val fnr: String, val navn: String?, )
0
Kotlin
0
0
c244d8d60d126a95e34be5859caf13a7b8e2291e
107
sykmeldinger-arbeidsgiver
MIT License
app/src/main/java/teka/android/organiks_platform_android/domain/authentication/models/AuthResponse.kt
samAricha
649,253,035
false
{"Kotlin": 593778}
package teka.android.organiks_platform_android.domain.authentication.models import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class AuthResponse( val isSuccessful: Boolean, val message: String?, val data: AuthData ) @Serializable data class AuthData( val user: User, @SerialName("access_token") val accessToken: String ) @Serializable data class User( val id: Int, val name: String, val email: String?, val phone: String?, @SerialName("created_at") val createdAt: String, @SerialName("updated_at") val updatedAt: String )
0
Kotlin
0
4
16d6c6787ebf18046b6ee8ef2c4ac3692d5e73e4
637
Organiks-Platform-Android
MIT License
app/src/main/java/com/kyagamy/step/room/repos/LevelRepository.kt
rovivi
262,239,890
false
{"Kotlin": 187381, "Java": 97322, "Lua": 26067}
package com.kyagamy.step.room.repos import androidx.lifecycle.LiveData import com.kyagamy.step.room.entities.Level import com.kyagamy.step.room.entities.LevelDao class LevelRepository(private val levelDao: LevelDao) { // Room executes all queries on a separate thread. // Observed LiveData will notify the observer when the data has changed. val alllevel: LiveData<List<Level>> = levelDao.getAll() fun getLevelBySongId (levelId :Int):LiveData<List<Level>> { return levelDao.getLevelBySongId(levelId) } fun deleteAll (){ levelDao.deleteAll() } suspend fun insert(level: Level) { levelDao.insert(level) } }
0
Kotlin
0
0
18e200d2f7f58349455a35b819b921c32adab853
671
Stepdroid2
MIT License
src/main/kotlin/com/rutilicus/uisetlist/controller/MovieController.kt
rutilicus
231,705,129
false
null
package com.rutilicus.uisetlist.controller import com.rutilicus.uisetlist.Commons import org.springframework.stereotype.Controller import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.util.UriComponentsBuilder @Controller @RequestMapping("movie") class MovieController() { @GetMapping("/**") fun moviePage(builder: UriComponentsBuilder): String { return "redirect:" + Commons.getPathUriString(builder, "/") } }
4
Kotlin
1
1
d3a8e7ea33baaed77003448b1a10090f597e0a80
531
uisetlist
Apache License 2.0
pandora/src/main/java/com/lodz/android/pandora/utils/coroutines/CoroutinesAction.kt
LZ9
137,967,291
false
{"Kotlin": 2174504}
package com.lodz.android.pandora.utils.coroutines import android.content.Context import androidx.appcompat.app.AlertDialog import com.lodz.android.corekt.anko.getMetaData import com.lodz.android.corekt.anko.runOnMainCatch import com.lodz.android.corekt.log.PrintLog import com.lodz.android.pandora.action.ApiAction import com.lodz.android.pandora.action.ApiPgAction import com.lodz.android.pandora.base.application.BaseApplication import com.lodz.android.pandora.rx.exception.ExceptionFactory import com.lodz.android.pandora.rx.status.ResponseStatus import com.lodz.android.pandora.utils.progress.ProgressDialogHelper import kotlinx.coroutines.* /** * 协程请求操作类 * @author zhouL * @date 2022/2/16 */ class CoroutinesAction<T>( private val mScope: CoroutineScope, private val mRequestFun: (suspend () -> T)? = null, private val mRequestDeferred: Deferred<T>? = null ) { /** 执行协程操作[action] */ fun action(action: ApiAction<T>.() -> Unit): Job { if (mRequestFun != null) { return execute(mScope, action) { mRequestFun.invoke() } } if (mRequestDeferred != null) { return execute(mScope, action) { mRequestDeferred.await() } } throw NullPointerException("request parameter is null") } private fun execute( scope: CoroutineScope, action: ApiAction<T>.() -> Unit, request: suspend () -> T ): Job = scope.launch(Dispatchers.IO) { val listener = ApiAction<T>().also(action) launch(Dispatchers.Main) { listener.mStartAction?.invoke() } try { val res = request.invoke() resHandle(this, res, listener) } catch (e: Exception) { errorHandle(this, e, listener) } } /** 执行带加载框[progressDialog]的协程操作[action] */ fun actionPg(progressDialog: AlertDialog, action: ApiPgAction<T>.() -> Unit): Job { if (mRequestFun != null) { return execute(mScope, progressDialog, action) { mRequestFun.invoke() } } if (mRequestDeferred != null) { return execute(mScope, progressDialog, action) { mRequestDeferred.await() } } throw NullPointerException("request parameter is null") } /** 执行默认加载框的协程操作[action] */ fun actionPg( context: Context, msg: String = "正在加载,请稍候", cancelable: Boolean = true, canceledOnTouchOutside: Boolean = false, action: ApiPgAction<T>.() -> Unit ): Job { val progressDialog = ProgressDialogHelper.get() .setCanceledOnTouchOutside(canceledOnTouchOutside) .setCancelable(cancelable) .setMsg(msg) .create(context) return actionPg(progressDialog, action) } private fun execute( scope: CoroutineScope, progressDialog: AlertDialog, action: ApiPgAction<T>.() -> Unit, request: suspend () -> T, ): Job { val listener = ApiPgAction<T>().also(action) runOnMainCatch({ progressDialog.show() listener.mStartAction?.invoke() }) val job = scope.launch(Dispatchers.IO) { try { val res = request.invoke() resHandle(this, res, listener) } catch (e: Exception) { errorHandle(this, e, listener) } finally { runOnMainCatch({ progressDialog.dismiss() }) } } progressDialog.setOnCancelListener { job.cancel() runOnMainCatch({ it.dismiss() listener.mPgCancelAction?.invoke() }) } return job } /** 处理异步结果 */ private fun <T> resHandle(scope: CoroutineScope, res: T, action: ApiAction<T>) { scope.launch(Dispatchers.Main) { if (res is ResponseStatus) { if (res.isTokenUnauth()) { action.mTokenUnauthAction?.invoke(res) return@launch } if (res.isSuccess()) { action.mSuccessAction?.invoke(res) action.mCompleteAction?.invoke() return@launch } errorHandle(scope, ExceptionFactory.createDataException(res), action) return@launch } action.mSuccessAction?.invoke(res) action.mCompleteAction?.invoke() } } /** 处理异常逻辑 */ private fun <T> errorHandle(scope: CoroutineScope, e: Exception, action: ApiAction<T>) { e.printStackTrace() printErrorLog(e) if (e !is CancellationException) { scope.launch(Dispatchers.Main) { action.mErrorAction?.invoke(e, ExceptionFactory.isNetworkError(e)) } } } /** 根据配置标签打印异常[t]日志 */ private fun printErrorLog(t: Throwable) { val app = BaseApplication.get() ?: return val tag = app.getMetaData(BaseApplication.ERROR_TAG) if (tag != null && tag is String) { if (tag.isNotEmpty()) { PrintLog.e(tag, t.toString(), t) } } } }
0
Kotlin
3
11
adc8471785a694ac7b49565465419f8f3b0664f3
5,136
AgileDevKt
Apache License 2.0
android/src/com/wvv/spinebrowser/AndroidLauncher.kt
WVVxm
741,269,283
false
{"Kotlin": 22347}
package com.wvv.spinebrowser import android.Manifest import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.provider.Settings import android.util.Log import android.view.GestureDetector import android.view.GestureDetector.SimpleOnGestureListener import android.view.MotionEvent import android.view.ScaleGestureDetector import android.view.ScaleGestureDetector.SimpleOnScaleGestureListener import android.view.Window import android.widget.Toast import androidx.core.content.ContextCompat import com.badlogic.gdx.backends.android.AndroidApplication import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration import java.io.File import java.util.Timer import java.util.TimerTask class AndroidLauncher : AndroidApplication() { private var gestureDetector: GestureDetector? = null private var scaleDetector: ScaleGestureDetector? = null var viewer: SpineView? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val config = AndroidApplicationConfiguration() scaleDetector = ScaleGestureDetector(context, ScaleListener()) gestureDetector = GestureDetector(context, GestureListener()) viewer = SpineView() initialize(viewer, config) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (requestCode == REQUEST_CODE_STORAGE) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { if (!Environment.isExternalStorageManager()) { // SYSTEM_ALERT_WINDOW permission not granted... Toast.makeText(this, "permission not granted", Toast.LENGTH_SHORT).show() } } } } var menuDialog: MenuDialog? = null fun startMenu() { // 6.0 val perms = arrayOf<String>( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, ) for (p in perms) { val f = ContextCompat.checkSelfPermission(this, p) Log.d("---", String.format("%s - %d", p, f)) if (f != PackageManager.PERMISSION_GRANTED) { requestPermissions(perms, REQUEST_CODE_STORAGE) return } } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R ) { if (!Environment.isExternalStorageManager()) { val intent = Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION) intent.data = Uri.parse("package:$packageName") startActivityForResult(intent, 1024) return } } if (menuDialog != null) return val menu= MenuDialog(this, android.R.style.Theme_Light) menu.window?.setBackgroundDrawable(ColorDrawable(Color.valueOf(0.0f, 0.0f, 0.0f, 0.3f).toArgb())) menu.requestWindowFeature(Window.FEATURE_NO_TITLE) menu.selectAnimationCallback = { path, animationName -> runOnUiThread { viewer?.run { viewer?.loadSpine(path, animationName) } } } menu.show() menuDialog = menu menu.dismissCallback = { Log.e("MenuDialog", "dialog dismissed") menuDialog = null } } override fun dispatchTouchEvent(event: MotionEvent): Boolean { scaleDetector?.onTouchEvent(event) gestureDetector?.onTouchEvent(event) return super.dispatchTouchEvent(event) } private inner class GestureListener : SimpleOnGestureListener() { override fun onScroll( e1: MotionEvent, e2: MotionEvent, distanceX: Float, distanceY: Float ): Boolean { Log.d( "GestureListener", String.format("onScroll: distanceX: %f, distanceY: %f", distanceX, distanceY) ) viewer?.translate(-distanceX, distanceY) return true } override fun onLongPress(e: MotionEvent) { startMenu() super.onLongPress(e) } } private inner class ScaleListener : SimpleOnScaleGestureListener() { override fun onScale(detector: ScaleGestureDetector): Boolean { viewer?.scale(detector.scaleFactor) return true } } companion object { const val REQUEST_CODE_STORAGE = 1 } }
0
Kotlin
0
0
2e689f36ddf31e4a536c9b5907c5046049ea3a35
4,736
SpineBrowser
Apache License 2.0
currencyconverter/src/main/java/com/skillsoft/currencyconverter/HelpPage.kt
dellius-alexander
538,427,626
false
null
package com.skillsoft.currencyconverter import android.os.Bundle import androidx.drawerlayout.widget.DrawerLayout import kotlinx.android.synthetic.main.activity_help_page.* class HelpPage : NavigationPane() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_help_page) val mDrawerLayout:DrawerLayout = findViewById(R.id.drawer_layout) onCreateDrawer(mDrawerLayout) help_page_ans_numcurr.text = homeFeed.rates.keySet().size.toString() help_page_ans_basecurr.text = homeFeed.base } }
0
Kotlin
0
0
13a9a2b5f0163d1ac412aa5dfd483907d79f32bb
615
android_projects
MIT License
currencyconverter/src/main/java/com/skillsoft/currencyconverter/HelpPage.kt
dellius-alexander
538,427,626
false
null
package com.skillsoft.currencyconverter import android.os.Bundle import androidx.drawerlayout.widget.DrawerLayout import kotlinx.android.synthetic.main.activity_help_page.* class HelpPage : NavigationPane() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_help_page) val mDrawerLayout:DrawerLayout = findViewById(R.id.drawer_layout) onCreateDrawer(mDrawerLayout) help_page_ans_numcurr.text = homeFeed.rates.keySet().size.toString() help_page_ans_basecurr.text = homeFeed.base } }
0
Kotlin
0
0
13a9a2b5f0163d1ac412aa5dfd483907d79f32bb
615
android_projects
MIT License
src/main/kotlin/jp/assasans/araumi/tx/server/ecs/components/item/MountedItemComponent.kt
AraumiTX
604,259,602
false
null
package jp.assasans.araumi.tx.server.ecs.components.item import jp.assasans.araumi.tx.server.ecs.components.IComponent import jp.assasans.araumi.tx.server.protocol.ProtocolId @ProtocolId(1434531840401) class MountedItemComponent : IComponent
0
Kotlin
2
3
6adc36adc5f7d83c965143f5d3108f6d6ceaf186
243
game-server
MIT License
runtime/src/main/java/com/instana/android/core/util/RateLimiter.kt
instana
81,942,955
false
{"Kotlin": 551437, "Shell": 184}
/* * (c) Copyright IBM Corp. 2021 * (c) Copyright Instana Inc. and contributors 2021 */ package com.instana.android.core.util internal class RateLimiter( private val maxPerFiveMinutes: Int, private val maxPerTenSeconds: Int ) { private var lastFiveMinuteCount = 0 private var lastTenSecondsCount = 0 private var lastFiveMinuteTimestamp = System.currentTimeMillis() private var lastTenSecondsTimestamp = System.currentTimeMillis() @Synchronized fun isRateExceeded(newItems: Int): Boolean { val now = System.currentTimeMillis() if (lastFiveMinuteTimestamp + 5 * 60 * 1000 < now) { lastFiveMinuteTimestamp = now lastFiveMinuteCount = 0 } if (lastTenSecondsTimestamp + 10 * 1000 < now) { lastTenSecondsTimestamp = now lastTenSecondsCount = 0 } lastFiveMinuteCount += newItems lastTenSecondsCount += newItems return lastFiveMinuteCount > maxPerFiveMinutes || lastTenSecondsCount > maxPerTenSeconds } }
0
Kotlin
4
19
97970b54be5e496cf2448f81db7d369ac7f40a12
1,052
android-agent
MIT License
database/src/main/kotlin/com/lightteam/modpeide/database/utils/Tables.kt
VickyBOSS
268,764,088
true
{"Kotlin": 572011, "HTML": 11571}
/* * Licensed to the Light Team Software (Light Team) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The Light Team licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lightteam.modpeide.database.utils object Tables { @Deprecated("Use Tables.DOCUMENTS instead") const val FILE_HISTORY = "tbl_file_history" const val DOCUMENTS = "tbl_documents" const val FONTS = "tbl_fonts" const val THEMES = "tbl_themes" }
0
null
0
0
16c12bed2d116ec7ba8bb6ece8bf2a62dee03d32
1,083
ModPE-IDE
Apache License 2.0
sms/src/main/java/com/beeper/sms/database/models/ChatThread.kt
raymand211092
610,818,444
false
null
package com.beeper.sms.database.models import com.beeper.sms.BuildConfig import com.beeper.sms.commands.TimeMillis import com.beeper.sms.provider.ContactRow data class ChatThread( var threadId: String, var recipientIds: String, var snippet: String, var members: Map<String,ContactRow>, var timestamp: TimeMillis, var hasUnread: Boolean ){ fun getTitleFromMembers() : String{ val threadMemberNames = members.map { val contactRow = it.value contactRow.nickname ?: contactRow.last_name ?: contactRow.phoneNumber ?: it.key } return if(threadMemberNames.isEmpty()){ "Unknown contact" }else{ threadMemberNames.reduce { acc, s -> "$acc, $s" } } } override fun toString(): String { return "ChatThread(threadId='$threadId', snippet='${if (BuildConfig.DEBUG) snippet else "<redacted>"}', members=$members, timestamp=$timestamp, hasUnread=$hasUnread)" } }
0
Kotlin
0
0
d667c9c4376ab1e4564ccdfd5d579124f14d5cf7
1,019
android-sms
Apache License 2.0
app/src/main/java/com/mgpersia/androidbox/adapter/CategoryItemAdapter.kt
mahsak01
596,924,815
false
null
package com.mgpersia.androidbox.adapter import android.content.Context import android.graphics.Color import android.graphics.drawable.GradientDrawable import android.os.Build import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import android.widget.TextView import androidx.annotation.RequiresApi import androidx.constraintlayout.widget.ConstraintLayout import com.squareup.picasso.Picasso import com.mgpersia.androidbox.R import com.mgpersia.androidbox.common.RoundedTransformation import com.mgpersia.androidbox.data.model.General class CategoryItemAdapter( private val categoryItems: List<General>, private val eventListener: EventListener, private val context: Context, private val size: Int, private val nextFocusLeftId: Int = -1, private val nextFocusRightId: Int = -1, private val nextFocusUpId: Int = -1, private val nextFocusDownId: Int = -1, ) : BaseAdapter() { private var layoutInflater: LayoutInflater? = null interface EventListener { fun click(general: General) } override fun getCount(): Int = categoryItems.size override fun getItem(p0: Int): Any = categoryItems[p0] override fun getItemId(p0: Int): Long = p0.toLong() @RequiresApi(Build.VERSION_CODES.M) override fun getView(p0: Int, p1: View?, p2: ViewGroup?): View { var convertView = p1 if (layoutInflater == null) { layoutInflater = p2!!.context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater } if (convertView == null) { convertView = layoutInflater!!.inflate(R.layout.layout_category_item, null) } val general = getItem(p0) as General Picasso.with(p2!!.context).load(general.cover) .transform(RoundedTransformation(15, 0)) .fit().centerCrop() .into(convertView!!.findViewById<ImageView>(R.id.layoutCategoryItem_generalIv)) general.name.also { convertView.findViewById<TextView>(R.id.layoutCategoryItem_generalPTextIv).text = it } general.name_en.also { convertView.findViewById<TextView>(R.id.layoutCategoryItem_generalETextIv).text = it } val drawable = GradientDrawable() drawable.shape = GradientDrawable.RECTANGLE // if (general.first_color != null && general.second_color != null) // drawable.colors = intArrayOf( // Color.parseColor(("#3B" + general.first_color.replace("#", ""))), // Color.parseColor(("#3B" + general.second_color.replace("#", ""))), // ) drawable.cornerRadius = 15F drawable.setGradientCenter(0.3f, 0f) drawable.gradientType = GradientDrawable.SWEEP_GRADIENT drawable.also { convertView.findViewById<ImageView>(R.id.layoutCategoryItem_generalIv).foreground = it } convertView.findViewById<ConstraintLayout>(R.id.layoutCategoryItem_generalClRoot) .setOnClickListener { eventListener.click(general) } // convertView.findViewById<ConstraintLayout>(R.id.layoutCategoryItem_generalClRoot) // .setOnFocusChangeListener { view, isFocused -> // // add focus handling logic // if (isFocused) { // convertView.findViewById<ConstraintLayout>(R.id.layoutCategoryItem_generalClRoot).background = // context.resources.getDrawable(R.drawable.background_select_android_tv) // } else { // convertView.findViewById<ConstraintLayout>(R.id.layoutCategoryItem_generalClRoot).background = // context.resources.getDrawable(R.drawable.background_select_transparent_android_tv) // } // } // // if (nextFocusUpId != -1 && p0 < size) // convertView.findViewById<ConstraintLayout>(R.id.layoutCategoryItem_generalClRoot).nextFocusUpId = nextFocusUpId // // if (nextFocusDownId != -1 && p0>(categoryItems.size/size)*size) // convertView.findViewById<ConstraintLayout>(R.id.layoutCategoryItem_generalClRoot).nextFocusDownId = nextFocusDownId // // if (p0 == categoryItems.size - 1) // if (nextFocusLeftId != -1) // convertView.findViewById<ConstraintLayout>(R.id.layoutCategoryItem_generalClRoot).nextFocusLeftId = nextFocusLeftId // // if (p0 == 0) // if (nextFocusRightId != -1) // convertView.findViewById<ConstraintLayout>(R.id.layoutCategoryItem_generalClRoot).nextFocusRightId = nextFocusRightId return convertView } }
0
Kotlin
0
0
1fb772d72e14e9e05a72f9988c0c42b14773f608
4,749
ArianaFilm
The Unlicense
src/org/frice/game/obj/effects/Effects.kt
Ggz91
68,453,376
true
{"Kotlin": 75598, "HTML": 6189, "Java": 656, "Batchfile": 141}
package org.frice.game.obj.effects import org.frice.game.obj.AbstractObject import org.frice.game.obj.sub.ImageObject import org.frice.game.resource.graphics.ColorResource import org.frice.game.resource.graphics.FunctionResource import org.frice.game.resource.graphics.ParticleResource import org.frice.game.resource.image.ImageResource import org.frice.game.utils.graphics.shape.FRectangle import java.awt.Image import java.awt.image.BufferedImage /** * Created by ice1000 on 2016/8/19. * * @author ice1000 * @since v0.5 */ class LineEffect(var colorResource: ColorResource, override var x: Double, override var y: Double, var x2: Double, var y2: Double) : AbstractObject { override var rotate = 0.0 constructor(x: Double, y: Double, x2: Double, y2: Double) : this(ColorResource.BLACK, x, y, x2, y2) } /** * Created by ice1000 on 2016/8/17. * @author ice1000 * @since 0.3.2 */ class ParticleEffect(private var resource: ParticleResource, override var x: Double, override var y: Double) : ImageObject(resource.getResource(), x, y) { override val image: BufferedImage get() = resource.getResource() override val collideBox = FRectangle(x.toInt(), y.toInt()) override val width: Double get() = resource.width.toDouble() override val height: Double get() = resource.height.toDouble() override fun getResource() = ImageResource.create(image) override fun scale(x: Double, y: Double) { resource.width = (resource.width * x / 1000.0).toInt() resource.height = (resource.height * y / 1000.0).toInt() } // override fun isCollide(other: CollideBox): Boolean = false } /** * Tested, Work stably. * Created by ice1000 on 2016/8/24. * * @author ice1000 * @since v0.4.1 */ class FunctionEffect(res: FunctionResource, override var x: Double, override var y: Double) : ImageObject(res.getResource(), x, y) { constructor(FFunction: FFunction, x: Double, y: Double, width: Int, height: Int) : this(FunctionResource(ColorResource.BLUE, { x -> FFunction.call(x) }, width, height), x, y) override val width: Double get() = res.image.width.toDouble() override val height: Double get() = res.image.height.toDouble() override fun getResource() = ImageResource.create(image) override val image: BufferedImage get() = res.image override fun scale(x: Double, y: Double) { res.image = res.image.getScaledInstance((res.image.width * x / 1000.0).toInt(), (res.image.height * y / 1000.0).toInt(), Image.SCALE_DEFAULT) as BufferedImage } /** * Created by ice1000 on 2016/8/27. * * @author ice1000 * @since v0.4 */ interface FFunction { fun call(x: Double): Double } }
0
Kotlin
0
0
0f5df0de7de70f51e3d0b46a477440e3a155242d
2,645
FriceEngine
Apache License 2.0
app/src/main/java/com/example/e_commerce/ui/viewmodels/main/ChangePasswordViewModel.kt
elvinhuseynli
796,391,504
false
{"Kotlin": 149716, "HTML": 14038, "Java": 7013}
package com.example.e_commerce.ui.viewmodels.main import android.app.Activity import androidx.lifecycle.viewModelScope import com.example.e_commerce.R import com.example.e_commerce.core_utils.MviViewModel import com.example.e_commerce.domain.usecases.main.UpdatePasswordUseCase import com.example.e_commerce.ui.intents.main.ChangePassUIEffect import com.example.e_commerce.ui.intents.main.ChangePassUIEvent import com.example.e_commerce.ui.intents.main.ChangePassUIState import com.example.e_commerce.ui.reducers.main.ChangePasswordReducer import com.example.e_commerce.ui.reducers.main.ChangePasswordReducer.fieldValidation import com.example.e_commerce.ui.reducers.main.ChangePasswordReducer.updateSuccess import kotlinx.coroutines.launch import javax.inject.Inject class ChangePasswordViewModel @Inject constructor( private val updatePasswordUseCase: UpdatePasswordUseCase ) : MviViewModel<ChangePassUIState, ChangePassUIEvent, ChangePassUIEffect>() { override fun getInitialState(): ChangePassUIState = ChangePasswordReducer.getInitialState() override fun onEvent(event: ChangePassUIEvent) { when (event) { is ChangePassUIEvent.OnUpdateButtonClicked -> handleOnUpdateButtonClickedEvent( event.activity, event.password, event.passwordRepeated, event.userId ) } } private fun handleOnUpdateButtonClickedEvent( activity: Activity, password: String, passwordRepeated: String, userId: String ) { val passwordErrorText = if (!password.matches(activity.getString(R.string.password_regex).toRegex())) "Invalid password format" else "" val passwordRepeatedErrorText = if (!password.matches(activity.getString(R.string.password_regex).toRegex())) "Invalid password format" else "" updateState { fieldValidation(passwordErrorText, passwordRepeatedErrorText) } if (uiState.value.passwordError.isEmpty() && uiState.value.passwordRepeatedError.isEmpty()) { if (password == passwordRepeated) { viewModelScope.launch { try { updatePasswordUseCase.invoke(userId, password) { if (it == "success") { updateState { updateSuccess() } } else { trySendEffect { ChangePassUIEffect.ShowMessage(it) } } } } catch (e: Exception) { trySendEffect { ChangePassUIEffect.ShowMessage("Something unexpected happened") } } } } else { trySendEffect { ChangePassUIEffect.ShowMessage("Passwords don't match") } } } } }
0
Kotlin
0
0
91f9bb7dcf113867547a317c2adb09c1d96af3e1
2,976
Ecommerce
MIT License
app/src/main/java/com/rokoblak/chatbackup/domain/usecases/RetrieveContactUseCase.kt
oblakr24
598,672,859
false
{"Kotlin": 257266}
package com.rokoblak.chatbackup.domain.usecases import com.rokoblak.chatbackup.AppConstants import com.rokoblak.chatbackup.ui.commonui.PreviewDataUtils.obfuscate import com.rokoblak.chatbackup.data.model.Contact import com.rokoblak.chatbackup.data.repo.ContactsRepository import javax.inject.Inject class RetrieveContactUseCase @Inject constructor( private val repo: ContactsRepository, ) { suspend fun resolveContact(number: String): Contact? { val contacts = repo.retrieveContacts() val matching = contacts.firstOrNull { it.number == number } if (matching != null) { return matching } val resolvedName = repo.resolveContactName(number) if (resolvedName != null) { val contact = Contact( name = resolvedName, orgNumber = number, ).let { if (AppConstants.OBFUSCATE) it.obfuscate() else it } return contact } return null } }
0
Kotlin
0
2
60828f3173fdc0cd6b5f9e8b797f5e08c50dea24
983
chat-backup-app
Apache License 2.0
src/test/kotlin/net/dinkla/raytracer/colors/ColorTest.kt
jdinkla
38,753,756
false
null
package net.dinkla.raytracer.colors import net.dinkla.raytracer.colors.Color.Companion.fromInt import net.dinkla.raytracer.colors.Color.Companion.fromString import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.* internal class ColorTest { @Test fun plus() { assertEquals(Color(0.2, 0.4, 0.5), Color(0.1) + Color(0.1, 0.3, 0.4)) } @Test fun `multiplication of two colors`() { assertEquals(Color(0.25), Color(0.5) * Color(0.5) ) } @Test fun `multiplication with scalar`() { assertEquals(Color(0.25), Color(0.1) * 2.5) } @Test fun `multiplication with scalar from left`() { assertEquals(Color(0.25), 2.5 * Color(0.1)) } @Test fun pow() { assertEquals(Color(0.1*0.1, 0.2*0.2, 0.3*0.3), Color(0.1, 0.2, 0.3).pow(2.0)) } @Test fun asInt() { val c = Color(0.0, 0.0, 1.0); assertEquals(255, c.toInt()) } @Test fun createFromInt() { val r = 3.0 / 255.0 val g = 31.0 / 255.0 val b = 139.0 / 255.0 val rgb = Color(r, g, b).toInt(); val c = fromInt(rgb) assertEquals(r, c.red, 0.01) assertEquals(g, c.green, 0.01) assertEquals(b, c.blue, 0.01) } @Test fun createFromInts() { val color = Color.fromRGB(127, 0, 255) assertEquals(127.0/255.0, color.red, 0.01) assertEquals(0.0, color.green, 0.01) assertEquals(1.0, color.blue, 0.01) } @Test fun createFromString() { assertEquals(Color(1.0, 0.0, 0.0), fromString("FF0000")) assertEquals(Color(0.0, 1.0, 0.0), fromString("00FF00")) assertEquals(Color(0.0, 0.0, 1.0), fromString("0000FF")) } @Test fun clamp() { assertEquals(Color.RED, Color(1.1, 2.2, 3.3).clamp()) } @Test fun `clamp should return input if not clamped`() { val c = Color(0.1, 0.2, 0.3) assertEquals(c, c.clamp()) } @Test fun maxToOne() { assertEquals(Color(1.0), Color(1.0).maxToOne()) assertEquals(Color(0.25, 0.25, 1.0), Color(0.5, 0.5, 2.0).maxToOne()) assertEquals(Color(0.25, 1.0, 0.25), Color(0.5, 2.0, 0.5).maxToOne()) assertEquals(Color(1.0, 0.25, 0.25), Color(2.0, 0.5, 0.5).maxToOne()) } @Test fun equals() { assertEquals(Color(0.5, 0.2, 0.3), Color(0.5, 0.2, 0.3)) assertFalse(Color(0.5, 0.2, 0.3).equals(3.0)) assertFalse(Color(0.5, 0.2, 0.3).equals(null)) } }
0
Kotlin
0
3
a765bcf12251e6f1d9b85c3b7e9bbc730902a2e7
2,523
from-the-ground-up-ray-tracer
Apache License 2.0
core-parent/core/src/main/java/love/forte/simbot/core/SimbotApp.kt
wdcodecn
369,478,140
true
{"Kotlin": 1111734, "Java": 206366}
/* * * * Copyright (c) 2020. ForteScarlet All rights reserved. * * Project simple-robot * * File MiraiAvatar.kt * * * * You can contact the author through the following channels: * * github https://github.com/ForteScarlet * * gitee https://gitee.com/ForteScarlet * * email <EMAIL> * * QQ 1149159218 * */ @file:JvmName("SimbotApps") package love.forte.simbot.core import cn.hutool.core.io.FileUtil import love.forte.common.configuration.Configuration import love.forte.common.configuration.ConfigurationManagerRegistry import love.forte.common.configuration.ConfigurationParserManager import love.forte.common.configuration.impl.LinkedMapConfiguration import love.forte.common.configuration.impl.MergedConfiguration import love.forte.common.exception.ResourceException import love.forte.common.ifOr import love.forte.common.ioc.DependBeanFactory import love.forte.common.ioc.DependCenter import love.forte.common.ioc.InstanceBeanDepend import love.forte.common.ioc.annotation.Beans import love.forte.common.listAs import love.forte.common.utils.ResourceUtil import love.forte.common.utils.annotation.AnnotationUtil import love.forte.common.utils.scanner.HutoolClassesScanner import love.forte.common.utils.scanner.ResourcesScanner import love.forte.common.utils.scanner.Scanner import love.forte.simbot.* import love.forte.simbot.annotation.SimbotApplication import love.forte.simbot.bot.BotManager import love.forte.simbot.constant.PriorityConstant import love.forte.simbot.listener.MsgGetProcessor import org.slf4j.Logger import org.slf4j.LoggerFactory import java.io.* import java.net.HttpURLConnection import java.net.URL import kotlin.concurrent.thread private const val RESOURCE_FILE = "file:" private const val RESOURCE_CLASSPATH = "classpath:" private const val RESOURCE_HTTP = "http" /** * 如果在 [SimbotApp.run] 的时候填入的参数为此接口实现,则会在必要的流程中调用它们。 */ public interface SimbotProcess { fun pre(config: Configuration) fun post(context: SimbotContext) } /** * 默认的无内容流程接口实现。 */ internal object NothingProcess : SimbotProcess { override fun pre(config: Configuration) {} override fun post(context: SimbotContext) {} } /** * simbot 启动完成后的部分数据信息。 */ public class SimbotContext internal constructor( private val dependBeanFactory: DependBeanFactory, val botManager: BotManager, val environment: SimbotEnvironment, val msgProcessor: MsgGetProcessor, val configuration: Configuration, private val closeHandleList: List<SimbotContextClosedHandle> = emptyList(), ) : DependBeanFactory by dependBeanFactory, Closeable { private companion object : TypedCompLogger(SimbotContext::class.java) override fun close() { // run doClosed list closeHandleList.forEach { handle -> kotlin.runCatching { logger.debug("Execute handle ${handle.handleName}") handle.simbotClose(this) logger.debug("Execute handle ${handle.handleName} finish.") }.getOrElse { e -> val handleLogger = if (handle is LogAble) handle.log else LoggerFactory.getLogger(handle::class.java) handleLogger.error("SimbotContext close handle '${handle.handleName}' execute failed!", e) } } } } /** * [SimbotContext] 被 [SimbotContext.close] 的时候所使用的处理器。 * * 尽可能不要在此逻辑中使用带有阻塞的逻辑。 * * 所有异常均会被捕获并输出为错误日志。 * * 所有的 [SimbotContextClosedHandle] 都会在 [SimbotContext] 构建的时候被初始化完毕. * */ public interface SimbotContextClosedHandle { /** * 一个名称,可重写并用于日志提示。 */ @JvmDefault val handleName: String get() = "SimbotContextClosedHandle-Default" /** * 执行close操作。 * * @throws Exception 可能出现任何异常, 异常均会被捕获。 */ @Throws(Exception::class) fun simbotClose(context: SimbotContext) } internal val simbotAppLogger: Logger = LoggerFactory.getLogger(SimbotApp::class.java) /** * simbot app 启动类。 * * 启动时,最优先的事就是构建依赖中心并确定扫描所有的默认资源; * * 其次进行配置文件读取,并构建配置信息。 * * 其次进行扫描并构建依赖中心; * * ... // * */ public open class SimbotApp protected constructor( /** 当不存在 scanPackage 配置项的时候,使用此扫描路径。不可为空。 */ defaultScanPackage: Array<String>, private val loader: ClassLoader, private val parentDependBeanFactory: DependBeanFactory?, resourceData: List<SimbotResourceData>, private val process: SimbotProcess, // 可以提供一个基础的额外配置信息。 private val defaultConfiguration: Configuration?, args: List<String>, internal val logger: Logger = simbotAppLogger, ) { private var showLogo: Boolean = runCatching { defaultConfiguration?.getConfig(Logo.ENABLE_KEY)?.boolean }.getOrNull() ?: true private var showTips: Boolean = runCatching { defaultConfiguration?.getConfig(Tips.ENABLE_KEY)?.boolean }.getOrNull() ?: true protected open val defaultScanPackageArray: Array<String> = defaultScanPackage /** 资源环境,即启动的时候使用的配置文件环境,会在 [initDependCenterWithRunData] 阶段注入依赖。 */ protected open val simbotResourceEnvironment: SimbotResourceEnvironment = SimbotResourceEnvironmentImpl(resourceData) /** 启动参数环境,会在 [initDependCenterWithRunData] 阶段注入依赖。 */ protected open val simbotArgsEnvironment: SimbotArgsEnvironment = SimbotArgsEnvironmentImpl(args.toTypedArray()) /** * 获取一个配置类解析管理器。 */ protected open val configurationManager: ConfigurationParserManager = ConfigurationManagerRegistry.defaultManager() // /** // * 流程配置。 // */ // protected open val appConfiguration = SimbotAppConfiguration() /** * 包扫描器。 默认为 [HutoolClassesScanner]。 * 每次获取都是一个新的实例。 */ protected open val scanner: Scanner<String, Class<*>> get() = HutoolClassesScanner() /** * 依赖注入中心。 */ private lateinit var dependCenter: DependCenter /** * 启动执行。 */ @Synchronized internal fun run(): SimbotContext { // show logo. if (showLogo) { Logo.show() } runCatching { defaultConfiguration?.getConfig(Tips.RESOURCE_CONF_KEY)?.getObject(TipOnline::class.java)?.let { Tips.TIP_ONLINE_PATH = it } } if (showTips) { Tips.show() } // load configs. val config: Configuration = loadResourcesToConfiguration().let { if (defaultConfiguration != null) MergedConfiguration.merged(defaultConfiguration, it) else it } // process pre config. process.pre(config) // load all auto config. val autoConfigures = initDependCenterWithAutoConfigures(config) // init with run data. initDependCenterWithRunData() // val hi = config.getConfig("simbot.core.init")?.string ?: "hello!!!!!!!!!!!!!!!~" // println(hi) // merge depend center config. // dependCenter.mergeConfig { c -> MergedConfiguration.merged(c, config) } // scan and inject. scanPackagesAndInject(dependCenter.configuration, autoConfigures) // init depend. initDependCenter() // return. return createSimbotContext(config).also { // post try { process.post(it) } catch (e: Exception) { logger.error("SimbotProcess.post failed.", e) } } } /** * 获取自动装配信息并加载所有auto config类, 以及扫描的包路径。 */ private fun initDependCenterWithAutoConfigures(config: Configuration): AutoConfiguresData { // 首先扫描并加载所有默认配置信息。 val autoConfigures = autoConfigures(loader, logger) dependCenter = DependCenter(parent = parentDependBeanFactory, configuration = config) // register shutdown hook Runtime.getRuntime().addShutdownHook(thread(start = false) { dependCenter.close() }) // 加载所有的自动配置类 autoConfigures.classes.forEach { dependCenter.register(it) } return autoConfigures } /** * 将部分初始化、启动资源进行初始化。 */ private fun initDependCenterWithRunData() { // depend center 注册自己 dependCenter.registerInstance("dependCenter", dependCenter) // 注册部分环境: // simbotResourceEnvironment: SimbotResourceEnvironment // simbotArgsEnvironment: SimbotArgsEnvironment dependCenter.registerInstance("simbotResourceEnvironment", simbotResourceEnvironment) dependCenter.registerInstance("simbotArgsEnvironment", simbotArgsEnvironment) } /** * 读取所有的配置文件信息并整合为一个 [Configuration] 实例。 */ private fun loadResourcesToConfiguration(): Configuration { val confReaderManager = configurationManager val activeResources = simbotResourceEnvironment.resourceDataList.filter { val commands = it.commands commands.isEmpty() || commands.all { c -> simbotArgsEnvironment.contains(c) } } logger.info("Active resources: ${activeResources.map { it.resource }}") // 加载所有的配置类信息 return activeResources.mapNotNull { resourceData -> val resourceName = resourceData.resource // get reader. val resourceReader: Reader? = runCatching { when { resourceName.startsWith(RESOURCE_FILE) -> { // starts with 'file', try get Reader by file FileUtil.getUtf8Reader(resourceName.substring(RESOURCE_FILE.length)) } resourceName.startsWith(RESOURCE_CLASSPATH) -> { ResourceUtil.getResourceUtf8Reader(resourceName.substring(RESOURCE_CLASSPATH.length)) } resourceName.startsWith(RESOURCE_HTTP) -> { URL(resourceName).connection { "Online resource connection failed. $it" } } else -> { // try file first. val file = File(resourceName) if (file.exists()) { // file exist FileUtil.getUtf8Reader(file) } else { ResourceUtil.getResourceUtf8Reader(resourceName) } } } }.getOrElse { e -> if (resourceData.orIgnore) { null } else { throw ResourceException("Unable to read resource: $resourceName", e) } } // parse to configuration. resourceReader?.use { reader -> logger.debugf("resource [{}] loaded.", resourceName) val type: String = resourceData.type confReaderManager.parse(type, reader) } }.reduceOrNull { c1, c2 -> MergedConfiguration.merged(c1, c2) } ?: LinkedMapConfiguration() } /** * 扫描并注入。 */ private fun scanPackagesAndInject(config: Configuration, autoConfigure: AutoConfiguresData) { val ignored: Set<Class<*>> = autoConfigure.classes // scanPackage. val scanPackages = config.getConfig(SCAN_PACKAGES_KEY)?.getObject(Array<String>::class.java)?.asList() ?: (defaultScanPackageArray + autoConfigure.packages).distinct() val scanner = this.scanner scanPackages.forEach { scanner.scan(it) { c -> c !in ignored && AnnotationUtil.containsAnnotation(c, Beans::class.java) } logger.debug("package scan: {}", it) } val collection = scanner.collection // .toMutableSet().apply { // // remove all ignored. // removeAll(ignored) // } // inject classes. dependCenter.inject(types = collection.toTypedArray()) // register simbotPackageScanEnvironment. dependCenter.registerInstance( "simbotPackageScanEnvironment", SimbotPackageScanEnvironmentImpl(scanPackages.toTypedArray()) ) } /** * 初始化 depend center. */ private fun initDependCenter() { dependCenter.init() } /** * 构建一个 [SimbotContext] 实例并返回。 */ private fun createSimbotContext(configuration: Configuration): SimbotContext { // 获取 botManager. val botManager = dependCenter[BotManager::class.java] val environment = dependCenter[SimbotEnvironment::class.java] val msgGetProcessor = dependCenter[MsgGetProcessor::class.java] // 获取所有的异常处理器。 val handles: List<SimbotContextClosedHandle> = dependCenter.getListByType(SimbotContextClosedHandle::class.java).toList() return SimbotContext(dependCenter, botManager, environment, msgGetProcessor, configuration, handles) } /** * companion for static run. */ companion object Run { internal const val SCAN_PACKAGES_KEY = "simbot.core.scan-package" /** * 启动,使用一个class启动。 */ @JvmStatic @JvmOverloads public fun run( appType: Class<*>, loader: ClassLoader = Thread.currentThread().contextClassLoader ?: ClassLoader.getSystemClassLoader(), parentDependBeanFactory: DependBeanFactory? = null, defaultConfiguration: Configuration? = null, vararg args: String, ): SimbotContext { // 资源配置数据,获取appType的注解。 @Suppress("UNCHECKED_CAST") val resourceData: List<SimbotResourceData> = AnnotationUtil.getAnnotation(appType, SimbotApplication::class.java)?.value ?.map { it.toData() } ?: throw IllegalArgumentException("There is no resource data info or SimbotApplication annotation.") // 流程接口实例。 val process: SimbotProcess = if (SimbotProcess::class.java.isAssignableFrom(appType)) { kotlin.runCatching { appType.newInstance() as SimbotProcess }.getOrElse { e -> throw IllegalStateException("$appType cannot be SimbotProcess instance: ${e.localizedMessage}", e) } } else NothingProcess // 默认扫描使用的启动器实例。 val defPackage: String = appType.`package`.name // run and return. return SimbotApp( arrayOf(defPackage), loader, parentDependBeanFactory, resourceData, process, defaultConfiguration, args.asList(), LoggerFactory.getLogger(appType) ).run() } /** * 启动,使用一个类实例启动。 */ @JvmStatic @JvmOverloads public fun run( app: Any, loader: ClassLoader = Thread.currentThread().contextClassLoader ?: ClassLoader.getSystemClassLoader(), parentDependBeanFactory: DependBeanFactory? = null, defaultConfiguration: Configuration? = null, vararg args: String, ): SimbotContext { // 资源配置数据,允许app直接作为注解数据填入。 @Suppress("UNCHECKED_CAST") val resourceData: List<SimbotResourceData> = when { /** 如果是class,执行另一个方法。 */ app is Class<*> -> return run(app, loader, parentDependBeanFactory, defaultConfiguration, *args) app is SimbotResourceData -> listOf(app) app is List<*> && listAs<SimbotResourceData, Any?>(app) != null -> app as List<SimbotResourceData> else -> { AnnotationUtil.getAnnotation(app::class.java, SimbotApplication::class.java)?.value ?.map { it.toData() } ?: throw IllegalArgumentException("There is no resource data info.") } } // 流程接口实例。 val process: SimbotProcess = ifOr<SimbotProcess>(app) { NothingProcess } val defPackage: String = app::class.java.`package`.name // run and return. return SimbotApp( arrayOf(defPackage), loader, parentDependBeanFactory, resourceData, process, defaultConfiguration, args.asList(), LoggerFactory.getLogger(app::class.java) ).run() } } } /** * 注册一个实例单例。 */ internal fun <T> DependCenter.registerInstance(name: String, instance: T) { this.register(InstanceBeanDepend(name, PriorityConstant.CORE_TENTH, instance = instance)) } // logo. logo? logo! private object Logo { private const val DEF_LOGO = """ _ _ _ (_) | | | | ___ _ _ __ ___ | |__ ___ | |_ / __| | '_ ` _ \| '_ \ / _ \| __| \__ \ | | | | | | |_) | (_) | |_ |___/_|_| |_| |_|_.__/ \___/ \__| @ForteScarlet """ internal const val ENABLE_KEY = "simbot.core.logo.enable" private val LOGO_PATH: String = "META-INF" + File.separator + "simbot" + File.separator + "logo" val logo: String = runCatching { ResourcesScanner().scan(LOGO_PATH) { it.toASCIIString().endsWith("simbLogo") } .collection.randomOrNull() ?.toURL()?.readText(Charsets.UTF_8) ?: return@runCatching DEF_LOGO }.getOrDefault(DEF_LOGO) } private fun Logo.show(print: PrintStream = System.out) { print.println(logo) print.println() } private class DisableTips : NullPointerException("Disable online tips.") // tips! Do you know? private object Tips { private val logger: Logger = LoggerFactory.getLogger("love.forte.simbot.tips") internal const val RESOURCE_CONF_KEY = "simbot.core.tips.resource" internal const val ENABLE_KEY = "simbot.core.tips.enable" private val TIP_PATH: String = "META-INF" + File.separator + "simbot" + File.separator + "simbTip.tips" internal var TIP_ONLINE_PATH: TipOnline? = null get() { // if (field != null) { // return field // } return field ?: when (val resource = System.getProperty(RESOURCE_CONF_KEY)) { "gitee", "GITEE", null -> TipOnline.GITEE "github", "GITHUB" -> TipOnline.GITHUB else -> { logger.warn("Unknown tips resource: {}, used Gitee resource.", resource) TipOnline.GITEE } } } val randomTip: String? = runCatching { val url = TIP_ONLINE_PATH?.url ?: throw DisableTips() logger.trace("Tips online resource {}, url: {}", TIP_ONLINE_PATH, url) URL(url).connection { "Online tips connection failed. $it" } }.getOrElse { e -> if (e !is DisableTips) { logger.debugEf("Read online tips failed: {}", e, e.localizedMessage) } runCatching { ResourceUtil.getResourceUtf8Reader(TIP_PATH) }.getOrNull() }?.useLines { it.filter { s -> s.isNotBlank() }.toList().randomOrNull() } } internal enum class TipOnline(val url: String) { GITHUB("https://raw.githubusercontent.com/ForteScarlet/simpler-robot/dev/tips/tips.tips"), GITEE("https://gitee.com/ForteScarlet/simpler-robot/raw/dev/tips/tips.tips"), } private fun Tips.show(print: PrintStream = System.out) { randomTip?.run { print.println("Tips: $this") print.println() } } private inline fun URL.connection( readTimeout: Int = 5000, connectTimeout: Int = 5000, onError: (errorStreamReaderText: String) -> String, ): Reader { // 网络请求 return (this.openConnection() as HttpURLConnection).run { this.readTimeout = readTimeout this.connectTimeout = connectTimeout connect() takeIf { responseCode < 300 } ?: throw IOException(onError(errorStream.reader().use { it.readText() })) }.inputStream.reader() }
0
null
0
0
a88b601a757367427321ca8df91d66bbbaafbe37
20,107
simpler-robot
Apache License 2.0
src/main/kotlin/kr/heartpattern/spikot/config/TransformConfigProperty.kt
Spikot
129,165,327
false
null
/* * Copyright 2020 Spikot project authors * * 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 kr.heartpattern.spikot.config import kr.heartpattern.spikot.misc.Converter import kotlin.properties.ReadWriteProperty import kotlin.reflect.KClass import kotlin.reflect.KProperty @PublishedApi internal class TransformConfigProperty<T : Any, R : Any>(private val rawType: KClass<T>, private val default: R, private val converter: Converter<T, R>) : ReadWriteProperty<ConfigSpec, R> { private var cache: R? = null private var cached = false @Suppress("UNCHECKED_CAST") override fun getValue(thisRef: ConfigSpec, property: KProperty<*>): R { if (!cached) { val raw = thisRef.yaml.getByType("${thisRef.path}.${property.name}", rawType) if (raw != null) { cache = converter.read(raw as T) } cached = true } return cache ?: default } override fun setValue(thisRef: ConfigSpec, property: KProperty<*>, value: R) { thisRef.yaml.set(property.name, converter.write(value)) cache = value cached = true } }
0
Kotlin
3
11
a44e2c9ad3203f3ea1bbf65ae9ef53f6f6283d77
1,658
SpikotLegacy
Apache License 2.0
app/src/androidTest/java/com/gmail/uia059466/liska/screen/ListsScreen.kt
serhiq
374,399,892
false
null
package com.gmail.uia059466.liska.screen import androidx.annotation.StringRes import androidx.recyclerview.widget.RecyclerView import androidx.test.espresso.Espresso import androidx.test.espresso.Espresso.onView import androidx.test.espresso.Espresso.openActionBarOverflowOrOptionsMenu import androidx.test.espresso.action.ViewActions import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.assertion.ViewAssertions import androidx.test.espresso.assertion.ViewAssertions.matches import androidx.test.espresso.contrib.RecyclerViewActions import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.* import androidx.test.platform.app.InstrumentationRegistry import androidx.test.uiautomator.UiDevice import com.gmail.uia059466.liska.BaseScreen import com.gmail.uia059466.liska.R import com.gmail.uia059466.liska.TestUtils class ListsScreen(on: UiDevice) : BaseScreen(on) { override val contentLayout: Int= R.id.list_content // in recycler view private val title = R.id.title_tv private val description = R.id.description_tv private val menuSort = R.string.menu_sort private val list = R.id.list private val addFab = R.id.add_fab fun createListFromFab(){ Espresso.onView(ViewMatchers.withId(addFab)).perform(ViewActions.click()) // val new=SignUpScreen(device) // new.waitForScreenToBeDisplayed() // return new } fun openSortList(): SelectSortDialogScreen { openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getInstrumentation().targetContext) onView(withText(menuSort)).perform(click()) val new=SelectSortDialogScreen(device) new.waitForScreenToBeDisplayed() return new } override fun checkDefaultLayout() { // onView(withId(contentLayout)).check(matches(isDisplayed())) // onView(withId(emailTv)).check(matches(isDisplayed())) // onView(withId(deleteButton)).check(matches(isDisplayed())) // onView(withId(signOutButton)).check(matches(isDisplayed())) } fun openList(i: Int): ListDetailScreen { Thread.sleep(500) val recyclerView = onView( withId(R.id.list) ) recyclerView.perform( RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>( i, click() ) ) Thread.sleep(200) return ListDetailScreen(device) // onView(withId(R.id.list)).perform( // RecyclerViewActions.actionOnItemAtPosition<RecyclerView.ViewHolder>( // 0, // click() // ) // ) } fun openNavigationDrawer():NavigationDrawerScreen{ onView(ViewMatchers.withContentDescription("open")) .perform(click()) val screen=NavigationDrawerScreen(device) screen.waitForScreenToBeDisplayed() return screen } fun isDisplayedSnackbar(@StringRes emptyListDeleted: Int) { onView(withText(emptyListDeleted)) .check(matches(isDisplayed())) } fun deleteList() { val menu_delete = R.string.menu_delete_list openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getInstrumentation().targetContext) onView(withText(menu_delete)).perform(click()) } fun copyList() { val text = R.string.menu_copy_list openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getInstrumentation().targetContext) onView(withText(text)).perform(click()) } fun checkItemInList(title: String,position:Int) { onView(TestUtils.withRecyclerView(R.id.list).atPositionOnView(position,R.id. title_tv)).check( ViewAssertions.matches(ViewMatchers.withText(title)) ) } }
0
Kotlin
0
0
5f830c9bd3aea467ac31449f383506e56990400a
3,836
LiskaDev
Apache License 2.0
src/main/kotlin/miragefairy2024/mod/placeditem/PlacedItemModule.kt
MirageFairy
721,291,232
false
{"Kotlin": 662780, "Java": 13872, "Shell": 751}
package miragefairy2024.mod.placeditem import miragefairy2024.ModContext context(ModContext) fun initPlacedItemModule() { initPlacedItemBlock() }
0
Kotlin
1
1
2802dfd7285ca4eac558f2e8cb3cbe52a0dc8abc
152
MirageFairy2024
Apache License 2.0
src/main/kotlin/typical90/032.kt
kirimin
197,707,422
false
null
package typical90 import java.util.* fun main(args: Array<String>) { val sc = Scanner(System.`in`) val n = sc.nextInt() val a = (0 until n).map { (0 until n).map { sc.next().toInt() } } val m = sc.nextInt() val xy = (0 until m).map { sc.next().toInt() to sc.next().toInt() } println(problem032(n, a, m, xy)) } fun problem032(n: Int, a: List<List<Int>>, m: Int, xy: List<Pair<Int, Int>>): Int { fun nextPermutation(array: IntArray): Boolean { var i = array.size - 1 while (i > 0 && array[i - 1] >= array[i]) i-- if (i <= 0) return false var j = array.size - 1 while (array[j] <= array[i - 1]) j-- var temp = array[i - 1] array[i - 1] = array[j] array[j] = temp j = array.size - 1 while (i < j) { temp = array[i] array[i] = array[j] array[j] = temp i++ j-- } return true } val array = (0 until n).toList().toIntArray() var isNotLast = true var min = Integer.MAX_VALUE while (isNotLast) { var isWrong = false for (i in 0 until m) { val (x, y) = xy[i] for (j in 0 until n - 1) { if ((array[j] == x - 1 && array[j + 1] == y - 1) || (array[j] == y - 1 && array[j + 1] == x - 1) ) { isWrong = true break } } if (isWrong) break } if (isWrong) { isNotLast = nextPermutation(array) continue } var sum = 0 for (i in 0 until n) { sum += a[array[i]][i] } min = Math.min(min, sum) isNotLast = nextPermutation(array) } return if (min == Integer.MAX_VALUE) -1 else min }
0
Kotlin
1
5
c6e31eb2fb5b73456bdfac07b2528d401c6c884a
1,843
AtCoderLog
The Unlicense
core/theme/src/main/kotlin/xyz/stylianosgakis/shape/android/core/theme/Color.kt
StylianosGakis
600,573,917
false
null
package xyz.stylianosgakis.shape.android.core.theme import androidx.compose.ui.graphics.Color // https://www.canva.com/colors/color-wheel/ with #6C947F and 2 Analogous colors, #7F6C94 and #947F6C. // https://m3.material.io/theme-builder#/custom with #0080FF, #0000FF, #00FFFF, the colors gotten from canva @Suppress("unused") private val seed = Color(0xFF6C947F) val light_primary = Color(0xFF006C4B) val light_onPrimary = Color(0xFFFFFFFF) val light_primaryContainer = Color(0xFF8AF8C5) val light_onPrimaryContainer = Color(0xFF002114) val light_secondary = Color(0xFF724C9F) val light_onSecondary = Color(0xFFFFFFFF) val light_secondaryContainer = Color(0xFFEEDBFF) val light_onSecondaryContainer = Color(0xFF2A0053) val light_tertiary = Color(0xFF8A5100) val light_onTertiary = Color(0xFFFFFFFF) val light_tertiaryContainer = Color(0xFFFFDCBD) val light_onTertiaryContainer = Color(0xFF2C1600) val light_error = Color(0xFFBA1A1A) val light_errorContainer = Color(0xFFFFDAD6) val light_onError = Color(0xFFFFFFFF) val light_onErrorContainer = Color(0xFF410002) val light_background = Color(0xFFFBFDF9) val light_onBackground = Color(0xFF191C1A) val light_surface = Color(0xFFFBFDF9) val light_onSurface = Color(0xFF191C1A) val light_surfaceVariant = Color(0xFFDCE5DD) val light_onSurfaceVariant = Color(0xFF404943) val light_outline = Color(0xFF707973) val light_inverseOnSurface = Color(0xFFEFF1ED) val light_inverseSurface = Color(0xFF2E312F) val light_inversePrimary = Color(0xFF6DDBAA) @Suppress("unused") val light_shadow = Color(0xFF000000) val light_surfaceTint = Color(0xFF006C4B) val dark_primary = Color(0xFF6DDBAA) val dark_onPrimary = Color(0xFF003825) val dark_primaryContainer = Color(0xFF005137) val dark_onPrimaryContainer = Color(0xFF8AF8C5) val dark_secondary = Color(0xFFDAB9FF) val dark_onSecondary = Color(0xFF411B6D) val dark_secondaryContainer = Color(0xFF593485) val dark_onSecondaryContainer = Color(0xFFEEDBFF) val dark_tertiary = Color(0xFFFFB86E) val dark_onTertiary = Color(0xFF492900) val dark_tertiaryContainer = Color(0xFF693C00) val dark_onTertiaryContainer = Color(0xFFFFDCBD) val dark_error = Color(0xFFFFB4AB) val dark_errorContainer = Color(0xFF93000A) val dark_onError = Color(0xFF690005) val dark_onErrorContainer = Color(0xFFFFDAD6) val dark_background = Color(0xFF191C1A) val dark_onBackground = Color(0xFFE1E3DF) val dark_surface = Color(0xFF191C1A) val dark_onSurface = Color(0xFFE1E3DF) val dark_surfaceVariant = Color(0xFF404943) val dark_onSurfaceVariant = Color(0xFFBFC9C1) val dark_outline = Color(0xFF8A938C) val dark_inverseOnSurface = Color(0xFF191C1A) val dark_inverseSurface = Color(0xFFE1E3DF) val dark_inversePrimary = Color(0xFF006C4B) @Suppress("unused") val dark_shadow = Color(0xFF000000) val dark_surfaceTint = Color(0xFF6DDBAA)
0
Kotlin
0
0
b7542a43a1107ecefa265695f6c673218c133cd3
2,797
shape
Apache License 2.0
src/main/kotlin/io/github/nocomment1105/bedtime/database/Database.kt
NoComment1105
525,183,635
false
{"Kotlin": 29426}
/* * Copyright (c) 2022 NoComment1105 <<EMAIL>> * * This file is part of Bedtime. * * Licensed under the MIT license. For more information, * please see the LICENSE file */ package io.github.nocomment1105.bedtime.database import com.mongodb.ConnectionString import com.mongodb.MongoClientSettings import io.github.nocomment1105.bedtime.MONGO_URI import io.github.nocomment1105.bedtime.database.migrations.Migrator import org.bson.UuidRepresentation import org.litote.kmongo.coroutine.coroutine import org.litote.kmongo.reactivestreams.KMongo class Database { // Connect to the database using the provided connection URI private val settings = MongoClientSettings .builder() .uuidRepresentation(UuidRepresentation.STANDARD) .applyConnectionString(ConnectionString(MONGO_URI)) .build() private val client = KMongo.createClient(settings).coroutine /** The main database. */ val bedtimeDatabase get() = client.getDatabase("BedTime") suspend fun migrate() { Migrator.migrate() } }
0
Kotlin
0
2
7db4434f059a48d34edab18e591836e553d13c78
1,057
Bedtime
MIT License
2024/FireShell/ContainerM/src/jsMain/kotlin/HtmlUtils.kt
kyoya-p
253,926,918
false
{"Kotlin": 936789, "JavaScript": 85088, "HTML": 66635, "TypeScript": 55667, "Java": 30207, "C++": 29172, "CMake": 20891, "Dart": 14886, "Shell": 7841, "Batchfile": 6227, "CSS": 6205, "Dockerfile": 4906, "C": 3042, "Swift": 1622, "PowerShell": 234, "Objective-C": 78}
import kotlinx.browser.document import kotlinx.html.INPUT import kotlinx.html.TagConsumer import kotlinx.html.id import kotlinx.html.input import kotlinx.html.js.onChangeFunction import org.w3c.dom.Element import kotlin.reflect.KProperty class Cookie(val key: String, val default: String) { fun cookies() = document.cookie.split(";").filter { it.trim().isNotEmpty() }.map { it.trim().split("=", limit = 2) } .associate { it[0] to (it.getOrElse(1) { "" }) } operator fun getValue(nothing: Nothing?, property: KProperty<*>) = value operator fun setValue(nothing: Nothing?, property: KProperty<*>, v: String) = run { value = v } var value get():String = cookies()[key] ?: default set(v) = run { document.cookie = "$key=$v" } } fun <T> TagConsumer<T>.field(cookie: Cookie, opts: INPUT.() -> Unit = {}, onChange: (Element) -> Unit = {}) { var c by cookie input { id = cookie.key value = c onChangeFunction = { ev -> val e = document.querySelector("input[id='${cookie.key}']")!! c = e.asDynamic().value as String onChange(e) } opts() } }
16
Kotlin
0
2
1b0c90f02ecf5907eabbdd2e4f5f49e6d27d204e
1,163
samples
Apache License 2.0
lib/src/main/kotlin/discord/kt/annotations/InstallCommands.kt
stijndcl
369,295,782
false
null
package discord.kt.annotations import discord.kt.commands.Command import kotlin.reflect.KClass @Target(AnnotationTarget.CLASS) @Repeatable annotation class InstallCommands(vararg val commands: KClass<out Command>)
4
Kotlin
0
0
bde60351060264d239123b376e9593635c8ce2d6
215
discord-kt
MIT License
common-ui/src/main/java/com/drawiin/common_ui/composables/DrawerLayout.kt
Drawiin
404,929,005
false
null
package com.drawiin.common_ui.composables import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.width import androidx.compose.material.DrawerState import androidx.compose.material.DrawerValue import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.ModalDrawer import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.List import androidx.compose.material.rememberDrawerState import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.RectangleShape import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.tooling.preview.Preview import com.drawiin.common_ui.theme.FunFitTheme import com.drawiin.common_ui.theme.OnSurface import com.drawiin.common_ui.theme.Padding import com.drawiin.common_ui.theme.Shapes import com.drawiin.common_ui.theme.Values @Composable fun DrawerLayout( title: String, options: List<DrawerOption>, drawerState: DrawerState, content: @Composable () -> Unit ) { ModalDrawer( drawerState = drawerState, drawerContent = { DrawerBody(title = title, options = options) }, content = content, drawerShape = RectangleShape ) } @Composable fun DrawerBody( title: String, options: List<DrawerOption> ) { Column(Modifier.padding(Padding.small)) { Text(title, style = MaterialTheme.typography.h5) Spacer(modifier = Modifier.height(Values.x8)) Column { options.forEach { DrawerOptionItem(item = it) Spacer(modifier = Modifier.height(Values.x2)) } } } } @Composable fun DrawerOptionItem(item: DrawerOption) { val (title, icon, onItemClicked) = item Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.clickable { onItemClicked() }) { Icon(imageVector = icon, contentDescription = title, tint = OnSurface) Spacer(modifier = Modifier.width(Values.x3)) Text(title, style = MaterialTheme.typography.h5) } } data class DrawerOption( val title: String, val icon: ImageVector, val onItemClicked: () -> Unit ) @Preview(showBackground = true, showSystemUi = true) @Composable fun DrawerLayoutPreview() { FunFitTheme { DrawerLayout(title = "Ola, Pessoa", options = listOf( DrawerOption( "Licenças", Icons.Default.List ) {}, DrawerOption( "Licenças", Icons.Default.List ) {}, DrawerOption( "Licenças", Icons.Default.List ) {} ), drawerState = rememberDrawerState(initialValue = DrawerValue.Open) ) { Text(text = "Hey there my friend") } } }
1
Kotlin
0
0
62b6a87276bb517b43f8aa4c6e4f103aebf0e2a8
3,239
FunFit
MIT License
app/src/main/java/com/srg/citibox/common/di/dagger_activity/ActivityComponent.kt
sebrodgar
233,223,889
false
null
package com.srg.citibox.common.di.dagger_activity import com.srg.citibox.post_detail.ui.PostDetailActivity import com.srg.citibox.post_list.ui.PostListActivity import dagger.Subcomponent /** * Created by Sebastián Rodríguez on 13,January,2020 */ @Subcomponent(modules = [ActivityModule::class]) interface ActivityComponent { fun inject(postListActivity: PostListActivity) fun inject(postDetailActivity: PostDetailActivity) }
0
Kotlin
0
0
d5e4c74d9564a8dae7e3406775687f42acaecb81
439
candidate-test-citibox
Apache License 2.0
app/src/main/java/com/dreamsoftware/melodiqtv/ui/validation/SignUpValidationMessagesResolverImpl.kt
sergio11
201,446,449
false
{"Kotlin": 556766}
package com.dreamsoftware.melodiqtv.ui.validation import android.content.Context import com.dreamsoftware.melodiqtv.R import com.dreamsoftware.melodiqtv.domain.validation.ISignUpValidationMessagesResolver class SignUpValidationMessagesResolverImpl(private val context: Context) : ISignUpValidationMessagesResolver { override fun getInvalidEmailMessage(): String = context.getString(R.string.invalid_email_message) override fun getShortPasswordMessage(minLength: Int): String = context.getString(R.string.short_password_message, minLength) override fun getPasswordsDoNotMatchMessage(): String = context.getString(R.string.passwords_do_not_match_message) }
0
Kotlin
0
1
ad82e5cf46929cfb1c30608c89e717929939a8d2
698
melodiqtv_android
MIT License
feature/samples/file-browser/src/main/kotlin/top/chengdongqing/weui/feature/samples/filebrowser/filelist/FileListItem.kt
chengdongqing
782,566,304
false
{"Kotlin": 894390}
package top.chengdongqing.weui.feature.samples.filebrowser.filelist import android.graphics.BitmapFactory import android.net.Uri import androidx.compose.foundation.Image import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.asImageBitmap import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import top.chengdongqing.weui.core.ui.components.actionsheet.ActionSheetItem import top.chengdongqing.weui.core.ui.components.actionsheet.rememberActionSheetState import top.chengdongqing.weui.core.ui.components.cardlist.WeCardListItem import top.chengdongqing.weui.core.ui.components.dialog.rememberDialogState import top.chengdongqing.weui.core.ui.components.popup.WePopup import top.chengdongqing.weui.core.ui.components.toast.ToastIcon import top.chengdongqing.weui.core.ui.components.toast.rememberToastState import top.chengdongqing.weui.core.utils.calculateFileSize import top.chengdongqing.weui.core.utils.deleteFile import top.chengdongqing.weui.core.utils.format import top.chengdongqing.weui.core.utils.formatFileSize import top.chengdongqing.weui.core.utils.loadVideoThumbnail import top.chengdongqing.weui.feature.samples.filebrowser.R import top.chengdongqing.weui.feature.samples.filebrowser.data.model.FileItem import java.io.File import top.chengdongqing.weui.core.ui.theme.R as ThemeR @Composable internal fun FileListItem( file: FileItem, onFolderClick: () -> Unit, onFileClick: () -> Unit, onDeleted: () -> Unit ) { val actionSheet = rememberActionSheetState() val dialog = rememberDialogState() val toast = rememberToastState() val menus = remember { listOf( ActionSheetItem("详情"), ActionSheetItem("删除", color = Color.Red) ) } // 详情弹窗 val (visible, setVisible) = remember { mutableStateOf(false) } FileDetailsPopup(visible, file) { setVisible(false) } Row( modifier = Modifier .pointerInput(Unit) { detectTapGestures(onLongPress = { actionSheet.show(menus) { when (it) { 0 -> { setVisible(true) } 1 -> { dialog.show(title = "确定删除吗?") { if (!deleteFile(File(file.path))) { toast.show("删除失败", ToastIcon.FAIL) } else { onDeleted() } } } } } }) { if (file.isDirectory) { onFolderClick() } else { onFileClick() } } }, verticalAlignment = Alignment.CenterVertically ) { FileThumbnail(file) Spacer(modifier = Modifier.width(16.dp)) Column(modifier = Modifier.weight(1f)) { Text( text = file.name, color = MaterialTheme.colorScheme.onPrimary, fontSize = 16.sp, fontWeight = FontWeight.Bold, overflow = TextOverflow.Ellipsis, maxLines = 2 ) Spacer(modifier = Modifier.height(2.dp)) Row { Text( text = buildString { append(file.lastModified) append(" | ") if (file.isDirectory) { append("${file.childrenCount}项") } else { append(file.size) } }, color = MaterialTheme.colorScheme.onSecondary, fontSize = 14.sp ) } } Spacer(modifier = Modifier.width(20.dp)) Icon( painterResource(id = ThemeR.drawable.ic_arrow_right), contentDescription = "下一级", tint = MaterialTheme.colorScheme.secondary ) } } @Composable private fun FileThumbnail(file: FileItem) { @Composable fun FileIcon() { Image( painter = painterResource(id = file.iconId), contentDescription = "文件", modifier = Modifier.size(38.dp) ) } Box( modifier = Modifier.size(48.dp), contentAlignment = Alignment.Center ) { if (file.isDirectory) { Image( painter = painterResource(id = R.drawable.ic_folder), contentDescription = "文件夹", modifier = Modifier.matchParentSize() ) } else { if (file.isVisualMedia) { val context = LocalContext.current val thumbnail by produceState<ImageBitmap?>(initialValue = null) { value = withContext(Dispatchers.IO) { if (file.mimeType.startsWith("image")) { BitmapFactory.decodeFile(file.path) } else { context.loadVideoThumbnail(Uri.parse(file.path)) }?.asImageBitmap() } } thumbnail?.let { Image( bitmap = it, contentDescription = "文件", contentScale = ContentScale.Crop, modifier = Modifier .size(38.dp) .clip(RoundedCornerShape(6.dp)) ) } ?: FileIcon() } else { FileIcon() } } } } @Composable private fun FileDetailsPopup(visible: Boolean, file: FileItem, onClose: () -> Unit) { WePopup( visible, title = file.name, padding = PaddingValues(20.dp), onClose = onClose ) { val originalFile = remember { File(file.path) } val size by produceState(initialValue = 0L) { value = calculateFileSize(originalFile) } WeCardListItem(label = "位置", value = file.path) WeCardListItem(label = "大小", value = formatFileSize(size)) WeCardListItem(label = "时间", value = file.lastModified) WeCardListItem(label = "可读", value = originalFile.canRead().format()) WeCardListItem(label = "可写", value = originalFile.canWrite().format()) WeCardListItem(label = "隐藏", value = originalFile.isHidden.format()) } }
0
Kotlin
3
8
eb773e75aacb801cb24adb41db9fe17224eb883a
8,142
WeUI
Apache License 2.0
app/src/main/java/com/example/digimoncards/ui/notifications/NotificationsFragment.kt
rcdavis
626,141,621
false
null
package com.example.digimoncards.ui.notifications import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.example.digimoncards.databinding.FragmentNotificationsBinding import org.koin.androidx.viewmodel.ext.android.viewModel class NotificationsFragment : Fragment() { private lateinit var binding: FragmentNotificationsBinding private val viewModel: NotificationsViewModel by viewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { binding = FragmentNotificationsBinding.inflate(inflater, container, false) viewModel.text.observe(viewLifecycleOwner) { binding.textNotifications.text = it } return binding.root } }
0
Kotlin
0
0
3f030e6424712ba0812335edfca82f0236de113a
885
DigimonCards-Android
MIT License
compiler/frontend/src/org/jetbrains/kotlin/resolve/diagnostics/PrecomputedSuppressCache.kt
google
219,902,853
true
null
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.resolve.diagnostics import com.intellij.psi.PsiElement import org.jetbrains.kotlin.builtins.StandardNames import org.jetbrains.kotlin.descriptors.annotations.AnnotationDescriptor import org.jetbrains.kotlin.psi.KtAnnotated import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtTreeVisitorVoid import org.jetbrains.kotlin.resolve.BindingContext /** * A [KotlinSuppressCache] implementation that computes all suppressions at the moment of instantiation. * This is useful in the IR backend, where we clear the main binding context after psi2ir to avoid taking extra memory. * To make suppression of errors reported from backend possible though, we need to precompute all resolved `@Suppress` annotations, * and store this information outside of the binding context, which is going to be cleared. * * @param context the binding context where the data should be loaded from. Note that it shouldn't be stored as a property because the * primary use case of this class is when that binding context is cleared and thus is useless after a certain point. */ class PrecomputedSuppressCache(context: BindingContext, files: List<KtFile>) : KotlinSuppressCache() { val storage: Map<PsiElement, List<AnnotationDescriptor>> = mutableMapOf<PsiElement, List<AnnotationDescriptor>>().also { storage -> val visitor = PrecomputingVisitor(storage, BindingContextSuppressCache(context)) for (file in files) { file.accept(visitor, null) } } private class PrecomputingVisitor( val storage: MutableMap<PsiElement, List<AnnotationDescriptor>>, val computer: KotlinSuppressCache, ) : KtTreeVisitorVoid() { override fun visitKtElement(element: KtElement) { super.visitKtElement(element) if (element is KtAnnotated) { computeAnnotations(element) } } override fun visitKtFile(file: KtFile) { super.visitKtFile(file) computeAnnotations(file) } private fun computeAnnotations(element: KtAnnotated) { val suppressions = computer.getSuppressionAnnotations(element).filter { it.fqName == StandardNames.FqNames.suppress } if (suppressions.isNotEmpty()) { storage[element] = suppressions } } } override fun getSuppressionAnnotations(annotated: PsiElement): List<AnnotationDescriptor> = storage[annotated].orEmpty() } class OnDemandSuppressCache(private val context: BindingContext) : KotlinSuppressCache() { private val processedRoots = mutableSetOf<KtFile>() private val storage = mutableMapOf<PsiElement, List<AnnotationDescriptor>>() @Synchronized private fun ensureRootProcessed(rootElement: PsiElement) { require(rootElement is KtFile) if (!processedRoots.contains(rootElement)) { val visitor = PrecomputingVisitor(storage, BindingContextSuppressCache(context)) rootElement.accept(visitor, null) processedRoots.add(rootElement) } } private class PrecomputingVisitor( val storage: MutableMap<PsiElement, List<AnnotationDescriptor>>, val computer: KotlinSuppressCache, ) : KtTreeVisitorVoid() { override fun visitKtElement(element: KtElement) { super.visitKtElement(element) if (element is KtAnnotated) { computeAnnotations(element) } } override fun visitKtFile(file: KtFile) { super.visitKtFile(file) computeAnnotations(file) } private fun computeAnnotations(element: KtAnnotated) { val suppressions = computer.getSuppressionAnnotations(element).filter { it.fqName == StandardNames.FqNames.suppress } if (suppressions.isNotEmpty()) { storage[element] = suppressions } } } override fun getSuppressionAnnotations(annotated: PsiElement): List<AnnotationDescriptor> = storage[annotated].orEmpty() override fun getClosestAnnotatedAncestorElement(element: PsiElement, rootElement: PsiElement, excludeSelf: Boolean): PsiElement? { ensureRootProcessed(rootElement) return super.getClosestAnnotatedAncestorElement(element, rootElement, excludeSelf) } }
0
Kotlin
46
124
445156f2fc18640d8f7f26068d08bbb9e03c4290
4,643
kotlin
Apache License 2.0
frontend/statemachine/src/main/kotlin/statemachine/States.kt
85vmh
543,628,296
false
{"Kotlin": 956103, "C++": 75148, "Java": 7157, "Makefile": 2742, "HTML": 419, "Shell": 398, "CSS": 108}
package statemachine import ru.nsk.kstatemachine.DefaultState object States { object MachineStarted : DefaultState("Green") object MachineInEStop : DefaultState("Green") object MachineNotOn : DefaultState("Green") object MachineNotHomed : DefaultState("Green") object MachineHoming : DefaultState("Green") object MachineReady : DefaultState("Green") object SpindleRunning : DefaultState("Yellow") object AxisFeeding : DefaultState("Axis Feeding") object AxisJogging : DefaultState("Axis Jogging") }
0
Kotlin
1
3
5cf42426895ba8691c9b53ba1b97c274bbdabc07
536
mindovercnclathe
Apache License 2.0
app/src/main/java/com/hercan/harrypotterinfoapp/network/datasource/potterdb/PotterDBDataSource.kt
hanifeercan
678,372,571
false
{"Kotlin": 85260}
package com.hercan.harrypotterinfoapp.network.datasource.potterdb import com.hercan.harrypotterinfoapp.network.model.potion.PotionDetailModel import com.hercan.harrypotterinfoapp.network.model.potion.PotionModel import com.hercan.harrypotterinfoapp.network.model.spell.SpellDetailModel import com.hercan.harrypotterinfoapp.network.model.spell.SpellModel import retrofit2.Response interface PotterDBDataSource { suspend fun getAllPotions(): Response<PotionModel> suspend fun getAllSpells(): Response<SpellModel> suspend fun getPotionWithSlug(slug: String): Response<PotionDetailModel> suspend fun getSpellWithSlug(slug: String): Response<SpellDetailModel> }
0
Kotlin
0
1
3b57a21492b5ca9d94d8b441d931febe9aa7a4b5
674
HarryPotterInfoApp
MIT License
src/test/kotlin/generator/model/utils/DataClassWithNotRequiredStringParameterWithMinMaxLen.kt
OKGenTool
766,121,849
false
{"Kotlin": 122205}
package generator.model.utils import datamodel.Component import datamodel.ComponentProperty import datamodel.DataType val dataClassWithNotRequiredStringParameterWithMinMaxLen = Component( schemaName = "#/components/schemas/DataClassWithNotRequiredStringParameterWithMinMaxLen", parameters = listOf( ComponentProperty( name = "value", dataType = DataType.STRING, required = false, schemaName = "", minLength = 2, maxLength = 10 ) ), simplifiedName = "DataClassWithNotRequiredStringParameterWithMinMaxLen", superClassChildSchemaNames = emptyList() ) val dataClassWithNotRequiredStringParameterWithMinMaxLenComponents = listOf(dataClassWithNotRequiredStringParameterWithMinMaxLen)
25
Kotlin
0
2
a50ca78edfb22cb5e88a5251a62611f4f9fbaad9
788
okgentool
Apache License 2.0
library/src/main/kotlin/com/daniloaraujosilva/mathemagika/library/common/mathematica/functions/HeaderAlignment.kt
Danilo-Araujo-Silva
271,904,885
false
null
package com.daniloaraujosilva.mathemagika.library.common.mathematica.functions import com.daniloaraujosilva.mathemagika.library.common.mathematica.MathematicaFunction /** *```` * * Name: HeaderAlignment * * Full name: System`HeaderAlignment * * Usage: HeaderAlignment is an option for Dataset that specifies how the contents of a header should be aligned within the available area in the header. * * Options: None * * Protected * Attributes: ReadProtected * * local: paclet:ref/HeaderAlignment * Documentation: web: http://reference.wolfram.com/language/ref/HeaderAlignment.html * * Definitions: None * * Own values: None * * Down values: None * * Up values: None * * Sub values: None * * Default value: None * * Numeric values: None */ fun headerAlignment(vararg arguments: Any?, options: MutableMap<String, Any?> = mutableMapOf()): MathematicaFunction { return MathematicaFunction("HeaderAlignment", arguments.toMutableList(), options) }
2
Kotlin
0
3
4fcf68af14f55b8634132d34f61dae8bb2ee2942
1,091
mathemagika
Apache License 2.0
app/src/main/java/com/mohfahmi/moneytracker/ui/on_boarding/screen_two/ScreenTwoFragment.kt
MohFahmi27
474,054,024
false
null
package com.mohfahmi.moneytracker.ui.on_boarding.screen_two import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import com.mohfahmi.moneytracker.R class ScreenTwoFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_screen_two, container, false) } }
1
Kotlin
0
4
ed1517544a5e30167da22220819bab99a42b52fe
516
anak-kost-money-tracker
MIT License
Common/src/main/java/at/petrak/hexcasting/common/casting/operators/math/OpFloor.kt
floatonfire
566,158,079
true
{"Java Properties": 2, "Groovy": 1, "Text": 3, "Gradle": 5, "Shell": 1, "Markdown": 2, "Git Attributes": 1, "Batchfile": 1, "Ignore List": 1, "Kotlin": 183, "Java": 293, "JSON": 988, "GLSL": 1, "YAML": 1, "HTML": 1, "Python": 1, "INI": 3, "TOML": 1}
package at.petrak.hexcasting.common.casting.operators.math import at.petrak.hexcasting.api.spell.ConstMediaAction import at.petrak.hexcasting.api.spell.aplKinnie import at.petrak.hexcasting.api.spell.casting.CastingContext import at.petrak.hexcasting.api.spell.getNumOrVec import at.petrak.hexcasting.api.spell.iota.Iota import kotlin.math.floor object OpFloor : ConstMediaAction { override val argc: Int get() = 1 override fun execute(args: List<Iota>, ctx: CastingContext): List<Iota> { val value = args.getNumOrVec(0, argc) return listOf(aplKinnie(value, ::floor)) } }
0
null
0
0
03dd09c6decefd357bc206666f0eb49b107c619f
611
hexmod-fork
MIT License
plugins/kotlin/refactorings/kotlin.refactorings.introduce.k2/src/org/jetbrains/kotlin/idea/k2/refactoring/introduce/introduceVariable/KotlinIntroduceVariableServiceK2Impl.kt
sprigogin
93,194,179
false
{"Text": 9376, "INI": 516, "YAML": 419, "Ant Build System": 11, "Batchfile": 33, "Dockerfile": 10, "Shell": 633, "Markdown": 744, "Ignore List": 143, "Git Revision List": 1, "Git Attributes": 11, "EditorConfig": 260, "XML": 7826, "SVG": 4416, "Kotlin": 58363, "Java": 83686, "HTML": 3782, "Java Properties": 220, "Gradle": 447, "Maven POM": 95, "JavaScript": 229, "CSS": 79, "JSON": 1419, "JFlex": 33, "Makefile": 5, "Diff": 137, "XSLT": 113, "Gradle Kotlin DSL": 713, "Groovy": 3131, "desktop": 1, "JAR Manifest": 17, "PHP": 47, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 13, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 26, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 72, "GraphQL": 125, "Nginx": 1, "HAProxy": 1, "OpenStep Property List": 47, "Python": 17005, "C": 111, "C++": 42, "Protocol Buffer": 3, "fish": 2, "PowerShell": 3, "Go": 36, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "HCL": 4, "Elixir": 2, "Ruby": 4, "XML Property List": 84, "E-mail": 18, "Roff": 283, "Roff Manpage": 40, "Swift": 3, "TOML": 196, "Checksums": 49, "Java Server Pages": 11, "Vue": 1, "Dotenv": 1, "reStructuredText": 67, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 17, "Handlebars": 1, "Rust": 17, "Go Checksums": 1, "Go Module": 1, "NSIS": 8, "PlantUML": 6, "SCSS": 2, "Thrift": 3, "Cython": 13, "Regular Expression": 3, "JSON5": 4, "OASv3-json": 3, "OASv3-yaml": 1}
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.k2.refactoring.introduce.introduceVariable import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.util.elementType import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol import org.jetbrains.kotlin.idea.base.analysis.api.utils.analyzeInModalWindow import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.k2.refactoring.introduce.introduceVariable.K2IntroduceVariableHandler.getCandidateContainers import org.jetbrains.kotlin.idea.refactoring.introduce.IntroduceRefactoringException import org.jetbrains.kotlin.idea.refactoring.introduce.KotlinIntroduceVariableHelper import org.jetbrains.kotlin.idea.refactoring.introduce.KotlinIntroduceVariableService import org.jetbrains.kotlin.idea.refactoring.introduce.findStringTemplateOrStringTemplateEntryExpression import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.ElementKind import org.jetbrains.kotlin.idea.util.findElement import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtDotQualifiedExpression import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtSimpleNameExpression internal class KotlinIntroduceVariableServiceK2Impl(private val project: Project) : KotlinIntroduceVariableService { override fun findElement( file: KtFile, startOffset: Int, endOffset: Int, failOnNoExpression: Boolean, elementKind: ElementKind ): PsiElement? { var element = findElement(file, startOffset, endOffset, elementKind) ?: findStringTemplateOrStringTemplateEntryExpression(file, startOffset, endOffset, elementKind) ?: findStringTemplateFragment(file, startOffset, endOffset, elementKind) if (element is KtSimpleNameExpression) { val qualifiedExpression = element.parent as? KtDotQualifiedExpression if (qualifiedExpression != null && qualifiedExpression.receiverExpression == element) { val resolved = element.mainReference.resolve() val isObjectReferenceInQualifier = resolved is KtClassOrObject && resolved.getDeclarationKeyword()?.elementType == KtTokens.OBJECT_KEYWORD if (!isObjectReferenceInQualifier) { element = null } } } if (element == null) { if (failOnNoExpression) { throw IntroduceRefactoringException(KotlinBundle.message("cannot.refactor.not.expression")) } return null } return element } override fun getContainersForExpression(expression: KtExpression): List<KotlinIntroduceVariableHelper.Containers> { return expression.getCandidateContainers() } override fun findOccurrences( expression: KtExpression, occurrenceContainer: KtElement, ): List<KtExpression> = with(K2IntroduceVariableHandler) { expression.findOccurrences(occurrenceContainer) } override fun doRefactoringWithContainer( editor: Editor?, expressionToExtract: KtExpression, container: KtElement, occurrencesToReplace: List<KtExpression>? ) { K2IntroduceVariableHandler.doRefactoringWithSelectedTargetContainer( project, editor, expressionToExtract, // TODO: fix occurence container (currently it is not used in K2-implementation) KotlinIntroduceVariableHelper.Containers(container, container), isVar = false, ) } override fun hasUnitType(element: KtExpression): Boolean { return analyzeInModalWindow(element, KotlinBundle.message("find.usages.prepare.dialog.progress")) { val expressionType = element.getKtType() expressionType == null || expressionType.isUnit } } }
1
null
1
1
f1b733c79fd134e6646f28d1dc99af144c942785
4,411
intellij-community
Apache License 2.0
app/src/main/java/com/abh80/smartedge/flashalert/db/AppSelectorDao.kt
atifkhandeveloper
665,493,042
false
{"Java": 323075, "Kotlin": 68101, "JavaScript": 3143}
package com.abh80.smartedge.flashalert.db import androidx.room.* import com.abh80.smartedge.flashalert.poko.AppItem @Dao interface AppSelectorDao { @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertApp(item: AppItem) // @Update // fun updateApp(item: AppItem) // @Query("UPDATE appitem SET selected= :selected WHERE name= :name") // fun updateFromName(name: String, selected: Boolean) @Query("UPDATE appitem SET selected= :selected WHERE packageId= :packageId") fun updateFromPackage(packageId: String, selected: Boolean) @Query("SELECT * FROM AppItem WHERE packageId = :packageId") fun getAppItemByPackageId(packageId: String) : AppItem? @Delete fun deleteApp(item: AppItem) @Query("SELECT * FROM AppItem") fun getAppItem(): List<AppItem> }
1
null
1
1
99b9e8945c03bd357fc2f4b6ee2679e9768ee692
812
Edge-Notification
MIT License
android/common-ui/src/main/java/any/ui/common/lazy/ScrollToTopFab.kt
dokar3
572,488,513
false
null
package any.ui.common.lazy import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.animation.ExperimentalAnimationApi import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.foundation.layout.size import androidx.compose.material.FloatingActionButton import androidx.compose.material.Icon import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.runtime.Composable import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import any.base.R import kotlinx.coroutines.launch import java.util.TreeMap import kotlin.math.abs @OptIn(ExperimentalAnimationApi::class) @Composable fun ScrollToTopFab( scrollableState: LazyScrollableState, modifier: Modifier = Modifier, size: Dp = 48.dp, toggleScrollThreshold: Dp = 180.dp, enterTransition: EnterTransition = scaleIn() + slideInVertically { it * 2 }, exitTransition: ExitTransition = scaleOut() + slideOutVertically { it * 2 }, icon: @Composable () -> Unit = { Icon( imageVector = Icons.Default.KeyboardArrowUp, contentDescription = stringResource(R.string.go_to_top), tint = Color.White, ) } ) { val scope = rememberCoroutineScope() val density = LocalDensity.current val currThreshold = rememberUpdatedState(toggleScrollThreshold) val itemHeights = rememberSaveable(inputs = emptyArray()) { TreeMap<Int, Int>() } val showScrollToTopButton by remember(scrollableState, density) { val threshold = with(density) { -(currThreshold.value.roundToPx()) } derivedStateOf { scrollableState.visibleItemsInfo.let { items -> if (items.isEmpty()) { return@let false } if (items.first().offset < threshold) { return@let true } for (item in items) { itemHeights[item.index] = item.size } val firstIndex = items.first().index var invisibleItemsHeight = 0 for ((index, height) in itemHeights) { if (index < firstIndex) { invisibleItemsHeight += height if (invisibleItemsHeight > abs(threshold)) { return@let true } } else { // Safely break the loop because the map is a TreeMap break } } -invisibleItemsHeight + items.first().offset < threshold } } } AnimatedVisibility( visible = showScrollToTopButton, modifier = modifier, enter = enterTransition, exit = exitTransition, ) { FloatingActionButton( onClick = { scope.launch { scrollableState.quickScrollToTop() } }, modifier = Modifier.size(size), ) { icon() } } }
11
Kotlin
0
9
ca38d70740515c699ed5f79daced8b0d7687ae12
3,786
any
Apache License 2.0
app/src/main/java/dev/vladimirj/login/di/AppModule.kt
VladimirWrites
393,602,658
false
null
package dev.vladimirj.login.di import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import dev.vladimirj.base.ui.CoroutineDispatcherProvider import dev.vladimirj.login.LoginNavigatorImpl import dev.vladimirj.login.ui.LoginNavigator import kotlinx.coroutines.Dispatchers import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object AppModule { @Singleton @Provides fun provideTaxiNavigator(): LoginNavigator { return LoginNavigatorImpl() } @Provides fun provideCoroutineDispatcherProvider(): CoroutineDispatcherProvider { return CoroutineDispatcherProvider(main = Dispatchers.Main, io = Dispatchers.IO) } }
0
Kotlin
0
3
b363e2965e18c182136e59e24de4da285ce17e7b
748
LoginExample
Apache License 2.0
android/app/src/main/java/com/algorand/android/modules/algosdk/domain/model/dto/AssetConfigParametersDTO.kt
perawallet
364,359,642
false
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
/* * Copyright 2022 Pera Wallet, LDA * 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.algorand.android.modules.algosdk.domain.model.dto data class AssetConfigParametersDTO( val totalSupply: String? = null, val decimal: Long? = null, val isFrozen: Boolean? = null, val unitName: String? = null, val name: String? = null, val url: String? = null, val metadataHash: String? = null, val managerAddress: String? = null, val reserveAddress: String? = null, val frozenAddress: String? = null, val clawbackAddress: String? = null )
22
Swift
62
181
92fc77f73fa4105de82d5e87b03c1e67600a57c0
1,079
pera-wallet
Apache License 2.0
android/src/main/kotlin/uk/co/objectivity/beacon_monitoring/plugin/receiver/BluetoothStateReceiver.kt
VinniciusJesus
442,466,273
false
{"Swift": 77863, "Kotlin": 76055, "Dart": 13707, "Ruby": 2323, "Objective-C": 38}
// Copyright (c) 2020 Objectivity. All rights reserved. // Use of this source code is governed by The MIT License (MIT) that can be // found in the LICENSE file. package uk.co.objectivity.beacon_monitoring.plugin.receiver import android.bluetooth.BluetoothAdapter import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import uk.co.objectivity.beacon_monitoring.plugin.connection.DependencyContainer class BluetoothStateReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { if (BluetoothAdapter.ACTION_STATE_CHANGED == intent.action) { val state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR) toggleBeaconMonitoring(context, BluetoothAdapter.STATE_ON == state) } } private fun toggleBeaconMonitoring(context: Context, enable: Boolean) { val dependencyContainer = DependencyContainer.getInstance(context) val monitoringService = dependencyContainer.monitoringService val beaconClient = dependencyContainer.beaconClient if (enable && monitoringService.allRequirementsMet()) { beaconClient.enableMonitoring() } else { beaconClient.disableMonitoring() } } }
0
Swift
0
0
361b91e4084851dc015663788a21051e9eb3a314
1,300
beacon_monitoring
MIT License
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/CongruentTo.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup public val OutlineGroup.CongruentTo: ImageVector get() { if (_congruentTo != null) { return _congruentTo!! } _congruentTo = Builder(name = "CongruentTo", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(5.0f, 13.0f) horizontalLineToRelative(14.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(5.0f, 17.0f) horizontalLineToRelative(14.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(5.0f, 7.686f) curveToRelative(2.333f, -2.624f, 4.667f, -1.856f, 7.0f, 0.064f) reflectiveCurveToRelative(4.667f, 2.688f, 7.0f, 0.064f) } } .build() return _congruentTo!! } private var _congruentTo: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,353
compose-icon-collections
MIT License
Android/BLUR/presentation/src/main/java/com/blur/blur/presentation/main/RegisterProduct/RegisterProductScreen.kt
kim-do-hyeon
752,461,840
false
{"Kotlin": 365399, "Swift": 75215, "Python": 66512, "JavaScript": 41759, "CSS": 6957, "HTML": 2674, "Shell": 176}
package com.blur.blur.presentation.Main.RegisterProduct import android.content.Intent import android.widget.Toast import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material3.CenterAlignedTopAppBar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.Font import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import com.blur.blur.components.TextField.AddDeviceTextField import com.blur.blur.presentation.Component.Button.FillButton import com.blur.blur.presentation.R import com.blur.blur.presentation.SplashActivity import org.orbitmvi.orbit.compose.collectAsState import org.orbitmvi.orbit.compose.collectSideEffect @Composable fun RegisterProductScreen( viewModel: RegisterProductViewModel = hiltViewModel(), ) { val state = viewModel.collectAsState().value val context = LocalContext.current viewModel.collectSideEffect { sideEffect -> when (sideEffect) { RegisterProductSideEffect.NavigateToMainActivity -> { context.startActivity( Intent(context, SplashActivity::class.java).apply { flags = Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK } ) } is RegisterProductSideEffect.Toast -> { Toast.makeText(context, sideEffect.message, Toast.LENGTH_SHORT).show() } else -> {} } } RegisterProductScreen( deviceCode = state.code, onDeviceCode = viewModel::onDeviceCode, onClick = viewModel::onClick, onMainScreen = viewModel::onMainScreen ) } @OptIn(ExperimentalMaterial3Api::class) @Composable private fun RegisterProductScreen( deviceCode: String, onDeviceCode: (String) -> Unit, onClick: () -> Unit, onMainScreen: () -> Unit ) { Scaffold( topBar = { CenterAlignedTopAppBar( colors = TopAppBarDefaults.topAppBarColors( containerColor = MaterialTheme.colorScheme.primaryContainer, titleContentColor = MaterialTheme.colorScheme.primary, ), title = { Text(text = "기기 등록") }, navigationIcon = { IconButton( onClick = onMainScreen ) { Icon(Icons.Filled.ArrowBack, contentDescription = "뒤로 가기") } } ) } ) { contentPadding -> Column( horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center, modifier = Modifier .fillMaxSize() .padding(horizontal = 16.dp) .padding(contentPadding), ) { Spacer(modifier = Modifier.weight(1f)) Text( text = "제품의 제품 코드를 입력해 주세요", style = TextStyle( fontSize = 24.sp, lineHeight = 39.sp, fontFamily = FontFamily(Font(R.font.roboto_bold)), fontWeight = FontWeight(700), color = MaterialTheme.colorScheme.onBackground, textAlign = TextAlign.Center, ) ) Spacer(modifier = Modifier.height(12.dp)) Text( text = "제품코드를 입력할때 - 을 빼고 입력해주세요", style = TextStyle( fontSize = 16.sp, lineHeight = 23.4.sp, fontFamily = FontFamily(Font(R.font.roboto_regular)), fontWeight = FontWeight(500), color = Color(0xFF828282), textAlign = TextAlign.Center, ) ) Spacer(modifier = Modifier.height(20.dp)) AddDeviceTextField( modifier = Modifier .fillMaxWidth(), value = deviceCode, onValueChange = onDeviceCode, ) FillButton( modifier = Modifier .padding(vertical = 24.dp) .fillMaxWidth(), text = "제품 등록", onClick = onClick ) Spacer(modifier = Modifier.weight(1f)) } } } @Preview @Composable fun RegisterProductScreenPreview() { RegisterProductScreen( deviceCode = "", onDeviceCode = {}, onClick = {}, onMainScreen = {}, ) }
0
Kotlin
2
6
f350b6d1bc1a7630cb787107713ed47f50a7e84b
5,816
2024-jj-capstone-design
MIT License
base/src/main/java/com/wsg/base/common/CommonExt.kt
wushaoge
299,235,402
false
null
package com.wsg.base.common import com.google.gson.Gson /** * ================================================ * 作 者:wushaoge * 版 本:1.0 * 创建日期:2020-07-14 14:38 * 描 述:扩展类 * 修订历史: * ================================================ */ /** * 转换String */ fun Any?.toJsonString(): String { return Gson().toJson(this) } /** * 转换成对象 */ inline fun <reified T> String.toJsonObject(): T { return Gson().fromJson(this, T::class.java) }
0
Kotlin
16
53
d5c8722ecc013f17ae8a7d0419abb6daec8c7def
457
WsgMvvm
Apache License 2.0
cola-worker/src/native-test/kotlin/io/colability/ExampleResourceIT.kt
colability
668,018,364
false
null
/* * Copyright 2023 Colability * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.colability import io.quarkus.test.junit.QuarkusIntegrationTest @QuarkusIntegrationTest class ExampleResourceIT : ExampleResourceTest()
0
Kotlin
0
0
be9f6590b1a5b8a4c89eb3dfe97c5ae15f8046a6
739
cola-server
Apache License 2.0
example-speech-recognition/src/main/java/com/dailystudio/tflite/example/speech/recognition/fragment/SpeechRecognitionFragment.kt
dailystudio
267,263,865
false
null
package com.dailystudio.tflite.example.speech.recognition.fragment import android.content.res.AssetManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.dailystudio.devbricksx.audio.AudioConfig import com.dailystudio.devbricksx.audio.AudioProcessFragment import com.dailystudio.devbricksx.development.Logger import com.dailystudio.tflite.example.common.InferenceAgent import com.dailystudio.tflite.example.common.InferenceInfo import com.dailystudio.tflite.example.speech.recognition.AudioInferenceInfo import com.dailystudio.tflite.example.speech.recognition.R import org.tensorflow.lite.Interpreter import org.tensorflow.lite.examples.speech.RecognizeCommands import org.tensorflow.lite.examples.speech.RecognizeCommands.RecognitionResult import java.io.BufferedReader import java.io.FileInputStream import java.io.IOException import java.io.InputStreamReader import java.nio.MappedByteBuffer import java.nio.channels.FileChannel import java.util.* class SpeechRecognitionFragment : AudioProcessFragment() { companion object { // you are running your own model. private const val SAMPLE_RATE = 16000 private const val SAMPLE_DURATION_MS = 1000 private const val RECORDING_LENGTH = (SAMPLE_RATE * SAMPLE_DURATION_MS / 1000) private const val AVERAGE_WINDOW_DURATION_MS: Long = 1000 private const val DETECTION_THRESHOLD = 0.50f private const val SUPPRESSION_MS = 1500 private const val MINIMUM_COUNT = 3 private const val MINIMUM_TIME_BETWEEN_SAMPLES_MS: Long = 30 private const val LABEL_FILENAME = "conv_actions_labels.txt" private const val MODEL_FILENAME = "conv_actions_frozen.tflite" } private val labels: MutableList<String> = mutableListOf() private val displayedLabels: MutableList<String> = mutableListOf() private var recognizeCommands: RecognizeCommands? = null private var tfLite: Interpreter? = null private val tfliteOptions = Interpreter.Options() private var lastProcessingTimeMs: Long = 0 private var inferenceAgent: InferenceAgent<InferenceInfo, RecognitionResult> = InferenceAgent() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) initTflite() } private fun initTflite() { // Load the labels for the model, but only display those that don't start // with an underscore. val actualLabelFilename: String = LABEL_FILENAME Logger.debug("reading labels from: $actualLabelFilename") var br: BufferedReader? = null try { val stream = requireContext().assets.open(actualLabelFilename) Logger.debug("stream: $stream") val reader = InputStreamReader(stream) Logger.debug("reader: $reader") br = BufferedReader(reader) Logger.debug("br: $br") synchronized(labels) { var line: String? while (br.readLine().also { line = it } != null) { Logger.debug("line: $line") line?.let { labels.add(it) if (it[0] != '_') { displayedLabels.add(it.substring(0, 1).toUpperCase() + it.substring(1)) } } } } br.close() } catch (e: IOException) { throw RuntimeException("Problem reading label file!", e) } // Set up an object to smooth recognition results to increase accuracy. // Set up an object to smooth recognition results to increase accuracy. recognizeCommands = RecognizeCommands( labels, AVERAGE_WINDOW_DURATION_MS, DETECTION_THRESHOLD, SUPPRESSION_MS, MINIMUM_COUNT, MINIMUM_TIME_BETWEEN_SAMPLES_MS ) val actualModelFilename: String = MODEL_FILENAME try { val buffer = loadModelFile(requireContext().assets, actualModelFilename) buffer?.let { tfLite = Interpreter(it, tfliteOptions) } } catch (e: Exception) { throw RuntimeException(e) } tfLite?.resizeInput(0, intArrayOf(RECORDING_LENGTH, 1)) tfLite?.resizeInput(1, intArrayOf(1)) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_speech_recognition, container, false) override fun onProcessAudioData(audioConfig: AudioConfig, audioData: ShortArray) { val inferenceInfo = AudioInferenceInfo() val floatInputBuffer = Array(RECORDING_LENGTH) { FloatArray(1) } val sampleRateList = intArrayOf(SAMPLE_RATE) val startTime = Date().time // We need to feed in float values between -1.0f and 1.0f, so divide the // signed 16-bit inputs. for (i in 0 until RECORDING_LENGTH) { floatInputBuffer[i][0] = audioData[i] / 32767.0f } val inputArray = arrayOf<Any>(floatInputBuffer, sampleRateList) val outputMap: MutableMap<Int, Any> = HashMap() var outputScores: Array<FloatArray> synchronized(labels) { // Logger.debug("labels = $labels") outputScores = Array(1) { kotlin.FloatArray(labels.size) } } outputMap[0] = outputScores val inferenceStartTime = Date().time // Run the model. try { tfLite?.runForMultipleInputsOutputs(inputArray, outputMap) } catch (e: Exception) { Logger.error("inference failed: $e") } // Use the smoother to figure out if we've had a real recognition event. val currentTime = System.currentTimeMillis() val result: RecognitionResult? = recognizeCommands?.processLatestResults(outputScores[0], currentTime) // Logger.debug("result: $result") val endTime = Date().time lastProcessingTimeMs = endTime - startTime inferenceInfo.sampleRate = SAMPLE_RATE inferenceInfo.bufferSize = audioData.size inferenceInfo.inferenceTime = endTime - inferenceStartTime inferenceInfo.analysisTime = lastProcessingTimeMs inferenceAgent.deliverInferenceInfo(inferenceInfo) result?.let { inferenceAgent.deliverResults(result) } } @Throws(IOException::class) private fun loadModelFile(assets: AssetManager, modelFilename: String): MappedByteBuffer? { val fileDescriptor = assets.openFd(modelFilename) val inputStream = FileInputStream(fileDescriptor.fileDescriptor) val fileChannel = inputStream.channel val startOffset = fileDescriptor.startOffset val declaredLength = fileDescriptor.declaredLength return fileChannel.map( FileChannel.MapMode.READ_ONLY, startOffset, declaredLength ) } }
1
Kotlin
6
17
62910b05ff88b6817d75082a5b93d26c2289c43e
7,253
tensorflow-lite-examples-android
Apache License 2.0
replica-core/src/jvmTest/kotlin/me/aartikov/replica/single/settings/StaleTimeTest.kt
aartikov
438,253,231
false
{"HTML": 3233987, "Kotlin": 685239, "CSS": 29063, "JavaScript": 19875}
package me.aartikov.replica.single.settings import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest import me.aartikov.replica.single.ReplicaSettings import me.aartikov.replica.single.currentState import me.aartikov.replica.single.utils.ReplicaProvider import me.aartikov.replica.utils.MainCoroutineRule import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import kotlin.time.Duration.Companion.milliseconds import kotlin.time.Duration.Companion.seconds import kotlin.time.ExperimentalTime @OptIn(ExperimentalCoroutinesApi::class) class StaleTimeTest { private val replicaProvider = ReplicaProvider() companion object { private const val DEFAULT_DELAY = 100L } @get:Rule var mainCoroutineRule = MainCoroutineRule() @OptIn(ExperimentalTime::class) @Test fun `is fresh if no stale time setup`() = runTest { val replica = replicaProvider.replica() replica.refresh() runCurrent() assertTrue(replica.currentState.hasFreshData) } @Test fun `is not fresh initially`() = runTest { val replica = replicaProvider.replica( replicaSettings = ReplicaSettings( staleTime = DEFAULT_DELAY.milliseconds ) ) assertFalse(replica.currentState.hasFreshData) } @Test fun `is fresh after refreshing`() = runTest { val replica = replicaProvider.replica( replicaSettings = ReplicaSettings( staleTime = (DEFAULT_DELAY * 2).milliseconds ) ) replica.refresh() runCurrent() assertTrue(replica.currentState.hasFreshData) } @Test fun `is stale after stale time passed`() = runTest { val replica = replicaProvider.replica( replicaSettings = ReplicaSettings( staleTime = DEFAULT_DELAY.milliseconds ) ) replica.refresh() delay(DEFAULT_DELAY + 1) // stale time is passed assertFalse(replica.currentState.hasFreshData) } @Test fun `is not fresh if data is cleared`() = runTest { val replica = replicaProvider.replica( replicaSettings = ReplicaSettings( staleTime = 30.seconds ) ) replica.refresh() runCurrent() replica.clear() runCurrent() assertFalse(replica.currentState.hasFreshData) } @Test fun `is fresh if new data is loaded`() = runTest { val replica = replicaProvider.replica( replicaSettings = ReplicaSettings( staleTime = DEFAULT_DELAY.milliseconds ) ) replica.refresh() delay(DEFAULT_DELAY + 1) // stale time is passed replica.refresh() runCurrent() assertTrue(replica.currentState.hasFreshData) } }
0
HTML
1
33
dc55d0cb727b6854224ceb8b1a1d0d87c7faaddf
3,019
Replica
MIT License
app/src/main/java/com/elhady/movies/ui/seeAll/SeeAllMediaUiEvent.kt
islamelhady
301,591,032
false
{"Kotlin": 400229}
package com.elhady.movies.ui.seeAll sealed interface SeeAllMediaUiEvent { data class ClickMovieEvent(val mediaId: Int): SeeAllMediaUiEvent data class ClickSeriesEvent(val mediaId: Int): SeeAllMediaUiEvent data class ShowSnackBar(val message: String): SeeAllMediaUiEvent }
1
Kotlin
0
0
9c732fa8b96c2b4f618bc425e968ac56d0e5529e
284
movie-night-v2
Apache License 2.0
src/main/kotlin/org/madisonbikes/bikeweek/LocationWriter.kt
madisonbikes
291,119,897
false
{"HTML": 34218, "Kotlin": 23583}
package org.madisonbikes.bikeweek import okio.BufferedSink import org.supercsv.io.CsvMapWriter import org.supercsv.prefs.CsvPreference import java.io.OutputStreamWriter class LocationWriter( private val locationsSink: BufferedSink, private val events: List<Event>, private val day: EventDay, private val locationDisambiguator: LocationDisambiguator ) { fun writeLocationsToCsv() { CsvMapWriter( OutputStreamWriter(locationsSink.outputStream(), "UTF-8"), CsvPreference.STANDARD_PREFERENCE ).use { csvWriter -> val columns = arrayOf( "Name", "Location", "Description", "Date", "Time", "Event Type", "Sponsors", "Detailed Location" ) csvWriter.writeHeader(*columns) events .filter { it.eventDays.contains(day) } .filter { it.location.showOnMap } .forEach { event -> val item = mutableMapOf<String, String>() item["Name"] = event.name item["Location"] = requireNotNull(event.location.mapsDescription) item["Detailed Location"] = locationDisambiguator.disambiguateLocation(event.location.mapsQuery) item["Description"] = event.description item["Date"] = day.headerString event.renderedTime?.let { item["Time"] = it } item["Event Type"] = event.eventTypes.joinToString { it.description } item["Sponsors"] = event.sponsors.joinToString() csvWriter.write(item, *columns) } } } }
0
HTML
0
0
04150c3d1392846c31c622c11d30d933c667a840
1,831
bikeweek2020
Apache License 2.0
library/src/test/java/kwasm/format/binary/module/MemorySectionTest.kt
jasonwyatt
226,777,898
false
null
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package kwasm.format.binary.module import com.google.common.truth.Truth.assertThat import kwasm.ast.type.Limits import kwasm.ast.type.MemoryType import kwasm.format.binary.BinaryParser import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import java.io.ByteArrayInputStream @RunWith(JUnit4::class) class MemorySectionTest { @Test fun empty() { val section = MemorySection(emptyList()) val bytes = sequenceOf<Byte>(0x05) + section.toBytesNoHeader() val parser = BinaryParser(ByteArrayInputStream(bytes.toList().toByteArray())) assertThat(parser.readSection()).isEqualTo(section) } @Test fun nonEmpty() { val section = MemorySection( listOf( MemoryType(Limits(0, 256)), MemoryType(Limits(1337, 65536)), ) ) val bytes = sequenceOf<Byte>(0x05) + section.toBytesNoHeader() val parser = BinaryParser(ByteArrayInputStream(bytes.toList().toByteArray())) assertThat(parser.readSection()).isEqualTo(section) } }
4
WebAssembly
3
25
3c17988daaa8f37d654ee29428a37b330b3532ad
1,679
KWasm
Apache License 2.0
backend/rest-api/src/test/kotlin/at/sensatech/openfastlane/api/EntitlementsApiTest.kt
sensatech
724,093,399
false
{"Kotlin": 442921, "Dart": 408727, "HTML": 5563, "FreeMarker": 2659, "Dockerfile": 946, "Shell": 554}
package at.sensatech.openfastlane.api import at.sensatech.openfastlane.api.entitlements.EntitlementsApi import at.sensatech.openfastlane.api.testcommons.field import at.sensatech.openfastlane.common.newId import at.sensatech.openfastlane.documents.FileResult import at.sensatech.openfastlane.domain.cosumptions.ConsumptionPossibility import at.sensatech.openfastlane.domain.cosumptions.ConsumptionPossibilityType import at.sensatech.openfastlane.domain.cosumptions.ConsumptionsService import at.sensatech.openfastlane.domain.entitlements.CreateEntitlement import at.sensatech.openfastlane.domain.entitlements.EntitlementsError import at.sensatech.openfastlane.domain.entitlements.EntitlementsService import at.sensatech.openfastlane.domain.entitlements.UpdateEntitlement import at.sensatech.openfastlane.domain.exceptions.BadRequestException import at.sensatech.openfastlane.domain.models.AuditItem import at.sensatech.openfastlane.domain.models.Consumption import at.sensatech.openfastlane.domain.models.EntitlementCriteriaType import at.sensatech.openfastlane.domain.models.EntitlementValue import at.sensatech.openfastlane.mailing.MailError import com.ninjasquad.springmockk.MockkBean import io.mockk.every import io.mockk.verify import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.core.io.ResourceLoader import org.springframework.restdocs.payload.FieldDescriptor import org.springframework.restdocs.payload.JsonFieldType import org.springframework.restdocs.payload.JsonFieldType.STRING import org.springframework.restdocs.payload.PayloadDocumentation.requestFields import org.springframework.restdocs.payload.PayloadDocumentation.responseFields import org.springframework.test.context.ContextConfiguration import org.springframework.test.web.servlet.result.MockMvcResultMatchers import java.io.File import java.time.ZoneId import java.time.ZonedDateTime @WebMvcTest(controllers = [EntitlementsApi::class]) @ContextConfiguration(classes = [EntitlementsApi::class]) internal class EntitlementsApiTest : AbstractRestApiUnitTest() { private val testUrl = "/entitlements" @MockkBean private lateinit var service: EntitlementsService @MockkBean private lateinit var consumptionsService: ConsumptionsService @Autowired lateinit var resourceLoader: ResourceLoader private val firstOne = entitlements.first() private val consumedAt = ZonedDateTime.of(2024, 1, 1, 12, 0, 0, 0, ZoneId.systemDefault()) private val consumptions = mockConsumptions(entitlements, consumedAt) @BeforeEach fun beforeEach() { every { service.listAllEntitlements(any()) } returns entitlements every { service.getEntitlement(any(), any()) } returns null every { service.getEntitlement(any(), eq(firstOne.id)) } returns firstOne every { service.createEntitlement(any(), any()) } returns firstOne every { service.updateEntitlement(any(), any(), any()) } throws EntitlementsError.NoEntitlementFound("NOPE") every { service.updateEntitlement(any(), eq(firstOne.id), any()) } returns firstOne every { service.extendEntitlement(any(), any()) } throws EntitlementsError.NoEntitlementFound("NOPE") every { service.extendEntitlement(any(), eq(firstOne.id)) } returns firstOne every { service.viewQrPdf(any(), any()) } throws EntitlementsError.NoEntitlementFound("NOPE") every { service.sendQrPdf(any(), any(), any()) } returns Unit val dataFile: File = resourceLoader.getResource("classpath:example.pdf").file every { service.viewQrPdf(any(), eq(firstOne.id)) } returns FileResult( "example.pdf", "classpath:example.pdf", file = dataFile ) every { consumptionsService.checkConsumptionPossibility(any(), any()) } throws EntitlementsError.NoEntitlementFound("NOPE") every { consumptionsService.checkConsumptionPossibility(any(), eq(firstOne.id)) } returns ConsumptionPossibility(ConsumptionPossibilityType.CONSUMPTION_POSSIBLE) every { consumptionsService.getConsumptionsOfEntitlement(any(), eq(firstOne.id)) } returns consumptions every { consumptionsService.getConsumption(any(), eq(consumptions.first().id)) } returns consumptions.first() } @TestAsReader fun `listAllEntitlements RESTDOC`() { this.performGet(testUrl) .expectOk() .document( "entitlements-list", responseFields(entitlementFields("[].")) ) verify { service.listAllEntitlements(any()) } } @TestAsReader fun `getEntitlement RESTDOC`() { val url = "$testUrl/${firstOne.id}" this.performGet(url) .expectOk() .document( "entitlements-get", responseFields(entitlementFields()) ) verify { service.getEntitlement(any(), eq(firstOne.id)) } } @TestAsReader fun `getEntitlement should return 404`() { val url = "$testUrl/${newId()}" this.performGet(url).isNotFound() } @TestAsReader fun `getEntitlementAudit RESTDOC`() { val url = "$testUrl/${firstOne.id}/history" val results = performGet(url).document( "entitlements-get-audit", responseFields(auditItemFields("[].")), ).returnsList(AuditItem::class.java) assertThat(results).isNotNull assertThat(results).isNotEmpty } @Nested inner class CheckConsumptionPossibility { @TestAsManager fun `checkConsumptionPossibility RESTDOC`() { val url = "$testUrl/${firstOne.id}/can-consume" performGet(url) .expectOk() .document( "entitlements-can-consume", responseFields(consumptionPossibilityFields()) ) verify { consumptionsService.checkConsumptionPossibility(any(), eq(firstOne.id)) } } @TestAsManager fun `checkConsumptionPossibility should return 404`() { val url = "$testUrl/${newId()}/can-consume" performGet(url).isNotFound() } @TestAsReader fun `checkConsumptionPossibility should return encoded ConsumptionPossibility`() { val url = "$testUrl/${firstOne.id}/can-consume" val result: ConsumptionPossibility = performGet(url).returns() assertThat(result.status).isEqualTo(ConsumptionPossibilityType.CONSUMPTION_POSSIBLE) } @TestAsReader fun `checkConsumptionPossibility should be allowed for READER`() { val url = "$testUrl/${firstOne.id}/can-consume" performGet(url).expectOk() verify { consumptionsService.checkConsumptionPossibility(any(), eq(firstOne.id)) } } } @Nested inner class GetConsumptionsOfEntitlement { @TestAsManager fun `getConsumptionsOfEntitlement RESTDOC`() { val url = "$testUrl/${firstOne.id}/consumptions" performGet(url) .expectOk() .document( "entitlements-get-consumptions-list", responseFields(consumptionFields("[].")) ) verify { consumptionsService.getConsumptionsOfEntitlement(any(), eq(firstOne.id)) } } @TestAsManager fun `getConsumptionsOfEntitlement should return 404`() { val url = "$testUrl/${newId()}/consumptions" performGet(url).isNotFound() } @TestAsReader fun `getConsumptionsOfEntitlement should be allowed for READER`() { val url = "$testUrl/${firstOne.id}/consumptions" val result = performGet(url).expectOk().returnsList(Consumption::class.java) verify { consumptionsService.getConsumptionsOfEntitlement(any(), eq(firstOne.id)) } val bla = ZonedDateTime.now() assertThat(result.map { it.copy(consumedAt = bla) }) .containsExactlyElementsOf(consumptions.map { it.copy(consumedAt = bla) }) } } @Nested inner class PerformConsumption { @TestAsScanner fun `performConsumption RESTDOC`() { every { consumptionsService.performConsumption(any(), eq(firstOne.id)) } returns consumptions.first() val url = "$testUrl/${firstOne.id}/consume" performPost(url) .expectOk() .document( "entitlements-perform-consumption", responseFields(consumptionFields()) ) verify { consumptionsService.performConsumption(any(), eq(firstOne.id)) } } @TestAsScanner fun `performConsumption should return 404`() { val url = "$testUrl/${newId()}/consume" performPost(url).isNotFound() } @TestAsReader fun `performConsumption should not be allowed for READER`() { every { consumptionsService.performConsumption(any(), eq(firstOne.id)) } returns consumptions.first() val url = "$testUrl/${firstOne.id}/consume" performPost(url).expectForbidden() } } @Nested inner class GetConsumption { @TestAsManager fun `getConsumption RESTDOC`() { val url = "$testUrl/${firstOne.id}/consumptions/${consumptions.first().id}" performGet(url) .expectOk() .document( "entitlements-get-consumptions-get", responseFields(consumptionFields()) ) verify { consumptionsService.getConsumption(any(), eq(consumptions.first().id)) } } @TestAsManager fun `getConsumption should return 404`() { val url = "$testUrl/${newId()}/consumptions/${newId()}" performGet(url).isNotFound() } @TestAsReader fun `getConsumption should be allowed for READER`() { val url = "$testUrl/${firstOne.id}/consumptions/${consumptions.first().id}" val result: Consumption = performGet(url).expectOk().returns() verify { consumptionsService.getConsumption(any(), eq(consumptions.first().id)) } assertThat(result.id).isEqualTo(consumptions.first().id) assertThat(result.personId).isEqualTo(consumptions.first().personId) assertThat(result.entitlementCauseId).isEqualTo(consumptions.first().entitlementCauseId) assertThat(result.entitlementData).isEqualTo(consumptions.first().entitlementData) } } @Nested inner class CreateEntitlement { private val request = CreateEntitlement( personId = newId(), entitlementCauseId = newId(), values = listOf( EntitlementValue( criteriaId = newId(), type = EntitlementCriteriaType.TEXT, value = "value" ) ) ) @TestAsManager fun `createEntitlement RESTDOC`() { performPost(testUrl, request) .expectOk() .document( "entitlements-create", requestFields(createEntitlementFields()), responseFields(entitlementFields()), ) verify { service.createEntitlement(any(), eq(request)) } } @TestAsManager fun `createEntitlement should return 400 when failing `() { every { service.createEntitlement(any(), eq(request)) } throws BadRequestException("NOPE", "no") performPost(testUrl, request).expectBadRequest() } @TestAsReader fun `createEntitlement should not be allowed for READER`() { performPost(testUrl, request).expectForbidden() verify(exactly = 0) { service.createEntitlement(any(), eq(request)) } } } @Nested inner class updateEntitlement { val request = UpdateEntitlement( values = listOf( EntitlementValue( criteriaId = newId(), type = EntitlementCriteriaType.TEXT, value = "value" ) ) ) @TestAsManager fun `updateEntitlement RESTDOC`() { performPatch("$testUrl/${firstOne.id}", request) .expectOk() .document( "entitlements-update", requestFields(updateEntitlementFields()), responseFields(entitlementFields()), ) verify { service.updateEntitlement(any(), eq(firstOne.id), eq(request)) } } @TestAsManager fun `updateEntitlement should return 400 when failing `() { every { service.updateEntitlement(any(), eq(firstOne.id), eq(request)) } throws BadRequestException( "NOPE", "no" ) performPatch("$testUrl/${firstOne.id}", request).expectBadRequest() } @TestAsReader fun `updateEntitlement should not be allowed for READER`() { performPatch("$testUrl/${firstOne.id}", request).expectForbidden() verify(exactly = 0) { service.updateEntitlement(any(), eq(firstOne.id), eq(request)) } } } @Nested inner class extendEntitlement { @TestAsManager fun `extendEntitlement RESTDOC`() { performPut("$testUrl/${firstOne.id}/extend") .expectOk() .document( "entitlements-extend", responseFields(entitlementFields()), ) verify { service.extendEntitlement(any(), eq(firstOne.id)) } } @TestAsManager fun `extendEntitlement should return 400 when failing `() { every { service.extendEntitlement(any(), eq(firstOne.id)) } throws BadRequestException("NOPE", "no") performPut("$testUrl/${firstOne.id}/extend").expectBadRequest() } @TestAsReader fun `extendEntitlement should not be allowed for READER`() { performPut("$testUrl/${firstOne.id}/extend").expectForbidden() verify(exactly = 0) { service.extendEntitlement(any(), eq(firstOne.id)) } } } @Nested inner class viewQrPdf { @TestAsManager fun `viewQrPdf RESTDOC`() { performGet("$testUrl/${firstOne.id}/pdf").document("entitlements-view-qr") verify { service.viewQrPdf(any(), eq(firstOne.id)) } } @TestAsManager fun `viewQrPdf should return 404 when failing `() { every { service.viewQrPdf(any(), eq(firstOne.id)) } throws EntitlementsError.InvalidEntitlementNoQr("NOPE") performGet("$testUrl/${firstOne.id}/pdf").isNotFound() } @TestAsReader fun `viewQrPdf should not be allowed for READER`() { performGet("$testUrl/${firstOne.id}/pdf").expectForbidden() verify(exactly = 0) { service.viewQrPdf(any(), eq(firstOne.id)) } } } @Nested inner class sendQrPdf { @TestAsManager fun `sendQrPdf RESTDOC`() { performPost( "$testUrl/${firstOne.id}/send-pdf", body = mapOf("recipient" to "<EMAIL>") ) .document( "entitlements-send-qr", requestFields(sendMailFields()), ) verify { service.sendQrPdf(any(), eq(firstOne.id), eq("<EMAIL>")) } } @TestAsManager fun `sendQrPdf should be callable without extra mail`() { performPost("$testUrl/${firstOne.id}/send-pdf") verify { service.sendQrPdf(any(), eq(firstOne.id), null) } } @TestAsManager fun `sendQrPdf should return 400 when invalid mail `() { every { service.sendQrPdf(any(), eq(firstOne.id), any()) } throws MailError.SendingFailedInvalidRecipient("NOPE") performPost("$testUrl/${firstOne.id}/send-pdf").expectBadRequest() } @TestAsManager fun `sendQrPdf should return 404 when missing mail `() { every { service.sendQrPdf(any(), eq(firstOne.id), any()) } throws MailError.SendingFailedMissingRecipient("NOPE") performPost("$testUrl/${firstOne.id}/send-pdf").isNotFound() } @TestAsManager fun `sendQrPdf should return 501 when mailing was not configured `() { every { service.sendQrPdf(any(), eq(firstOne.id), any()) } throws MailError.SendingFailedMisconfiguredServer("NOPE", "NOPE") performPost("$testUrl/${firstOne.id}/send-pdf").andExpect(MockMvcResultMatchers.status().isNotImplemented) } @TestAsManager fun `sendQrPdf should return 503 when mailing is not available `() { every { service.sendQrPdf(any(), eq(firstOne.id), any()) } throws MailError.SendingFailedServerError("NOPE", "NOPE") performPost("$testUrl/${firstOne.id}/send-pdf").andExpect(MockMvcResultMatchers.status().isServiceUnavailable) } @TestAsReader fun `sendQrPdf should not be allowed for READER`() { performPost("$testUrl/${firstOne.id}/send-pdf").expectForbidden() verify(exactly = 0) { service.sendQrPdf(any(), eq(firstOne.id), any()) } } } } fun createEntitlementFields(prefix: String = ""): List<FieldDescriptor> { return listOf( field(prefix + "entitlementCauseId", STRING, "ObjectId"), field(prefix + "personId", STRING, "ObjectId of Person"), field(prefix + "values", JsonFieldType.ARRAY, "EntitlementValueDto"), ).toMutableList().apply { addAll(entitlementValueFields(prefix + "values[].")) } } fun updateEntitlementFields(prefix: String = ""): List<FieldDescriptor> { return listOf( field(prefix + "values", JsonFieldType.ARRAY, "EntitlementValueDto"), ).toMutableList().apply { addAll(entitlementValueFields(prefix + "values[].")) } } fun sendMailFields(prefix: String = ""): List<FieldDescriptor> { return listOf( field(prefix + "recipient", STRING, "Mail address (nullable)").optional(), ) }
0
Kotlin
1
1
f80421a9db7a2b3b4fee71ebc9724789623d74bd
18,754
openfastlane
Apache License 2.0
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Arrowright.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup public val OutlineGroup.Arrowright: ImageVector get() { if (_arrowright != null) { return _arrowright!! } _arrowright = Builder(name = "Arrowright", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.0f, 22.75f) horizontalLineTo(9.0f) curveTo(3.57f, 22.75f, 1.25f, 20.43f, 1.25f, 15.0f) verticalLineTo(9.0f) curveTo(1.25f, 3.57f, 3.57f, 1.25f, 9.0f, 1.25f) horizontalLineTo(15.0f) curveTo(20.43f, 1.25f, 22.75f, 3.57f, 22.75f, 9.0f) verticalLineTo(15.0f) curveTo(22.75f, 20.43f, 20.43f, 22.75f, 15.0f, 22.75f) close() moveTo(9.0f, 2.75f) curveTo(4.39f, 2.75f, 2.75f, 4.39f, 2.75f, 9.0f) verticalLineTo(15.0f) curveTo(2.75f, 19.61f, 4.39f, 21.25f, 9.0f, 21.25f) horizontalLineTo(15.0f) curveTo(19.61f, 21.25f, 21.25f, 19.61f, 21.25f, 15.0f) verticalLineTo(9.0f) curveTo(21.25f, 4.39f, 19.61f, 2.75f, 15.0f, 2.75f) horizontalLineTo(9.0f) close() } path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(10.7397f, 16.2802f) curveTo(10.5497f, 16.2802f, 10.3597f, 16.2102f, 10.2097f, 16.0602f) curveTo(9.9197f, 15.7702f, 9.9197f, 15.2902f, 10.2097f, 15.0002f) lineTo(13.2097f, 12.0002f) lineTo(10.2097f, 9.0002f) curveTo(9.9197f, 8.7102f, 9.9197f, 8.2302f, 10.2097f, 7.9402f) curveTo(10.4997f, 7.6502f, 10.9797f, 7.6502f, 11.2697f, 7.9402f) lineTo(14.7997f, 11.4702f) curveTo(15.0897f, 11.7602f, 15.0897f, 12.2402f, 14.7997f, 12.5302f) lineTo(11.2697f, 16.0602f) curveTo(11.1197f, 16.2102f, 10.9297f, 16.2802f, 10.7397f, 16.2802f) close() } } .build() return _arrowright!! } private var _arrowright: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
3,346
VuesaxIcons
MIT License
app/src/androidTest/java/com/guru/cocktails/di/component/ApplicationMockComponent.kt
morristech
143,734,527
false
null
package com.guru.cocktails.di.component import com.guru.cocktails.di.module.ApplicationMockModule import com.guru.cocktails.di.module.InteractorMockModule import dagger.Component import javax.inject.Singleton @Singleton @Component( modules = arrayOf( ApplicationMockModule::class, InteractorMockModule::class ) ) interface ApplicationMockComponent : ApplicationComponent { }
0
Kotlin
0
0
f3feac05ebb51a7a30c2d37ccf76f4269da92f07
401
client-android
MIT License
feature/main/src/main/java/kr/pe/ssun/template/feature/main/search/SearchPagingDataAdapter.kt
SunChulBaek
799,219,689
false
{"Kotlin": 62209}
package kr.pe.ssun.template.feature.main.search import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.findViewTreeLifecycleOwner import androidx.lifecycle.lifecycleScope import androidx.paging.PagingDataAdapter import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.RecyclerView import kotlinx.coroutines.launch import kr.pe.ssun.template.core.event.OpenImageViewEvent import kr.pe.ssun.template.core.event.SetBookmarkEvent import kr.pe.ssun.template.core.model.SearchItem import kr.pe.ssun.template.core.util.EventBus import kr.pe.ssun.template.feature.main.databinding.ItemSearchPageBinding import kr.pe.ssun.template.feature.main.databinding.ItemSearchResultBinding import java.util.Date class SearchPagingDataAdapter : PagingDataAdapter<SearchItem, SearchViewHolder>(diffCallback) { companion object { const val VIEW_TYPE_RESULT = 0 const val VIEW_TYPE_PAGE = 1 val diffCallback = object : DiffUtil.ItemCallback<SearchItem>() { override fun areItemsTheSame(oldItem: SearchItem, newItem: SearchItem): Boolean { return oldItem == newItem } override fun areContentsTheSame(oldItem: SearchItem, newItem: SearchItem): Boolean = when { oldItem is SearchItem.SearchResult && newItem is SearchItem.SearchResult -> { oldItem.content == newItem.content && oldItem.bookmarked == newItem.bookmarked } else -> false } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchViewHolder = when (viewType) { VIEW_TYPE_RESULT -> SearchViewHolder.SearchResultViewHolder( ItemSearchResultBinding.inflate(LayoutInflater.from(parent.context), parent, false) ) VIEW_TYPE_PAGE -> SearchViewHolder.SearchPageViewHolder( ItemSearchPageBinding.inflate(LayoutInflater.from(parent.context), parent, false) ) else -> TODO() } override fun onBindViewHolder(holder: SearchViewHolder, position: Int) { holder.bind(position, getItem(position)) } override fun getItemViewType(position: Int): Int = when (getItem(position)) { is SearchItem.SearchResult -> VIEW_TYPE_RESULT is SearchItem.SearchPage -> VIEW_TYPE_PAGE else -> -1 } } sealed class SearchViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { abstract fun bind(position: Int, item: SearchItem?): Unit? class SearchResultViewHolder( private val binding: ItemSearchResultBinding ) : SearchViewHolder(binding.root) { override fun bind(position: Int, item: SearchItem?) = (item as? SearchItem.SearchResult)?.let { binding.item = item binding.onClickListener = View.OnClickListener { binding.root.findViewTreeLifecycleOwner()?.lifecycleScope?.launch { EventBus.publish(OpenImageViewEvent(item.isImage, item.title, item.thumbnail, item.datetime.time)) } } binding.onClickBookmark = View.OnClickListener { binding.root.findViewTreeLifecycleOwner()?.lifecycleScope?.launch { EventBus.publish(SetBookmarkEvent( imageUrl = item.thumbnail, isImage = item.isImage, title = item.title, datetime = item.datetime.time, savetime = Date().time, target = !item.bookmarked )) } } binding.thumbnail.clipToOutline = true } } class SearchPageViewHolder( private val binding: ItemSearchPageBinding ) : SearchViewHolder(binding.root) { override fun bind(position: Int, item: SearchItem?) = (item as? SearchItem.SearchPage)?.let { binding.page = it.page binding.executePendingBindings() } } }
0
Kotlin
0
0
3876154aad7a585bbab08f6e420cdb8d478a806f
4,060
KakaoBank
Apache License 2.0
api/src/main/java/dev/doubledot/doki/api/remote/DokiApiService.kt
doubledotlabs
174,850,580
false
null
package dev.doubledot.doki.api.remote import dev.doubledot.doki.api.extensions.DONT_KILL_MY_APP_BASE_ENDPOINT import dev.doubledot.doki.api.models.DokiManufacturer import io.reactivex.Observable import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import retrofit2.http.GET import retrofit2.http.Path interface DokiApiService { @GET("{manufacturer}.json") fun getManufacturer(@Path("manufacturer") manufacturer : String) : Observable<DokiManufacturer> companion object { fun create() : DokiApiService { val retrofit = Retrofit.Builder() .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(DONT_KILL_MY_APP_BASE_ENDPOINT) .build() return retrofit.create(DokiApiService::class.java) } } }
11
null
15
161
4bed979c7db295af263f0f97f75d0d3a429513ff
965
doki
MIT License
Framework/src/main/kotlin/net/milosvasic/factory/security/Permissions.kt
Server-Factory
326,063,014
true
{"Kotlin": 470923, "Shell": 188}
package net.milosvasic.factory.security import net.milosvasic.factory.common.obtain.Obtain data class Permissions( var user: Permission, var group: Permission, var others: Permission ) : Obtain<String> { @Throws(IllegalArgumentException::class) override fun obtain(): String { val validator = PermissionsValidator() if (validator.validate(user, group, others)) { return "${user.value}${group.value}${others.value}" } return "000" } }
0
Kotlin
0
1
7c9a48ac22541c01d56cb7ed404348f9dbcf6d6d
517
Core-Framework
Apache License 2.0
src/main/kotlin/algorithms/DeBruijnGraphFromKmers.kt
jimandreas
377,843,697
false
null
@file:Suppress("unused") package algorithms /** * from a [d] list of kmer strings, * produce a map of kmer to kmer connections * * Example: val input = listOf( "GAGG", "CAGG", "GGGG", "GGGA", "CAGG", "AGGG", "GGAG" ) output: (as a map of string to list of strings) AGG -> GGG CAG -> AGG,AGG GAG -> AGG GGA -> GAG GGG -> GGG,GGA */ fun deBruijnGraphFromKmers(d: List<String>): Map<String, List<String>> { val strLen = d[0].length val resultMap: MutableMap<String, MutableList<String>> = mutableMapOf() for (s in d) { val prefix = s.substring(0, strLen - 1) val suffix = s.substring(1, strLen) if (resultMap.containsKey(prefix)) { val list = resultMap[prefix] list!!.add(suffix) } else { resultMap.putIfAbsent(prefix, mutableListOf(suffix)) } } return (resultMap.toSortedMap()) } /** * for a [input] map of kmer to kmer list, iterate over the * list and output a string with the representation. */ fun deBruijnDirectedGraphConversion(input: Map<String, List<String>>): String { val buf = StringBuilder() for (entry in input) { buf.append("${entry.key} -> ") val theList = entry.value buf.append(theList.joinToString(separator = ",")) buf.append("\n") } return buf.toString() } /** * for a [s] string of kmers (e.g. text from a problem description - * return a list of parsed lines. * Assumptions: the string is a trimmed list of just kmers - no whitespace */ fun parseKmerString(s: String): List<String> { val reader = s.reader() val lines = reader.readLines() val stringList: MutableList<String> = mutableListOf() for (line in lines) { stringList.add(line) } return stringList }
0
Kotlin
0
0
fa92b10ceca125dbe47e8961fa50242d33b2bb34
1,780
stepikBioinformaticsCourse
Apache License 2.0
notifications/src/test/java/io/karte/android/notifications/integration/TokenEventTest.kt
plaidev
208,185,127
false
null
// // Copyright 2020 PLAID, 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // package io.karte.android.notifications.integration import com.google.common.truth.Truth import io.karte.android.KarteApp import io.karte.android.TrackerTestCase import io.karte.android.assertThatNoEventOccured import io.karte.android.notifications.internal.TokenRegistrar import io.karte.android.notifications.manager import io.karte.android.notifications.registerFCMToken import io.karte.android.notifications.setPermission import io.karte.android.parseBody import io.karte.android.proceedBufferedCall import okhttp3.mockwebserver.MockResponse import org.json.JSONObject import org.junit.Test import org.junit.experimental.runners.Enclosed import org.junit.runner.RunWith import kotlin.test.assertNotNull private fun TrackerTestCase.enqueue() { server.enqueue( MockResponse().setBody(body.toString()) .addHeader("Content-Type", "text/html; charset=utf-8") ) } private fun TrackerTestCase.tokenEvent(): JSONObject { return JSONObject(server.takeRequest().parseBody()).getJSONArray("events").getJSONObject(0) } @Suppress("NonAsciiCharacters") @RunWith(Enclosed::class) class TokenEventTest { @RunWith(Enclosed::class) class FCMトークンの取得に成功した場合 { class 通知が許可されている場合 : TrackerTestCase() { @Test fun plugin_native_app_identifyイベントがサーバに送信されること() { enqueue() manager.setPermission(true) KarteApp.registerFCMToken("dummy_fcm_token") proceedBufferedCall() val event = tokenEvent() assertNotNull(event, "plugin_native_app_identifyがtrackサーバに送信されること") val eventValues = event.getJSONObject("values") Truth.assertWithMessage("FCMトークンがfcm_tokenパラメータとしてtrackサーバに送信されること") .that(eventValues.getString("fcm_token")) .isEqualTo("dummy_fcm_token") Truth.assertWithMessage("通知の可否がsubscribeパラメータとしてtrackサーバに送信されること") .that(eventValues.getString("subscribe")) .isEqualTo("true") } } class 通知が許可されていない場合 : TrackerTestCase() { @Test fun plugin_native_app_identifyイベントがサーバに送信されること() { enqueue() manager.setPermission(false) KarteApp.registerFCMToken("dummy_fcm_token") proceedBufferedCall() val event = tokenEvent() assertNotNull(event, "plugin_native_app_identifyがtrackサーバに送信されること") val eventValues = event.getJSONObject("values") Truth.assertWithMessage("FCMトークンがfcm_tokenパラメータとしてtrackサーバに送信されること") .that(eventValues.getString("fcm_token")) .isEqualTo("dummy_fcm_token") Truth.assertWithMessage("通知の可否がsubscribeパラメータとしてtrackサーバに送信されること") .that(eventValues.getString("subscribe")) .isEqualTo("false") } } } class FCMトークンの取得に失敗した場合 : TrackerTestCase() { @Test fun FCMトークンがサーバに送信されないこと() { TokenRegistrar(application).registerFCMToken(null) proceedBufferedCall() server.assertThatNoEventOccured() } } }
1
Kotlin
4
2
649b5eda74c47c6d8209a37cef5f6a2a9bef176b
3,854
karte-android-sdk
Apache License 2.0