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
composeApp/src/commonMain/kotlin/io/shortway/kobankat/sample/SimpleLogHandler.kt
JayShortway
758,647,648
false
{"Kotlin": 225838, "Ruby": 2360, "Swift": 594}
package io.shortway.kobankat.sample import io.shortway.kobankat.LogHandler class SimpleLogHandler( private val log: (message: String) -> Unit ) : LogHandler { override fun v(tag: String, msg: String) = log(tag, msg) override fun d(tag: String, msg: String) = log(tag, msg) override fun i(tag: String, msg: String) = log(tag, msg) override fun w(tag: String, msg: String) = log(tag, msg) override fun e(tag: String, msg: String, throwable: Throwable?) = log(tag, msg) private fun log(tag: String, msg: String) = log("[$tag] $msg") }
8
Kotlin
3
9
f374c234be5b1fc5da36dbf0ddcfe0398d871cf5
576
kobankat
MIT License
imitate/src/main/java/com/engineer/imitate/KotlinRootActivity.kt
REBOOTERS
65,188,539
false
null
package com.engineer.imitate import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.annotation.SuppressLint import android.content.Intent import android.content.res.Configuration import android.net.Uri import android.os.Build import android.os.Bundle import android.os.Environment import android.text.TextUtils import android.util.Log import android.view.Gravity import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.PopupMenu import android.widget.TextView import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.metrics.performance.JankStats import androidx.metrics.performance.PerformanceMetricsState import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.alibaba.android.arouter.facade.annotation.Route import com.alibaba.android.arouter.launcher.ARouter import com.engineer.imitate.databinding.ActivityKotlinRootBinding import com.engineer.imitate.model.FragmentItem import com.engineer.imitate.ui.activity.ReverseGifActivity import com.engineer.imitate.util.* import com.example.cpp_native.app.NativeRoot import com.gyf.immersionbar.ImmersionBar import com.scwang.smart.refresh.footer.ClassicsFooter import com.scwang.smart.refresh.header.BezierRadarHeader import com.scwang.smart.refresh.header.ClassicsHeader import com.scwang.smart.refresh.header.FalsifyHeader import com.scwang.smart.refresh.header.MaterialHeader import com.scwang.smart.refresh.layout.api.RefreshHeader import com.skydoves.transformationlayout.onTransformationStartContainer import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import org.apache.commons.io.FileUtils import org.json.JSONArray import org.json.JSONObject import java.io.File import java.util.concurrent.TimeUnit @Route(path = Routes.INDEX) @SuppressLint("LogNotTimber") class KotlinRootActivity : AppCompatActivity() { private val TAG = KotlinRootActivity::class.java.simpleName private val ORIGINAL_URL = "file:///android_asset/index.html" private lateinit var hybridHelper: HybridHelper private var currentFragment: Fragment? = null private lateinit var mLinearManager: LinearLayoutManager private lateinit var mGridLayoutManager: GridLayoutManager private lateinit var mLayoutManager: RecyclerView.LayoutManager private var adapter: FastListAdapter<FragmentItem>? = null private lateinit var viewBinding: ActivityKotlinRootBinding private lateinit var jankStatus: JankStats override fun onCreate(savedInstanceState: Bundle?) { onTransformationStartContainer() super.onCreate(savedInstanceState) ImmersionBar.with(this).fitsSystemWindows(true).statusBarColor(R.color.colorPrimary).init() viewBinding = ActivityKotlinRootBinding.inflate(layoutInflater) setContentView(viewBinding.root) setSupportActionBar(viewBinding.toolbar) loadView() jsonTest() // autoStartPage() NativeRoot.init() NativeRoot.test() val patchViewModel = ViewModelProvider(this)[PatchViewModel::class.java] patchViewModel.copyFile() jankStatus = JankStats.createAndTrack(window) { if (it.isJank) { Log.i("${TAG}_Jank", "frameData $it") } } jankStatus.jankHeuristicMultiplier = 3f val state = PerformanceMetricsState.getHolderForHierarchy(viewBinding.root) state.state?.putState("Activity_Name", this::class.java.simpleName) } override fun onResume() { super.onResume() jankStatus.isTrackingEnabled = true } override fun onPause() { super.onPause() jankStatus.isTrackingEnabled = false } private fun autoStartPage() { val fragment: Fragment = ARouter.getInstance().build("/anim/fresco").navigation(this) as Fragment currentFragment = fragment viewBinding.contentKotlinRoot.content.visibility = View.VISIBLE viewBinding.contentKotlinRoot.index.visibility = View.GONE val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.content, fragment).commit() } private fun loadView() { mLinearManager = LinearLayoutManager(this) mGridLayoutManager = GridLayoutManager(this, 2) mLayoutManager = mLinearManager // if (isNetworkConnected()) { // loadWebView() // } else { // } loadRecyclerView() // loadWebView() viewBinding.gif.setOnClickListener { // startActivity(Intent(this, ReverseGifActivity::class.java)) val bundle = viewBinding.transformationLayout.withView( viewBinding.transformationLayout, "myTransitionName" ) val intent = Intent(this, ReverseGifActivity::class.java) intent.putExtra( "TransformationParams", viewBinding.transformationLayout.getParcelableParams() ) startActivity(intent, bundle) } } // <editor-fold defaultstate="collapsed" desc="拷贝一些文件到特定目录,不是每个手机都需要"> /** * 拷贝一些文件到特定目录,不是每个手机都需要 */ private fun personalCopy() { val path = filesDir.absolutePath + "/gif/" val fileDir = File(path) val files = fileDir.listFiles() files?.apply { if (fileDir.exists()) { val destDir = Environment.getExternalStorageDirectory() for (file in this) { Log.e(TAG, ": " + file.absolutePath) Observable.just("").subscribeOn(Schedulers.io()).subscribe { FileUtils.copyFileToDirectory(file, destDir) } } } } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="init fragments"> private fun initList(): MutableList<FragmentItem> { return mutableListOf( FragmentItem("/anim/entrance", "entrance"), FragmentItem("/anim/dependency_injection", "dependency_injection"), FragmentItem("/anim/rx_play", "rx_play"), FragmentItem("/anim/motion_layout", "motion_layout"), FragmentItem("/anim/github", "github features"), FragmentItem("/anim/circleLoading", "circle-loading"), FragmentItem("/anim/coroutines", "coroutines"), FragmentItem("/anim/recycler_view", "RecyclerView"), FragmentItem("/anim/slide", "slide"), FragmentItem("/anim/drawable_example", "drawable_example"), FragmentItem("/anim/elevation", "elevation"), FragmentItem("/anim/fresco", "fresco"), FragmentItem("/anim/constraint", "constraint animation"), FragmentItem("/anim/scroller", "scroller"), FragmentItem("/anim/vh_fragment", "vh_fragment"), FragmentItem("/anim/parallax", "parallax") ) } // </editor-fold> private fun loadRecyclerView() { viewBinding.contentKotlinRoot.hybrid.animate().alpha(0f) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) viewBinding.contentKotlinRoot.hybrid.visibility = View.GONE viewBinding.contentKotlinRoot.smartRefreshLayout.visibility = View.VISIBLE } }).start() val list = initList() adapter = viewBinding.contentKotlinRoot.recyclerView.bind( list, R.layout.view_item ) { item: FragmentItem, _: Int -> val desc = findViewById<TextView>(R.id.desc) val path = findViewById<TextView>(R.id.path) val more_menu = findViewById<ImageView>(R.id.more_menu) val shell = findViewById<ViewGroup>(R.id.shell) desc.text = item.name path.text = item.path path.setOnClickListener { AnimDelegate.apply(context, path, viewBinding.gif, viewBinding.shellRoot) } more_menu.setOnClickListener { showMenu(more_menu) } shell.setOnClickListener { viewBinding.gif.hide() val fragment: Fragment = ARouter.getInstance().build(item.path).navigation(context) as Fragment currentFragment = fragment viewBinding.contentKotlinRoot.content.visibility = View.VISIBLE viewBinding.contentKotlinRoot.index.visibility = View.GONE val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.content, fragment).commit() updateState() } }.layoutManager(mLayoutManager) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { viewBinding.contentKotlinRoot.recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() { override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) { super.onScrolled(recyclerView, dx, dy) Log.e(TAG, "dy==$dy") Log.e(TAG, "是否可以 scroll up==${recyclerView.canScrollVertically(-1)}") Log.e(TAG, "是否可以 scroll down==${recyclerView.canScrollVertically(1)}") } }) } val heads = arrayListOf<RefreshHeader>( ClassicsHeader(this), BezierRadarHeader(this), FalsifyHeader(this), MaterialHeader(this) ) viewBinding.contentKotlinRoot.smartRefreshLayout.autoRefresh() viewBinding.contentKotlinRoot.smartRefreshLayout.setRefreshHeader(heads.random()) viewBinding.contentKotlinRoot.smartRefreshLayout.setRefreshFooter(ClassicsFooter(this)) viewBinding.contentKotlinRoot.smartRefreshLayout.setOnRefreshListener { viewBinding.contentKotlinRoot.smartRefreshLayout.finishRefresh(2000) } } private fun showMenu(view: View) { val popupMenu = PopupMenu(this, view, Gravity.END) popupMenu.menuInflater.inflate(R.menu.index_setting_menu, popupMenu.menu) popupMenu.show() } @SuppressLint("SetJavaScriptEnabled") private fun loadWebView() { viewBinding.contentKotlinRoot.hybrid.animate().alpha(1f) .setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { super.onAnimationEnd(animation) viewBinding.contentKotlinRoot.hybrid.visibility = View.VISIBLE viewBinding.contentKotlinRoot.smartRefreshLayout.visibility = View.GONE } }).start() viewBinding.contentKotlinRoot.hybrid.settings.javaScriptEnabled = true viewBinding.contentKotlinRoot.hybrid.settings.allowFileAccess = true hybridHelper = HybridHelper(this) hybridHelper.setOnItemClickListener(SimpleClickListener()) viewBinding.contentKotlinRoot.hybrid.addJavascriptInterface(hybridHelper, "hybrid") viewBinding.contentKotlinRoot.hybrid.loadUrl(ORIGINAL_URL) } private inner class SimpleClickListener : HybridHelper.OnItemClickListener { override fun reload() { runOnUiThread { loadRecyclerView() } } @SuppressLint("RestrictedApi") override fun onClick(fragment: Fragment, title: String) { runOnUiThread { if (!TextUtils.isEmpty(title)) { setTitle(title) } viewBinding.contentKotlinRoot.content.visibility = View.VISIBLE viewBinding.contentKotlinRoot.index.visibility = View.GONE viewBinding.gif.hide() currentFragment = fragment val transaction = supportFragmentManager.beginTransaction() transaction.replace(R.id.content, fragment).commit() } } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_kotlin_root, menu) return true } private fun isNightMode(): Boolean { val flag = resources.configuration.uiMode and Configuration.UI_MODE_NIGHT_MASK return flag == Configuration.UI_MODE_NIGHT_YES } override fun onPrepareOptionsMenu(menu: Menu?): Boolean { val item = menu?.findItem(R.id.theme_switch) if (isNightMode()) { item?.setIcon(R.drawable.ic_brightness_low_white_24dp) item?.title = "日间模式" } else { item?.setIcon(R.drawable.ic_brightness_high_white_24dp) item?.title = "夜间模式" } val change = menu?.findItem(R.id.action_change) val refresh = menu?.findItem(R.id.refresh) change?.isVisible = (viewBinding.contentKotlinRoot.smartRefreshLayout.visibility == View.VISIBLE) refresh?.isVisible = (viewBinding.contentKotlinRoot.smartRefreshLayout.visibility == View.VISIBLE) return super.onPrepareOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (item.itemId == android.R.id.home) { if (viewBinding.contentKotlinRoot.content.visibility == View.VISIBLE) { releaseFragment() } else { finish() } } else if (item.itemId == R.id.action_switch_view) { if (viewBinding.contentKotlinRoot.smartRefreshLayout.visibility == View.VISIBLE) { loadWebView() } else { loadRecyclerView() } return true } else if (item.itemId == R.id.action_change) { if (viewBinding.contentKotlinRoot.smartRefreshLayout.visibility == View.VISIBLE) { if (viewBinding.contentKotlinRoot.recyclerView.layoutManager == mLinearManager) { mLayoutManager = mGridLayoutManager } else { mLayoutManager = mLinearManager } adapter?.layoutManager(mLayoutManager)?.notifyDataSetChanged() return true } } else if (item.itemId == R.id.theme_switch) { if (isNightMode()) { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) SpUtil(this).saveBool(SpUtil.KEY_THEME_NIGHT_ON, false) } else { AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) SpUtil(this).saveBool(SpUtil.KEY_THEME_NIGHT_ON, true) } // recreate() } else if (item.itemId == R.id.refresh) { if (viewBinding.contentKotlinRoot.recyclerView.visibility == View.VISIBLE) { viewBinding.contentKotlinRoot.smartRefreshLayout.autoRefresh() } } return super.onOptionsItemSelected(item) } override fun onBackPressed() { if (viewBinding.contentKotlinRoot.content.visibility == View.VISIBLE) { releaseFragment() } else { super.onBackPressed() } } private fun releaseFragment() { viewBinding.contentKotlinRoot.content.visibility = View.GONE viewBinding.contentKotlinRoot.index.visibility = View.VISIBLE viewBinding.gif.show() Log.e(TAG, "fragments size = " + supportFragmentManager.fragments.size) currentFragment?.let { if (supportFragmentManager.fragments.size > 0) { supportFragmentManager.beginTransaction().remove(it).commitAllowingStateLoss() currentFragment = null updateState() } } } private fun updateState() { Observable.just(1).delay(1, TimeUnit.SECONDS).observeOn(AndroidSchedulers.mainThread()) .doOnNext { Log.e(TAG, "updateState: ======================================================\n") Log.e(TAG, "fragments size = " + supportFragmentManager.fragments.size) supportFragmentManager.fragments.forEach { Log.e( TAG, "fragment [ ${it.javaClass.name} ] in activity [ ${it.activity?.javaClass?.simpleName} ]" ) } Log.e(TAG, "updateState: ======================================================\n") }.subscribe() } private fun jsonTest() { val uri = "https://www.zhihu.com/search?q=%E5%88%A9%E7%89%A9%E6%B5%A6&type=content" val parseUri = Uri.parse(uri) Log.e(TAG, "type : " + parseUri::class.java.canonicalName) Log.e(TAG, "query: ${parseUri.query}") Log.e(TAG, "isOpaque: ${parseUri.isOpaque}") val jsonArray = JSONArray() for (i in 0..3) { val jsonObj = JSONObject() jsonObj.put("name", "name_$i") jsonArray.put(jsonObj) } Log.e(TAG, "result ==$jsonArray") } override fun onDestroy() { super.onDestroy() viewBinding.contentKotlinRoot.hybrid.removeJavascriptInterface("hybrid") } }
4
null
352
1,880
278998c8da1da2b47778dba3dbd3f2de1e12f2ed
17,644
AndroidAnimationExercise
Apache License 2.0
libraries/tools/kotlin-gradle-compiler-types/src/generated/kotlin/org/jetbrains/kotlin/gradle/dsl/JsDiagnosticMode.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// DO NOT EDIT MANUALLY! // Generated by org/jetbrains/kotlin/generators/arguments/GenerateGradleOptions.kt // To regenerate run 'generateGradleOptions' task @file:Suppress("RemoveRedundantQualifierName", "Deprecation", "DuplicatedCode") package org.jetbrains.kotlin.gradle.dsl enum class JsDiagnosticMode(val mode: String) { RUNTIME_DIAGNOSTIC_EXCEPTION("exception"), RUNTIME_DIAGNOSTIC_LOG("log"), ; companion object { @JvmStatic fun fromMode(mode: String): JsDiagnosticMode = JsDiagnosticMode.values().firstOrNull { it.mode == mode } ?: throw IllegalArgumentException("Unknown JS diagnostic mode: $mode") } }
181
Kotlin
5771
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
679
kotlin
Apache License 2.0
QuickRecyclerView/src/main/java/com/wpf/app/quickrecyclerview/data/QuickClickData.kt
walgr
487,438,913
false
null
package com.wpf.app.quickrecyclerview.data import android.view.View import android.view.ViewGroup import com.wpf.app.quick.annotations.bind.BindData2View import com.wpf.app.quickbind.helper.binddatahelper.ItemClick import com.wpf.app.quickutil.run.RunOnContextWithSelf import com.wpf.app.quickutil.run.itemClick import java.io.Serializable /** * 监听了点击的Item */ abstract class QuickClickData @JvmOverloads constructor( layoutId: Int = 0, layoutViewCreate: RunOnContextWithSelf<ViewGroup, View>? = null, autoSet: Boolean = false, //自动映射 isSuspension: Boolean = false, ) : QuickBindData( layoutId = layoutId, layoutViewCreate = layoutViewCreate, autoSet = autoSet, isSuspension = isSuspension ), Serializable { @Transient @BindData2View(helper = ItemClick::class) var itemClick = itemClick { onClick(it) } abstract fun onClick(view: View) }
0
null
3
29
6b4da7f07e347ca6d4fbaa7a555ebcedde1494d6
914
Quick
MIT License
mobile/src/main/java/be/mygod/vpnhotspot/room/Converters.kt
zacharee
424,610,602
false
null
package hanson.xyz.vpnhotspotmod.room import android.net.MacAddress import android.text.TextUtils import androidx.room.TypeConverter import be.mygod.librootkotlinx.useParcel import hanson.xyz.vpnhotspotmod.net.MacAddressCompat import hanson.xyz.vpnhotspotmod.net.MacAddressCompat.Companion.toLong import timber.log.Timber import java.net.InetAddress object Converters { @JvmStatic @TypeConverter fun persistCharSequence(cs: CharSequence) = useParcel { p -> TextUtils.writeToParcel(cs, p, 0) p.marshall() } @JvmStatic @TypeConverter fun unpersistCharSequence(data: ByteArray) = useParcel { p -> p.unmarshall(data, 0, data.size) p.setDataPosition(0) try { TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(p)!! } catch (e: RuntimeException) { Timber.w(e) "" } } @JvmStatic @TypeConverter fun persistMacAddress(address: MacAddress) = address.toLong() @JvmStatic @TypeConverter fun unpersistMacAddress(address: Long) = MacAddressCompat(address).toPlatform() @JvmStatic @TypeConverter fun persistInetAddress(address: InetAddress): ByteArray = address.address @JvmStatic @TypeConverter fun unpersistInetAddress(data: ByteArray): InetAddress = InetAddress.getByAddress(data) }
13
null
368
9
09ae37f5bc5eecab978d4fffab1a1886b00a23d5
1,348
VPNHotspot
Apache License 2.0
app/src/main/java/com/therouter/app/serviceprovider/IKotlinServiceProvider.kt
HuolalaTech
530,172,359
false
{"Kotlin": 212660, "Java": 110402, "Groovy": 75228, "QMake": 68}
package com.therouter.app.serviceprovider import android.content.Context import android.widget.Toast import com.therouter.inject.ServiceProvider @ServiceProvider(returnType = IKotlinSerivce::class, params = [Context::class, String::class]) fun create(context: Context, str: String): IKotlinSerivce = object : IKotlinSerivce { override fun hello() { Toast.makeText(context, str, Toast.LENGTH_SHORT).show() } }
6
Kotlin
122
994
74c000d6b582fee4eb78b8987e488a2315693aeb
426
hll-wp-therouter-android
Apache License 2.0
app/src/main/java/com/simbiri/equityjamii/ui/main_activity/news_page/official_coms/OfficialFragment.kt
SimbaSimbiri
706,250,529
false
{"Kotlin": 145092}
package com.simbiri.equityjamii.ui.main_activity.news_page.official_coms import androidx.lifecycle.ViewModelProvider import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.simbiri.equityjamii.R import com.simbiri.equityjamii.adapters.OfficialAdapter import com.simbiri.equityjamii.data.model.OfficialNewsTexts class OfficialFragment : Fragment() { companion object { fun newInstance() = OfficialFragment() } private lateinit var viewModel: OfficialViewModel private lateinit var recylerViewOfficial : RecyclerView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.news_page_official, container, false) recylerViewOfficial = view.findViewById(R.id.officialRecycler) setUpRecyclerOfficial(view) return view } private fun setUpRecyclerOfficial(view: View?) { val context = requireContext() val officialAdapter = OfficialAdapter(context, OfficialNewsTexts.officialNewsList!!) val layoutManager = LinearLayoutManager(context) layoutManager.orientation = RecyclerView.VERTICAL recylerViewOfficial.adapter = officialAdapter recylerViewOfficial.layoutManager = layoutManager recylerViewOfficial.hasFixedSize() } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) viewModel = ViewModelProvider(this).get(OfficialViewModel::class.java) // TODO: Use the ViewModel } }
0
Kotlin
0
0
e98c23ed36802f4dd997581e824d39d8f53b3b83
1,823
EquiJamii
Apache License 2.0
domain/src/main/java/com/mreigar/domain/model/EmailEmoji.kt
mreigosa
256,570,565
false
null
package com.mreigar.domain.model data class EmailEmoji( val email: EmailPattern, val emojis: String )
1
Kotlin
0
1
d9b9433d084d791bc8bfe2bee91704d60b0c626e
110
post-app-kotlin
MIT License
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/CloudDown.kt
walter-juan
868,046,028
false
null
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.CloudDown: ImageVector get() { if (_cloudDown != null) { return _cloudDown!! } _cloudDown = Builder(name = "CloudDown", 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(12.0f, 18.004f) horizontalLineToRelative(-5.343f) curveToRelative(-2.572f, -0.004f, -4.657f, -2.011f, -4.657f, -4.487f) curveToRelative(0.0f, -2.475f, 2.085f, -4.482f, 4.657f, -4.482f) curveToRelative(0.393f, -1.762f, 1.794f, -3.2f, 3.675f, -3.773f) curveToRelative(1.88f, -0.572f, 3.956f, -0.193f, 5.444f, 1.0f) curveToRelative(1.488f, 1.19f, 2.162f, 3.007f, 1.77f, 4.769f) horizontalLineToRelative(0.99f) curveToRelative(1.38f, 0.0f, 2.573f, 0.813f, 3.13f, 1.99f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.0f, 16.0f) verticalLineToRelative(6.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(22.0f, 19.0f) lineToRelative(-3.0f, 3.0f) lineToRelative(-3.0f, -3.0f) } } .build() return _cloudDown!! } private var _cloudDown: ImageVector? = null
0
null
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,807
compose-icon-collections
MIT License
format-core/src/main/kotlin/org/d7z/objects/format/rules/StringDataFormat.kt
d7z-team
458,429,900
false
{"Kotlin": 38063, "Java": 1682}
package org.d7z.objects.format.rules import org.d7z.objects.format.CovertException import org.d7z.objects.format.api.IFormat import org.d7z.objects.format.api.IFormatContext import kotlin.reflect.KClass class StringDataFormat : IFormat { override val types = setOf(String::class, StringBuilder::class, StringBuffer::class) override fun <T : Any> format(data: T, type: KClass<out T>, context: IFormatContext): String { return when (type) { String::class, StringBuilder::class, StringBuffer::class -> data.toString() else -> throw CovertException("$type 不受支持.") } } @Suppress("UNCHECKED_CAST") override fun <T : Any> reduce(data: String, type: KClass<T>, context: IFormatContext): T { return when (type) { String::class -> data StringBuffer::class -> StringBuffer(data) StringBuilder::class -> StringBuilder(data) else -> throw CovertException("$type 不受支持.") } as T } }
0
Kotlin
0
0
5306ca92310d43be7b9d6e4cbc0ab79d3488e6e1
1,000
object-format
MIT License
2018/src/GridList/GridListMatrixExtensions.kt
Mattias1
116,139,424
false
null
package gridList operator fun GridList<Int>.plus(other: GridList<Int>): GridList<Int> { if (width != other.width || height != other.height) { throw IllegalArgumentException("GridList sizes are not equal") } return GridList(width, height) { x, y -> this[x, y] + other[x, y] } } operator fun GridList<Int>.minus(other: GridList<Int>): GridList<Int> { return GridList(width, height) { x, y -> this[x, y] - other[x, y] } } operator fun GridList<Int>.times(other: GridList<Int>): GridList<Int> { if (width != other.width || height != other.height) { throw IllegalArgumentException("GridList sizes are not equal") } return GridList(width, height) { x, y -> dotProduct(this.getRow(y), other.getColumn(x)) } } fun dotProduct(a: List<Int>, b: List<Int>): Int { if (a.count() != b.count()) { throw IllegalArgumentException("Vector counts are not equal") } return a.zip(b) .map { p -> p.first * p.second } .sum() }
0
Kotlin
0
0
6bcd889c6652681e243d493363eef1c2e57d35ef
1,000
advent-of-code
MIT License
app/spotifyapi/src/main/java/com/kpstv/spotifyapi/data/models/Search.kt
KaustubhPatange
269,351,196
false
null
package com.kpstv.spotifyapi.data.models import com.google.gson.annotations.SerializedName data class Search( val albums: Albums?, val artists: Artists?, val episodes: Episodes?, val playlists: Playlists?, val shows: Shows?, val tracks: Tracks? ) { data class Albums( val href: String, val items: List<Item>, val limit: Int, val next: String, val offset: Int, val previous: Any?, val total: Int ) { data class Item( @SerializedName("album_type") val albumType: String, val artists: List<Artist>, @SerializedName("available_markets") val availableMarkets: List<String>, @SerializedName("external_urls") val externalUrls: ExternalUrls, val href: String, val id: String, val images: List<Image>, val name: String, @SerializedName("release_date") val releaseDate: String, @SerializedName("release_date_precision") val releaseDatePrecision: String, @SerializedName("total_tracks") val totalTracks: Int, val type: String, val uri: String ) { data class Artist( @SerializedName("external_urls") val externalUrls: ExternalUrls, val href: String, val id: String, val name: String, val type: String, val uri: String ) } } data class Artists( val href: String, val items: List<Item>, val limit: Int, val next: String, val offset: Int, val previous: Any?, val total: Int ) { data class Item( @SerializedName("external_urls") val externalUrls: ExternalUrls, val followers: Followers, val genres: List<String>, val href: String, val id: String, val images: List<Image>, val name: String, val popularity: Int, val type: String, val uri: String ) } data class Episodes( val href: String, val items: List<Item>, val limit: Int, val next: String, val offset: Int, val previous: Any?, val total: Int ) { data class Item( @SerializedName("audio_preview_url") val audioPreviewUrl: String, val description: String, @SerializedName("duration_ms") val durationMs: Int, val explicit: Boolean, @SerializedName("external_urls") val externalUrls: ExternalUrls, val href: String, val id: String, val images: List<Image>, @SerializedName("is_externally_hosted") val isExternallyHosted: Boolean, @SerializedName("is_playable") val isPlayable: Boolean, val language: String, val languages: List<String>, val name: String, @SerializedName("release_date") val releaseDate: String, @SerializedName("release_date_precision") val releaseDatePrecision: String, val type: String, val uri: String ) } data class Playlists( val href: String, val items: List<Item>, val limit: Int, val next: String, val offset: Int, val previous: Any?, val total: Int ) { data class Item( val collaborative: Boolean, val description: String, @SerializedName("external_urls") val externalUrls: ExternalUrls, val href: String, val id: String, val images: List<Image>, val name: String, val owner: Owner, @SerializedName("primary_color") val primaryColor: Any?, val `public`: Any?, @SerializedName("snapshot_id") val snapshotId: String, val tracks: Tracks, val type: String, val uri: String ) { data class Owner( @SerializedName("display_name") val displayName: String, @SerializedName("external_urls") val externalUrls: ExternalUrls, val href: String, val id: String, val type: String, val uri: String ) data class Tracks( val href: String, val total: Int ) } } data class Shows( val href: String, val items: List<Item>, val limit: Int, val next: String, val offset: Int, val previous: Any?, val total: Int ) { data class Item( @SerializedName("available_markets") val availableMarkets: List<String>, val copyrights: List<Any>, val description: String, val explicit: Boolean, @SerializedName("external_urls") val externalUrls: ExternalUrls, val href: String, val id: String, val images: List<Image>, @SerializedName("is_externally_hosted") val isExternallyHosted: Boolean, val languages: List<String>, @SerializedName("media_type") val mediaType: String, val name: String, val publisher: String, val type: String, val uri: String ) } data class Tracks( val href: String, val items: List<Item>, val limit: Int, val next: String, val offset: Int, val previous: Any?, val total: Int ) { data class Item( val album: Album, val artists: List<Artist>, @SerializedName("available_markets") val availableMarkets: List<String>, @SerializedName("disc_number") val discNumber: Int, @SerializedName("duration_ms") val durationMs: Int, val explicit: Boolean, @SerializedName("external_ids") val externalIds: ExternalIds, @SerializedName("external_urls") val externalUrls: ExternalUrls, val href: String, val id: String, @SerializedName("is_local") val isLocal: Boolean, val name: String, val popularity: Int, @SerializedName("preview_url") val previewUrl: Any?, @SerializedName("track_number") val trackNumber: Int, val type: String, val uri: String ) { data class Album( @SerializedName("album_type") val albumType: String, val artists: List<Artist>, @SerializedName("available_markets") val availableMarkets: List<String>, @SerializedName("external_urls") val externalUrls: ExternalUrls, val href: String, val id: String, val images: List<Image>, val name: String, @SerializedName("release_date") val releaseDate: String, @SerializedName("release_date_precision") val releaseDatePrecision: String, @SerializedName("total_tracks") val totalTracks: Int, val type: String, val uri: String ) { data class Artist( @SerializedName("external_urls") val externalUrls: ExternalUrls, val href: String, val id: String, val name: String, val type: String, val uri: String ) } data class Artist( @SerializedName("external_urls") val externalUrls: ExternalUrls, val href: String, val id: String, val name: String, val type: String, val uri: String ) } } }
0
Kotlin
0
9
51410cfa2a8008da06689bd8c82928e4123efd13
8,505
Unofficial-Spotify-SDK
Apache License 2.0
src/main/kotlin/org/jetbrains/intellij/model/XmlExtractor.kt
JetBrains
33,932,778
false
null
package org.jetbrains.intellij.model import com.jetbrains.plugin.structure.intellij.utils.JDOMUtil import org.jetbrains.intellij.transformXml import org.jetbrains.intellij.warn import java.io.File import java.io.InputStream import javax.xml.bind.JAXBContext import javax.xml.bind.JAXBException class XmlExtractor<T>(private val context: String? = null) { private val jaxbContext by lazy { JAXBContext.newInstance("org.jetbrains.intellij.model", ObjectFactory::class.java.classLoader) } @Throws(JAXBException::class) fun unmarshal(file: File) = unmarshal(file.inputStream()) @Throws(JAXBException::class) fun unmarshal(inputStream: InputStream) = jaxbContext.createUnmarshaller().unmarshal(inputStream) as T @Throws(JAXBException::class) fun marshal(bean: T, file: File) { jaxbContext.createMarshaller().marshal(bean, file) val document = JDOMUtil.loadDocument(file.inputStream()) transformXml(document, file) } fun fetch(path: String) = runCatching { unmarshal(File(path)) }.onFailure { warn(context, "Failed to get products releases list: ${it.message}", it) }.getOrNull() }
67
null
260
1,188
b5c204b012b9484753677ce84a35c70594dd57dc
1,179
gradle-intellij-plugin
Apache License 2.0
template/shared/data/src/commonMain/kotlin/shared/data/source/encryption/korlibs/KorlibsEncryptionSource.kt
kotlitecture
790,159,970
false
{"Kotlin": 545071, "Swift": 543, "JavaScript": 313, "HTML": 234}
package shared.data.source.encryption.korlibs import shared.data.source.encryption.BasicEncryptionSource import shared.data.source.encryption.EncryptionMethod import shared.data.source.encryption.EncryptionSource /** * An implementation of the [EncryptionSource] interface using the Korlibs encryption library. * * This class uses a basic encryption source with an [AesResolver] to perform encryption * and decryption operations. */ open class KorlibsEncryptionSource : EncryptionSource { private val source = BasicEncryptionSource( AesResolver(), Pbkdf2Resolver() ) override fun encrypt(text: String, method: EncryptionMethod): String { return source.encrypt(text, method) } override fun decrypt(text: String, method: EncryptionMethod): String { return source.decrypt(text, method) } }
2
Kotlin
3
55
0ea8aa724e156259d5d5c9c8a423513c61b5156b
852
template-multiplatform-compose
MIT License
lib/src/main/java/com/kirkbushman/araw/models/enums/SubmissionsSorting.kt
KirkBushman
182,531,355
false
null
package com.kirkbushman.araw.models.enums import com.kirkbushman.araw.models.base.Sorting enum class SubmissionsSorting( override val requiresTimePeriod: Boolean = false, override val sortingStr: String ) : Sorting { HOT(sortingStr = "hot"), BEST(sortingStr = "best"), NEW(sortingStr = "new"), RISING(sortingStr = "rising"), CONTROVERSIAL(true, "controversial"), TOP(true, "top") }
9
Kotlin
9
84
aeae071fa8d2a4e378de4a71420dc2a9792591f3
419
ARAW
MIT License
src/main/kotlin/day1/Day1.kt
Wicked7000
573,552,409
false
{"Kotlin": 106288}
package day1 import Day import checkWithMessage import parserCombinators.* import parserCombinators.newLine import readInput import readInputString import runTimedPart @Suppress("unused") class Day1(): Day() { private fun parseInput(input: String): List<List<Int>> { val parseTree = parseTillEnd(sequenceOf(group(oneOrMoreTimes(sequenceOf(number(Int::class), optional(newLine())))), optional(newLine()))) val result = parseTree(BaseParser(input)) if(result.hasError){ throw Error(result.error) } return result.results as List<List<Int>> } private fun part1(input: String): Int { val elves = parseInput(input) var currentMaxCalories = Int.MIN_VALUE; for(elf in elves){ val summedVal = elf.sum() if(summedVal > currentMaxCalories){ currentMaxCalories = summedVal } } return currentMaxCalories } private fun part2(input: String): Int { val elves = parseInput(input) val currentTopThree = MutableList(3) { _: Int -> Int.MIN_VALUE } for(elf in elves){ val summedVal = elf.sum() for(topThreeIdx in currentTopThree.size-1 downTo 0){ val topAmount = currentTopThree[topThreeIdx] if(topAmount <= summedVal){ if(topThreeIdx + 1 < currentTopThree.size){ val tempVal = currentTopThree[topThreeIdx] currentTopThree[topThreeIdx] = summedVal currentTopThree[topThreeIdx+1] = tempVal } else { currentTopThree[topThreeIdx] = summedVal } } } } return currentTopThree.sum() } override fun run(){ val testInput = readInputString(1, "test") val p1Input = readInputString(1, "input") val testResult1 = part1(testInput) checkWithMessage(testResult1, 24000) runTimedPart(1, { part1(it) }, p1Input) val testResult2 = part2(testInput) checkWithMessage(testResult2,45000) runTimedPart(2, { part2(it) }, p1Input) } }
0
Kotlin
0
0
7919a8ad105f3b9b3a9fed048915b662d3cf482d
2,218
aoc-2022
Apache License 2.0
app/src/main/java/com/example/notes/notes/NewNoteFragment.kt
abdo-essam
692,581,410
false
{"Kotlin": 23278}
package com.example.notes.notes import ConvertToDate import android.annotation.SuppressLint import android.app.Activity import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.inputmethod.InputMethodManager import android.widget.Toast import androidx.activity.OnBackPressedCallback import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.lifecycleScope import androidx.navigation.findNavController import androidx.navigation.fragment.findNavController import com.example.notes.NotesViewModel import com.example.notes.R import com.example.notes.database.Note import com.example.notes.databinding.FragmentNewNoteBinding import kotlinx.coroutines.launch import java.util.* class NewNoteFragment : Fragment() { private var _binding: FragmentNewNoteBinding? = null private val binding get() = _binding!! private lateinit var mUserEmail: String private lateinit var preferences: SharedPreferences private lateinit var notesViewModel: NotesViewModel private lateinit var mView: View private lateinit var mOldNote: Note override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate the layout for this fragment _binding = FragmentNewNoteBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) mView = view init() } @SuppressLint("SuspiciousIndentation") private fun init() { preferences = context?.getSharedPreferences("com.example.notes", Context.MODE_PRIVATE)!! mUserEmail = preferences.getString("email", "none").toString() notesViewModel = ViewModelProvider(this).get(NotesViewModel::class.java) binding.noteTime.text = ConvertToDate().convertTimeStampToDate(System.currentTimeMillis()) val toEdit: Boolean = arguments!!.getBoolean("edit") if (toEdit) { mOldNote = (arguments?.getSerializable("note") as Note?)!! binding.noteTitle.setText(mOldNote.title) binding.noteContent.setText(mOldNote.note_content) binding.noteTime.text = mOldNote.date binding.saveNoteBtn.text = "Update" binding.deleteNoteBtn.visibility = View.VISIBLE binding.deleteNoteBtn.setOnClickListener { notesViewModel.let { viewModel -> lifecycleScope.launch { viewModel.deleteNote(mOldNote) } } Toast.makeText(context, "Note is Deleted", Toast.LENGTH_SHORT).show() findNavController().navigate(R.id.action_newNoteFragment_to_notesFragment) } } binding.saveNoteBtn.setOnClickListener { if (checkIfEmpty()) { if (toEdit) { mOldNote.title = binding.noteTitle.text.toString() mOldNote.note_content = binding.noteContent.text.toString() mOldNote.date = ConvertToDate().convertTimeStampToDate(System.currentTimeMillis()) lifecycleScope.launch { notesViewModel.updateNote(mOldNote) } Toast.makeText(context, "Note is Updated", Toast.LENGTH_SHORT).show() goToNotesFragment() } else { val newNote = Note( title = binding.noteTitle.text.toString(), note_content = binding.noteContent.text.toString(), date = ConvertToDate().convertTimeStampToDate(System.currentTimeMillis()), card_color = getRandomColor(), email = mUserEmail ) lifecycleScope.launch { notesViewModel.insertNote(newNote) } Toast.makeText(context, "Note is Added", Toast.LENGTH_SHORT).show() mView.findNavController().popBackStack() hideSoftKeyboard() } } } val callback: OnBackPressedCallback = object : OnBackPressedCallback(true) { override fun handleOnBackPressed() { goToNotesFragment() } } requireActivity().onBackPressedDispatcher.addCallback(requireActivity(), callback) binding.backBtn.setOnClickListener { goToNotesFragment() } } private fun hideSoftKeyboard() { val imm: InputMethodManager = context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view?.windowToken, 0) } private fun checkIfEmpty(): Boolean { return if (binding.noteTitle.length() == 0 || binding.noteContent.length() == 0) { Toast.makeText(context, "Field cannot be empty", Toast.LENGTH_SHORT).show() false } else true } private fun getRandomColor(): Int { val androidColors = resources.getIntArray(R.array.card_colors) return androidColors[Random().nextInt(androidColors.size)] } private fun goToNotesFragment() { hideSoftKeyboard() mView.findNavController().navigate(R.id.action_newNoteFragment_to_notesFragment) } }
0
Kotlin
0
0
c988d4f267d76cfd3ec9c1c164b2f9af30067dcc
5,588
Notes
Apache License 2.0
app/src/main/java/com/hakmar/employeelivetracking/features/pm_store/di/PmStoreDataModule.kt
enginemre
584,733,724
false
null
package com.hakmar.employeelivetracking.features.pm_store.di import com.hakmar.employeelivetracking.common.domain.repository.DataStoreRepository import com.hakmar.employeelivetracking.features.pm_store.data.remote.PmStoreApi import com.hakmar.employeelivetracking.features.pm_store.data.repository.PmStoreRepositoryImpl import com.hakmar.employeelivetracking.features.pm_store.domain.repository.PmStoreRepository import com.hakmar.employeelivetracking.util.AppConstants import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.create import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object PmStoreDataModule { @Provides @Singleton fun providesPmStoreRepository( pmStoreApi: PmStoreApi, dataStoreRepository: DataStoreRepository ): PmStoreRepository { return PmStoreRepositoryImpl(pmStoreApi, dataStoreRepository) } @Provides @Singleton fun provideBsStoreApi(client: OkHttpClient): PmStoreApi { return Retrofit.Builder() .baseUrl(AppConstants.BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .client(client) .build() .create() } }
0
Kotlin
0
0
5e348e0a5aac89b4e60607a14a4ef9bbd68545a5
1,389
employee_live_tracking
The Unlicense
app/src/main/java/org/ballistic/dreamjournalai/store_billing/data/repository/SubscriptionRepositoryImpl.kt
ErickSorto
546,852,272
false
null
package org.ballistic.dreamjournalai.store_billing.data.repository import com.google.firebase.firestore.FirebaseFirestore import kotlinx.coroutines.tasks.await import org.ballistic.dreamjournalai.core.Resource import org.ballistic.dreamjournalai.store_billing.domain.model.Subscription import org.ballistic.dreamjournalai.store_billing.domain.repository.SubscriptionRepository class SubscriptionRepositoryImpl(private val fireStore: FirebaseFirestore) : SubscriptionRepository { override suspend fun getSubscription(userId: String): Resource<Subscription> { return try { val document = fireStore.collection("subscriptions").document(userId).get().await() if (document.exists()) { val subscription = document.toObject(Subscription::class.java) Resource.Success(subscription) } else { Resource.Error("Subscription not found", null) } } catch (e: Exception) { Resource.Error("Failed to retrieve subscription", null) } } override suspend fun purchaseMonthlySubscription( userId: String, price: Double, tier: Int, ): Resource<Boolean> { return try { val subscription = Subscription(tier, 60, true, true) fireStore.collection("subscriptions").document(userId).set(subscription).await() Resource.Success(true) } catch (e: Exception) { Resource.Error("Failed to purchase monthly subscription", false) } } override suspend fun purchaseYearlySubscription( userId: String, price: Double, tier: Int, ): Resource<Boolean> { return try { val subscription = Subscription(tier, 720, true, true ) fireStore.collection("subscriptions").document(userId).set(subscription).await() Resource.Success(true) } catch (e: Exception) { Resource.Error("Failed to purchase yearly subscription", false) } } override suspend fun upgradeSubscription(userId: String, newTier: Int): Resource<Boolean> { return try { val document = fireStore.collection("subscriptions").document(userId).get().await() if (document.exists()) { val subscription = document.toObject(Subscription::class.java) val updatedSubscription = subscription?.copy(tier = newTier) if (updatedSubscription != null) { fireStore.collection("subscriptions").document(userId).set(updatedSubscription) .await() } Resource.Success(true) } else { Resource.Error("Subscription not found", false) } } catch (e: Exception) { Resource.Error("Failed to upgrade subscription", false) } } override suspend fun addDreamTokens(userId: String, amount: Int): Resource<Boolean> { return try { val document = fireStore.collection("subscriptions").document(userId).get().await() if (document.exists()) { val subscription = document.toObject(Subscription::class.java) val updatedSubscription = subscription?.copy(dreamTokens = subscription.dreamTokens + amount) if (updatedSubscription != null) { fireStore.collection("subscriptions").document(userId).set(updatedSubscription) .await() } Resource.Success(true) } else { Resource.Error("Subscription not found", false) } } catch (e: Exception) { Resource.Error("Failed to add dream tokens", false) } } override suspend fun deductDreamTokens(userId: String, amount: Int): Resource<Boolean> { return try { val document = fireStore.collection("subscriptions").document(userId).get().await() if (document.exists()) { val subscription = document.toObject(Subscription::class.java) val updatedSubscription = subscription?.copy(dreamTokens = subscription.dreamTokens - amount) if (updatedSubscription != null) { fireStore.collection("subscriptions").document(userId).set(updatedSubscription) .await() } Resource.Success(true) } else { Resource.Error("Subscription not found", false) } } catch (e: Exception) { Resource.Error("Failed to deduct dream tokens", false) } } }
0
Kotlin
0
1
133a328b5e89c62f53bdfdab7d5e257977fb89b1
4,686
Dream-Journal-AI
MIT License
machamp-client-spring-boot-starter/src/main/kotlin/io/github/yakovsirotkin/machamp/client/sqlserver/springboot/ClientMachampProperties.kt
YakovSirotkin
456,107,227
false
{"Kotlin": 108816, "PLSQL": 472}
package io.github.yakovsirotkin.machamp.client.mysql.springboot import org.springframework.boot.context.properties.ConfigurationProperties /** * Machamp client configuration properties */ @ConfigurationProperties(prefix = "machamp") open class ClientMachampProperties { val priority = Priority() var taskTable = "async_task" class Priority { var defaultValue: Int = 100 } }
2
Kotlin
0
8
9b2e0367519001dd438a5a96d360bd50fef35a9a
402
machamp
MIT License
java/java-tests/testSrc/com/intellij/util/indexing/SharedIndexDumpTest.kt
mymilkbottles
238,348,396
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.util.indexing import com.intellij.index.SharedIndexExtensions import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.VirtualFileWithId import com.intellij.psi.impl.cache.impl.id.IdIndex import com.intellij.psi.impl.cache.impl.id.IdIndexEntry import com.intellij.testFramework.SkipSlowTestLocally import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase import com.intellij.util.hash.ContentHashEnumerator import com.intellij.util.indexing.hash.FileContentHashIndex import com.intellij.util.indexing.hash.FileContentHashIndexExtension import com.intellij.util.indexing.hash.SharedIndexChunk import com.intellij.util.indexing.hash.building.IndexChunk import com.intellij.util.indexing.hash.building.IndexesExporter import com.intellij.util.indexing.impl.IndexStorage import com.intellij.util.indexing.snapshot.IndexedHashesSupport import com.intellij.util.indexing.snapshot.OneRecordValueContainer import com.intellij.util.indexing.zipFs.UncompressedZipFileSystem import com.intellij.util.indexing.zipFs.UncompressedZipFileSystemProvider import junit.framework.AssertionFailedError import junit.framework.TestCase import java.nio.file.Files import java.nio.file.Path import java.util.stream.Collectors private const val CHUNK_NAME = "source" @SkipSlowTestLocally class SharedIndexDumpTest : LightJavaCodeInsightFixtureTestCase() { fun testOpenSharedIndexes() { val indexZipPath = generateTestSharedIndex() val chunkId = 1 val sourceFileId = (getSourceFile() as VirtualFileWithId).id val hashIndex = FileContentHashIndex(FileContentHashIndexExtension(), object : IndexStorage<Long?, Void?> { override fun clear() = throw AssertionFailedError() override fun clearCaches() = throw AssertionFailedError() override fun removeAllValues(key: Long, inputId: Int) = throw AssertionFailedError() override fun flush() = throw AssertionFailedError() override fun addValue(key: Long?, inputId: Int, value: Void?) = throw AssertionFailedError() override fun close() = throw AssertionFailedError() override fun read(key: Long?): ValueContainer<Void?> { return OneRecordValueContainer(sourceFileId, null) } }) var readFileId: Int? = null UncompressedZipFileSystem(indexZipPath, UncompressedZipFileSystemProvider()).use { zipFs -> return ContentHashEnumerator(zipFs.getPath(CHUNK_NAME, "hashes")).use { hashEnumerator -> val idIndexChunk = SharedIndexChunk(zipFs.getPath(CHUNK_NAME), IdIndex.NAME, chunkId, hashEnumerator, 0) val findExtension = SharedIndexExtensions.findExtension(IdIndex.NAME.getExtension()) val extension = IdIndex.NAME.getExtension() val index = idIndexChunk.open(findExtension, extension, hashIndex) index.getData(IdIndexEntry("methodCall", true)).forEach { id, _ -> readFileId = id true } assertNotNull(readFileId) assertEquals(sourceFileId, readFileId) } } } fun testSharedIndexHashes() { val indexZipPath = generateTestSharedIndex() val indexFs = UncompressedZipFileSystem(indexZipPath, UncompressedZipFileSystemProvider()) val hashEnumerator = indexFs.getPath(CHUNK_NAME, "hashes") val hash = getSourceFileHash() val hashId = ContentHashEnumerator(hashEnumerator).use { it.tryEnumerate(hash) } assertTrue(hashId > 0) } fun testSharedIndexLayout() { val indexZipPath = generateTestSharedIndex() val actualFiles = UncompressedZipFileSystem(indexZipPath, UncompressedZipFileSystemProvider()).use { val root = it.rootDirectories.first() Files.walk(root).map { p -> p.toString() }.sorted().collect(Collectors.joining("\n")).trimStart() } assertEquals(actualFiles, """ source source/IdIndex source/IdIndex/IdIndex.forward source/IdIndex/IdIndex.forward.len source/IdIndex/IdIndex.forward.values.at source/IdIndex/IdIndex.forward_i source/IdIndex/IdIndex.forward_i.len source/IdIndex/IdIndex.storage source/IdIndex/IdIndex.storage.len source/IdIndex/IdIndex.storage.values.at source/IdIndex/IdIndex.storage_i source/IdIndex/IdIndex.storage_i.len source/Stubs source/Stubs/Stubs.storage source/Stubs/Stubs.storage.len source/Stubs/Stubs.storage.values.at source/Stubs/Stubs.storage_i source/Stubs/Stubs.storage_i.len source/Stubs/java.class.fqn source/Stubs/java.class.fqn/java.class.fqn.forward source/Stubs/java.class.fqn/java.class.fqn.forward.len source/Stubs/java.class.fqn/java.class.fqn.storage source/Stubs/java.class.fqn/java.class.fqn.storage.len source/Stubs/java.class.fqn/java.class.fqn.storage.values.at source/Stubs/java.class.fqn/java.class.fqn.storage_i source/Stubs/java.class.fqn/java.class.fqn.storage_i.len source/Stubs/java.class.shortname source/Stubs/java.class.shortname/java.class.shortname.forward source/Stubs/java.class.shortname/java.class.shortname.forward.len source/Stubs/java.class.shortname/java.class.shortname.storage source/Stubs/java.class.shortname/java.class.shortname.storage.keystream source/Stubs/java.class.shortname/java.class.shortname.storage.keystream.len source/Stubs/java.class.shortname/java.class.shortname.storage.len source/Stubs/java.class.shortname/java.class.shortname.storage.values.at source/Stubs/java.class.shortname/java.class.shortname.storage_i source/Stubs/java.class.shortname/java.class.shortname.storage_i.len source/Stubs/java.method.name source/Stubs/java.method.name/java.method.name.forward source/Stubs/java.method.name/java.method.name.forward.len source/Stubs/java.method.name/java.method.name.storage source/Stubs/java.method.name/java.method.name.storage.keystream source/Stubs/java.method.name/java.method.name.storage.keystream.len source/Stubs/java.method.name/java.method.name.storage.len source/Stubs/java.method.name/java.method.name.storage.values.at source/Stubs/java.method.name/java.method.name.storage_i source/Stubs/java.method.name/java.method.name.storage_i.len source/Stubs/rep.names source/Stubs/rep.names.keystream source/Stubs/rep.names.keystream.len source/Stubs/rep.names.len source/Stubs/rep.names_i source/Stubs/rep.names_i.len source/Trigram.Index source/Trigram.Index/Trigram.Index.forward source/Trigram.Index/Trigram.Index.forward.len source/Trigram.Index/Trigram.Index.forward.values.at source/Trigram.Index/Trigram.Index.forward_i source/Trigram.Index/Trigram.Index.forward_i.len source/Trigram.Index/Trigram.Index.storage source/Trigram.Index/Trigram.Index.storage.len source/Trigram.Index/Trigram.Index.storage.values.at source/Trigram.Index/Trigram.Index.storage_i source/Trigram.Index/Trigram.Index.storage_i.len source/empty-indices.txt source/empty-stub-indices.txt source/hashes source/hashes.keystream source/hashes.keystream.len source/hashes.len source/hashes_i source/hashes_i.len source/java.null.method.argument source/java.null.method.argument/java.null.method.argument.forward source/java.null.method.argument/java.null.method.argument.forward.len source/java.null.method.argument/java.null.method.argument.forward.values.at source/java.null.method.argument/java.null.method.argument.forward_i source/java.null.method.argument/java.null.method.argument.forward_i.len source/java.null.method.argument/java.null.method.argument.storage source/java.null.method.argument/java.null.method.argument.storage.keystream source/java.null.method.argument/java.null.method.argument.storage.keystream.len source/java.null.method.argument/java.null.method.argument.storage.len source/java.null.method.argument/java.null.method.argument.storage.values.at source/java.null.method.argument/java.null.method.argument.storage_i source/java.null.method.argument/java.null.method.argument.storage_i.len source/java.simple.property source/java.simple.property/java.simple.property.storage source/java.simple.property/java.simple.property.storage.len source/java.simple.property/java.simple.property.storage.values.at source/java.simple.property/java.simple.property.storage_i source/java.simple.property/java.simple.property.storage_i.len """.trimIndent()) } @Suppress("UNCHECKED_CAST") private fun <K, V> ID<K, V>.getExtension(): FileBasedIndexExtension<K, V> { return FileBasedIndexExtension.EXTENSION_POINT_NAME.findFirstSafe{ it.name == this } as FileBasedIndexExtension<K, V> } private fun getSourceFileHash(): ByteArray { val content = FileContentImpl.createByFile(getSourceFile(), project) as FileContentImpl return IndexedHashesSupport.getOrInitIndexedHash(content, false) } private fun getSourceFile() = myFixture.findClass("A").containingFile.virtualFile private fun generateTestSharedIndex(): Path { val file = myFixture.configureByText("A.java", """ public class A { public void foo() { //Comment methodCall(null) } public String getName() { return name; } } """.trimIndent()).virtualFile val tempDir = FileUtil.createTempDirectory("shared-indexes-test", "").toPath() val indexZipPath = tempDir.resolve("shared-index.zip") val chunks = arrayListOf<IndexChunk>() chunks += IndexChunk(setOf(file), CHUNK_NAME) IndexesExporter .getInstance(project) .exportIndices(chunks, indexZipPath, EmptyProgressIndicator()) return indexZipPath } }
0
null
0
0
d96c2161534f95e7983683a601c69c4628bd0589
10,114
intellij-community
Apache License 2.0
app/src/test/java/eu/se_bastiaan/marietje/data/SongsDataManagerTest.kt
se-bastiaan
32,793,162
false
{"Java": 203204, "Kotlin": 37089, "Shell": 1455}
package eu.se_bastiaan.marietje.data import eu.se_bastiaan.marietje.data.model.Songs import eu.se_bastiaan.marietje.data.remote.SongsService import eu.se_bastiaan.marietje.test.common.TestDataFactory import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.Mockito.`when` import org.mockito.Mockito.verify import org.mockito.junit.MockitoJUnitRunner import rx.Observable import rx.observers.TestSubscriber @RunWith(MockitoJUnitRunner::class) class SongsDataManagerTest { @Mock lateinit var mockSongsService: SongsService lateinit var dataManager: SongsDataManager @Before fun setUp() { dataManager = SongsDataManager(mockSongsService) } @Test fun songsEmitsValues() { val currentPage = 0 val response = stubSongsResponse(currentPage) val result = TestSubscriber<Songs>() dataManager.songs(currentPage.toLong(), null).subscribe(result) result.assertNoErrors() result.assertReceivedOnNext(listOf(response)) } @Test fun songsCallsApi() { val currentPage = 4 stubSongsResponse(currentPage) dataManager.songs(currentPage.toLong(), null).subscribe() verify<SongsService>(mockSongsService).songs(currentPage.toLong(), 50, null, null) } @Test fun manageSongsEmitsValues() { val currentPage = 1 val response = stubSongsResponse(currentPage) val result = TestSubscriber<Songs>() dataManager.manageSongs(currentPage.toLong(), null, null).subscribe(result) result.assertNoErrors() result.assertReceivedOnNext(listOf(response)) } @Test fun manageSongsCallsApi() { val currentPage = 2 stubSongsResponse(currentPage) dataManager.manageSongs(currentPage.toLong(), null, null).subscribe() verify<SongsService>(mockSongsService).manageSongs(currentPage.toLong(), 50, null, null) } private fun stubSongsResponse(currentPage: Int): Songs { val response = TestDataFactory.makeSongsResponse(currentPage.toLong()) `when`(mockSongsService.songs(currentPage.toLong(), 50, null, null)) .thenReturn(Observable.just(response)) `when`(mockSongsService.manageSongs(currentPage.toLong(), 50, null, null)) .thenReturn(Observable.just(response)) return response } }
0
Java
1
1
56640fc3636ccf00e64e67b12872687217862273
2,424
Marietje-Android
Apache License 2.0
app/src/main/kotlin/com/example/tasty/data/local/dao/RecipeDao.kt
stevan-milovanovic
765,694,666
false
{"Kotlin": 119318}
package com.example.tasty.data.local.dao import androidx.paging.PagingSource import androidx.room.Dao import androidx.room.Query import androidx.room.Upsert import com.example.tasty.data.local.model.Recipe import com.example.tasty.data.local.model.RecipeTagCrossRef import com.example.tasty.data.local.model.RecipeWithTags import com.example.tasty.data.local.model.TagWithRecipes import kotlinx.coroutines.flow.Flow /** * Data Access Object for the Recipe table. */ @Dao interface RecipeDao { /** * Observes a single recipe. * * @param recipeId the recipe id. * @return the recipe with recipeId. */ @Query("SELECT * FROM recipe WHERE recipeId = :recipeId") fun observeById(recipeId: Int): Flow<RecipeWithTags> /** * Load all recipes paged */ @Query("SELECT * FROM recipe WHERE recipeId IN (:recipeIds)") fun loadRecipesPaged(recipeIds: List<Int>): PagingSource<Int, Recipe> /** * Load all recipes for tag paged */ @Query("SELECT * FROM recipeTag WHERE (:tagId IS NULL OR tagId = :tagId)") fun loadAllRecipesForTagPaged(tagId: Int?): PagingSource<Int, TagWithRecipes> /** * Select a recipe by id. * * @param recipeId the recipe id. * @return the recipe with recipeId. */ @Query("SELECT * FROM recipe WHERE recipeId = :recipeId") suspend fun getById(recipeId: Int): Recipe /** * Insert or update recipes in the database. If a recipe already exists, replace it. * * @param recipes the recipes to be inserted or updated. */ @Upsert suspend fun upsertAll(recipes: List<Recipe>) /** * Insert or update recipes tags cross references in the database. * * @param recipesTags the recipes tags cross references to be inserted or updated. */ @Upsert suspend fun upsertRecipeTagsCrossRefs(recipesTags: List<RecipeTagCrossRef>) /** * Check if [Recipe] table is empty */ @Query("SELECT (SELECT COUNT(*) FROM recipe) == 0") fun isEmpty(): Boolean @Query("SELECT COUNT(recipeId) FROM recipe") fun getRecipesCount(): Int }
0
Kotlin
0
2
b8c54ff5679bfafea6a9c44e44b3bf38e43cb9a9
2,129
Tasty
Apache License 2.0
lib/sisyphus-common/src/main/kotlin/com/bybutter/sisyphus/string/case/UpperSpaceCaseFormatter.kt
ButterCam
264,589,207
false
null
package io.kanro.idea.plugin.protobuf.string.case object UpperDotCaseFormatter : BaseCaseFormatter() { override fun formatWord( index: Int, word: CharSequence, ): CharSequence { return word.toString().uppercase() } override fun appendDelimiter(builder: StringBuilder) { builder.append('.') } }
9
null
11
92
1f9851c7c45030fa08e018e961110851e029f940
348
sisyphus
MIT License
plugins/devkit/devkit-core/src/inspections/missingApi/BuildNumberValidator.kt
ingokegel
72,937,917
true
null
// 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.idea.devkit.inspections.missingApi import com.intellij.codeInspection.options.StringValidator import com.intellij.openapi.project.Project import com.intellij.openapi.util.BuildNumber import org.jetbrains.idea.devkit.DevKitBundle class BuildNumberValidator: StringValidator { override fun validatorId(): String = "devkit.buildNumber" override fun getErrorMessage(project: Project?, buildNumber: String): String? { return if (buildNumber.isNotBlank() && BuildNumber.fromStringOrNull(buildNumber) == null) { DevKitBundle.message("inspections.missing.recent.api.settings.invalid.build.number", buildNumber) } else null } }
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
784
intellij-community
Apache License 2.0
app/src/main/java/com/vension/mvp/http/RetrofitFactory.kt
Vension
127,116,341
false
null
package com.vension.mvp.http import com.vension.frame.VFrame import com.vension.frame.utils.NetworkUtil import com.vension.frame.utils.VPreference import com.vension.mvp.http.api.ApiEyesService import com.vension.mvp.http.api.ApiTouTiaoService import com.vension.mvp.http.api.GankApiService import okhttp3.* import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory import retrofit2.converter.gson.GsonConverterFactory import java.io.File import java.util.concurrent.TimeUnit /** * ======================================================== * 作 者:Vension * 日 期:2018/4/2 17:35 * 描 述:网络工厂 * ======================================================== */ object RetrofitFactory{ private var mClient: OkHttpClient? = null private var mRetrofitNews: Retrofit? = null private var mRetrofitEyes: Retrofit? = null private var mRetrofitGanks: Retrofit? = null @Volatile private var mRetrofit: Retrofit? = null val toutiaoService: ApiTouTiaoService by lazy { getRetrofitNews()!!.create(ApiTouTiaoService::class.java)} val eyesService: ApiEyesService by lazy { getRetrofitEyes()!!.create(ApiEyesService::class.java)} val gankService: GankApiService by lazy { getRetrofitGanks()!!.create(GankApiService::class.java)} private var token:String by VPreference("token","") /** * 设置公共参数 */ private fun addQueryParameterInterceptor(): Interceptor { return Interceptor { chain -> val originalRequest = chain.request() val request: Request val modifiedUrl = originalRequest.url().newBuilder() // Provide your custom parameter here .addQueryParameter("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.108 Safari/537.36 2345Explorer/8.0.0.13547") .addQueryParameter("Cache-Control", "max-age=0") .addQueryParameter("Upgrade-Insecure-Requests", "1") .addQueryParameter("X-Requested-With", "XMLHttpRequest") .addQueryParameter("Cookie", "uuid=\"w:f2e0e469165542f8a3960f67cb354026\"; __tasessionId=4p6q77g6q1479458262778; csrftoken=<PASSWORD>; tt_webid=36385357187") .addQueryParameter("phoneSystem", "") .addQueryParameter("phoneModel", "") .build() request = originalRequest.newBuilder().url(modifiedUrl).build() chain.proceed(request) } } /** * 设置头 */ private fun addHeaderInterceptor(): Interceptor { return Interceptor { chain -> val originalRequest = chain.request() val requestBuilder = originalRequest.newBuilder() // Provide your custom header here .header("token", token) .method(originalRequest.method(), originalRequest.body()) val request = requestBuilder.build() chain.proceed(request) } } /** * 缓存机制 * 在响应请求之后在 data/data/<包名>/cache 下建立一个response 文件夹,保持缓存数据。 * 这样我们就可以在请求的时候,如果判断到没有网络,自动读取缓存的数据。 * 同样这也可以实现,在我们没有网络的情况下,重新打开App可以浏览的之前显示过的内容。 * 也就是:判断网络,有网络,则从网络获取,并保存到缓存中,无网络,则从缓存中获取。 * https://werb.github.io/2016/07/29/%E4%BD%BF%E7%94%A8Retrofit2+OkHttp3%E5%AE%9E%E7%8E%B0%E7%BC%93%E5%AD%98%E5%A4%84%E7%90%86/ */ private fun addCacheInterceptor(): Interceptor { return Interceptor { chain -> var request = chain.request() //网络不可用 if (!NetworkUtil.isNetworkAvailable(VFrame.getContext())) { request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build() } val response = chain.proceed(request) //网络已连接 if (NetworkUtil.isNetworkAvailable(VFrame.getContext())) { val maxAge = 0 // 有网络时 设置缓存超时时间0个小时 ,意思就是不读取缓存数据,只对get有用,post没有缓冲 response.newBuilder() .header("Cache-Control", "public, max-age=$maxAge") .removeHeader("Pragma")// 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效 .build() } else { // 无网络时,设置超时为1周 只对get有用,post没有缓冲 val maxStale = 60 * 60 * 24 * 7 response.newBuilder() .header("Cache-Control", "public, only-if-cached, max-stale=$maxStale") .removeHeader("Pragma") .build() } response } } private fun getRetrofitNews(): Retrofit? { if (mRetrofitNews == null) { synchronized(RetrofitFactory::class.java) { if (mRetrofitNews == null) { // 获取retrofit的实例 mRetrofitNews = Retrofit.Builder() .baseUrl(UriConstant.BASE_URL_TOUTIAO) //自己配置 .client( createClient()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() } } } return mRetrofitNews } private fun getRetrofitEyes(): Retrofit? { if (mRetrofitEyes == null) { synchronized(RetrofitFactory::class.java) { if (mRetrofitEyes == null) { // 获取retrofit的实例 mRetrofitEyes = Retrofit.Builder() .baseUrl(UriConstant.BASE_URL_EYES) //自己配置 .client( createClient()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() } } } return mRetrofitEyes } private fun getRetrofitGanks(): Retrofit? { if (mRetrofitGanks == null) { synchronized(RetrofitFactory::class.java) { if (mRetrofitGanks == null) { // 获取retrofit的实例 mRetrofitGanks = Retrofit.Builder() .baseUrl(UriConstant.BASE_URL_GANKS) //自己配置 .client( createClient()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() } } } return mRetrofitGanks } fun getRetrofit(): Retrofit? { if (mRetrofit == null) { synchronized(RetrofitFactory::class.java) { if (mRetrofit == null) { // 获取retrofit的实例 mRetrofit = Retrofit.Builder() .baseUrl(UriConstant.BASE_URL_GANKS) //自己配置 .client( createClient()) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create()) .build() } } } return mRetrofit } private fun createClient(): OkHttpClient? { if (mClient == null) { synchronized(RetrofitFactory::class.java) { if (mClient == null) { //添加一个log拦截器,打印所有的log val httpLoggingInterceptor = HttpLoggingInterceptor() //可以设置请求过滤的水平,body,basic,headers httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY //设置 请求的缓存的大小跟位置 val cacheFile = File(VFrame.getContext().cacheDir, "HttpCache") val cache = Cache(cacheFile, 1024 * 1024 * 50) //50Mb 缓存的大小 // Cookie 持久化 // val cookieJar = PersistentCookieJar(SetCookieCache(), SharedPrefsCookiePersistor(InitApp.AppContext)) mClient = OkHttpClient.Builder() // .cookieJar(cookieJar) .addInterceptor(addQueryParameterInterceptor()) //参数添加 .addInterceptor(addHeaderInterceptor()) // token过滤 .addInterceptor(addCacheInterceptor()) //添加网络缓存拦截 .addInterceptor(httpLoggingInterceptor) //日志,所有的请求响应度看到 .cache(cache) //添加缓存 .connectTimeout(60L, TimeUnit.SECONDS) .readTimeout(60L, TimeUnit.SECONDS) .writeTimeout(60L, TimeUnit.SECONDS) .retryOnConnectionFailure(true)//重连 .build() } } } return mClient } }
1
null
1
1
efa939c0325b1b05fad235a1314d87f9d3dc1338
9,006
KV-MVP-Frame
Apache License 2.0
app/src/main/java/de/drtobiasprinz/summitbook/fragments/AddSegmentEntryFragment.kt
prinztob
370,702,913
false
null
package de.drtobiasprinz.summitbook.fragments import android.graphics.Color import android.graphics.Paint import android.graphics.drawable.Drawable import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.AdapterView import android.widget.ImageButton import android.widget.TextView import android.widget.Toast import androidx.appcompat.widget.SwitchCompat import androidx.core.content.res.ResourcesCompat import androidx.fragment.app.Fragment import com.chivorn.smartmaterialspinner.SmartMaterialSpinner import com.github.mikephil.charting.charts.LineChart import com.github.mikephil.charting.components.* import com.github.mikephil.charting.data.Entry import com.github.mikephil.charting.data.LineData import com.github.mikephil.charting.data.LineDataSet import com.github.mikephil.charting.formatter.ValueFormatter import com.github.mikephil.charting.highlight.Highlight import com.github.mikephil.charting.interfaces.datasets.ILineDataSet import com.github.mikephil.charting.listener.OnChartValueSelectedListener import de.drtobiasprinz.gpx.TrackPoint import de.drtobiasprinz.summitbook.BuildConfig import de.drtobiasprinz.summitbook.R import de.drtobiasprinz.summitbook.adapter.SegmentsViewAdapter import de.drtobiasprinz.summitbook.models.* import de.drtobiasprinz.summitbook.models.GpsTrack.Companion.interpolateColor import de.drtobiasprinz.summitbook.ui.CustomMapViewToAllowScrolling import de.drtobiasprinz.summitbook.ui.utils.OpenStreetMapUtils import de.drtobiasprinz.summitbook.ui.utils.OpenStreetMapUtils.addDefaultSettings import de.drtobiasprinz.summitbook.ui.utils.OpenStreetMapUtils.selectedItem import de.drtobiasprinz.summitbook.ui.utils.OpenStreetMapUtils.setTileSource import de.drtobiasprinz.summitbook.ui.utils.OpenStreetMapUtils.showMapTypeSelectorDialog import de.drtobiasprinz.summitbook.ui.utils.SummitSlope import org.osmdroid.api.IGeoPoint import org.osmdroid.config.Configuration import org.osmdroid.util.BoundingBox import org.osmdroid.util.GeoPoint import org.osmdroid.views.MapView import org.osmdroid.views.overlay.Marker import org.osmdroid.views.overlay.simplefastpoint.LabelledGeoPoint import org.osmdroid.views.overlay.simplefastpoint.SimpleFastPointOverlay import org.osmdroid.views.overlay.simplefastpoint.SimpleFastPointOverlayOptions import org.osmdroid.views.overlay.simplefastpoint.SimplePointTheme import java.util.* import kotlin.math.roundToInt import kotlin.math.roundToLong class AddSegmentEntryFragment : Fragment() { private lateinit var root: View private lateinit var osMap: CustomMapViewToAllowScrolling private lateinit var lineChart: LineChart private var gpsTrack: GpsTrack? = null private var startMarker: Marker? = null private var stopMarker: Marker? = null private var pointOverlay: SimpleFastPointOverlay? = null private var summitToCompare: Summit? = null private var summitsToCompare: List<Summit> = emptyList() private lateinit var resultReceiver: FragmentResultReceiver private var selectedCustomizeTrackItem = TrackColor.None private var startSelected = true private var startPointId: Int = 0 private var endPointId: Int = 0 private var segmentId: Long = 0 private var segmentEntryId: Long? = null private var segmentEntry: SegmentEntry? = null private var segment: Segment? = null private var segmentsViewAdapter: SegmentsViewAdapter? = null private var isUpdate = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) resultReceiver = context as FragmentResultReceiver setHasOptionsMenu(true) segmentEntry = segmentEntryId?.let { resultReceiver.getSortFilterHelper().database.segmentsDao()?.getSegmentEntry(it) } segment = segmentsViewAdapter?.segments?.first { it.segmentDetails.segmentDetailsId == segmentId } summitToCompare = segmentEntry?.activityId?.let { resultReceiver.getSortFilterHelper().database.summitDao()?.getSummitFromActivityId(it) } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { root = inflater.inflate(R.layout.fragment_add_segment_entry, container, false) lineChart = root.findViewById(R.id.lineChart) osMap = root.findViewById(R.id.osmap) setTileSource(selectedItem, osMap) root.findViewById<com.google.android.material.button.MaterialButton>(R.id.cancel).setOnClickListener { activity?.supportFragmentManager?.popBackStack(); } root.findViewById<com.google.android.material.button.MaterialButton>(R.id.save).setOnClickListener { val summit = summitToCompare val segmentEntryLocal = segmentEntry if (summit != null && segmentEntryLocal != null) { if (isUpdate) { resultReceiver.getSortFilterHelper().database.segmentsDao()?.updateSegmentEntry(segmentEntryLocal) segmentsViewAdapter?.segments?.first { it.segmentDetails.segmentDetailsId == segmentId }?.segmentEntries?.remove(segmentEntryLocal) } else { resultReceiver.getSortFilterHelper().database.segmentsDao()?.addSegmentEntry(segmentEntryLocal) } segmentsViewAdapter?.segments?.first { it.segmentDetails.segmentDetailsId == segmentId }?.segmentEntries?.add(segmentEntryLocal) segmentsViewAdapter?.notifyDataSetChanged() } activity?.supportFragmentManager?.popBackStack(); } root.findViewById<SwitchCompat>(R.id.startOrStop).setOnCheckedChangeListener { _, isChecked -> startSelected = !isChecked } root.findViewById<com.google.android.material.switchmaterial.SwitchMaterial>(R.id.mapOnOff).setOnCheckedChangeListener { _, isChecked -> if (isChecked) { osMap.visibility = View.VISIBLE val scale = root.resources.displayMetrics.density val pixels = (150 * scale + 0.5f).toInt() lineChart.layoutParams.height = pixels } else { osMap.visibility = View.GONE lineChart.layoutParams.height = ViewGroup.LayoutParams.MATCH_PARENT } } root.findViewById<com.google.android.material.switchmaterial.SwitchMaterial>(R.id.chartOnOff).setOnCheckedChangeListener { _, isChecked -> lineChart.visibility = if (isChecked) View.VISIBLE else View.GONE } setHasOptionsMenu(true) if (summitToCompare != null) { setGpsTrack(summitToCompare) val segmentEntryLocal = segmentEntry if (segmentEntryLocal != null) { startPointId = segmentEntryLocal.startPositionInTrack endPointId = segmentEntryLocal.endPositionInTrack } setOpenStreetMap() setStartMarker(startPointId, false) setEndMarker(endPointId) } prepareCompareAutoComplete() return root } private fun prepareCompareAutoComplete() { val summitToCompareSpinner: SmartMaterialSpinner<String> = root.findViewById(R.id.summit_name_to_use) val items = getSummitsSuggestions() summitToCompareSpinner.item = items val summit = summitToCompare if (summit != null) { val position = items.indexOf("${summit.getDateAsString()} ${summit.name}") if (position >= 0) { summitToCompareSpinner.setSelection(position) } } summitToCompareSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(adapterView: AdapterView<*>?, view: View?, position: Int, id: Long) { if (view != null) { val text = items[position] if (text != "" && text != "None") { val newlySelectedSummit = summitsToCompare.find { "${it.getDateAsString()} ${it.name}" == text } if (newlySelectedSummit != summitToCompare) { summitToCompare = newlySelectedSummit setGpsTrack(summitToCompare) setOpenStreetMap() drawChart() setTextView() } } } } override fun onNothingSelected(adapterView: AdapterView<*>?) {} } } private fun setTextView() { root.findViewById<TextView>(R.id.tour_date).text = summitToCompare?.getDateAsString() val allTrackPoints = gpsTrack?.trackPoints val summit = summitToCompare if (summit != null && allTrackPoints != null && allTrackPoints.isNotEmpty()) { val startTrackPoint = allTrackPoints[startPointId] val endTrackPoint = allTrackPoints[endPointId] val selectedTrackPoints = allTrackPoints.subList(startPointId, endPointId) val averageHeartRate = selectedTrackPoints.sumBy { it.extension?.heartRate ?: 0 } / selectedTrackPoints.size val averagePower = selectedTrackPoints.sumBy { it.extension?.power ?: 0 } / selectedTrackPoints.size val pointsOnlyWithMaximalValues = SummitSlope.keepOnlyMaximalValues(selectedTrackPoints) val heightMeterResult = SummitSlope.removeDeltasSmallerAs(10, pointsOnlyWithMaximalValues) val duration = ((endTrackPoint.time ?: 0L) - (startTrackPoint.time ?: 0L)).toDouble() / 60000.0 val distance = ((endTrackPoint.extension?.distance ?: 0.0) - (startTrackPoint.extension?.distance ?: 0.0)) / 1000.0 root.findViewById<TextView>(R.id.duration).text = String.format(requireContext().resources.configuration.locales[0], "%.1f %s", duration, getString(R.string.min)) root.findViewById<TextView>(R.id.kilometers).text = String.format(requireContext().resources.configuration.locales[0], "%.1f %s", distance, getString(R.string.km)) root.findViewById<TextView>(R.id.averageHr).text = String.format(requireContext().resources.configuration.locales[0], "%s %s", averageHeartRate, getString(R.string.bpm)) root.findViewById<TextView>(R.id.averagePower).text = String.format(requireContext().resources.configuration.locales[0], "%s %s", averagePower, getString(R.string.watt)) root.findViewById<TextView>(R.id.height_meter).text = String.format(requireContext().resources.configuration.locales[0], "%s/%s %s", heightMeterResult.second.roundToInt(), heightMeterResult.third.roundToInt(), getString(R.string.hm)) val saveButton = root.findViewById<com.google.android.material.button.MaterialButton>(R.id.save) saveButton.isEnabled = true if (isUpdate) { saveButton.text = getString(R.string.update) } segmentEntry = SegmentEntry(segmentEntryId?:0, segmentId, summit.date, summit.activityId, startPointId, startTrackPoint.lat, startTrackPoint.lon, endPointId, endTrackPoint.lat, endTrackPoint.lon, duration, distance, heightMeterResult.second.roundToInt(), heightMeterResult.third.roundToInt(), averageHeartRate, averagePower ) } } private fun getSummitsSuggestions(): ArrayList<String> { val suggestions: MutableList<String> = mutableListOf(getString(R.string.none)) val summitsToCompareFromActivity = resultReceiver.getSortFilterHelper().entries val summitsWithTrack = summitsToCompareFromActivity.filter { it.hasGpsTrack() }.sortedByDescending { it.date } val entries = segment?.segmentEntries summitsToCompare = if (entries != null && entries.isNotEmpty()) { val latNorth = if (entries.first().startPositionLatitude > entries.first().endPositionLatitude) entries.first().startPositionLatitude else entries.first().endPositionLatitude val latSouth = if (entries.first().startPositionLatitude < entries.first().endPositionLatitude) entries.first().startPositionLatitude else entries.first().endPositionLatitude val longEast = if (entries.first().startPositionLongitude > entries.first().endPositionLongitude) entries.first().startPositionLongitude else entries.first().endPositionLongitude val longWest = if (entries.first().startPositionLongitude < entries.first().endPositionLongitude) entries.first().startPositionLongitude else entries.first().endPositionLongitude summitsWithTrack.filter { it.trackBoundingBox?.intersects( BoundingBox(latNorth, longEast, latSouth, longWest) ) == true } } else { summitsWithTrack } summitsToCompare.forEach { suggestions.add("${it.getDateAsString()} ${it.name}") } return suggestions as ArrayList } private fun setGpsTrack(localSummit: Summit?) { if (localSummit != null && localSummit.hasGpsTrack()) { localSummit.setGpsTrack(useSimplifiedTrack = false, loadFullTrackAsynchronous = true) gpsTrack = localSummit.gpsTrack startPointId = 0 endPointId = (gpsTrack?.trackGeoPoints?.size ?: 1) - 1 if (gpsTrack?.trackPoints?.any { val value = TrackColor.Elevation.f(it) value != null && value != 0.0 } == true) { selectedCustomizeTrackItem = TrackColor.Elevation } } } private fun drawChart() { val localGpsTrack = gpsTrack if (localGpsTrack != null) { lineChart.clear() lineChart.xAxis.removeAllLimitLines() setXAxis(lineChart) val dataSets: MutableList<ILineDataSet> = ArrayList() val trackColor = selectedCustomizeTrackItem val lineChartEntries = localGpsTrack.getTrackGraph(trackColor.f) val label = getString(trackColor.labelId) val leftAxis: YAxis = lineChart.axisLeft leftAxis.textColor = Color.BLACK leftAxis.setDrawGridLines(true) leftAxis.isGranularityEnabled = true val dataSet = LineDataSet(lineChartEntries, label) setGraphView(dataSet) setColors(lineChartEntries, dataSet) dataSets.add(dataSet) lineChart.data = LineData(dataSets) lineChart.setOnChartValueSelectedListener(object : OnChartValueSelectedListener { override fun onValueSelected(e: Entry, h: Highlight?) { if (e.data is TrackPoint) { val trackPoint = e.data as TrackPoint val index = gpsTrack?.trackPoints?.indexOf(trackPoint) if (index != null) { if (startSelected) { setStartMarker(index) } else { setEndMarker(index) } osMap.controller.setCenter(gpsTrack?.trackGeoPoints?.get(index)) } } } override fun onNothingSelected() {} }) setLegend(lineChart, label) drawVerticalLine(startPointId, Color.GREEN) drawVerticalLine(endPointId, Color.RED) } else { lineChart.visibility = View.GONE } } private fun drawVerticalLine(index: Int, color: Int) { val distance = gpsTrack?.trackPoints?.get(index)?.extension?.distance?.toFloat() if (distance != null) { val ll = LimitLine(distance) ll.lineColor = color ll.lineWidth = 2f lineChart.xAxis.addLimitLine(ll) } } private fun setLegend(lineChart: LineChart, label: String?) { val l: Legend = lineChart.legend l.entries l.yEntrySpace = 10f l.isWordWrapEnabled = true val l1 = LegendEntry("$label ${getString(R.string.min)}", Legend.LegendForm.CIRCLE, 9f, 5f, null, selectedCustomizeTrackItem.minColor) val l2 = LegendEntry("$label ${getString(R.string.max)}", Legend.LegendForm.CIRCLE, 9f, 5f, null, selectedCustomizeTrackItem.maxColor) l.setCustom(arrayOf(l1, l2)) l.isEnabled = true } private fun setColors(lineChartEntries: MutableList<Entry>, dataSet: LineDataSet) { val min = lineChartEntries.minByOrNull { it.y }?.y val max = lineChartEntries.maxByOrNull { it.y }?.y if (min != null && max != null) { val colors = lineChartEntries.map { val fraction = (it.y - min) / (max - min) interpolateColor(selectedCustomizeTrackItem.minColor, selectedCustomizeTrackItem.maxColor, fraction) } dataSet.colors = colors } } private fun setXAxis(lineChart: LineChart) { val xAxis = lineChart.xAxis xAxis?.position = XAxis.XAxisPosition.BOTTOM xAxis?.valueFormatter = object : ValueFormatter() { override fun getFormattedValue(value: Float): String { return String.format(requireContext().resources.configuration.locales[0], "%.1f km", (value / 100f).roundToLong() / 10f) } } } private fun setOpenStreetMap() { osMap.overlays?.clear() osMap.overlayManager?.clear() val changeMapTypeFab: ImageButton = root.findViewById(R.id.change_map_type) changeMapTypeFab.setImageResource(R.drawable.ic_more_vert_black_24dp) changeMapTypeFab.setOnClickListener { showMapTypeSelectorDialog(requireContext(), osMap) } addDefaultSettings(requireContext(), osMap, requireActivity()) Configuration.getInstance().userAgentValue = BuildConfig.APPLICATION_ID val summit = summitToCompare if (summit != null) { val hasPoints = gpsTrack?.hasOnlyZeroCoordinates() == false || summit.latLng != null if (summitToCompare != null && hasPoints) { if (gpsTrack?.osMapRoute == null) { gpsTrack?.addGpsTrack(osMap, selectedCustomizeTrackItem, rootView = root) } showSinglePoints() osMap.post { gpsTrack?.let { OpenStreetMapUtils.calculateBoundingBox(osMap, it.trackGeoPoints) } } } } val entries = segment?.segmentEntries if (entries != null && entries.isNotEmpty()) { val averageStartPoint = GeoPoint(entries.sumByDouble { it.startPositionLatitude }/entries.size, entries.sumByDouble { it.startPositionLongitude }/entries.size) val averageEndPoint = GeoPoint(entries.sumByDouble { it.endPositionLatitude } / entries.size, entries.sumByDouble { it.endPositionLatitude } / entries.size) addMarker(osMap, averageStartPoint, ResourcesCompat.getDrawable(requireContext().resources, R.drawable.ic_filled_location_lightbrown_48, null)) addMarker(osMap, averageEndPoint, ResourcesCompat.getDrawable(requireContext().resources, R.drawable.ic_filled_location_darkbrown_48, null)) } } private fun showSinglePoints() { val trackGeoPoints = gpsTrack?.trackGeoPoints if (trackGeoPoints != null && trackGeoPoints.isNotEmpty()) { osMap.overlays.remove(pointOverlay) val filteredPoints = ArrayList<IGeoPoint>(); for ((i, point) in trackGeoPoints.withIndex()) { if (i > startPointId - 30 && i < endPointId + 30) { filteredPoints.add(LabelledGeoPoint(point.latitude, point.longitude, i.toString())); } } val pt = SimplePointTheme(filteredPoints, true); val textStyle = Paint(); textStyle.style = Paint.Style.FILL textStyle.color = Color.BLACK textStyle.textAlign = Paint.Align.CENTER textStyle.textSize = 55f textStyle.isAntiAlias = true textStyle.isDither = true textStyle.style = Paint.Style.STROKE textStyle.strokeJoin = Paint.Join.ROUND textStyle.strokeCap = Paint.Cap.ROUND textStyle.strokeWidth = 5f val opt = SimpleFastPointOverlayOptions.getDefaultStyle() .setAlgorithm(SimpleFastPointOverlayOptions.RenderingAlgorithm.NO_OPTIMIZATION) .setRadius(10f) .setIsClickable(true) .setCellSize(20) .setMinZoomShowLabels(19) .setTextStyle(textStyle) pointOverlay = SimpleFastPointOverlay(pt, opt); pointOverlay?.setOnClickListener { _: SimpleFastPointOverlay.PointAdapter, i: Int -> val indexOfTrackPoint = (filteredPoints[i] as LabelledGeoPoint).label.toInt() if (startSelected) { setStartMarker(indexOfTrackPoint) } else { setEndMarker(indexOfTrackPoint) } } osMap.overlays?.add(pointOverlay); } } private fun setEndMarker(i: Int) { if (i >= startPointId) { endPointId = i updateMapAndChart() } else { Toast.makeText(root.context, getString(R.string.stop_before_start), Toast.LENGTH_SHORT).show() } } private fun setStartMarker(i: Int, updateView: Boolean = true) { if (i <= endPointId) { startPointId = i updateMapAndChart(updateView) } else { Toast.makeText(root.context, getString(R.string.start_after_stop), Toast.LENGTH_SHORT).show() } } private fun updateMapAndChart(updateView: Boolean = true) { if (updateView) { drawChart() showSinglePoints() setTextView() } osMap.overlays.remove(startMarker) osMap.overlays.remove(stopMarker) startMarker = addMarker(osMap, gpsTrack?.trackGeoPoints?.get(startPointId), ResourcesCompat.getDrawable(requireContext().resources, R.drawable.ic_filled_location_green_48, null)) stopMarker = addMarker(osMap, gpsTrack?.trackGeoPoints?.get(endPointId), ResourcesCompat.getDrawable(requireContext().resources, R.drawable.ic_filled_location_red_48, null)) } private fun setGraphView(set1: LineDataSet?) { set1?.setDrawValues(false) set1?.setDrawFilled(true) set1?.setDrawCircles(false) set1?.axisDependency = YAxis.AxisDependency.LEFT set1?.color = Color.RED set1?.setCircleColor(Color.RED) set1?.lineWidth = 5f set1?.circleRadius = 3f set1?.fillAlpha = 50 set1?.fillColor = Color.RED set1?.setDrawCircleHole(false) set1?.highLightColor = Color.rgb(244, 117, 117) set1?.setDrawHorizontalHighlightIndicator(true) } private fun addMarker(mMapView: MapView, startPoint: GeoPoint?, drawable: Drawable?): Marker? { try { val marker = Marker(mMapView) marker.position = startPoint marker.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_BOTTOM) marker.icon = drawable mMapView.overlays.add(marker) marker.setOnMarkerClickListener { _, _ -> false } mMapView.invalidate() return marker } catch (e: NullPointerException) { e.printStackTrace() return null } } companion object { fun getInstance(segmentId: Long, segmentsViewAdapter: SegmentsViewAdapter, segmentEntryId: Long?): AddSegmentEntryFragment { val fragment = AddSegmentEntryFragment() fragment.segmentId = segmentId if (segmentEntryId != null) { fragment.segmentEntryId = segmentEntryId fragment.isUpdate = true } fragment.segmentsViewAdapter = segmentsViewAdapter return fragment } const val TAG = "osmBaseFrag" } }
0
Kotlin
0
0
3d9df15193c892f42ad1c04348bc1245df51141a
24,467
summitbook
MIT License
src/test/resources/PostorderTraversal.kt
pipen2
114,119,918
true
{"YAML": 2, "Gradle": 2, "Shell": 1, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "XML": 2, "Groovy": 1, "Kotlin": 39, "Java": 42, "Java Properties": 1}
import com.jalgoarena.type.TreeNode import java.util.* import com.jalgoarena.type.* class PostorderTraversal { fun postorderTraversal(root: TreeNode?): IntArray { val items = ArrayList<Int>() postorder(root, items) return items.toIntArray() } private fun postorder(root: TreeNode?, items: MutableList<Int>) { if (root != null) { postorder(root.left, items) postorder(root.right, items) items.add(root.data) } } }
0
Java
0
0
70135d5de26f9eb47905253c84abe7c8c13156be
508
JAlgoArena-Judge
Apache License 2.0
src/main/kotlin/com/korektur/scheduler/strategy/FixedDelaySchedulingStrategy.kt
korektur
134,327,082
false
{"Kotlin": 29594, "Java": 804}
package com.korektur.scheduler.strategy import java.time.Instant import java.time.temporal.ChronoUnit.MILLIS import java.time.temporal.TemporalUnit /** * Strategy that calculates next execution time based on fixed delay since end of the last execution. * @param delay fixed period between the end of the last invocation and the start of the next. * @param timeUnit time unit for the delay * @param initialDelay Number of milliseconds to wait before the first execution after task was registered * @param initialDelayTimeUnit time unit for the initial delay */ open class FixedDelaySchedulingStrategy(private val delay: Long, private val timeUnit: TemporalUnit = MILLIS, initialDelay: Long = 0L, initialDelayTimeUnit: TemporalUnit = MILLIS) : BaseSchedulingStrategy(initialDelay, initialDelayTimeUnit) { override fun afterExecution(currentTime: Instant) { lastExecutionTime = currentTime nextExecutionExpectedTime = currentTime.plus(delay, timeUnit) } }
0
Kotlin
0
0
def5b3adce0df5b939615c19eff00b61c2ab192a
1,090
distributed-scheduler
Apache License 2.0
PushNotification/app/src/main/java/com/juhwan/anyang_yi/domain/usecase/keyword/WriteKeywordUseCase.kt
juhwankim-dev
324,930,598
false
null
package com.juhwan.anyang_yi.domain.usecase.keyword import com.juhwan.anyang_yi.domain.repository.KeywordRepository import javax.inject.Inject class WriteKeywordUseCase @Inject constructor( private val keywordRepository: KeywordRepository ) { suspend operator fun invoke(keyword: String) = keywordRepository.writeKeyword(keyword) }
1
Kotlin
1
5
ae17bf81ec4bdf7a8704710b742b44cfc84a6b04
353
pushNotificationApp
Apache License 2.0
src/Day06.kt
GarrettShorr
571,769,671
false
null
fun main() { fun part1(input: List<String>): Int { println(input) val potentialMarkers = input[0].windowed(4).map { it.windowed(1).sorted() } println(potentialMarkers) for(i in potentialMarkers.indices) { if(potentialMarkers[i][0] != potentialMarkers[i][1] && potentialMarkers[i][1] != potentialMarkers[i][2] && potentialMarkers[i][2] != potentialMarkers[i][3]) { return i + 4 } } return 0 } fun part2(input: List<String>): Int { println(input) val potentialMarkers = input[0].windowed(14).map { it.windowed(1) } println(potentialMarkers) for(i in potentialMarkers.indices) { val markerSet = mutableSetOf<String>() markerSet.addAll(potentialMarkers[i]) if(markerSet.size == 14) { return i + 14 } } return 0 } // test if implementation meets criteria from the description, like: val testInput = readInput("Day06_test") // println(part1(testInput)) println(part2(testInput)) val input = readInput("Day06") // output(part1(input)) output(part2(input)) }
0
Kotlin
0
0
391336623968f210a19797b44d027b05f31484b5
1,082
AdventOfCode2022
Apache License 2.0
src/main/kotlin/no/nav/helse/inntektsmeldingsvarsel/AltinnVarselMapper.kt
navikt
255,909,562
false
{"Kotlin": 155970, "HTML": 7618, "Shell": 1622, "Dockerfile": 389}
package no.nav.helse.inntektsmeldingsvarsel import no.altinn.schemas.services.serviceengine.correspondence._2010._10.ExternalContentV2 import no.altinn.schemas.services.serviceengine.correspondence._2010._10.InsertCorrespondenceV2 import no.altinn.schemas.services.serviceengine.notification._2009._10.NotificationBEList import no.nav.helse.inntektsmeldingsvarsel.NotificationAltinnGenerator.opprettEpostNotification import no.nav.helse.inntektsmeldingsvarsel.NotificationAltinnGenerator.opprettSMSNotification import no.nav.helse.inntektsmeldingsvarsel.domene.varsling.Varsling import java.time.format.DateTimeFormatter class AltinnVarselMapper(val altinnTjenesteKode: String) { private fun opprettManglendeInnsendingNotifications(): NotificationBEList { val epost = opprettEpostNotification( "Inntektsmelding mangler - sykepenger", "<p>NAV mangler inntektsmelding for en eller flere av deres ansatte i \$reporteeName\$. Vi får ikke utbetalt penger før inntektsmeldingen er sendt. Gå til meldingsboksen i Altinn for å se hvem det gjelder, og hvilken periode det handler om.</p>" + "<p>Vennlig hilsen NAV</p>" ) val sms = opprettSMSNotification( "NAV mangler inntektsmelding for en eller flere av deres ansatte i: \$reporteeName\$.", "Vi får ikke utbetalt penger før inntektsmeldingen er sendt. Gå til meldingsboksen i Altinn for å se hvem det gjelder, og hvilken periode det handler om. \n\nVennlig hilsen NAV" ) return NotificationBEList() .withNotification(epost, sms) } fun mapVarslingTilInsertCorrespondence(altinnVarsel: Varsling): InsertCorrespondenceV2 { val formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy") val tittel = "Inntektsmelding mangler for sykepenger" val innhold = """ <html> <head> <meta charset="UTF-8"> </head> <body> <div class="melding"> <p>NAV mangler inntektsmelding for ansatte ved virksomheten (${altinnVarsel.virksomhetsNr}). For at vi skal kunne vurdere retten til sykepenger det søkes om må inntektsmelding sendes oss så snart som mulig. Dere kan se bort fra varselet hvis dere har sendt inntektsmelding i løpet av de siste 24 timene for disse ansatte:</p> ${altinnVarsel.liste.map { """ <p> <strong>${it.navn}</strong><br> Fødselsnummer: ${it.personnumer}<br> Periode: ${it.periode.fom.format(formatter)} - ${it.periode.tom.format(formatter)} </p> """.trimIndent() }.joinToString(separator = "\n")} <p> <a href="https://www.altinn.no/skjemaoversikt/arbeids--og-velferdsetaten-nav/Inntektsmelding-til-NAV/">Skjema for inntektsmelding (NAV 08-30.01) finner du her</a><br> Benytter dere eget HR-system for å sende inntektsmeldinger kan dere fortsatt benytte dette. </p> <h4>Om denne meldingen:</h4> <p>Denne meldingen er automatisk generert og skal hjelpe arbeidsgivere med å få oversikt over inntektsmeldinger som mangler. NAV påtar seg ikke ansvar for eventuell manglende påminnelse. Vi garanterer heller ikke for at foreldelsesfristen ikke er passert, eller om det er andre grunner til at retten til sykepenger ikke er oppfylt. Dersom arbeidstakeren har åpnet en søknad og avbrutt den, vil det ikke bli sendt melding til dere.</p> </div> </body> </html> """.trimIndent() val meldingsInnhold = ExternalContentV2() .withLanguageCode("1044") .withMessageTitle(tittel) .withMessageBody(innhold) .withMessageSummary("Inntektsmelding mangler for sykepenger") return InsertCorrespondenceV2() .withAllowForwarding(false) .withReportee(altinnVarsel.virksomhetsNr) .withMessageSender("NAV (Arbeids- og velferdsetaten)") .withServiceCode(altinnTjenesteKode) .withServiceEdition("1") .withNotifications(opprettManglendeInnsendingNotifications()) .withContent(meldingsInnhold) } }
0
Kotlin
0
0
41c17cc53332a3655a366ce7bc8fbb7e1536b24e
4,487
im-varsel
MIT License
audio-sink/src/main/java/io/github/rosariopfernandes/bluetoothingspeaker/remotecontrol/ActionType.kt
thatfiredev
190,218,019
true
{"Kotlin": 25856, "Java": 16257}
package io.github.rosariopfernandes.bluetoothingspeaker.remotecontrol enum class ActionType { PAIR, DISCONNECT }
1
Kotlin
1
4
d21d8de617c84fa69819fdbd99b1cab46381119c
121
bluetoothingspeaker
Apache License 2.0
onetap-compose/src/main/kotlin/com/vk/id/onetap/compose/onetap/sheet/content/SheetContentAuthFailed.kt
VKCOM
696,297,549
false
null
@file:OptIn(InternalVKIDApi::class) package com.vk.id.onetap.compose.onetap.sheet.content import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.BasicText import androidx.compose.material.ripple.rememberRipple import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clipToBounds import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.colorResource import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle 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 com.vk.id.common.InternalVKIDApi import com.vk.id.onetap.common.alternate.style.InternalVKIDAlternateAccountButtonStyle import com.vk.id.onetap.compose.R import com.vk.id.onetap.compose.button.alternate.style.asColorResource import com.vk.id.onetap.compose.button.alternate.style.background import com.vk.id.onetap.compose.button.auth.style.asColor import com.vk.id.onetap.compose.button.auth.style.border import com.vk.id.onetap.compose.onetap.sheet.OneTapBottomSheetAnalytics import com.vk.id.onetap.compose.onetap.sheet.style.OneTapBottomSheetStyle import com.vk.id.onetap.compose.onetap.style.asFontSize import com.vk.id.onetap.compose.onetap.style.clip @Composable internal fun SheetContentAuthFailed( serviceName: String, style: OneTapBottomSheetStyle, dismissSheet: () -> Unit, repeatClicked: () -> Unit, ) { OneTapBottomSheetAnalytics.BottomSheetErrorShown() SheetContentBox( serviceName, style, dismissSheet, ) { Spacer(modifier = Modifier.height(48.dp)) Image( painter = painterResource(R.drawable.vkid_sheet_content_error), contentDescription = null, ) BasicText( text = stringResource(R.string.vkid_sheet_state_auth_failed), modifier = Modifier.padding(top = 12.dp), style = TextStyle( color = colorResource(style.contentTextColor), fontSize = 16.sp, fontWeight = FontWeight.W400, letterSpacing = 0.1.sp, lineHeight = 20.sp ) ) RepeatButton(style.oneTapStyle.alternateAccountButtonStyle, repeatClicked) Spacer(modifier = Modifier.height(48.dp)) } } @Composable private fun RepeatButton(style: InternalVKIDAlternateAccountButtonStyle, repeatClicked: () -> Unit) { // todo alternate and this button to uikit Box( modifier = Modifier .padding(top = 16.dp) .border(style.borderStyle, style.cornersStyle) .clip(style.cornersStyle) .clipToBounds() .background(style.backgroundStyle) .clickable( interactionSource = remember { MutableInteractionSource() }, indication = rememberRipple( color = style.rippleStyle.asColor(), ), onClick = repeatClicked ) .testTag("vkid_retry_btn"), contentAlignment = Alignment.Center ) { BasicText( modifier = Modifier.padding(start = 16.dp, end = 16.dp, top = 6.5.dp, bottom = 7.5.dp), text = stringResource(R.string.vkid_sheet_state_auth_failed_retry), style = TextStyle( color = style.textStyle.asColorResource(), fontSize = style.sizeStyle.asFontSize(), fontWeight = FontWeight.Medium, textAlign = TextAlign.Center, ) ) } } @Preview @Composable private fun OneTapBottomSheetProgressPreview() { SheetContentAuthFailed( "<Название сервиса>", OneTapBottomSheetStyle.Light(), dismissSheet = {}, repeatClicked = {}, ) }
2
null
3
8
ac0870dd548c2c4bb0ac5a7cf4b973e7add590b2
4,403
vkid-android-sdk
MIT License
typescript/ts-translator/src/org/jetbrains/dukat/ts/translator/TypescriptLowerer.kt
Kotlin
159,510,660
false
null
package org.jetbrains.dukat.ts.translator import IntroduceMissingConstructors import org.jetbrains.dukat.astCommon.NameEntity import org.jetbrains.dukat.astModel.SourceSetModel import org.jetbrains.dukat.commonLowerings.AddExplicitGettersAndSetters import org.jetbrains.dukat.commonLowerings.AddImports import org.jetbrains.dukat.commonLowerings.AnyfyUnresolvedTypes import org.jetbrains.dukat.commonLowerings.ExtractNestedInheritedInterfaces import org.jetbrains.dukat.commonLowerings.RemoveDuplicateMembers import org.jetbrains.dukat.commonLowerings.RemoveParentAny import org.jetbrains.dukat.commonLowerings.RemoveUnsupportedJsNames import org.jetbrains.dukat.commonLowerings.RemoveUnusedGeneratedInterfaces import org.jetbrains.dukat.commonLowerings.ReplaceSimpleGeneratedInterfacesWithLambdas import org.jetbrains.dukat.commonLowerings.SeparateNonExternalEntities import org.jetbrains.dukat.commonLowerings.SubstituteTsStdLibEntities import org.jetbrains.dukat.commonLowerings.merge.MergeClassLikesAndModuleDeclarations import org.jetbrains.dukat.commonLowerings.merge.MergeVarsAndInterfaces import org.jetbrains.dukat.model.commonLowerings.AddStandardImportsAndAnnotations import org.jetbrains.dukat.model.commonLowerings.CorrectStdLibTypes import org.jetbrains.dukat.model.commonLowerings.EscapeIdentificators import org.jetbrains.dukat.model.commonLowerings.IntroduceAmbiguousInterfaceMembers import org.jetbrains.dukat.model.commonLowerings.LowerOverrides import org.jetbrains.dukat.model.commonLowerings.ModelContextAwareLowering import org.jetbrains.dukat.model.commonLowerings.RearrangeConstructors import org.jetbrains.dukat.model.commonLowerings.RemoveConflictingOverloads import org.jetbrains.dukat.model.commonLowerings.RemoveKotlinBuiltIns import org.jetbrains.dukat.model.commonLowerings.RemoveRedundantTypeParams import org.jetbrains.dukat.model.commonLowerings.lower import org.jetbrains.dukat.moduleNameResolver.ModuleNameResolver import org.jetbrains.dukat.nodeIntroduction.introduceModels import org.jetbrains.dukat.tsLowerings.ConvertKeyOfsAndLookups import org.jetbrains.dukat.tsLowerings.EscapeLiterals import org.jetbrains.dukat.tsLowerings.FilterOutNonDeclarations import org.jetbrains.dukat.tsLowerings.FixImpossibleInheritance import org.jetbrains.dukat.tsLowerings.GenerateInterfaceReferences import org.jetbrains.dukat.tsLowerings.LowerPartialOf import org.jetbrains.dukat.tsLowerings.LowerPrimitives import org.jetbrains.dukat.tsLowerings.LowerThisType import org.jetbrains.dukat.tsLowerings.MergeClassLikes import org.jetbrains.dukat.tsLowerings.MergeModules import org.jetbrains.dukat.tsLowerings.MoveAliasesFromMergeableModules import org.jetbrains.dukat.tsLowerings.PreprocessUnionTypes import org.jetbrains.dukat.tsLowerings.ProcessForOfStatements import org.jetbrains.dukat.tsLowerings.ProcessNullabilityChecks import org.jetbrains.dukat.tsLowerings.ProcessOptionalMethods import org.jetbrains.dukat.tsLowerings.RemoveThisParameters import org.jetbrains.dukat.tsLowerings.RenameImpossibleDeclarations import org.jetbrains.dukat.tsLowerings.ResolveCollections import org.jetbrains.dukat.tsLowerings.ResolveDefaultTypeParams import org.jetbrains.dukat.tsLowerings.ResolveLambdaParents import org.jetbrains.dukat.tsLowerings.ResolveLoops import org.jetbrains.dukat.tsLowerings.ResolveTypeAliases import org.jetbrains.dukat.tsLowerings.ResolveTypescriptUtilityTypes import org.jetbrains.dukat.tsLowerings.SpecifyUnionType import org.jetbrains.dukat.tsLowerings.lower import org.jetbrains.dukat.tsmodel.SourceSetDeclaration open class TypescriptLowerer( private val moduleNameResolver: ModuleNameResolver, private val packageName: NameEntity?, private val addSuppressAnnotations: Boolean, private val kotlinStdLib: SourceSetModel? = null ) : ECMAScriptLowerer { override fun lower(sourceSet: SourceSetDeclaration): SourceSetModel { val declarations = sourceSet .lower( IntroduceMissingConstructors(), RemoveThisParameters(), MergeModules(), MergeClassLikes(), ResolveLambdaParents(), FilterOutNonDeclarations(), RenameImpossibleDeclarations(), ResolveTypescriptUtilityTypes(), ResolveDefaultTypeParams(), ConvertKeyOfsAndLookups(), LowerPrimitives(), GenerateInterfaceReferences(), FixImpossibleInheritance(), LowerPartialOf(), ResolveLoops(), ResolveCollections(), LowerThisType(), ResolveTypeAliases(), PreprocessUnionTypes(), SpecifyUnionType(), ProcessOptionalMethods(), ProcessForOfStatements(), ProcessNullabilityChecks(), EscapeLiterals(), MoveAliasesFromMergeableModules() ) val models = declarations .introduceModels(moduleNameResolver) .lower( RearrangeConstructors(), RemoveRedundantTypeParams(), RemoveConflictingOverloads(), SubstituteTsStdLibEntities(), RemoveParentAny(), EscapeIdentificators(), RemoveUnsupportedJsNames(), MergeClassLikesAndModuleDeclarations(), MergeVarsAndInterfaces(), ExtractNestedInheritedInterfaces(), ModelContextAwareLowering() .lower { context, inheritanceContext -> IntroduceAmbiguousInterfaceMembers(context, inheritanceContext) } .lower { context, inheritanceContext -> LowerOverrides(context, inheritanceContext) }, AddExplicitGettersAndSetters(), AnyfyUnresolvedTypes(), RemoveKotlinBuiltIns(), CorrectStdLibTypes(), RemoveDuplicateMembers(), RearrangeConstructors(), SeparateNonExternalEntities(), ReplaceSimpleGeneratedInterfacesWithLambdas(), RemoveUnusedGeneratedInterfaces(), AddImports(), AddStandardImportsAndAnnotations(addSuppressAnnotations) ) return models } }
244
null
42
535
d50b9be913ce8a2332b8e97fd518f1ec1ad7f69e
6,929
dukat
Apache License 2.0
tmp/arrays/youTrackTests/8300.kt
DaniilStepanov
228,623,440
false
{"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4}
// Original bug: KT-22317 class Test { init { a = 1 // No error, despite of later declaration of 'a' } constructor() { a = 2 } private var a: Int init { a = 3 } }
1
null
1
1
602285ec60b01eee473dcb0b08ce497b1c254983
216
bbfgradle
Apache License 2.0
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/IntelliJKotlinNewProjectWizard.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.tools.projectWizard import com.intellij.ide.projectWizard.NewProjectWizardConstants.BuildSystem.INTELLIJ import com.intellij.ide.projectWizard.generators.AssetsNewProjectWizardStep import com.intellij.ide.projectWizard.generators.IntelliJNewProjectWizardStep import com.intellij.ide.starters.local.StandardAssetsProvider import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.name import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.path import com.intellij.ide.wizard.NewProjectWizardStep import com.intellij.ide.wizard.chain import com.intellij.openapi.project.Project import com.intellij.ui.dsl.builder.* import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType internal class IntelliJKotlinNewProjectWizard : BuildSystemKotlinNewProjectWizard { override val name = INTELLIJ override val ordinal = 0 override fun createStep(parent: KotlinNewProjectWizard.Step) = Step(parent).chain(::AssetsStep) class Step(parent: KotlinNewProjectWizard.Step) : IntelliJNewProjectWizardStep<KotlinNewProjectWizard.Step>(parent), BuildSystemKotlinNewProjectWizardData by parent { override fun setupSettingsUI(builder: Panel) { setupJavaSdkUI(builder) setupSampleCodeUI(builder) setupKmpWizardLinkUI(builder) } override fun setupAdvancedSettingsUI(builder: Panel) { } override fun setupProject(project: Project) = KotlinNewProjectWizard.generateProject( project = project, projectPath = "$path/$name", projectName = name, sdk = sdk, buildSystemType = BuildSystemType.Jps, addSampleCode = addSampleCode ) } private class AssetsStep(parent: NewProjectWizardStep) : AssetsNewProjectWizardStep(parent) { override fun setupAssets(project: Project) { outputDirectory = "$path/$name" addAssets(StandardAssetsProvider().getIntelliJIgnoreAssets()) } } }
229
null
4931
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
2,259
intellij-community
Apache License 2.0
libnavigation-voice/src/main/java/com/mapbox/navigation/voice/api/VoiceApiProvider.kt
mapbox
87,455,763
false
{"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624}
package com.mapbox.navigation.voice.api import android.content.Context import com.mapbox.navigation.core.internal.accounts.MapboxNavigationAccounts import com.mapbox.navigation.ui.utils.internal.resource.ResourceLoaderFactory import com.mapbox.navigation.voice.options.MapboxSpeechApiOptions import java.io.File internal object VoiceApiProvider { private const val MAPBOX_INSTRUCTIONS_CACHE = "mapbox_instructions_cache" fun retrieveMapboxVoiceApi( context: Context, language: String, options: MapboxSpeechApiOptions, ): MapboxVoiceApi = MapboxVoiceApi( MapboxSpeechProvider( language, MapboxNavigationAccounts(), options, ResourceLoaderFactory.getInstance(), ), MapboxSpeechFileProvider( File( context.applicationContext.cacheDir, MAPBOX_INSTRUCTIONS_CACHE, ), ), ) }
508
Kotlin
318
621
88163ae3d7e34948369d6945d5b78a72bdd68d7c
949
mapbox-navigation-android
Apache License 2.0
app/src/main/java/com/umang/stumate/general/ClassMatesActivity.kt
saikiran1224
308,093,102
false
null
package com.umang.stumate.general import android.app.Dialog import android.content.Intent import android.opengl.Visibility import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Button import android.widget.TextView import android.widget.Toast import androidx.recyclerview.widget.LinearLayoutManager import com.google.android.gms.auth.api.signin.GoogleSignIn import com.google.android.gms.auth.api.signin.GoogleSignInClient import com.google.android.gms.auth.api.signin.GoogleSignInOptions import com.google.android.material.bottomappbar.BottomAppBar import com.google.android.material.bottomsheet.BottomSheetDialog import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.umang.stumate.R import com.umang.stumate.adapters.ClassMatesAdapter import com.umang.stumate.auth.AuthenticationActivity import com.umang.stumate.modals.StudentData import com.umang.stumate.utils.AppPreferences import kotlinx.android.synthetic.main.activity_class_mates.* import kotlinx.android.synthetic.main.activity_class_notes.closeButton class ClassMatesActivity : AppCompatActivity() { private lateinit var linearLayoutManager: LinearLayoutManager private lateinit var classMatesList: ArrayList<StudentData> lateinit var bottomnav: BottomAppBar lateinit var mGoogleSignInClient: GoogleSignInClient override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_class_mates) bottomnav=findViewById(R.id.bottomNavigation) val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestIdToken(getString(R.string.default_web_client_id)) .requestEmail() .build() // Build a GoogleSignInClient with the options specified by gso. mGoogleSignInClient = GoogleSignIn.getClient(this, gso) AppPreferences.init(this) closeButton.setOnClickListener { val intent = Intent(this, HomeActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) finish() } classMatesList = ArrayList<StudentData>() // ClassNotesAdapter Layout Manager linearLayoutManager = LinearLayoutManager(this) linearLayoutManager.orientation = LinearLayoutManager.VERTICAL linearLayoutManager.reverseLayout = false uploadFilesButtonfab.setOnClickListener { val intent = Intent(this, UploadFilesActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) finish() } bottomnav.setOnClickListener { val dialog= BottomSheetDialog(this,R.style.BottomSheetDialog) val view=layoutInflater.inflate(R.layout.bottom_home, null) view.findViewById<TextView>(R.id.homePage).setOnClickListener { view.findViewById<TextView>(R.id.homePage).setBackgroundResource(R.drawable.bottom_sheet_dialog_button) view.findViewById<TextView>(R.id.homePage).setTextColor(resources.getColor(R.color.colorPrimary)) val intent = Intent(this, HomeActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) finish() view.findViewById<TextView>(R.id.classNotes).setBackgroundResource(0) view.findViewById<TextView>(R.id.remainders).setBackgroundResource(0) view.findViewById<TextView>(R.id.profile).setBackgroundResource(0) view.findViewById<TextView>(R.id.collegeMates).setBackgroundResource(0) view.findViewById<TextView>(R.id.rateUs).setBackgroundResource(0) view.findViewById<TextView>(R.id.logOut).setBackgroundResource(0) //dialog.dismiss() } view.findViewById<TextView>(R.id.classNotes).setOnClickListener { view.findViewById<TextView>(R.id.classNotes).setBackgroundResource(R.drawable.bottom_sheet_dialog_button) view.findViewById<TextView>(R.id.classNotes).setTextColor(resources.getColor(R.color.colorPrimary)) val intent = Intent(this, ClassNotesActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) finish() view.findViewById<TextView>(R.id.homePage).setBackgroundResource(0) view.findViewById<TextView>(R.id.remainders).setBackgroundResource(0) view.findViewById<TextView>(R.id.profile).setBackgroundResource(0) view.findViewById<TextView>(R.id.collegeMates).setBackgroundResource(0) view.findViewById<TextView>(R.id.rateUs).setBackgroundResource(0) view.findViewById<TextView>(R.id.logOut).setBackgroundResource(0) //dialog.dismiss() } view.findViewById<TextView>(R.id.remainders).setOnClickListener { view.findViewById<TextView>(R.id.remainders).setBackgroundResource(R.drawable.bottom_sheet_dialog_button) view.findViewById<TextView>(R.id.remainders).setTextColor(resources.getColor(R.color.colorPrimary)) val intent = Intent(this, ReminderActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) finish() view.findViewById<TextView>(R.id.homePage).setBackgroundResource(0) view.findViewById<TextView>(R.id.classNotes).setBackgroundResource(0) view.findViewById<TextView>(R.id.profile).setBackgroundResource(0) view.findViewById<TextView>(R.id.collegeMates).setBackgroundResource(0) view.findViewById<TextView>(R.id.rateUs).setBackgroundResource(0) view.findViewById<TextView>(R.id.logOut).setBackgroundResource(0) // dialog.dismiss() } view.findViewById<TextView>(R.id.profile).setOnClickListener { view.findViewById<TextView>(R.id.profile).setBackgroundResource(R.drawable.bottom_sheet_dialog_button) view.findViewById<TextView>(R.id.profile).setTextColor(resources.getColor(R.color.colorPrimary)) val intent = Intent(this, StudentProfileActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) finish() view.findViewById<TextView>(R.id.homePage).setBackgroundResource(0) view.findViewById<TextView>(R.id.classNotes).setBackgroundResource(0) view.findViewById<TextView>(R.id.remainders).setBackgroundResource(0) view.findViewById<TextView>(R.id.collegeMates).setBackgroundResource(0) view.findViewById<TextView>(R.id.rateUs).setBackgroundResource(0) view.findViewById<TextView>(R.id.logOut).setBackgroundResource(0) // dialog.dismiss() } view.findViewById<TextView>(R.id.rateUs).setOnClickListener { view.findViewById<TextView>(R.id.rateUs).setBackgroundResource(R.drawable.bottom_sheet_dialog_button) view.findViewById<TextView>(R.id.rateUs).setTextColor(resources.getColor(R.color.colorPrimary)) val intent = Intent(this, AboutActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) finish() view.findViewById<TextView>(R.id.homePage).setBackgroundResource(0) view.findViewById<TextView>(R.id.classNotes).setBackgroundResource(0) view.findViewById<TextView>(R.id.profile).setBackgroundResource(0) view.findViewById<TextView>(R.id.collegeMates).setBackgroundResource(0) view.findViewById<TextView>(R.id.remainders).setBackgroundResource(0) view.findViewById<TextView>(R.id.logOut).setBackgroundResource(0) // dialog.dismiss() } view.findViewById<TextView>(R.id.logOut).setOnClickListener { view.findViewById<TextView>(R.id.logOut).setBackgroundResource(R.drawable.bottom_sheet_dialog_button) view.findViewById<TextView>(R.id.logOut).setTextColor(resources.getColor(R.color.colorPrimary)) val logoutDialog = Dialog(this) logoutDialog.setContentView(R.layout.logout_dialog) logoutDialog.setCancelable(false) logoutDialog.setCanceledOnTouchOutside(false) logoutDialog.window!!.setBackgroundDrawableResource(android.R.color.transparent) logoutDialog.findViewById<Button>(R.id.btnLogout).setOnClickListener { val account = GoogleSignIn.getLastSignedInAccount(this) if (account != null) { //Some one is already logged in // Google sign out // Google sign out mGoogleSignInClient.signOut().addOnCompleteListener(this) { // Logout the user from session AppPreferences.isLogin = false AppPreferences.studentID = "" AppPreferences.studentName = "" val intent = Intent(this, AuthenticationActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) finish() } } else { // Logout the user from session AppPreferences.isLogin = false AppPreferences.studentID = "" AppPreferences.studentName = "" val intent = Intent(this, AuthenticationActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) finish() } } logoutDialog.findViewById<Button>(R.id.btnCancel).setOnClickListener { logoutDialog.dismiss() } logoutDialog.show() view.findViewById<TextView>(R.id.homePage).setBackgroundResource(0) view.findViewById<TextView>(R.id.classNotes).setBackgroundResource(0) view.findViewById<TextView>(R.id.profile).setBackgroundResource(0) view.findViewById<TextView>(R.id.collegeMates).setBackgroundResource(0) view.findViewById<TextView>(R.id.rateUs).setBackgroundResource(0) view.findViewById<TextView>(R.id.remainders).setBackgroundResource(0) // dialog.dismiss() } view.findViewById<TextView>(R.id.collegeMates).setOnClickListener { view.findViewById<TextView>(R.id.collegeMates).setBackgroundResource(R.drawable.bottom_sheet_dialog_button) view.findViewById<TextView>(R.id.collegeMates).setTextColor(resources.getColor(R.color.colorPrimary)) val intent = Intent(this, ClassMatesActivity::class.java) intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP startActivity(intent) finish() view.findViewById<TextView>(R.id.homePage).setBackgroundResource(0) view.findViewById<TextView>(R.id.classNotes).setBackgroundResource(0) view.findViewById<TextView>(R.id.profile).setBackgroundResource(0) view.findViewById<TextView>(R.id.remainders).setBackgroundResource(0) view.findViewById<TextView>(R.id.rateUs).setBackgroundResource(0) view.findViewById<TextView>(R.id.logOut).setBackgroundResource(0) // dialog.dismiss() } dialog.setContentView(view) //dialog.window!!.setBackgroundDrawableResource(android.R.color.transparent) dialog.show() } // Retrieving Data from Firebase Realtime Database retreiveClassNotesData() } private fun retreiveClassNotesData() { animationView.visibility = View.VISIBLE val myRef = FirebaseDatabase.getInstance().reference.child("students_data").orderByChild("studentID").equalTo(AppPreferences.studentID) val classMatesListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { if(dataSnapshot.exists()) { animationView.visibility = View.GONE for (ds in dataSnapshot.children) { val classMatesData = ds.getValue(StudentData::class.java) if (classMatesData != null) { classMatesList.add(classMatesData) } } val classMatesAdapter = ClassMatesAdapter(baseContext,classMatesList) linearLayoutManager.orientation = LinearLayoutManager.VERTICAL linearLayoutManager.reverseLayout = true linearLayoutManager.stackFromEnd = true classMatesRecycler.layoutManager = linearLayoutManager classMatesRecycler.setHasFixedSize(true) classMatesRecycler.adapter = classMatesAdapter classMatesAdapter.notifyDataSetChanged() } else { animationView.visibility = View.GONE noDataAnimation.visibility = View.VISIBLE } } override fun onCancelled(error: DatabaseError) { animationView.visibility = View.GONE noDataAnimation.visibility = View.VISIBLE Toast.makeText(baseContext,error.message, Toast.LENGTH_LONG).show() } } myRef.addValueEventListener(classMatesListener) } }
0
Kotlin
1
8
7624189eabbb449b00b2df8b89fad04c7649603f
14,776
Stumate
MIT License
http_server_jetty/src/test/kotlin/com/hexagonkt/http/HelloWorldTest.kt
mrpascal1
248,485,404
true
{"Kotlin": 421825, "HTML": 25440, "Scala": 3554, "JavaScript": 2701, "Dockerfile": 2196, "CSS": 1122, "Shell": 894}
package com.hexagonkt.http import com.hexagonkt.http.client.Client import com.hexagonkt.http.client.ahc.AhcAdapter import org.testng.annotations.AfterClass import org.testng.annotations.BeforeClass import org.testng.annotations.Test @Test class HelloWorldTest { private val client: Client by lazy { Client(AhcAdapter(), "http://localhost:${server.runtimePort}") } @BeforeClass fun initialize() { main() } @AfterClass fun shutdown() { server.stop() } @Test fun `Create book returns 201 and new book ID`() { val result = client.get("/hello") assert(result.body == "Hello World!") assert(200 == result.status) } }
0
Kotlin
0
0
9e26bc9400cf73b2c5ba1f77d6e1b732cd059f11
697
hexagon
MIT License
src/main/kotlin/no/nav/tilleggsstonader/klage/behandling/BehandlingService.kt
navikt
811,308,518
false
{"Kotlin": 599532, "Dockerfile": 202}
package no.nav.tilleggsstonader.klage.behandling import no.nav.familie.prosessering.internal.TaskService import no.nav.tilleggsstonader.klage.behandling.domain.Behandling import no.nav.tilleggsstonader.klage.behandling.domain.FagsystemRevurdering import no.nav.tilleggsstonader.klage.behandling.domain.Klagebehandlingsresultat import no.nav.tilleggsstonader.klage.behandling.domain.PåklagetVedtak import no.nav.tilleggsstonader.klage.behandling.domain.PåklagetVedtakDetaljer import no.nav.tilleggsstonader.klage.behandling.domain.StegType.BEHANDLING_FERDIGSTILT import no.nav.tilleggsstonader.klage.behandling.domain.erLåstForVidereBehandling import no.nav.tilleggsstonader.klage.behandling.domain.harManuellVedtaksdato import no.nav.tilleggsstonader.klage.behandling.dto.BehandlingDto import no.nav.tilleggsstonader.klage.behandling.dto.HenlagtDto import no.nav.tilleggsstonader.klage.behandling.dto.PåklagetVedtakDto import no.nav.tilleggsstonader.klage.behandling.dto.tilDto import no.nav.tilleggsstonader.klage.behandling.dto.tilPåklagetVedtakDetaljer import no.nav.tilleggsstonader.klage.behandlingshistorikk.BehandlingshistorikkService import no.nav.tilleggsstonader.klage.fagsak.FagsakService import no.nav.tilleggsstonader.klage.fagsak.domain.Fagsak import no.nav.tilleggsstonader.klage.felles.domain.SporbarUtils import no.nav.tilleggsstonader.klage.infrastruktur.exception.brukerfeilHvis import no.nav.tilleggsstonader.klage.infrastruktur.exception.feilHvis import no.nav.tilleggsstonader.klage.infrastruktur.exception.feilHvisIkke import no.nav.tilleggsstonader.klage.integrasjoner.FagsystemVedtakService import no.nav.tilleggsstonader.klage.kabal.KlageresultatRepository import no.nav.tilleggsstonader.klage.kabal.domain.tilDto import no.nav.tilleggsstonader.klage.oppgave.OppgaveTaskService import no.nav.tilleggsstonader.klage.repository.findByIdOrThrow import no.nav.tilleggsstonader.kontrakter.felles.Fagsystem import no.nav.tilleggsstonader.kontrakter.klage.BehandlingResultat import no.nav.tilleggsstonader.kontrakter.klage.BehandlingStatus.FERDIGSTILT import no.nav.tilleggsstonader.kontrakter.klage.KlageinstansResultatDto import org.slf4j.Logger import org.slf4j.LoggerFactory import org.springframework.stereotype.Service import org.springframework.transaction.annotation.Transactional import java.time.LocalDateTime import java.util.UUID @Service class BehandlingService( private val behandlingRepository: BehandlingRepository, private val fagsakService: FagsakService, private val klageresultatRepository: KlageresultatRepository, private val behandlinghistorikkService: BehandlingshistorikkService, private val oppgaveTaskService: OppgaveTaskService, private val taskService: TaskService, private val fagsystemVedtakService: FagsystemVedtakService, ) { val logger: Logger = LoggerFactory.getLogger(this::class.java) fun hentBehandling(behandlingId: UUID): Behandling = behandlingRepository.findByIdOrThrow(behandlingId) fun hentBehandlingDto(behandlingId: UUID): BehandlingDto { val fagsak = fagsakService.hentFagsakForBehandling(behandlingId) return behandlingRepository.findByIdOrThrow(behandlingId) .tilDto(fagsak, hentKlageresultatDto(behandlingId)) } fun opprettBehandling(behandling: Behandling): Behandling { return behandlingRepository.insert(behandling) } fun hentKlageresultatDto(behandlingId: UUID): List<KlageinstansResultatDto> { val klageresultater = klageresultatRepository.findByBehandlingId(behandlingId) return klageresultater.tilDto() } fun finnKlagebehandlingsresultat(eksternFagsakId: String, fagsystem: Fagsystem): List<Klagebehandlingsresultat> { return behandlingRepository.finnKlagebehandlingsresultat(eksternFagsakId, fagsystem) } fun hentAktivIdent(behandlingId: UUID): Pair<String, Fagsak> { val behandling = hentBehandling(behandlingId) val fagsak = fagsakService.hentFagsak(behandling.fagsakId) return Pair(fagsak.hentAktivIdent(), fagsak) } fun oppdaterBehandlingMedResultat( behandlingId: UUID, behandlingsresultat: BehandlingResultat, opprettetRevurdering: FagsystemRevurdering?, ) { val behandling = hentBehandling(behandlingId) if (behandling.resultat != BehandlingResultat.IKKE_SATT) { error("Kan ikke endre på et resultat som allerede er satt") } val oppdatertBehandling = behandling.copy( resultat = behandlingsresultat, vedtakDato = LocalDateTime.now(), fagsystemRevurdering = opprettetRevurdering, ) behandlingRepository.update(oppdatertBehandling) } @Transactional fun oppdaterPåklagetVedtak(behandlingId: UUID, påklagetVedtakDto: PåklagetVedtakDto) { val behandling = hentBehandling(behandlingId) brukerfeilHvis(behandling.status.erLåstForVidereBehandling()) { "Kan ikke oppdatere påklaget vedtak siden behandlingen er låst for videre saksbehandling" } feilHvisIkke(påklagetVedtakDto.erGyldig()) { "Påklaget vedtak er i en ugyldig tilstand: EksternFagsystemBehandlingId:${påklagetVedtakDto.eksternFagsystemBehandlingId}, PåklagetVedtakType: ${påklagetVedtakDto.påklagetVedtakstype}" } feilHvis(påklagetVedtakDto.manglerVedtaksDato()) { "Må fylle inn vedtaksdato når valgt vedtakstype er ${påklagetVedtakDto.påklagetVedtakstype}" } val påklagetVedtakDetaljer = påklagetVedtakDetaljer(behandlingId, påklagetVedtakDto) val behandlingMedPåklagetVedtak = behandling.copy( påklagetVedtak = PåklagetVedtak( påklagetVedtakstype = påklagetVedtakDto.påklagetVedtakstype, påklagetVedtakDetaljer = påklagetVedtakDetaljer, ), ) behandlingRepository.update(behandlingMedPåklagetVedtak) } private fun påklagetVedtakDetaljer( behandlingId: UUID, påklagetVedtakDto: PåklagetVedtakDto, ): PåklagetVedtakDetaljer? { if (påklagetVedtakDto.påklagetVedtakstype.harManuellVedtaksdato()) { return tilPåklagetVedtakDetaljerMedManuellDato(påklagetVedtakDto) } return påklagetVedtakDto.eksternFagsystemBehandlingId?.let { fagsystemVedtakService.hentFagsystemVedtakForPåklagetBehandlingId(behandlingId, it) .tilPåklagetVedtakDetaljer() } } private fun tilPåklagetVedtakDetaljerMedManuellDato(påklagetVedtakDto: PåklagetVedtakDto) = PåklagetVedtakDetaljer( eksternFagsystemBehandlingId = null, behandlingstype = "", resultat = "", vedtakstidspunkt = påklagetVedtakDto.manuellVedtaksdato?.atStartOfDay() ?: error("Mangler vedtaksdato"), ) @Transactional fun henleggBehandling(behandlingId: UUID, henlagt: HenlagtDto) { val behandling = hentBehandling(behandlingId) validerKanHenleggeBehandling(behandling) val henlagtBehandling = behandling.copy( henlagtÅrsak = henlagt.årsak, resultat = BehandlingResultat.HENLAGT, steg = BEHANDLING_FERDIGSTILT, status = FERDIGSTILT, vedtakDato = SporbarUtils.now(), ) behandlinghistorikkService.opprettBehandlingshistorikk(behandlingId, BEHANDLING_FERDIGSTILT) oppgaveTaskService.lagFerdigstillOppgaveForBehandlingTask(behandling.id) behandlingRepository.update(henlagtBehandling) // TODO: Utkommenter denne etter at BehandlingsstatistikkTask er re-implementert // taskService.save(taskService.save(BehandlingsstatistikkTask.opprettFerdigTask(behandlingId = behandlingId))) } private fun validerKanHenleggeBehandling(behandling: Behandling) { brukerfeilHvis(behandling.status.erLåstForVidereBehandling()) { "Kan ikke henlegge behandling med status ${behandling.status}" } } }
2
Kotlin
0
0
d924d2e653546832fb135b28595d0eb181d107a3
8,002
tilleggsstonader-klage
MIT License
app/src/main/java/org/kaqui/mainmenu/VocabularyMenuActivity.kt
btp
180,280,286
false
null
package org.kaqui.mainmenu import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Gravity import android.widget.TextView import org.jetbrains.anko.* import org.kaqui.R import org.kaqui.menuWidth import org.kaqui.model.TestType import org.kaqui.settings.JlptSelectionActivity import org.kaqui.startTest import java.io.Serializable class VocabularyMenuActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) verticalLayout { gravity = Gravity.CENTER scrollView { verticalLayout { padding = dip(8) imageView(R.drawable.kakugo).lparams(width = matchParent, height = dip(80)) { margin = dip(8) } verticalLayout { button(R.string.word_reading_quizz) { setOnClickListener { startTest(this@VocabularyMenuActivity, TestType.WORD_TO_READING) } }.lparams(width = matchParent, height = wrapContent) { margin = dip(8) } button(R.string.reading_word_quizz) { setOnClickListener { startTest(this@VocabularyMenuActivity, TestType.READING_TO_WORD) } }.lparams(width = matchParent, height = wrapContent) { margin = dip(8) } button(R.string.word_meaning_quizz) { setOnClickListener { startTest(this@VocabularyMenuActivity, TestType.WORD_TO_MEANING) } }.lparams(width = matchParent, height = wrapContent) { margin = dip(8) } button(R.string.meaning_word_quizz) { setOnClickListener { startTest(this@VocabularyMenuActivity, TestType.MEANING_TO_WORD) } }.lparams(width = matchParent, height = wrapContent) { margin = dip(8) } button(R.string.word_selection) { setOnClickListener { startActivity<JlptSelectionActivity>("mode" to JlptSelectionActivity.Mode.WORD as Serializable) } }.lparams(width = matchParent, height = wrapContent) { margin = dip(8) } } } }.lparams(width = menuWidth) } } }
0
Kotlin
0
0
9d828245c1726a9cca8a085d8b736862a1b75457
2,641
kakngo
MIT License
cobalt.core/src/commonMain/kotlin/org/hexworks/cobalt/core/platform/factory/IdentifierFactory.kt
cobalt
155,008,361
false
null
package org.hexworks.cobalt.core.platform.factory import org.hexworks.cobalt.core.api.Identifier expect object IdentifierFactory { fun randomIdentifier(): Identifier fun fromString(str: String): Identifier }
0
Kotlin
5
5
51fc64a311cfb7fffdd5e1b7ccdb64319f7602f1
220
cobalt
Apache License 2.0
app/src/main/java/com/msomodi/imageverse/model/auth/request/RegisterRequest.kt
MarioSomodi
602,268,671
false
{"Kotlin": 274194}
package com.msomodi.imageverse.model.auth.request import kotlinx.serialization.Serializable @Serializable data class RegisterRequest( val username : String, val name : String, val surname : String, val email : String, val password : String, val packageId : String, val profileImage : String?, val authenticationProviderId : String?, val AuthenticationType : Int )
0
Kotlin
0
0
879469f59f4417f3a3e3d1de63d31723f81fb2b4
402
Imageverse
MIT License
intellijPlugin/src/main/kotlin/pw/binom/fbx/file/FbxUtils.kt
caffeine-mgn
223,796,620
false
null
package pw.binom.fbx.file import org.joml.Math import org.joml.Vector3f import org.joml.Vector3fc fun FbxRoot.connectionByValue(value: Long) = get("Connections").single().get("C").map { if (it.properties[2] as Long == value) it.properties[1] as Long else null }.filterNotNull() fun FbxRoot.connectionByKey(key: Long) = get("Connections").single().get("C").map { if (it.properties[1] as Long == key) it.properties[2] as Long else null }.filterNotNull() fun FbxRoot.connectionByKeyEx(key: Long) = get("Connections").single().get("C").map { if (it.properties[1] as Long == key) it else null }.filterNotNull() fun FbxRoot.getModels() = get("Objects").first().get("Model").map { val id = it.properties[0] as Long val translation = Vector3f(0f, 0f, 0f) val scale = Vector3f(1f, 1f, 1f) val rotation = Vector3f(0f, 0f, 0f) it.get("Properties70").first().get("P").forEach { when (it.properties[0] as String) { "Lcl Translation" -> translation.set(it.double(4).toFloat(), it.double(5).toFloat(), it.double(6).toFloat()) "Lcl Scaling" -> scale.set(it.double(4).toFloat(), it.double(5).toFloat(), it.double(6).toFloat()) "Lcl Rotation" -> rotation.set( Math.toRadians(it.double(4)).toFloat(), Math.toRadians(it.double(5)).toFloat(), Math.toRadians(it.double(6)).toFloat() ) } } FbxModel(id = id, position = translation, rotation = rotation, scale = scale, name = it.properties[1] as String) } class FbxModel(val id: Long, val name: String, val position: Vector3fc, val scale: Vector3fc, val rotation: Vector3fc)
6
Kotlin
0
4
e673acfcb20e2d62d8e68c43d395731bd9d9d882
1,876
mogot
Apache License 2.0
app/src/main/java/me/qcuncle/nowinnews/util/WebViewPool.kt
QCuncle
768,718,477
false
{"Kotlin": 313407}
package me.qcuncle.nowinnews.util import android.annotation.SuppressLint import android.app.Application import android.os.Looper import android.util.Log import android.webkit.WebResourceRequest import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlin.coroutines.resume import kotlin.coroutines.suspendCoroutine object WebViewCachePool { private lateinit var application: Application private val looper = Looper.getMainLooper() private val webViewMap = hashMapOf<String, WebView>() private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob()) fun init(application: Application) { this.application = application } @SuppressLint("SetJavaScriptEnabled") private fun getOrCreateWebView(url: String, onCreated: (WebView) -> Unit) { Log.d("getOrCreateWebView", url) return if (webViewMap[url] != null) { onCreated(webViewMap[url]!!) } else { looper.queue.addIdleHandler { val webView = WebView(application) webView.settings.apply { // 禁用缩放 setSupportZoom(false) builtInZoomControls = false displayZoomControls = false loadsImagesAutomatically = false mediaPlaybackRequiresUserGesture = false mixedContentMode = WebSettings.MIXED_CONTENT_NEVER_ALLOW cacheMode = WebSettings.LOAD_DEFAULT javaScriptEnabled = true domStorageEnabled = true userAgentString = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0" } webView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading( view: WebView?, request: WebResourceRequest? ): Boolean { return false } } webViewMap[url] = webView onCreated(webView) false } } } suspend fun loadAndRetrieveHtmlContent(url: String, delay: Long): String { var resumed = false // 添加一个标志来确保 resume 只被调用一次 return withContext(Dispatchers.IO) { suspendCoroutine { continuation -> getOrCreateWebView(url) { webView -> coroutineScope.launch { webView.apply { webViewClient = object : WebViewClient() { override fun onPageFinished(view: WebView?, url: String?) { coroutineScope.launch { delay(delay) webView.evaluateJavascript( "(function() { return '<html>' + document.getElementsByTagName('html')[0].innerHTML + '</html>'; })();" ) { value -> if (!resumed) { resumed = true continuation.resume(value) webView.stopLoading() } } } } } getUrl()?.let { reload() } ?: run { loadUrl(url) } } } } } } } }
0
Kotlin
0
7
2105632328876c3c23349470c05a0b7cde226931
4,187
nowinnews
Apache License 2.0
src/main/kotlin/enum/Cargo.kt
GabrielDragone
594,284,484
false
null
package enum enum class Cargo { ASSISTENTE { override fun getProximoCargo(): Cargo { return ANALISTA } }, ANALISTA { override fun getProximoCargo(): Cargo { return ESPECIALISTA } }, ESPECIALISTA { override fun getProximoCargo(): Cargo { return GERENTE } }, GERENTE { override fun getProximoCargo(): Cargo { return GERENTE } }; abstract fun getProximoCargo(): Cargo // abstract pra forçarmos a implementação em cima de cada Constantes acima. }
0
Kotlin
0
0
6e9ab912d4fb05ceb634b702a5ab123a3341c4f2
592
solid-kotlin-example
MIT License
app/src/main/java/com/romandevyatov/bestfinance/viewmodels/foreachmodel/TransferHistoryViewModel.kt
RomanDevyatov
587,557,441
false
null
package com.romandevyatov.bestfinance.viewmodels.foreachmodel import androidx.lifecycle.LiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.romandevyatov.bestfinance.db.entities.TransferHistory import com.romandevyatov.bestfinance.repositories.TransferHistoryRepository import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class TransferHistoryViewModel @Inject constructor( private val transferHistoryRepository: TransferHistoryRepository ) : ViewModel() { val transferHistoriesLiveData: LiveData<List<TransferHistory>> = transferHistoryRepository.getAllTransferHistories() val notArchivedTransferHistoriesLiveData: LiveData<List<TransferHistory>> = transferHistoryRepository.getAllTransferHistoriesByArchivedDate(null) fun insertTransferHistory(transferHistory: TransferHistory) = viewModelScope.launch(Dispatchers.IO) { transferHistoryRepository.insertTransferHistory(transferHistory) } fun updateTransferHistory(transferHistory: TransferHistory) = viewModelScope.launch(Dispatchers.IO) { transferHistoryRepository.updateTransferHistory(transferHistory) } fun deleteTransferHistory(transferHistory: TransferHistory) = viewModelScope.launch(Dispatchers.IO) { transferHistoryRepository.deleteTransferHistory(transferHistory) } }
0
Kotlin
0
1
b810131126c84cd6daf6fcfb86b700ece556fd5b
1,462
BestFinance
Apache License 2.0
dbflow-tests/src/test/java/com/raizlabs/android/dbflow/test/example/Breed.kt
junyuecao
85,771,215
true
{"Java": 603671, "Kotlin": 575680}
package com.raizlabs.android.dbflow.test.example import com.raizlabs.android.dbflow.annotation.PrimaryKey import com.raizlabs.android.dbflow.annotation.Table import com.raizlabs.android.dbflow.structure.BaseModel import com.raizlabs.android.dbflow.test.TestDatabase /** * Description: */ @Table(database = TestDatabase::class) class Breed : BaseModel() { @PrimaryKey var breed_id: Long = 0 }
0
Java
0
0
42fdeb4e00d73ef24a8721ff87d394581911611b
405
DBFlow
MIT License
app/src/main/java/com/lee/toollibrary/adapters/ViewAdapter.kt
leenickcode
145,098,316
false
{"Java": 518714, "Kotlin": 180501}
package com.lee.toollibrary.adapters import android.content.Context import android.view.ViewGroup import com.lee.mylibrary.BaseRecyclerViewAdapter import com.lee.mylibrary.UniversalViewHolder import com.lee.toollibrary.R import kotlinx.android.synthetic.main.item_views.view.* /** * Created by nick on 2018/8/15. * 自定义view列表适配器 * @author nick */ class ViewAdapter(mContext: Context?, mDefaultItemLayoutId: Int) : BaseRecyclerViewAdapter<String>(mContext, mDefaultItemLayoutId) { override fun bindData(holder: UniversalViewHolder?, position: Int, bean: String?) { holder?.getTextView(R.id.textView)?.text= bean } override fun setItemChildListener(helper: UniversalViewHolder?, viewType: Int) { helper?.setItemChildOnClickListener(R.id.textView) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): UniversalViewHolder { print("恩航") return super.onCreateViewHolder(parent, viewType) } override fun setData(data: MutableList<String>?) { super.setData(data) } }
1
null
1
1
df867f9a851826d5e1354bb72e605272932cc0c9
1,056
ToolLibrary
Apache License 2.0
app/src/main/java/com/dreamsoftware/fudge/component/player/audio/FudgeTvAudioPlayerControllerIndicator.kt
sergio11
189,831,547
false
{"Kotlin": 186613}
package com.dreamsoftware.fudge.component.player.audio import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Devices import androidx.compose.ui.tooling.preview.Preview import com.dreamsoftware.fudge.component.player.FudgeTvPlayerControllerIndicator @Composable fun FudgeTvAudioPlayerControllerIndicator( progress: Float, onSeek: (seekProgress: Float) -> Unit, modifier: Modifier = Modifier, ) { var isSelected by remember { mutableStateOf(false) } FudgeTvPlayerControllerIndicator( progress = progress, onSeek = onSeek, isSelected = isSelected, onSelected = { isSelected = !isSelected }, modifier = modifier ) } @Preview(device = Devices.TV_1080p) @Composable fun PreviewAudioPlayerControllerIndicator() { FudgeTvAudioPlayerControllerIndicator(progress = 1f, {}) }
0
Kotlin
2
4
700078433b12fd52452fe6252749825688d29f29
1,074
fudge_tv_compose_library
MIT License
app/src/main/java/com/example/speedrun/network/model/dto/GamesDataResponseDto.kt
alejandromr92
171,358,320
false
null
package com.example.speedrun.network.model.dto import com.google.gson.annotations.SerializedName data class GamesDataResponseDto ( val data: List<GameDataDto> ) data class GameDataDto( val id: String, val assets: GameAssets, val names: GameNames ) data class GameNames( val international: String ) data class GameAssets( @SerializedName("cover-large") val cover_large: GameCover ) data class GameCover( val uri: String ) data class GameRunResponseDto( val data: List<GameRunDto> ) data class GameRunDto( val videos: GameRunVideoDto, val times: GameRunTimeDto, val players: List<GameRunPlayer> ) data class GameRunVideoDto( val links: List<GameRunLink> ) data class GameRunLink( val uri: String ) data class GameRunTimeDto( val primary: String ) data class GameRunPlayer( val id: String )
0
Kotlin
0
0
56654f13567957711e39b08405f3d305bb997dfc
860
SpeedRun
Apache License 2.0
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/structured_concurrency/1_coroutines_need_to_be_started_in_scope.kt
rafaykt
377,293,866
false
null
package com.lukaslechner.coroutineusecasesonandroid.playground.structured_concurrency import kotlinx.coroutines.* val scope = CoroutineScope(Dispatchers.Default) fun main() = runBlocking { val job = scope.launch{ delay(100) println("Coroutine completed") } job.invokeOnCompletion { throwable-> if(throwable is CancellationException){ println("Coroutine was cancelled") } } delay(50) onDestroy() } fun onDestroy() { println("Life-time of scope ends here") scope.cancel() }
0
Kotlin
0
0
dd51eb77d03b60c16b854c1cba607854ee3e74fb
561
coroutine_mastering
Apache License 2.0
feature/pick-color/src/main/java/ru/tech/imageresizershrinker/feature/pick_color/presentation/viewModel/PickColorViewModel.kt
T8RIN
478,710,402
false
null
/* * ImageToolbox is an image editor for android * Copyright (c) 2024 T8RIN (<NAME>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the 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. * * You should have received a copy of the Apache License * along with this program. If not, see <http://www.apache.org/licenses/LICENSE-2.0>. */ package ru.tech.imageresizershrinker.feature.pick_color.presentation.viewModel import android.graphics.Bitmap import android.net.Uri import androidx.compose.runtime.MutableState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.ui.graphics.Color import androidx.exifinterface.media.ExifInterface import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import ru.tech.imageresizershrinker.core.domain.dispatchers.DispatchersHolder import ru.tech.imageresizershrinker.core.domain.image.ImageGetter import ru.tech.imageresizershrinker.core.domain.image.ImageScaler import ru.tech.imageresizershrinker.core.ui.utils.BaseViewModel import javax.inject.Inject @HiltViewModel class PickColorViewModel @Inject constructor( private val imageGetter: ImageGetter<Bitmap, ExifInterface>, private val imageScaler: ImageScaler<Bitmap>, dispatchersHolder: DispatchersHolder ) : BaseViewModel(dispatchersHolder) { private val _bitmap: MutableState<Bitmap?> = mutableStateOf(null) val bitmap: Bitmap? by _bitmap private val _color: MutableState<Color> = mutableStateOf(Color.Unspecified) val color: Color by _color private val _uri = mutableStateOf<Uri?>(null) val uri by _uri fun setUri( uri: Uri, onError: (Throwable) -> Unit ) { _uri.value = uri viewModelScope.launch { runCatching { updateBitmap( imageGetter.getImage( data = uri, originalSize = false ) ) }.onFailure(onError) } } private fun updateBitmap(bitmap: Bitmap?) { viewModelScope.launch { _isImageLoading.value = true _bitmap.value = imageScaler.scaleUntilCanShow(bitmap) _isImageLoading.value = false } } fun updateColor(color: Color) { _color.value = color } }
27
null
95
3,817
486410d4a9ea3c832fc5aa63eb5bdc7b1fab871d
2,723
ImageToolbox
Apache License 2.0
app/src/main/java/app/simple/peri/utils/StringUtils.kt
Hamza417
667,998,169
false
{"Kotlin": 197196, "Java": 27255}
package app.simple.peri.utils object StringUtils { fun String?.endsWithAny(vararg strings: String): Boolean { strings.forEach { if (this?.endsWith(it) == true) { return true } } return false } }
3
Kotlin
1
98
406114eb0de0fcc80c1e5c9df86ae44a8eea2eb3
268
Peristyle
Apache License 2.0
android/src/com/android/tools/idea/welcome/wizard/MissingSdkAlertStep.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.welcome.wizard import com.android.tools.idea.wizard.model.ModelWizardStep import com.intellij.ui.layout.panel import javax.swing.JComponent /** * Step to show a message that the SDK is missing. */ class MissingSdkAlertStep : ModelWizardStep.WithoutModel("Missing SDK") { private val panel = panel { row { label("No Android SDK found.", bold = true) } row { label("Before continuing, you must download the necessary components or select an existing SDK.") } } override fun getComponent(): JComponent = panel }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
1,198
android
Apache License 2.0
web/src/jsMain/kotlin/de/jensklingenberg/sheasy/web/model/DrawerItems.kt
Foso
129,130,317
false
{"Markdown": 12, "Gradle": 13, "INI": 3, "YAML": 7, "Java Properties": 3, "Proguard": 2, "Shell": 3, "Text": 6, "Ignore List": 5, "Batchfile": 3, "Git Attributes": 1, "Kotlin": 329, "XML": 156, "Java": 2, "CSS": 18, "HTML": 17, "JavaScript": 27, "JSON": 3, "Gradle Kotlin DSL": 1, "JAR Manifest": 1, "OASv2-yaml": 3, "PlantUML": 1}
package de.jensklingenberg.sheasy.web.model import de.jensklingenberg.sheasy.web.model.StringRes.Companion.TOOLBAR_ABOUT import de.jensklingenberg.sheasy.web.model.StringRes.Companion.TOOLBAR_APPS import de.jensklingenberg.sheasy.web.model.StringRes.Companion.TOOLBAR_HOME import de.jensklingenberg.sheasy.web.model.StringRes.Companion.TOOLBAR_SHARE enum class DrawerItems(val title: String, val destination: String) { HOME(TOOLBAR_HOME, Navigation.navigateToHome), APPS(TOOLBAR_APPS, Navigation.navigateToApps), FILES("Files", Navigation.navigateToFiles), SHARE(TOOLBAR_SHARE, Navigation.navigateToShare), ABOUT(TOOLBAR_ABOUT, Navigation.navigateToAbout) }
1
Kotlin
4
36
069989f8c92924b7db3b7744fe54f73e2e138463
679
Sheasy
Apache License 2.0
src/main/kotlin/masternetworkmanager/handler/action/UpdateGoboImage.kt
BAC2-Graf-Rohatynski
208,084,545
false
null
package masternetworkmanager.handler.action import masternetworkmanager.slave.modifier.UpdateGoboImage import apibuilder.network.UpdateGoboImageItem import databaseclient.action.GoboAction import enumstorage.database.DatabaseCommand import masternetworkmanager.handler.interfaces.ICommandHandlerAction import org.slf4j.Logger import org.slf4j.LoggerFactory object UpdateGoboImage: ICommandHandlerAction { private val logger: Logger = LoggerFactory.getLogger(UpdateGoboImage::class.java) private lateinit var goboItem: UpdateGoboImageItem @Synchronized override fun run(): Any { logger.info("Command '${DatabaseCommand.UpdateDeviceById.name}' will be executed ...") GoboAction.updateItemById(item = goboItem.item) return UpdateGoboImage.update(fileName = goboItem.item.fileName, ipAddress = goboItem.ipAddress) } @Synchronized override fun build(message: String): ICommandHandlerAction { goboItem = UpdateGoboImageItem().toObject(message = message) return this } }
0
Kotlin
0
0
4c39c7718fdab9e0cdf4f275f3f9dab9d2f3085f
1,039
MasterNetworkManager
MIT License
code/src/main/kotlin/com/expediagroup/sdk/rapid/models/Area.kt
ExpediaGroup
774,903,007
false
{"Kotlin": 1589222}
/* * Copyright (C) 2022 Expedia, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. * */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport", ) package com.expediagroup.sdk.rapid.models import com.fasterxml.jackson.annotation.JsonProperty import org.hibernate.validator.constraints.Length import javax.validation.Valid import javax.validation.constraints.Max import javax.validation.constraints.Min import javax.validation.constraints.Pattern import javax.validation.constraints.Size /** * Information about the area of the room. * @param squareMeters The room's area, measured in square meters. * @param squareFeet The room's area, measured in square feet. */ data class Area( // The room's area, measured in square meters. @JsonProperty("square_meters") @field:Valid val squareMeters: java.math.BigDecimal? = null, // The room's area, measured in square feet. @JsonProperty("square_feet") @field:Valid val squareFeet: java.math.BigDecimal? = null, ) { companion object { @JvmStatic fun builder() = Builder() } class Builder( private var squareMeters: java.math.BigDecimal? = null, private var squareFeet: java.math.BigDecimal? = null, ) { fun squareMeters(squareMeters: java.math.BigDecimal?) = apply { this.squareMeters = squareMeters } fun squareFeet(squareFeet: java.math.BigDecimal?) = apply { this.squareFeet = squareFeet } fun build(): Area { return Area( squareMeters = squareMeters, squareFeet = squareFeet, ) } } fun toBuilder() = Builder( squareMeters = squareMeters, squareFeet = squareFeet, ) }
6
Kotlin
1
3
eb9676760e9f60ef98fb912cee2401f2e50a8019
2,461
rapid-java-sdk
Apache License 2.0
testdata/example-print/example-print-01.kt
thumannw
454,522,002
true
{"Kotlin": 99539}
// This file was automatically generated from example-print.in.md by Knit tool. Do not edit. package com.example.examplePrint01 fun main() { "OW".replace('W', 'K') .let { println(it) } }
0
null
0
0
35c55522f1982164764e57fe15fbfe11ec519fbe
198
kotlinx-knit
Apache License 2.0
plugin-azure-server/src/test/kotlin/jetbrains/buildServer/clouds/azure/arm/web/update/UpdateImageControllerTest.kt
JetBrains
22,468,117
false
{"Kotlin": 566528, "Java": 114877, "JavaScript": 97208, "CSS": 2805}
package jetbrains.buildServer.clouds.azure.arm.web.update import io.mockk.MockKAnnotations import io.mockk.Runs import io.mockk.every import io.mockk.impl.annotations.InjectMockKs import io.mockk.impl.annotations.MockK import io.mockk.just import io.mockk.mockk import jetbrains.buildServer.serverSide.SBuildServer import jetbrains.buildServer.web.openapi.WebControllerManager import org.assertj.core.api.Assertions import org.testng.annotations.BeforeMethod import org.testng.annotations.Test import java.io.ByteArrayOutputStream import java.util.* import java.util.stream.Collectors import javax.servlet.ServletOutputStream import javax.servlet.WriteListener import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse class UpdateImageControllerTest { @MockK private lateinit var server: SBuildServer @MockK private lateinit var webControllerManager: WebControllerManager @MockK private lateinit var updateImageProcessor: UpdateImageProcessor @InjectMockKs private lateinit var updateImageController: UpdateImageController @BeforeMethod fun setUp() = run { MockKAnnotations.init(this, relaxUnitFun = true) every { webControllerManager.registerController(any(), any()) } just Runs } @Test fun testWrongHttpVerb() { val req = mockk<HttpServletRequest>() every { req.method } returns "GET" val resp = mockk<HttpServletResponse>(relaxed = true) every { resp.setHeader(any(), any()) } just Runs val stream = TestServletOutputStream() every { resp.outputStream } returns stream updateImageController.handleRequest(req, resp) stream.flush() val res = stream.out.toString("UTF-8") Assertions.assertThat(res).contains("GET is not supported") } @Test fun testMissingProperties() { val req = mockk<HttpServletRequest>() every { req.method } returns "POST" every { req.parameterMap } returns emptyMap() val resp = mockk<HttpServletResponse>(relaxed = true) every { resp.setHeader(any(), any()) } just Runs val stream = TestServletOutputStream() every { resp.outputStream } returns stream updateImageController.handleRequest(req, resp) stream.flush() val res = stream.out.toString("UTF-8") val requiredProps = EnumSet.allOf(ImageUpdateProperties::class.java) .stream() .map { it.propertyName } .collect(Collectors.toList()) Assertions.assertThat(res).contains("Missing required properties for the images data update: $requiredProps") } @Test fun runsNormally() { val req = mockk<HttpServletRequest>() every { req.method } returns "POST" val map = EnumSet.allOf(ImageUpdateProperties::class.java) .map { "prop:" + it.propertyName } .associateWith { arrayOf(UUID.randomUUID().toString()) } every { req.parameterMap } returns map every { req.getParameter(any()) } returns "prop:someProp" val resp = mockk<HttpServletResponse>(relaxed = true) every { resp.setHeader(any(), any()) } just Runs every { updateImageProcessor.processImageUpdate(any()) } returns UpdateImageResult("encrypted_val") val stream = TestServletOutputStream() every { resp.outputStream } returns stream updateImageController.handleRequest(req, resp) stream.flush() val res = stream.out.toString("UTF-8") Assertions.assertThat(res).contains("<passwords_data>") } @Test fun exceptionInServerLogic() { val req = mockk<HttpServletRequest>() every { req.method } returns "POST" val map = EnumSet.allOf(ImageUpdateProperties::class.java) .map { "prop:" + it.propertyName } .associateWith { arrayOf(UUID.randomUUID().toString()) } every { req.parameterMap } returns map every { req.getParameter(any()) } returns "prop:someProp" val resp = mockk<HttpServletResponse>(relaxed = true) every { resp.setHeader(any(), any()) } just Runs every { updateImageProcessor.processImageUpdate(any()) } throws RuntimeException() val stream = TestServletOutputStream() every { resp.outputStream } returns stream updateImageController.handleRequest(req, resp) stream.flush() val res = stream.out.toString("UTF-8") Assertions.assertThat(res).contains("Unexpected exception during the images data update") } } class TestServletOutputStream : ServletOutputStream() { val out = ByteArrayOutputStream() override fun write(b: Int) { out.write(b) } override fun isReady(): Boolean { return true } override fun setWriteListener(p0: WriteListener?) { } }
19
Kotlin
22
48
253adaa64d9f541d361f419d91594844cfb26715
4,884
teamcity-azure-agent
Apache License 2.0
app/src/test/kotlin/com/adesso/movee/scene/moviedetail/MovieDetailViewModelTest.kt
adessoTurkey
291,657,858
false
null
package com.adesso.movee.scene.moviedetail import androidx.arch.core.executor.testing.InstantTaskExecutorRule import com.adesso.movee.domain.FetchMovieDetailFlowUseCase import com.adesso.movee.internal.popup.PopupModel import com.adesso.movee.internal.util.Failure import com.adesso.movee.scene.moviedetail.model.MovieDetailUiModel import com.adesso.movee.scene.movielist.model.MovieGenreItemUiModel import io.mockk.MockKAnnotations import io.mockk.impl.annotations.MockK import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.TestCoroutineDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain import org.junit.After import org.junit.Before import org.junit.Rule @ExperimentalCoroutinesApi class MovieDetailViewModelTest { private val mockMovieDetailSuccessUIModel = MovieDetailUiModel( id = 100, title = "Joker", overview = "Joker Overview", posterPath = "https...", average = "Joker Average", runtime = "122 min", releaseDate = "10.07.1990", popularity = "9.0", genres = listOf(MovieGenreItemUiModel(id = 122, name = "Drama")) ) private val apiErrorMessage = "Undefined Movie ID" private val mockMovieDetailFailureModel = Failure.NetworkError(message = apiErrorMessage) private val exceptedFailurePopupModel = PopupModel(message = apiErrorMessage) @get:Rule val instantExecutorRule = InstantTaskExecutorRule() private lateinit var viewModel: MovieDetailViewModel @MockK lateinit var useCase: FetchMovieDetailFlowUseCase private val testDispatcher = TestCoroutineDispatcher() @Before fun setup() { Dispatchers.setMain(testDispatcher) MockKAnnotations.init(this) viewModel = MovieDetailViewModel(useCase) } @After fun tearDown() { Dispatchers.resetMain() testDispatcher.cleanupTestCoroutines() } }
1
Kotlin
13
88
e5f2d152f9330f7162beff85b37e07fd155407ea
2,000
android-boilerplate
Apache License 2.0
src/commonMain/kotlin/at/asitplus/io/BaseN.kt
a-sit-plus
830,902,417
false
{"Kotlin": 18326}
/* Originally created by Protocol labs, published at GitHub: https://github.com/changjiashuai/kotlin-multibase under the terms of the MIT License. Slightly tweaked to allow for multiplatform use in 2024 by A-SIT Plus GmbH Copyright (c) 2018-2022 Protocol Labs 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 at.asitplus.io import com.ionspin.kotlin.bignum.integer.BigInteger import com.ionspin.kotlin.bignum.integer.Sign import io.matthewnelson.encoding.base16.Base16 import io.matthewnelson.encoding.base32.Base32Default import io.matthewnelson.encoding.base32.Base32Hex import io.matthewnelson.encoding.base64.Base64 import io.matthewnelson.encoding.base64.Base64ConfigBuilder import io.matthewnelson.encoding.core.Decoder.Companion.decodeToByteArray import io.matthewnelson.encoding.core.Encoder.Companion.encodeToString import io.matthewnelson.encoding.core.EncodingException /** * Use this to manually encode/decode BaseN, but only if you know what you're doing! * Originally created by [CJS](mailto:<EMAIL>) on 2018/7/14 without documentation and since -- even though * it is extremely versatile -- it performs poorly, we better keep it like that. After all, we don't want to tempt * folk to produce code that performs poorly. */ object BaseN { fun decode(alphabet: String, base: BigInteger, input: String): ByteArray { val bytes = decodeToBigInteger(alphabet, base, input).toByteArray() val stripSignByte = bytes.size > 1 && bytes[0].compareTo(0) == 0 && bytes[1] < 0 var leadingZeros = 0 var i = 0 while (input[i] == alphabet[0]) { leadingZeros++ i++ } val tmp = ByteArray(bytes.size - (if (stripSignByte) 1 else 0) + leadingZeros) bytes.copyInto( tmp, startIndex = if (stripSignByte) 1 else 0, destinationOffset = leadingZeros, endIndex = tmp.size - leadingZeros ) return tmp } fun encode(alphabet: String, base: BigInteger, input: ByteArray): String { var bi = BigInteger.fromByteArray(input, Sign.POSITIVE) val sb = StringBuilder() while (bi >= base) { //求余 val mod = bi.mod(base) sb.insert(0, alphabet[mod.intValue()]) bi = bi.subtract(mod).divide(base) } sb.insert(0, alphabet[bi.intValue()]) //convert leading zeros. for (b in input) { if (b.compareTo(0) == 0) { sb.insert(0, alphabet[0]) } else { break } } return sb.toString() } fun decodeToBigInteger(alphabet: String, base: BigInteger, input: String): BigInteger { var bi = BigInteger.ZERO for (i in input.length - 1 downTo 0) { val alphaIndex = alphabet.indexOf(input[i]) if (alphaIndex == -1) { throw EncodingException("Illegal character " + input[i] + " at " + i) } bi = bi.add(BigInteger.fromLong(alphaIndex.toLong()).multiply(base.pow(input.length - 1 - i))) } return bi } } /** * [RFC4648](https://www.ietf.org/rfc/rfc4648.txt) Multibase encoder/decoder * Initially Created by [CJS](mailto:<EMAIL>) on 2018/7/12. */ object MultiBase { /** * Multibase encoding identifier. * Each multibase-encoded string is identified by a [prefix], followed by data composed of [alphabet] characters. * The prefix is also part of the alphabet. See also [RFC4648](https://www.ietf.org/rfc/rfc4648.txt). */ enum class Base(val prefix: Char, val alphabet: String) { BASE10('9', "0123456789"), BASE16('f', "0123456789abcdef"), BASE16_UPPER('F', "0123456789ABCDEF"), BASE32('b', "abcdefghijklmnopqrstuvwxyz234567"), BASE32_UPPER('B', "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"), BASE32_PAD('c', "abcdefghijklmnopqrstuvwxyz234567="), BASE32_PAD_UPPER('C', "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567="), BASE32_HEX('v', "0123456789abcdefghijklmnopqrstuvw"), BASE32_HEX_UPPER('V', "0123456789ABCDEFGHIJKLMNOPQRSTUVW"), BASE32_HEX_PAD('t', "0123456789abcdefghijklmnopqrstuvw="), BASE32_HEX_PAD_UPPER('T', "0123456789ABCDEFGHIJKLMNOPQRSTUVW="), BASE58_FLICKR('Z', "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"), BASE58_BTC('z', "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"), BASE64('m', "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"), BASE64_URL('u', "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"), BASE64_PAD('M', "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="), BASE64_URL_PAD('U', "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_="); companion object { /** * Returns a [Base] matching the provided [prefix] or `null` if none was found. */ fun lookup(prefix: Char): Base? { return entries.firstOrNull { it.prefix == prefix } } } } /** * Encodes the given [data] into the specified [base]. */ fun encode(base: Base, data: ByteArray): String { return when (base) { Base.BASE10 -> base.prefix + BaseN.encode(base.alphabet, BigInteger(10), data) Base.BASE16 -> base.prefix + data.encodeToString(Base16Lower) Base.BASE16_UPPER -> base.prefix + data.encodeToString(Base16Upper) Base.BASE32 -> base.prefix + data.encodeToString(Base32Lower) Base.BASE32_UPPER -> base.prefix + data.encodeToString(Base32Upper) Base.BASE32_PAD -> base.prefix + data.encodeToString(Base32Pad) Base.BASE32_PAD_UPPER -> base.prefix + data.encodeToString(Base32PadUpper) Base.BASE32_HEX -> base.prefix + data.encodeToString(Base32HexLower) Base.BASE32_HEX_UPPER -> base.prefix + data.encodeToString(Base32HexUpper) Base.BASE32_HEX_PAD -> base.prefix + data.encodeToString(Base32HexPadLower) Base.BASE32_HEX_PAD_UPPER -> base.prefix + data.encodeToString(Base32HexPadUpper) Base.BASE58_FLICKR -> base.prefix + BaseN.encode(base.alphabet, BigInteger(58), data) Base.BASE58_BTC -> base.prefix + BaseN.encode(base.alphabet, BigInteger(58), data) Base.BASE64 -> base.prefix + data.encodeToString(Base64NoPadding) Base.BASE64_URL -> base.prefix + data.encodeToString(Base64UrlNoPadding) Base.BASE64_PAD -> base.prefix + data.encodeToString(Base64) Base.BASE64_URL_PAD -> base.prefix + data.encodeToString(Base64UrlPadding) } } /** * Decodes the given multibase [data] into a ByteArray. * This method throws Exceptions for strings that are not valid multibase encodings. * * Returns `null` if the encoding is not supported (e.g. Base-256 Emoji). */ @Throws(Throwable::class) fun decode(data: String): ByteArray? { val prefix = data[0] val rest = data.substring(1) return when (val base = Base.lookup(prefix)) { Base.BASE10 -> BaseN.decode(base.alphabet, BigInteger(10), rest) Base.BASE16 -> rest.decodeToByteArray(Base16Lower) Base.BASE16_UPPER -> rest.decodeToByteArray(Base16Upper) Base.BASE32 -> rest.decodeToByteArray(Base32Lower) Base.BASE32_PAD -> rest.decodeToByteArray(Base32Pad) Base.BASE32_HEX_PAD -> rest.decodeToByteArray(Base32HexPadLower) Base.BASE32_UPPER -> rest.uppercase().decodeToByteArray(Base32Upper) Base.BASE32_PAD_UPPER -> rest.uppercase().decodeToByteArray(Base32Pad) Base.BASE32_HEX -> rest.decodeToByteArray(Base32HexLower) Base.BASE32_HEX_UPPER -> rest.uppercase().decodeToByteArray(Base32HexLower) Base.BASE32_HEX_PAD_UPPER -> rest.uppercase().decodeToByteArray(Base32HexPadLower) Base.BASE58_FLICKR -> BaseN.decode(base.alphabet, BigInteger(58), rest) Base.BASE58_BTC -> BaseN.decode(base.alphabet, BigInteger(58), rest) Base.BASE64 -> rest.decodeToByteArray(Base64NoPadding) Base.BASE64_URL -> rest.decodeToByteArray(Base64UrlNoPadding) Base.BASE64_PAD -> rest.decodeToByteArray(Base64) Base.BASE64_URL_PAD -> rest.decodeToByteArray(Base64UrlPadding) null -> null } } } /** * Decodes this string into a ByteArray. * This method throws Exceptions for strings that are not valid multibase encodings. * * Returns `null` if the encoding is not supported (e.g. Base-256 Emoji). */ fun String.multibaseDecode() = MultiBase.decode(this) /** * Encodes this ByteArray into the specified [base]. */ fun ByteArray.multibaseEncode(base: MultiBase.Base) = MultiBase.encode(base, this) private val Base64UrlPadding = Base64(config = Base64ConfigBuilder().apply { lineBreakInterval = 0 encodeToUrlSafe = true isLenient = false padEncoded = true }.build()) private val Base64UrlNoPadding = Base64(config = Base64ConfigBuilder().apply { lineBreakInterval = 0 encodeToUrlSafe = true isLenient = false padEncoded = false }.build()) private val Base64 = Base64(config = Base64ConfigBuilder().apply { lineBreakInterval = 0 encodeToUrlSafe = false isLenient = false padEncoded = true }.build()) private val Base64NoPadding = Base64(config = Base64ConfigBuilder().apply { lineBreakInterval = 0 encodeToUrlSafe = false isLenient = true padEncoded = false }.build()) private val Base32Lower = Base32Default { encodeToLowercase = true; padEncoded = false } private val Base32Upper = Base32Default { encodeToLowercase = false; padEncoded = false } private val Base32Pad = Base32Default { isLenient = false; padEncoded = true; encodeToLowercase = true } private val Base32PadUpper = Base32Default { isLenient = false; padEncoded = true;encodeToLowercase = false } private val Base32HexPadLower = Base32Hex { isLenient = false; padEncoded = true;encodeToLowercase = true } private val Base32HexPadUpper = Base32Hex { isLenient = false; padEncoded = true;encodeToLowercase = false } private val Base32HexLower = Base32Hex { padEncoded = false;encodeToLowercase = true } private val Base32HexUpper = Base32Hex { padEncoded = false;encodeToLowercase = false } private val Base16Lower = Base16 { encodeToLowercase = true } private val Base16Upper = Base16 { encodeToLowercase = false }
0
Kotlin
0
2
710c2f0f72bdf8f5c0991afdb066356e45195b2e
11,540
multibase
MIT License
app/src/main/java/ee/ioc/phon/android/speak/demo/EncoderListDemo.kt
kshravi86
136,645,939
true
{"Markdown": 5, "Shell": 5, "Python": 2, "HTML": 1, "Java": 55, "Kotlin": 11}
package ee.ioc.phon.android.speak.demo import android.app.ListActivity import android.os.Bundle import android.widget.ArrayAdapter import ee.ioc.phon.android.speak.R import ee.ioc.phon.android.speechutils.utils.AudioUtils import java.util.* class EncoderListDemo : ListActivity() { public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val info = ArrayList<String>() info.add("FLAC encoders: " + AudioUtils.getEncoderNamesForType("audio/flac").toString()) info.addAll(AudioUtils.getAvailableEncoders(16000)) listAdapter = ArrayAdapter(this, R.layout.list_item_detail, info.toTypedArray()) } }
0
Java
0
1
254951175dd80cf5010055a09a6df97120cab099
684
K6nele
Apache License 2.0
postgres-native-sqldelight-driver/src/commonMain/kotlin/app/softwork/sqldelight/postgresdriver/PostgresNativeDriver.kt
hfhbd
491,982,242
false
{"Kotlin": 48764}
package app.softwork.sqldelight.postgresdriver import app.cash.sqldelight.* import app.cash.sqldelight.db.* import kotlinx.cinterop.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import libpq.* public class PostgresNativeDriver( private val conn: CPointer<PGconn>, private val listenerSupport: ListenerSupport ) : SqlDriver { private var transaction: Transacter.Transaction? = null private val notifications: Flow<String> init { require(PQstatus(conn) == ConnStatusType.CONNECTION_OK) { conn.error() } setDateOutputs() notifications = when (listenerSupport) { is ListenerSupport.Local -> listenerSupport.notifications is ListenerSupport.Remote -> listenerSupport.remoteListener(conn) is ListenerSupport.None -> emptyFlow() } } private fun setDateOutputs() { execute(null, "SET intervalstyle = 'iso_8601';", 0) execute(null, "SET datestyle = 'ISO';", 0) } private val listeners = mutableMapOf<Query.Listener, Job>() private fun CoroutineScope.listen(queryKeys: List<String>, action: suspend (String) -> Unit) = launch { notifications.filter { it in queryKeys }.collect { action(it) } } override fun addListener(listener: Query.Listener, queryKeys: Array<String>) { when (listenerSupport) { ListenerSupport.None -> return is ListenerSupport.Local -> { listeners[listener] = listenerSupport.notificationScope.listen(queryKeys.toList()) { listener.queryResultsChanged() } } is ListenerSupport.Remote -> { val queryKeysRenamed = queryKeys.map { listenerSupport.notificationName(it) } listeners[listener] = listenerSupport.notificationScope.listen(queryKeysRenamed) { listener.queryResultsChanged() } for (queryKey in queryKeysRenamed) { execute(null, "LISTEN ${conn.escaped(queryKey)}", parameters = 0) } } } } override fun notifyListeners(queryKeys: Array<String>) { when (listenerSupport) { is ListenerSupport.Local -> { listenerSupport.notificationScope.launch { for (queryKey in queryKeys) { listenerSupport.notify(queryKey) } } } is ListenerSupport.Remote -> { for (queryKey in queryKeys) { val name = listenerSupport.notificationName(queryKey) execute(null, "NOTIFY ${conn.escaped(name)}", parameters = 0) } } ListenerSupport.None -> return } } override fun removeListener(listener: Query.Listener, queryKeys: Array<String>) { val queryListeners = listeners[listener] if (queryListeners != null) { if (listenerSupport is ListenerSupport.Remote) { for (queryKey in queryKeys) { val name = listenerSupport.notificationName(queryKey) execute(null, "UNLISTEN ${conn.escaped(name)}", parameters = 0) } } queryListeners.cancel() listeners.remove(listener) } } override fun currentTransaction(): Transacter.Transaction? = transaction override fun execute( identifier: Int?, sql: String, parameters: Int, binders: (SqlPreparedStatement.() -> Unit)? ): QueryResult.Value<Long> { val preparedStatement = if (parameters != 0) PostgresPreparedStatement(parameters).apply { if (binders != null) { binders() } } else null val result = if (identifier != null) { if (!preparedStatementExists(identifier)) { PQprepare( conn, stmtName = identifier.toString(), query = sql, nParams = parameters, paramTypes = preparedStatement?.types?.refTo(0) ).check(conn).clear() } memScoped { PQexecPrepared( conn, stmtName = identifier.toString(), nParams = parameters, paramValues = preparedStatement?.values(this), paramFormats = preparedStatement?.formats?.refTo(0), paramLengths = preparedStatement?.lengths?.refTo(0), resultFormat = TEXT_RESULT_FORMAT ) } } else { memScoped { PQexecParams( conn, command = sql, nParams = parameters, paramValues = preparedStatement?.values(this), paramFormats = preparedStatement?.formats?.refTo(0), paramLengths = preparedStatement?.lengths?.refTo(0), resultFormat = TEXT_RESULT_FORMAT, paramTypes = preparedStatement?.types?.refTo(0) ) } }.check(conn) return QueryResult.Value(value = result.rows) } private val CPointer<PGresult>.rows: Long get() { val rows = PQcmdTuples(this)!!.toKString() clear() return rows.toLongOrNull() ?: 0 } private fun preparedStatementExists(identifier: Int): Boolean { val result = executeQuery(null, "SELECT name FROM pg_prepared_statements WHERE name = '$identifier'", parameters = 0, binders = null, mapper = { if (it.next()) { it.getString(0) } else null }) return result.value != null } private fun Int.escapeNegative(): String = if (this < 0) "_${toString().substring(1)}" else toString() private fun preparedStatement( parameters: Int, binders: (PostgresPreparedStatement.() -> Unit)? ): PostgresPreparedStatement? = if (parameters != 0) { PostgresPreparedStatement(parameters).apply { if (binders != null) { binders() } } } else null private fun checkPreparedStatement( identifier: Int, sql: String, parameters: Int, preparedStatement: PostgresPreparedStatement? ) { if (!preparedStatementExists(identifier)) { PQprepare( conn, stmtName = identifier.toString(), query = sql, nParams = parameters, paramTypes = preparedStatement?.types?.refTo(0) ).check(conn).clear() } } override fun <R> executeQuery( identifier: Int?, sql: String, mapper: (SqlCursor) -> R, parameters: Int, binders: (SqlPreparedStatement.() -> Unit)? ): QueryResult.Value<R> { val preparedStatement = preparedStatement(parameters, binders) val result = if (identifier != null) { checkPreparedStatement(identifier, sql, parameters, preparedStatement) memScoped { PQexecPrepared( conn, stmtName = identifier.toString(), nParams = parameters, paramValues = preparedStatement?.values(this), paramLengths = preparedStatement?.lengths?.refTo(0), paramFormats = preparedStatement?.formats?.refTo(0), resultFormat = TEXT_RESULT_FORMAT ) } } else { memScoped { PQexecParams( conn, command = sql, nParams = parameters, paramValues = preparedStatement?.values(this), paramLengths = preparedStatement?.lengths?.refTo(0), paramFormats = preparedStatement?.formats?.refTo(0), paramTypes = preparedStatement?.types?.refTo(0), resultFormat = TEXT_RESULT_FORMAT ) } }.check(conn) val value = NoCursor(result).use(mapper) return QueryResult.Value(value = value) } internal companion object { const val TEXT_RESULT_FORMAT = 0 const val BINARY_RESULT_FORMAT = 1 } override fun close() { PQfinish(conn) if (listenerSupport is ScopedListenerSupport) { listenerSupport.notificationScope.cancel() } } override fun newTransaction(): QueryResult.Value<Transacter.Transaction> { conn.exec("BEGIN") return QueryResult.Value(Transaction(transaction)) } private inner class Transaction( override val enclosingTransaction: Transacter.Transaction? ) : Transacter.Transaction() { override fun endTransaction(successful: Boolean): QueryResult.Unit { if (enclosingTransaction == null) { if (successful) { conn.exec("END") } else { conn.exec("ROLLBACK") } } transaction = enclosingTransaction return QueryResult.Unit } } // Custom functions /** * Each element of stdin can be up to 2 GB. */ public fun copy(stdin: Sequence<String>): Long { for (stdin in stdin) { val status = PQputCopyData(conn, stdin, stdin.encodeToByteArray().size) check(status == 1) { conn.error() } } val end = PQputCopyEnd(conn, null) check(end == 1) { conn.error() } val result = PQgetResult(conn).check(conn) return result.rows } public fun <R> executeQueryAsFlow( identifier: Int?, sql: String, mapper: suspend (PostgresCursor) -> R, parameters: Int, fetchSize: Int = 1, binders: (PostgresPreparedStatement.() -> Unit)? ): Flow<R> = flow { val (result, cursorName) = prepareQuery(identifier, sql, parameters, binders) RealCursor(result, cursorName, conn, fetchSize).use { while (it.next()) { emit(mapper(it)) } } } private fun prepareQuery( identifier: Int?, sql: String, parameters: Int, binders: (PostgresPreparedStatement.() -> Unit)? ): Pair<CPointer<PGresult>, String> { val cursorName = if (identifier == null) "myCursor" else "cursor${identifier.escapeNegative()}" val cursor = "DECLARE $cursorName CURSOR FOR" val preparedStatement = preparedStatement(parameters, binders) return if (identifier != null) { checkPreparedStatement(identifier, "$cursor $sql", parameters, preparedStatement) conn.exec("BEGIN") memScoped { PQexecPrepared( conn, stmtName = identifier.toString(), nParams = parameters, paramValues = preparedStatement?.values(this), paramLengths = preparedStatement?.lengths?.refTo(0), paramFormats = preparedStatement?.formats?.refTo(0), resultFormat = TEXT_RESULT_FORMAT ) } } else { conn.exec("BEGIN") memScoped { PQexecParams( conn, command = "$cursor $sql", nParams = parameters, paramValues = preparedStatement?.values(this), paramLengths = preparedStatement?.lengths?.refTo(0), paramFormats = preparedStatement?.formats?.refTo(0), paramTypes = preparedStatement?.types?.refTo(0), resultFormat = TEXT_RESULT_FORMAT ) } }.check(conn) to cursorName } @Deprecated( "Use executeQueryAsFlow instead or enter your use-case in https://github.com/hfhbd/postgres-native-sqldelight/issues/121", replaceWith = ReplaceWith("executeQueryAsFlow(identifier, sql, mapper, parameters, fetchSize, binders)") ) public fun <R> executeQueryWithNativeCursor( identifier: Int?, sql: String, mapper: (PostgresCursor) -> R, parameters: Int, fetchSize: Int = 1, binders: (PostgresPreparedStatement.() -> Unit)? ): QueryResult.Value<R> { val (result, cursorName) = prepareQuery(identifier, sql, parameters, binders) val value = RealCursor(result, cursorName, conn, fetchSize).use(mapper) return QueryResult.Value(value = value) } } private fun CPointer<PGconn>?.error(): String { val errorMessage = PQerrorMessage(this)!!.toKString() PQfinish(this) return errorMessage } internal fun CPointer<PGresult>?.clear() { PQclear(this) } internal fun CPointer<PGconn>.exec(sql: String) { val result = PQexec(this, sql) result.check(this) result.clear() } internal fun CPointer<PGresult>?.check(conn: CPointer<PGconn>): CPointer<PGresult> { val status = PQresultStatus(this) check(status == PGRES_TUPLES_OK || status == PGRES_COMMAND_OK || status == PGRES_COPY_IN) { conn.error() } return this!! } private fun CPointer<PGconn>.escaped(value: String): String { val cString = PQescapeIdentifier(this, value, value.length.convert()) val escaped = cString!!.toKString() PQfreemem(cString) return escaped } public fun PostgresNativeDriver( host: String, database: String, user: String, password: String, port: Int = 5432, options: String? = null, listenerSupport: ListenerSupport = ListenerSupport.None ): PostgresNativeDriver { val conn = PQsetdbLogin( pghost = host, pgport = port.toString(), pgtty = null, dbName = database, login = user, pwd = <PASSWORD>, pgoptions = options ) require(PQstatus(conn) == ConnStatusType.CONNECTION_OK) { conn.error() } return PostgresNativeDriver(conn!!, listenerSupport = listenerSupport) }
7
Kotlin
3
29
06e6613c442712e175018138a9d8b25d3827712b
14,548
postgres-native-sqldelight
Apache License 2.0
app/src/main/java/br/com/movieapp/core/paging/MovieSearchPagingSource.kt
wilsonleandro
724,752,199
false
{"Kotlin": 153692}
package br.com.movieapp.core.paging import androidx.paging.PagingSource import androidx.paging.PagingState import br.com.movieapp.core.domain.model.MovieSearch import br.com.movieapp.search.feature.domain.source.MovieSearchRemoteDataSource class MovieSearchPagingSource( private val query: String, private val remoteDataSource: MovieSearchRemoteDataSource ) : PagingSource<Int, MovieSearch>() { override fun getRefreshKey(state: PagingState<Int, MovieSearch>): Int? { return state.anchorPosition?.let { anchorPosition -> val anchorPage = state.closestPageToPosition(anchorPosition) anchorPage?.prevKey?.plus(LIMIT) ?: anchorPage?.nextKey?.minus(LIMIT) } } override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MovieSearch> { return try { val pageNumber = params.key ?: 1 val response = remoteDataSource.getSearchMovies(pageNumber, query) val movies = response.movies val totalPages = response.totalPages LoadResult.Page( data = movies, prevKey = if (pageNumber == 1) null else pageNumber - 1, nextKey = if (pageNumber == totalPages) null else pageNumber + 1, ) } catch (e: Exception) { LoadResult.Error(e) } } companion object { private const val LIMIT = 20 } }
0
Kotlin
0
0
0b26342f22b2790cf0dfdcdba3f53fdf1c121bfc
1,416
movieapp
MIT License
app/src/main/java/app/ferdyhaspin/quotes/ui/component/home/quotes/QuotesFragment.kt
ferdyhaspin
235,545,727
false
null
package app.ferdyhaspin.quotes.ui.component.home.quotes import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import app.ferdyhaspin.quotes.R import app.ferdyhaspin.quotes.data.db.entities.Quote import app.ferdyhaspin.quotes.ui.ViewModelFactory import app.ferdyhaspin.quotes.ui.base.BaseFragment import app.ferdyhaspin.quotes.utils.hide import app.ferdyhaspin.quotes.utils.observe import app.ferdyhaspin.quotes.utils.show import app.ferdyhaspin.quotes.utils.toast import com.xwray.groupie.GroupAdapter import com.xwray.groupie.ViewHolder import kotlinx.android.synthetic.main.fragment_quotes.* import javax.inject.Inject /** * A simple [Fragment] subclass. */ class QuotesFragment : BaseFragment(), QuoteListener { @Inject lateinit var viewModel: QuotesViewModel @Inject lateinit var viewModelFactory: ViewModelFactory override fun initializeViewModel() { viewModel = viewModelFactory.create(QuotesViewModel::class.java) viewModel.listener = this viewModel.getQuotes() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_quotes, container, false) } override fun observeViewModel() { observe(viewModel.quotes, ::initRecyclerView) } private fun List<Quote>.toQuoteItem(): List<QuoteItem> { return map { QuoteItem(it) } } private fun initRecyclerView(list: List<Quote>) { val listItem = list.toQuoteItem() val mAdapter = GroupAdapter<ViewHolder>().apply { addAll(listItem) } recyclerview.apply { layoutManager = LinearLayoutManager(requireContext()) addItemDecoration( DividerItemDecoration( context, (layoutManager as LinearLayoutManager).orientation ) ) setHasFixedSize(true) adapter = mAdapter } } override fun showProgress(show: Boolean) { if (show) progress_bar.show() else progress_bar.hide() } override fun onFailure(message: String) { requireContext().toast(message) } }
0
Kotlin
0
0
549a5dd3342562e2e450d1f04fbf8dad2db4fb37
2,503
quotes
MIT License
compiler/testData/diagnostics/tests/typealias/kt14518.kt
JakeWharton
99,388,807
false
null
// !DIAGNOSTICS: -UNUSED_VARIABLE -UNUSED_PARAMETER -TOPLEVEL_TYPEALIASES_ONLY class OuterClass<T1> { class NestedClass<T2> typealias NestedType<T> = NestedClass<T> } typealias ON1<T1, T2> = OuterClass<!TYPE_ARGUMENTS_FOR_OUTER_CLASS_WHEN_NESTED_REFERENCED!><T1><!>.NestedClass<T2> typealias ON2<T1, T2> = OuterClass<!TYPE_ARGUMENTS_FOR_OUTER_CLASS_WHEN_NESTED_REFERENCED!><T1><!>.NestedType<T2> typealias ON3<T2> = OuterClass.NestedType<T2>
181
null
5748
83
4383335168338df9bbbe2a63cb213a68d0858104
451
kotlin
Apache License 2.0
kvision-modules/kvision-bootstrap/src/main/kotlin/io/kvision/dropdown/ContextMenu.kt
rjaros
120,835,750
false
null
/* * Copyright (c) 2017-present <NAME> * * 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 io.kvision.dropdown import io.kvision.core.Display import io.kvision.core.Widget import io.kvision.panel.Root import io.kvision.panel.SimplePanel import io.kvision.utils.auto import io.kvision.utils.px import org.w3c.dom.events.MouseEvent /** * Context menu component. * * @constructor * @param element an element to bind * @param fixedPosition use fixed positioning * @param className CSS class names * @param init an initializer extension function */ open class ContextMenu( element: Widget? = null, protected val fixedPosition: Boolean = false, className: String? = null, init: (ContextMenu.() -> Unit)? = null ) : SimplePanel((className?.let { "$it " } ?: "") + "dropdown-menu") { init { @Suppress("LeakingThis") hide() @Suppress("LeakingThis") display = Display.BLOCK width = auto val root = element?.getRoot() ?: Root.getLastRoot() if (root != null) { @Suppress("LeakingThis") root.addContextMenu(this) } else { console.log("At least one Root object is required to create a context menu!") } @Suppress("LeakingThis") init?.invoke(this) } /** * Positions and shows a context menu based on a mouse event. * @param mouseEvent mouse event * @return current context menu */ open fun positionMenu(mouseEvent: MouseEvent): ContextMenu { if (fixedPosition) { this.top = DEFAULT_FIXED_POS_Y.px this.left = DEFAULT_FIXED_POS_X.px } else { this.top = mouseEvent.pageY.toInt().px this.left = mouseEvent.pageX.toInt().px } this.show() return this } companion object { const val DEFAULT_FIXED_POS_X = 5 const val DEFAULT_FIXED_POS_Y = 5 } } /** * Sets context menu for the current widget. * @param contextMenu a context menu * @return current widget */ fun Widget.setContextMenu(contextMenu: ContextMenu): Widget { this.setEventListener<Widget> { contextmenu = { e: MouseEvent -> e.preventDefault() contextMenu.positionMenu(e) } } return this } /** * DSL builder extension function. * * It takes the same parameters as the constructor of the built component. */ fun Widget.contextMenu( fixedPosition: Boolean = false, className: String? = null, init: (ContextMenu.() -> Unit)? = null ): ContextMenu { val contextMenu = ContextMenu(this, fixedPosition, className, init) this.setContextMenu(contextMenu) return contextMenu }
31
null
65
882
bde30bbfd3c1a837eeff58a0a81bf7a5d677c72f
3,729
kvision
MIT License
core/data/src/main/java/komu/seki/data/handlers/MediaHandler.kt
shrimqy
827,172,253
false
{"Kotlin": 238692}
package komu.seki.data.services import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.MediaSessionCompat import android.support.v4.media.session.PlaybackStateCompat import android.util.Log import androidx.core.app.NotificationCompat import androidx.core.graphics.drawable.IconCompat import komu.seki.common.util.base64ToBitmap import komu.seki.common.util.base64ToIconCompat import komu.seki.domain.models.MediaAction import komu.seki.domain.models.PlaybackData import komu.seki.domain.models.SocketMessage import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch fun mediaController( context: Context, playbackData: PlaybackData, sendMessage: suspend (SocketMessage) -> Unit ) { val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager val notificationId = 5941 // Get the existing or new MediaSession val mediaSession = MediaSessionManager.getMediaSession(context) // Update MediaSession metadata and playback state mediaSession.setMetadata( MediaMetadataCompat.Builder() .putString(MediaMetadataCompat.METADATA_KEY_TITLE, playbackData.trackTitle) .putString(MediaMetadataCompat.METADATA_KEY_ARTIST, playbackData.artist) .putBitmap( MediaMetadataCompat.METADATA_KEY_ALBUM_ART, playbackData.thumbnail?.let { base64ToBitmap(it) }) .build() ) mediaSession.setPlaybackState( PlaybackStateCompat.Builder() .setState( if (playbackData.isPlaying == true) PlaybackStateCompat.STATE_PLAYING else PlaybackStateCompat.STATE_PAUSED, PlaybackStateCompat.PLAYBACK_POSITION_UNKNOWN, 1f ) .setActions(PlaybackStateCompat.ACTION_PLAY_PAUSE or PlaybackStateCompat.ACTION_SKIP_TO_NEXT or PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS) .build() ) mediaSession.setCallback(object : MediaSessionCompat.Callback() { override fun onPlay() { handleMediaAction(playbackData, MediaAction.RESUME, sendMessage) } override fun onPause() { handleMediaAction(playbackData, MediaAction.PAUSE, sendMessage) } override fun onSkipToNext() { handleMediaAction(playbackData, MediaAction.NEXT_QUEUE, sendMessage) } override fun onSkipToPrevious() { handleMediaAction(playbackData, MediaAction.PREV_QUEUE, sendMessage) } }) val channel = NotificationChannel( "playback_channel", "Playback Notifications", NotificationManager.IMPORTANCE_LOW ) notificationManager.createNotificationChannel(channel) // Create or update the notification val notification = NotificationCompat.Builder(context, "playback_channel") .setSmallIcon(com.komu.seki.core.common.R.drawable.ic_splash) .setContentTitle(playbackData.trackTitle) .setContentText(playbackData.artist) .setLargeIcon(playbackData.thumbnail?.let { base64ToBitmap(it) }) .setStyle( androidx.media.app.NotificationCompat.MediaStyle() .setMediaSession(mediaSession.sessionToken) .setShowActionsInCompactView(0, 1, 2) ) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .setOngoing(true) .build() // Notify (update) the existing notification notificationManager.notify(notificationId, notification) Log.d("PlaybackData", "Notification updated for playback: ${playbackData.trackTitle}") } fun handleMediaAction( playbackData: PlaybackData, action: MediaAction, sendMessage: suspend (SocketMessage) -> Unit ) { playbackData.mediaAction = action CoroutineScope(Dispatchers.IO).launch { sendMessage(playbackData) } Log.d("MediaSession", "Action received: $action" + playbackData.trackTitle) } object MediaSessionManager { private var mediaSession: MediaSessionCompat? = null fun getMediaSession(context: Context): MediaSessionCompat { if (mediaSession == null) { mediaSession = MediaSessionCompat(context, "MediaSessionTag") mediaSession?.isActive = true } return mediaSession!! } fun release() { mediaSession?.release() mediaSession = null } }
1
Kotlin
0
45
b4601316ca792a7247ca08fa2a9af43761875a85
4,556
Sekia
Apache License 2.0
app/src/main/java/com/stratagile/qlink/ui/activity/reward/module/MyClaimModule.kt
qlcchain
115,608,966
false
null
package com.stratagile.qlink.ui.activity.reward.module import com.stratagile.qlink.data.api.HttpAPIWrapper import com.stratagile.qlink.ui.activity.base.ActivityScope import com.stratagile.qlink.ui.activity.reward.MyClaimActivity import com.stratagile.qlink.ui.activity.reward.contract.MyClaimContract import com.stratagile.qlink.ui.activity.reward.presenter.MyClaimPresenter import dagger.Module; import dagger.Provides; /** * @author hzp * @Package com.stratagile.qlink.ui.activity.claim * @Description: The moduele of MyClaimActivity, provide field for MyClaimActivity * @date 2019/10/09 11:57:31 */ @Module class MyClaimModule (private val mView: MyClaimContract.View) { @Provides @ActivityScope fun provideMyClaimPresenter(httpAPIWrapper: HttpAPIWrapper) :MyClaimPresenter { return MyClaimPresenter(httpAPIWrapper, mView) } @Provides @ActivityScope fun provideMyClaimActivity() : MyClaimActivity { return mView as MyClaimActivity } }
1
null
18
46
1c8066e4ebbb53c7401751ea3887a6315ccbe5eb
995
QWallet-Android
MIT License
app/src/main/java/com/mytests/testExam/presentation/Authorization.kt
FredNekrasov
766,574,196
false
{"Kotlin": 46367}
package com.mytests.testExam.presentation import androidx.compose.foundation.layout.* import androidx.compose.runtime.* import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.ui.* import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.navigation.NavHostController import com.mytests.R import com.mytests.testExam.domain.util.AuthStatus.SUCCESS import com.mytests.testExam.domain.util.AuthStatus.USER_NOT_FOUND import com.mytests.testExam.presentation.profile.view_model.UserVM import com.mytests.testExam.presentation.specialViews.UserNameTF import com.mytests.ui.customItems.* import com.mytests.ui.screenRoutes.ExamScreenRoutes @Composable fun Authorization(controller: NavHostController,userVM: UserVM) { val userData = userVM.resultSF.collectAsState().value var userName by rememberSaveable { mutableStateOf("") } var password by rememberSaveable { mutableStateOf("") } var isUserNameCorrect by rememberSaveable { mutableStateOf(false) } var isPasswordCorrect by rememberSaveable { mutableStateOf(false) } Column(Modifier.fillMaxSize(),Arrangement.Center,Alignment.CenterHorizontally) { FredTextHeader(stringResource(R.string.authorization)) Spacer(Modifier.height(64.dp)) UserNameTF(userName,{ userName = it },isUserNameCorrect) Spacer(Modifier.height(8.dp)) CustomOutlinedTF( password, { password = it }, isPasswordCorrect, KeyboardType.NumberPassword, R.string.enterPassword, R.string.incorrectPassword ) Spacer(Modifier.height(32.dp)) FredButton({ isUserNameCorrect = userName.isBlank() isPasswordCorrect = password.isBlank() || password.length < 8 if(!isUserNameCorrect && !isPasswordCorrect) userVM.authorization(userName, password) },stringResource(R.string.logIn)) Spacer(Modifier.height(8.dp)) FredButton({ controller.navigate(ExamScreenRoutes.Registration.route) },stringResource(R.string.registration)) if(userData.first == SUCCESS) controller.navigate(ExamScreenRoutes.Profile.route) if(userData.first == USER_NOT_FOUND) { isUserNameCorrect = true isPasswordCorrect = true } } }
0
Kotlin
0
1
e344e47e6cb1ba8f0634e3df75ffa3514270bc59
2,388
my-tests
MIT License
next/kmp/browser/src/commonMain/kotlin/org/dweb_browser/browser/desk/render/TaskBarAppIcon.kt
BioforestChain
594,577,896
false
{"Kotlin": 3446191, "TypeScript": 818538, "Swift": 369625, "Vue": 156647, "SCSS": 39016, "Objective-C": 17350, "HTML": 16184, "Shell": 13534, "JavaScript": 3982, "Svelte": 3504, "CSS": 818}
package org.dweb_browser.browser.desk.render import androidx.compose.animation.core.Spring import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.foundation.layout.BoxWithConstraints import androidx.compose.foundation.layout.requiredSize import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.blur import androidx.compose.ui.draw.scale import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Popup import kotlinx.coroutines.launch import org.dweb_browser.browser.desk.model.TaskbarAppModel import org.dweb_browser.core.module.NativeMicroModule import org.dweb_browser.core.std.file.ext.blobFetchHook import org.dweb_browser.helper.compose.clickableWithNoEffect import org.dweb_browser.helper.compose.pointerActions import org.dweb_browser.helper.platform.theme.LocalColorful import org.dweb_browser.sys.haptics.ext.vibrateHeavyClick import org.dweb_browser.sys.haptics.ext.vibrateImpact import org.dweb_browser.sys.window.render.AppIconContainer import org.dweb_browser.sys.window.render.AppLogo @Composable internal fun TaskBarAppIcon( app: TaskbarAppModel, microModule: NativeMicroModule.NativeRuntime, openAppOrActivate: () -> Unit, quitApp: () -> Unit, toggleWindow: () -> Unit, containerAlpha: Float? = null, shadow: Dp? = null, popupOffset: IntOffset? = null, modifier: Modifier = Modifier, ) { val scope = rememberCoroutineScope() var showQuit by remember(app.isShowClose) { mutableStateOf(app.isShowClose) } var isHover by remember { mutableStateOf(false) } val scaleTargetValue = when { app.opening -> 0.9f isHover -> when { app.running -> 1.05f else -> 0.9f } else -> 1f } BoxWithConstraints( contentAlignment = Alignment.Center, modifier = modifier.scale( animateFloatAsState( scaleTargetValue, when { scaleTargetValue >= 1f -> spring(Spring.DampingRatioHighBouncy) else -> tween(200) } ).value ).pointerActions( onHoverStart = { scope.launch { microModule.vibrateImpact() } isHover = true }, onHoverEnd = { isHover = false }, onTap = { openAppOrActivate() }, onDoubleTap = { scope.launch { microModule.vibrateImpact() } openAppOrActivate() if (app.running) { toggleWindow() } }, onMenu = { if (app.running) { scope.launch { microModule.vibrateHeavyClick() } showQuit = !showQuit } }, ), ) { AppLogo.from(app.icon, fetchHook = microModule.blobFetchHook, description = "taskbar:${app.mmid}").toDeskAppIcon( AppIconContainer(shadow = shadow ?: if (app.running) 2.dp else null), containerColor = if (app.running) null else LocalColorful.current.Gray.Shade_100, containerAlpha = containerAlpha ?: if (app.running) 1f else 0.8f, ).Render( logoModifier = if (showQuit) Modifier.blur(4.dp) else Modifier, innerContent = { if (showQuit) { Popup( onDismissRequest = { showQuit = false }, offset = popupOffset ?: IntOffset.Zero ) { CloseButton( Color.Black, Modifier.requiredSize(size = maxWidth).clickableWithNoEffect { quitApp() showQuit = false }, ) } } }, ) } }
66
Kotlin
5
20
6db1137257e38400c87279f4ccf46511752cd45a
4,038
dweb_browser
MIT License
app/src/main/java/com/wave/audiorecording/util/OnCopyListener.kt
SimformSolutionsPvtLtd
359,396,860
false
null
package com.wave.audiorecording.util /** * OnCopyListener */ interface OnCopyListener { val isCancel: Boolean fun onCopyProgress(percent: Int, progress: Long, total: Long) fun onCanceled() fun onCopyFinish() }
0
Kotlin
5
9
4b3ffa7bfc8c4718085bfc3c146863c659f8e09f
228
SSAudioRecorderWithWaveForm
Apache License 2.0
common/src/main/kotlin/com/agmtopy/kocketmq/common/namesrv/RegisterBrokerResult.kt
agmtopy
376,882,907
false
null
package com.agmtopy.kocketmq.common.namesrv import com.agmtopy.kocketmq.common.protocol.body.KVTable class RegisterBrokerResult { var haServerAddr: String? = null var masterAddr: String? = null var kvTable: KVTable? = null }
1
null
1
1
91e15b054ff8f1784d79b96e498894065ba025f8
238
kocketmq
Apache License 2.0
jersey/src/test/kotlin/org/ostelco/prime/jersey/auth/AuthTest.kt
ostelco
112,729,477
false
null
package org.ostelco.prime.client.api.auth import io.dropwizard.client.JerseyClientBuilder import io.dropwizard.testing.ConfigOverride import io.dropwizard.testing.ResourceHelpers import io.dropwizard.testing.junit.DropwizardAppRule import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.fail import org.glassfish.jersey.client.ClientProperties import org.junit.BeforeClass import org.junit.ClassRule import org.junit.Test import org.ostelco.prime.client.api.auth.helpers.TestApp import org.ostelco.prime.client.api.util.AccessToken import javax.ws.rs.client.Client import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response /** * Tests OAuth2 callback to '.../userinfo" endpoint. * */ class GetUserInfoTest { private val email = "boaty@internet.org" private val audience = listOf("http://kmmtest", "http://localhost:${RULE.localPort}/userinfo") @Test @Throws(Exception::class) fun getProfileNotFound() { // XXX Race condition makes test fail sometimes. // This is an abominiation :-) But it's whats necessary to consistently pass this // test on my workstation. waitForServer() val response = client!!.target( "http://localhost:${RULE.localPort}/profile") .request() .property(ClientProperties.CONNECT_TIMEOUT, 30000) .property(ClientProperties.READ_TIMEOUT, 30000) .header("Authorization", "Bearer ${AccessToken.withEmail(email, audience)}") .get(Response::class.java) assertThat(response.status).isEqualTo(Response.Status.NOT_FOUND.statusCode) assertThat(response.mediaType.toString()).startsWith(MediaType.APPLICATION_JSON) } private fun waitForServer() { var counter = 40 // Max wait time, ten seconds. while (counter > 0) { try { val r = client!!.target( "http://localhost:${RULE.adminPort}/healthcheck") .request() .get(Response::class.java) if (r.status == 200) { println("Connected") break } } catch (t: Throwable) { println("Caught throwable $t") } counter -= 1 Thread.sleep(250) } if (counter == 0) { fail("Couldn't connect to RULE server") } } companion object { private val key = "secret" private var client: Client? = null @JvmField @ClassRule val RULE = DropwizardAppRule(TestApp::class.java, ResourceHelpers.resourceFilePath("test.yaml"), ConfigOverride.config("secret", key)) @BeforeClass @JvmStatic fun setUpClient() { client = JerseyClientBuilder(RULE.environment).build("test client"); } } }
23
null
13
37
b072ada4aca8c4bf5c3c2f6fe0d36a5ff16c11af
2,967
ostelco-core
Apache License 2.0
samples/AlertDialog/common/src/desktopMain/kotlin/dev/atsushieno/composempp/samples/alertdialog/DesktopApp.kt
atsushieno
407,561,858
false
{"Kotlin": 10923}
package dev.atsushieno.composempp.samples.alertdialog import androidx.compose.desktop.ui.tooling.preview.Preview import androidx.compose.runtime.Composable @Preview @Composable fun AppPreview() { App() }
0
Kotlin
2
6
d2dada9ad14d778d2a852078e52811004b793974
209
compose-mpp
Apache License 2.0
prefpin-annotation/src/main/java/prefpin/OnPrefClick.kt
zacharee
203,059,924
true
{"Kotlin": 16843, "Java": 758}
package prefpin import androidx.annotation.StringRes import kotlin.reflect.KClass /** * Binds a method to the OnPreferenceClick handler of a preference for the specific key. */ @Retention(AnnotationRetention.BINARY) @Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER) annotation class OnPrefClick( @StringRes vararg val value: Int )
0
Kotlin
0
1
039374c466826c3f2d72c2b3fc0c92d7235b4899
396
prefpin
MIT License
app/src/main/java/com/fredrikbogg/android_chat_app/util/LiveDataExt.kt
dgewe
288,984,096
false
null
package com.fredrikbogg.android_chat_app.util import androidx.lifecycle.MutableLiveData fun <T> MutableLiveData<MutableList<T>>.addNewItem(item: T) { val newList = mutableListOf<T>() this.value?.let { newList.addAll(it) } newList.add(item) this.value = newList } fun <T> MutableLiveData<MutableList<T>>.updateItemAt(item: T, index: Int) { val newList = mutableListOf<T>() this.value?.let { newList.addAll(it) } newList[index] = item this.value = newList } fun <T> MutableLiveData<MutableList<T>>.removeItem(item: T) { val newList = mutableListOf<T>() this.value?.let { newList.addAll(it) } newList.remove(item) this.value = newList }
0
null
35
87
cff2f947a4496e46cbaa750b4e3fa768ba2308f0
686
Chat-App-Android
MIT License
common/ui/compose/src/main/java/app/tivi/common/compose/ui/ExpandingSummary.kt
chrisbanes
100,624,553
false
null
/* * Copyright 2020 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.common.compose.ui import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.spring import androidx.compose.foundation.clickable import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.style.TextOverflow @Composable fun ExpandingText( text: String, modifier: Modifier = Modifier, textStyle: TextStyle = MaterialTheme.typography.body2, expandable: Boolean = true, collapsedMaxLines: Int = 4, expandedMaxLines: Int = Int.MAX_VALUE ) { var canTextExpand by remember(text) { mutableStateOf(true) } var expanded by remember { mutableStateOf(false) } Text( text = text, style = textStyle, overflow = TextOverflow.Ellipsis, maxLines = if (expanded) expandedMaxLines else collapsedMaxLines, modifier = Modifier .clickable( enabled = expandable && canTextExpand, onClick = { expanded = !expanded } ) .animateContentSize(animationSpec = spring()) .then(modifier), onTextLayout = { if (!expanded) { canTextExpand = it.hasVisualOverflow } } ) }
39
null
792
5,749
5dc4d831fd801afab556165d547042c517f98875
2,149
tivi
Apache License 2.0
builder/src/main/java/com/kamer/builder/MainNavigationScreenHolder.kt
kamerok
192,063,678
false
{"Kotlin": 209086}
package com.kamer.builder import android.content.Intent import androidx.appcompat.app.AppCompatActivity import androidx.compose.animation.EnterTransition import androidx.compose.animation.ExitTransition import androidx.compose.animation.core.tween import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.animation.slideOutHorizontally import androidx.compose.animation.slideOutVertically import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.remember import androidx.core.util.Consumer import androidx.navigation.NavController import androidx.navigation.NavType import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.compose.rememberNavController import androidx.navigation.navArgument import androidx.navigation.navOptions import easydone.core.domain.DomainRepository import easydone.core.domain.RemoteDataSource import easydone.core.domain.SyncScheduler import easydone.core.domain.model.Task import easydone.feature.edittask.EditTaskArgs import easydone.feature.edittask.EditTaskNavigator import easydone.feature.edittask.EditTaskRoute import easydone.feature.home.HomeNavigator import easydone.feature.home.HomeRoute import easydone.feature.inbox.InboxNavigator import easydone.feature.inbox.InboxRoute import easydone.feature.settings.SettingScreen import easydone.feature.settings.SettingsNavigator import easydone.feature.setupflow.SetupRoute import easydone.feature.taskdetails.TaskDetailsNavigator import easydone.feature.taskdetails.TaskDetailsRoute import easydone.feature.waiting.WaitingNavigator import easydone.feature.waiting.WaitingRoute import easydone.service.trello.TrelloRemoteDataSource import easydone.service.trello.api.TrelloApi import kotlinx.coroutines.runBlocking import org.koin.android.ext.android.inject private enum class ScaleTransitionDirection { INWARDS, OUTWARDS } private fun scaleIntoContainer( direction: ScaleTransitionDirection = ScaleTransitionDirection.INWARDS, initialScale: Float = if (direction == ScaleTransitionDirection.OUTWARDS) 0.9f else 1.1f ): EnterTransition = scaleIn( animationSpec = tween(220, delayMillis = 90), initialScale = initialScale ) + fadeIn(animationSpec = tween(220, delayMillis = 90)) private fun scaleOutOfContainer( direction: ScaleTransitionDirection = ScaleTransitionDirection.OUTWARDS, targetScale: Float = if (direction == ScaleTransitionDirection.INWARDS) 0.9f else 1.1f ): ExitTransition = scaleOut( animationSpec = tween( durationMillis = 220, delayMillis = 90 ), targetScale = targetScale ) + fadeOut(tween(delayMillis = 90)) private fun taskExitMove(): ExitTransition = slideOutHorizontally( animationSpec = tween( 220, delayMillis = 90 ), ) { it } + fadeOut(tween(delayMillis = 90)) private fun taskExitArchive(): ExitTransition = slideOutVertically( animationSpec = tween( 220, delayMillis = 90 ), ) { it } + fadeOut(tween(delayMillis = 90)) private enum class TaskPopAnimation { Move, Archive } private const val TASK_POP_ANIMATION_KEY = "task_close_animation" class MainNavigationScreenHolder( private val activity: AppCompatActivity ) { private val syncScheduler: SyncScheduler by activity.inject() private val domainRepository: DomainRepository by activity.inject() private val remoteDataSource: RemoteDataSource by activity.inject() private val trelloRemoteDataSource: TrelloRemoteDataSource by activity.inject() private val trelloApi: TrelloApi by activity.inject() private val trelloApiKey: String by lazy { trelloRemoteDataSource.apiKey } fun NavController.openViewTask(id: String) { navigate("task/$id") } fun NavController.openEditTask(id: String) { navigate("task/edit/$id") } fun NavController.openCreateTask() { navigate("task/create") } @Composable fun MainScreen() { val navController = rememberNavController() val isRemoteDataSourceConnected = remember { runBlocking { remoteDataSource.isConnected() } } val startDestination = if (isRemoteDataSourceConnected) { "home" } else { "setup" } LaunchedEffect(Unit) { val intent = activity.intent val isInboxLaunch = !intent.isOpenedFromHistory() && intent.getBooleanExtra("inbox", false) if (isInboxLaunch) { navController.navigate("inbox") } } DisposableEffect(Unit) { val listener = Consumer<Intent> { intent -> //check inbox deeplink if (intent.getBooleanExtra("inbox", false)) { with(navController) { navigate("inbox", navOptions { popUpTo("home") {} }) } } } activity.addOnNewIntentListener(listener) onDispose { activity.removeOnNewIntentListener(listener) } } NavHost( navController = navController, startDestination = startDestination, enterTransition = { scaleIntoContainer() }, exitTransition = { scaleOutOfContainer(direction = ScaleTransitionDirection.INWARDS) }, popEnterTransition = { scaleIntoContainer(direction = ScaleTransitionDirection.OUTWARDS) }, popExitTransition = { scaleOutOfContainer() } ) { composable("setup") { SetupRoute( trelloRemoteDataSource = trelloRemoteDataSource, trelloApi = trelloApi, trelloApiKey = trelloApiKey ) { navController.popBackStack("setup", true) navController.navigate("home") } } composable("home") { HomeRoute(syncScheduler, domainRepository, object : HomeNavigator { override fun navigateToCreate() { navController.openCreateTask() } override fun navigateToSettings() { navController.navigate("settings") } override fun navigateToInbox() { navController.navigate("inbox") } override fun navigateToWaiting() { navController.navigate("waiting") } override fun navigateToTask(id: String) { navController.openViewTask(id) } }) } composable("inbox") { InboxRoute( domainRepository, object : InboxNavigator { override fun openTask(id: String) { navController.openViewTask(id) } override fun close() { navController.popBackStack() } } ) } composable("waiting") { WaitingRoute(domainRepository, object : WaitingNavigator { override fun openTask(id: String) { navController.openViewTask(id) } }) } composable("settings") { SettingScreen(remoteDataSource, object : SettingsNavigator { override fun navigateToSetup() { navController.navigate("setup", navOptions { popUpTo("home") { inclusive = true } }) } }) } composable( route = "task/{taskId}", arguments = listOf(navArgument("taskId") { type = NavType.StringType }), popExitTransition = { val animation = initialState.savedStateHandle .get<TaskPopAnimation>(TASK_POP_ANIMATION_KEY) println("asdf $animation") when (animation) { TaskPopAnimation.Move -> taskExitMove() TaskPopAnimation.Archive -> taskExitArchive() else -> scaleOutOfContainer() } } ) { backStackEntry -> val id = checkNotNull(backStackEntry.arguments?.getString("taskId")) { "Task id is required" } TaskDetailsRoute(id, domainRepository, object : TaskDetailsNavigator { override fun editTask(id: String) { navController.openEditTask(id) } override fun closeMove() { navController.currentBackStackEntry ?.savedStateHandle ?.set(TASK_POP_ANIMATION_KEY, TaskPopAnimation.Move) navController.popBackStack() } override fun closeArchive() { navController.currentBackStackEntry ?.savedStateHandle ?.set(TASK_POP_ANIMATION_KEY, TaskPopAnimation.Archive) navController.popBackStack() } }) } composable( route = "task/edit/{taskId}", arguments = listOf(navArgument("taskId") { type = NavType.StringType }) ) { backStackEntry -> val id = checkNotNull(backStackEntry.arguments?.getString("taskId")) { "Task id is required" } val args = remember { EditTaskArgs.Edit(id) } EditTaskRoute(args, domainRepository, object : EditTaskNavigator { override fun close() { activity.onBackPressedDispatcher.onBackPressed() } }) } composable("task/create") { EditTaskRoute( EditTaskArgs.Create(type = Task.Type.ToDo), domainRepository, object : EditTaskNavigator { override fun close() { activity.onBackPressedDispatcher.onBackPressed() } }) } } } } private fun Intent.isOpenedFromHistory(): Boolean = flags == (Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)
0
Kotlin
0
4
d8dff0a567a7e6209ae8518c8060f252b04679fc
11,115
EasyDone
Apache License 2.0
app/src/main/java/com/example/gcore_vod_demo/screens/main/tabs/videos/remote/model/UiVideoItem.kt
G-Core
464,986,406
false
{"Kotlin": 122519}
package com.example.gcore_vod_demo.screens.main.tabs.videos.remote.model import android.os.Parcelable import com.example.gcore_vod_demo.data.remote.video.VideoItemResponse import kotlinx.parcelize.Parcelize @Parcelize data class UiVideoItem( val id: Int, val name: String, var uri: String, val previewUri: String, val originWidth: Int, val originHeight: Int ) : Parcelable { companion object { fun getInstance(videoItem: VideoItemResponse): UiVideoItem { return UiVideoItem( id = videoItem.id, name = videoItem.name, uri = videoItem.hlsURL, previewUri = videoItem.screenshot ?: "", originWidth = videoItem.originWidthVideo, originHeight = videoItem.originHeightVideo ) } } }
0
Kotlin
1
1
2a194cd24ef5b5d2cbefe465a2fdd3a00f9b7ee3
846
android-demo-vod-hosting
Apache License 2.0
app/src/main/java/ar/com/wolox/android/example/ui/splashcreen/SplashFragment.kt
wolox-training
337,096,244
false
null
package ar.com.wolox.android.example.ui.splashcreen import ar.com.wolox.android.R import ar.com.wolox.android.databinding.FragmentSplashBinding import ar.com.wolox.android.example.ui.home.HomeActivity import ar.com.wolox.android.example.ui.login.LoginActivity import ar.com.wolox.wolmo.core.fragment.WolmoFragment import ar.com.wolox.android.example.utils.fadeInAnimation class SplashFragment private constructor() : WolmoFragment<FragmentSplashBinding, SplashPresenter>(), SplashView { override fun layout() = R.layout.fragment_splash override fun init() { binding.woloxSplashLogo.fadeInAnimation { presenter.onAnimationFinish() } } override fun goToHomeScreen() = HomeActivity.startClearingCurrentTask(requireContext()) override fun goToLogInScreen() = LoginActivity.startClearingCurrentTask(requireContext()) companion object { fun newInstance() = SplashFragment() } }
0
Kotlin
0
0
4687a08577516d021ab24afd86d229ac877617d0
922
ldm-android
MIT License
library/src/androidTest/java/OperationExpirationTests.kt
wultra
259,247,352
false
{"Kotlin": 284396, "Shell": 18200, "Java": 310}
/* * Copyright 2022 Wultra s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions * and limitations under the License. */ package com.wultra.android.mtokensdk.test import com.wultra.android.mtokensdk.operation.expiration.ExpirableOperation import com.wultra.android.mtokensdk.operation.expiration.OperationExpirationWatcher import com.wultra.android.mtokensdk.operation.expiration.OperationExpirationWatcherListener import org.junit.After import org.junit.Assert import org.junit.Test import org.threeten.bp.ZonedDateTime import org.threeten.bp.zone.TzdbZoneRulesProvider import org.threeten.bp.zone.ZoneRulesProvider import java.util.concurrent.CompletableFuture import java.util.concurrent.TimeUnit class OperationExpirationTests { private val watcher = OperationExpirationWatcher() init { initThreeTen() } @After fun clear() { watcher.listener = null watcher.removeAll() } @Test fun testAddOperation() { val op = Operation() watcher.add(op) val ops = watcher.getWatchedOperations() Assert.assertTrue(ops.count() == 1 && ops.first().equals(op)) } @Test fun testAddSameOperationTwice() { val op = Operation() watcher.add(op) val ops = watcher.add(op) Assert.assertTrue(ops.count() == 1 && ops.first().equals(op)) } @Test fun testAddOperations() { val ops = watcher.add(listOf(Operation(), Operation())) Assert.assertTrue(ops.count() == 2) } @Test fun testRemoveOperation() { val op = Operation() val ops = watcher.add(op) Assert.assertTrue(ops.count() == 1 && ops.first().equals(op)) val opsAfterRemoved = watcher.remove(op) Assert.assertTrue(opsAfterRemoved.isEmpty()) } @Test fun testRemoveNonAddedOperation() { val op = Operation() val ops = watcher.add(op) Assert.assertTrue(ops.count() == 1 && ops.first().equals(op)) val opsAfterRemoved = watcher.remove(Operation()) Assert.assertTrue(opsAfterRemoved.count() == 1) } @Test fun testRemoveOperations() { val op = Operation() val op2 = Operation() watcher.add(op) val ops = watcher.add(op2) Assert.assertTrue(ops.count() == 2) val opsAfterRemoved = watcher.remove(listOf(op, op2)) Assert.assertTrue(opsAfterRemoved.isEmpty()) } @Test fun testRemoveAllOperations() { watcher.add(Operation()) val ops = watcher.add(listOf(Operation(), Operation())) Assert.assertTrue(ops.count() == 3) val opsAfterRemoved = watcher.removeAll() Assert.assertTrue(opsAfterRemoved.isEmpty()) } @Test fun testExpiring() { val future = CompletableFuture<Any?>() val op = Operation() watcher.listener = WatcherListener { ops -> if (ops.count() != 1 || !ops.first().equals(op)) { future.completeExceptionally(Throwable()) return@WatcherListener } val curOps = watcher.getWatchedOperations() if (curOps.isNotEmpty()) { future.completeExceptionally(Throwable()) return@WatcherListener } future.complete(null) } watcher.add(op) // we need to wait longer, because minimum report time is 5 seconds Assert.assertNull(future.get(10, TimeUnit.SECONDS)) } @Test fun testExpiring2() { val future = CompletableFuture<Any?>() watcher.listener = WatcherListener { ops -> if (ops.count() != 1) { future.completeExceptionally(Throwable()) return@WatcherListener } val curOps = watcher.getWatchedOperations() if (curOps.count() != 1) { future.completeExceptionally(Throwable()) return@WatcherListener } future.complete(null) } watcher.add(listOf(Operation(), Operation(ZonedDateTime.now().plusSeconds(20)))) // we need to wait longer, because minimum report time is 5 seconds Assert.assertNull(future.get(10, TimeUnit.SECONDS)) } } private class WatcherListener( private val callback: (List<ExpirableOperation>) -> Unit): OperationExpirationWatcherListener { override fun operationsExpired(expiredOperations: List<ExpirableOperation>) { callback(expiredOperations) } } private class Operation( override val expires: ZonedDateTime = ZonedDateTime.now() ): ExpirableOperation fun Any.initThreeTen() { if (ZoneRulesProvider.getAvailableZoneIds().isEmpty()) { val stream = this.javaClass.classLoader!!.getResourceAsStream("TZDB.dat") stream.use(::TzdbZoneRulesProvider).apply { ZoneRulesProvider.registerProvider(this) } } }
5
Kotlin
0
0
ee125bc9e8c9ebee1ad3e9f3c6d581031fec3ea2
5,426
mtoken-sdk-android
Apache License 2.0
sample/todo/common/src/commonMain/kotlin/moe/tlaster/common/App.kt
Tlaster
349,750,473
false
{"Kotlin": 182474}
package moe.tlaster.common import androidx.compose.animation.scaleIn import androidx.compose.animation.scaleOut import androidx.compose.animation.slideInVertically import androidx.compose.animation.slideOutVertically import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import moe.tlaster.common.repository.FakeRepository import moe.tlaster.common.scene.NoteDetailScene import moe.tlaster.common.scene.NoteEditScene import moe.tlaster.common.scene.NoteListScene import moe.tlaster.common.viewmodel.NoteDetailViewModel import moe.tlaster.common.viewmodel.NoteEditViewModel import moe.tlaster.common.viewmodel.NoteListViewModel import moe.tlaster.precompose.navigation.NavHost import moe.tlaster.precompose.navigation.path import moe.tlaster.precompose.navigation.rememberNavigator import moe.tlaster.precompose.navigation.transition.NavTransition import moe.tlaster.precompose.stateholder.SavedStateHolder import org.koin.compose.KoinApplication import org.koin.dsl.module @OptIn(ExperimentalMaterialApi::class) @Composable fun App() { KoinApplication( application = { modules( module { single { FakeRepository() } factory { (id: Int) -> NoteDetailViewModel( id = id, fakeRepository = get(), ) } factory { (id: Int?, savedStateHolder: SavedStateHolder) -> NoteEditViewModel( id = id, savedStateHolder = savedStateHolder, fakeRepository = get(), ) } factory { NoteListViewModel(fakeRepository = get()) } }, ) }, ) { val navigator = rememberNavigator() MaterialTheme { NavHost( navigator = navigator, initialRoute = "/home", ) { scene("/home") { NoteListScene( onItemClicked = { navigator.navigate("/detail/${it.id}") }, onAddClicked = { navigator.navigate("/edit") }, onEditClicked = { navigator.navigate("/edit/${it.id}") }, ) } scene("/detail/{id:[0-9]+}") { backStackEntry -> backStackEntry.path<Int>("id")?.let { NoteDetailScene( id = it, onEdit = { navigator.navigate("/edit/$it") }, onBack = { navigator.goBack() }, ) } } scene( "/edit/{id:[0-9]+}?", navTransition = NavTransition( createTransition = slideInVertically(initialOffsetY = { it }), destroyTransition = slideOutVertically(targetOffsetY = { it }), pauseTransition = scaleOut(targetScale = 0.9f), resumeTransition = scaleIn(initialScale = 0.9f), exitTargetContentZIndex = 1f, ), ) { backStackEntry -> val id = backStackEntry.path<Int>("id") NoteEditScene( id = id, onDone = { navigator.goBack() }, onBack = { navigator.goBack() }, ) } } } } }
14
Kotlin
35
583
6abfc0b4b6215309c90398876cb750f59b23218a
4,123
PreCompose
MIT License
os-util/src/main/java/org/web25/util/os/OS.kt
Web25
94,020,945
false
null
package org.web25.util.os import java.io.BufferedReader import java.io.InputStreamReader /** * Created by felix on 6/8/17. */ val osname by lazy { System.getProperty("os.name").toLowerCase() } fun <T> onOS(windows: (() -> T)? = null, linux: (() -> T)? = null, mac: (() -> T)? = null, other: ((name: String) -> T)? = null): T? { when(osname) { "linux" -> { return linux?.invoke() } } return null } fun exec(vararg cmd: String): String { val process = Runtime.getRuntime().exec(cmd) val reader = BufferedReader(InputStreamReader(process.inputStream)) return reader.readLine()!! }
0
Kotlin
0
0
6427fa273e799f5af10440221c16e67c78aeb2f1
644
kotlin-util
MIT License
frontend/src/main/kotlin/engine/Bootstrap.kt
nanodeath
322,944,408
false
null
package engine import kotlinx.html.FlowContent import kotlinx.html.div class Bootstrap(val content: FlowContent) fun FlowContent.bootstrap(cb: Bootstrap.() -> Unit) { Bootstrap(this).cb() } fun Bootstrap.row(classes: String? = null, cb: FlowContent.() -> Unit) { simpleDivHelper("row", classes, cb = cb) } fun Bootstrap.column(classes: String? = null, cb: FlowContent.() -> Unit) { simpleDivHelper("col", classes, cb = cb) } fun Bootstrap.card(classes: String? = null, cb: FlowContent.() -> Unit) { simpleDivHelper("card", classes, cb = cb) } fun Bootstrap.formGroup(classes: String? = null, cb: FlowContent.() -> Unit) { simpleDivHelper("formGroup", classes, cb = cb) } private fun Bootstrap.simpleDivHelper(vararg css: String?, cb: FlowContent.() -> Unit) { content.div(css.asSequence().filterNotNull().map(String::trim).joinToString(" ")) { cb() } } // Spacing helpers // https://getbootstrap.com/docs/4.1/utilities/spacing/ fun marginTop(size: Int? = null) = "mt-${size ?: "auto"}" fun marginBottom(size: Int? = null) = "mb-${size ?: "auto"}" fun marginLeft(size: Int? = null) = "ml-${size ?: "auto"}" fun marginRight(size: Int? = null) = "mr-${size ?: "auto"}" fun marginX(size: Int? = null) = "mx-${size ?: "auto"}" fun marginY(size: Int? = null) = "my-${size ?: "auto"}" fun margin(size: Int? = null) = "m-${size ?: "auto"}" fun paddingTop(size: Int) = "pt-${size}" fun paddingBottom(size: Int) = "pb-${size}" fun paddingLeft(size: Int) = "pl-${size}" fun paddingRight(size: Int) = "pr-${size}" fun paddingX(size: Int) = "px-${size}" fun paddingY(size: Int) = "py-${size}" fun padding(size: Int) = "p-${size}"
1
null
1
4
3d697fcb75f623e24f1691d15ae6c15560a4bd7e
1,664
kotlin-aws-jamstack
The Unlicense
dnie/src/main/java/es/fnmtrcm/ceres/certificadoDigitalFNMT/dnie/utils/NFCWatchdogRefresher.kt
CodeNationDev
757,931,525
false
{"Kotlin": 1417005, "C": 485745, "C++": 480977, "CMake": 283671, "Java": 166491}
package es.fnmtrcm.ceres.certificadoDigitalFNMT.dnie.utils import android.nfc.Tag import android.nfc.tech.IsoDep import android.os.Handler import android.os.HandlerThread import android.util.Log import java.lang.ref.WeakReference internal object NFCWatchdogRefresher { private val TAG = NFCWatchdogRefresher::class.java.simpleName private const val TECHNOLOGY_ISO_DEP = 3 private var sHandlerThread: HandlerThread? = null private var sHandler: Handler? = null private var sRefresher: WatchdogRefresher? = null @Volatile private var sIsRunning = false fun holdConnection(isoDep: IsoDep) { Log.v(TAG, "holdConnection()") if (sHandlerThread != null || sHandler != null || sRefresher != null) { Log.d(TAG, "holdConnection(): Existing background thread found, stopping!") stopHoldingConnection() } sHandlerThread = HandlerThread("NFCWatchdogRefresherThread") try { sHandlerThread!!.start() } catch (e: IllegalThreadStateException) { Log.d(TAG, "holdConnection(): Failed starting background thread!", e) } val looper = sHandlerThread!!.looper sHandler = if (looper != null) { Handler(looper) } else { Log.d(TAG, "holdConnection(): No looper on background thread!") sHandlerThread!!.quit() Handler() } sIsRunning = true sRefresher = WatchdogRefresher(sHandler, isoDep) sHandler!!.post(sRefresher!!) } fun stopHoldingConnection() { Log.v(TAG, "stopHoldingConnection()") sIsRunning = false if (sHandler != null) { if (sRefresher != null) { sHandler!!.removeCallbacks(sRefresher!!) } sHandler!!.removeCallbacksAndMessages(null) sHandler = null } if (sRefresher != null) { sRefresher = null } if (sHandlerThread != null) { sHandlerThread!!.quit() sHandlerThread = null } } private class WatchdogRefresher constructor(handler: Handler?, isoDep: IsoDep) : Runnable { private val mHandler: WeakReference<Handler?> private val mIsoDep: WeakReference<IsoDep> private var mCurrentRuntime: Int init { mHandler = WeakReference(handler) mIsoDep = WeakReference(isoDep) mCurrentRuntime = 0 } override fun run() { val tag = tag if (tag != null) { try { val getTagService = Tag::class.java.getMethod("getTagService") val tagService = getTagService.invoke(tag) val getServiceHandle = Tag::class.java.getMethod("getServiceHandle") val serviceHandle = getServiceHandle.invoke(tag) val connect = tagService.javaClass.getMethod( "connect", Int::class.javaPrimitiveType, Int::class.javaPrimitiveType ) val result = connect.invoke(tagService, serviceHandle, TECHNOLOGY_ISO_DEP) val handler = handler if (result != null && result == 0 && handler != null && sIsRunning && mCurrentRuntime < RUNTIME_MAX) { handler.postDelayed(this, INTERVAL.toLong()) mCurrentRuntime += INTERVAL Log.v(TAG, "Told NFC Watchdog to wait") } else { Log.d(TAG, "result: $result") } } catch (t: Throwable) { Log.d(TAG, "WatchdogRefresher.run()", t) } } } private val handler: Handler? get() = mHandler.get() private val tag: Tag? get() { val isoDep = mIsoDep.get() return isoDep?.tag } companion object { private const val INTERVAL = 100 private const val RUNTIME_MAX = 30 * 1000 } } }
0
Kotlin
0
0
9c5d7b9355c406992ff9126d4bd01d49d4778048
4,180
FabricK
MIT License
app/src/main/java/app/rockstar/feature/songs/list/adapter/SongItemDiffer.kt
UsmonWasTaken
732,925,673
false
{"Kotlin": 53881}
/* * Copyright (c) 2023 The Rockstar authors and contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. */ package app.rockstar.feature.songs.list.adapter import androidx.recyclerview.widget.DiffUtil internal object SongItemDiffer : DiffUtil.ItemCallback<SongListItem>() { override fun areItemsTheSame(oldItem: SongListItem, newItem: SongListItem): Boolean { return oldItem.id == newItem.id } override fun areContentsTheSame(oldItem: SongListItem, newItem: SongListItem): Boolean { return oldItem.name == newItem.name && oldItem.artist == newItem.artist && oldItem.albumCoverUri == newItem.albumCoverUri } }
0
Kotlin
0
0
8ef42719e87a5f2d9fb0f02ece52e7dd48129f96
706
Rockstar
Apache License 2.0
app/src/main/java/com/poly/budgethelp/SpendingOverviewActivity.kt
Polystyreeni
649,404,923
false
{"Kotlin": 214505, "Java": 8486}
package com.poly.budgethelp import android.content.Intent import android.graphics.Color import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.CalendarView import android.widget.EditText import android.widget.PopupWindow import android.widget.Spinner import android.widget.TextView import android.widget.Toast import androidx.activity.addCallback import androidx.activity.viewModels import androidx.appcompat.app.AlertDialog import androidx.core.graphics.BlendModeColorFilterCompat import androidx.core.graphics.BlendModeCompat import androidx.core.view.isVisible import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.poly.budgethelp.adapter.SpendingItemAdapter import com.poly.budgethelp.config.UserConfig import com.poly.budgethelp.data.CategoryPricePojo import com.poly.budgethelp.data.DuplicateMapItem import com.poly.budgethelp.data.Product import com.poly.budgethelp.data.Receipt import com.poly.budgethelp.data.ReceiptWithProducts import com.poly.budgethelp.data.SpendingTimeBlock import com.poly.budgethelp.utility.ActivityUtils import com.poly.budgethelp.utility.DateUtils import com.poly.budgethelp.viewmodel.ProductViewModel import com.poly.budgethelp.viewmodel.ProductViewModelFactory import com.poly.budgethelp.viewmodel.ReceiptProductViewModel import com.poly.budgethelp.viewmodel.ReceiptProductViewModelFactory import com.poly.budgethelp.viewmodel.ReceiptViewModel import com.poly.budgethelp.viewmodel.ReceiptViewModelFactory import java.util.Calendar import java.util.Date import kotlin.math.abs class SpendingOverviewActivity : AppCompatActivity() { private val TAG = "SpendingOverviewActivity" private val BUNDLE_START_DATE = "startDate" private val BUNDLE_END_DATE = "endDate" private val BUNDLE_TIME_STEP = "timeStep" // UI Components private lateinit var fetchButton: Button private lateinit var recyclerView: RecyclerView private lateinit var recyclerViewAdapter: SpendingItemAdapter private lateinit var warningTextView: TextView private var startDate: Long? = null private var endDate: Long? = null private val timeSteps: ArrayList<Pair<Long, Long>> = arrayListOf() private val timeStepRange = hashMapOf(Pair("Viikko", 604800000L), Pair("Kuukausi", 2678400000L)) private var timeStep: Long? = null private var currentPopup: PopupWindow? = null // Overview state private var currentTimeStepIndex: Int = 0 private val spendingBlockList: ArrayList<SpendingTimeBlock> = arrayListOf() private val warningLimit: Long = 7889400000L // Viewmodels private val receiptProductViewModel: ReceiptProductViewModel by viewModels { ReceiptProductViewModelFactory((application as BudgetApplication).receiptProductRepository) } private val receiptViewModel: ReceiptViewModel by viewModels { ReceiptViewModelFactory((application as BudgetApplication).receiptRepository) } private val productViewModel: ProductViewModel by viewModels { ProductViewModelFactory((application as BudgetApplication).productRepository) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_spending_overview) // Assign UI components fetchButton = findViewById(R.id.spendingSearchButton) fetchButton.setOnClickListener { onFetchButtonPressed() } recyclerView = findViewById(R.id.spendingRecyclerView) recyclerViewAdapter = SpendingItemAdapter(spendingBlockList) recyclerViewAdapter.baseContext = this recyclerView.adapter = recyclerViewAdapter recyclerView.layoutManager = LinearLayoutManager(this) val timeStepSpinner: Spinner = findViewById(R.id.spendingTimeStepSpinner) ArrayAdapter.createFromResource(this, R.array.spending_timestep_array, android.R.layout.simple_spinner_item).also { adapter -> adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) timeStepSpinner.adapter = adapter } timeStepSpinner.onItemSelectedListener = object: AdapterView.OnItemSelectedListener { override fun onItemSelected(p0: AdapterView<*>?, p1: View?, position: Int, p3: Long) { if (position == 0) timeStep = null else generateTimeSteps(timeStepSpinner.getItemAtPosition(position).toString()) currentTimeStepIndex = position } override fun onNothingSelected(p0: AdapterView<*>?) { } } val startEdit: EditText = findViewById(R.id.spendingStartDate) val endEdit: EditText = findViewById(R.id.spendingEndDate) startEdit.setOnClickListener {_ -> createPopup(true, startEdit) } endEdit.setOnClickListener {_ -> createPopup(false, endEdit) } val returnButton: View = findViewById(R.id.spendingReturnButton) returnButton.setOnClickListener {_ -> if (currentPopup == null) { finish() } } warningTextView = findViewById(R.id.spendingWarningTextView) warningTextView.isVisible = false // Dark mode if (ActivityUtils.isUsingNightModeResources(this)) { returnButton.background.colorFilter = BlendModeColorFilterCompat.createBlendModeColorFilterCompat(Color.WHITE, BlendModeCompat.SRC_ATOP) } // Back button functionality onBackPressedDispatcher.addCallback(this) { if (currentPopup != null) { currentPopup?.dismiss() } else { finish() } } // Load values from save state (when activity is rotated) if (savedInstanceState != null) { val newStartDate = savedInstanceState.getLong(BUNDLE_START_DATE, 0L) val newEndDate = savedInstanceState.getLong(BUNDLE_END_DATE, 0L) val newTimeStep = savedInstanceState.getLong(BUNDLE_TIME_STEP, 0L) if (newStartDate > 0L) startDate = newStartDate if (newEndDate > 0L) endDate = newEndDate if (newTimeStep > 0L) timeStep = newTimeStep } } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) if (startDate != null) outState.putLong(BUNDLE_START_DATE, startDate!!) if (endDate != null) outState.putLong(BUNDLE_END_DATE, endDate!!) if (timeStep != null) outState.putLong(BUNDLE_TIME_STEP, timeStep!!) } private fun onFetchButtonPressed() { if (startDate == null) { Toast.makeText(baseContext, resources.getString(R.string.error_no_start_date), Toast.LENGTH_SHORT).show() return } if (endDate == null) { Toast.makeText(baseContext, resources.getString(R.string.error_no_end_date), Toast.LENGTH_SHORT).show() return } if (timeStep == null) { Toast.makeText(baseContext, resources.getString(R.string.error_no_timestep), Toast.LENGTH_SHORT).show() return } // Warning for long time (3 months) if (endDate!! - startDate!! > warningLimit) { createTimeWarningAlert() } else { beginDataFetch() } } private fun createTimeWarningAlert() { val builder = AlertDialog.Builder(this, R.style.AlertDialog) builder.setTitle(resources.getString(R.string.camera_reading_complete)) builder.setCancelable(false) builder.setMessage(resources.getString(R.string.spending_time_warning)) builder.setPositiveButton(resources.getString(R.string.spending_alert_positive)) {dialogInterface, index -> beginDataFetch() dialogInterface.dismiss() } builder.setNegativeButton(resources.getString(R.string.spending_alert_negative)) { dialogInterface, index -> dialogInterface.dismiss() } builder.show() } private fun beginDataFetch() { fetchButton.isClickable = false receiptViewModel.receiptsInRange(startDate!!, endDate!!).observe(this) {receipts -> getReceiptCrossRefData(receipts, timeStep!!) } } private fun createPopup(isStartDate: Boolean, parent: EditText) { currentPopup?.dismiss() val popupData = ActivityUtils.createPopup(R.layout.popup_calendar, this) popupData.second.isFocusable = true currentPopup = popupData.second val popupHeader: TextView = popupData.first.findViewById(R.id.calendarPopupHeader) val calendarView: CalendarView = popupData.first.findViewById(R.id.calendarPopupView) // Header text if (isStartDate) popupHeader.setText(R.string.receipt_list_start_date) else popupHeader.setText(R.string.receipt_list_end_date) // Set calendar range calendarView.maxDate = System.currentTimeMillis() calendarView.date = System.currentTimeMillis() popupData.second.setOnDismissListener { currentPopup = null } calendarView.setOnDateChangeListener {_, y, m, d -> val calendar: Calendar = Calendar.getInstance() calendar.set(Calendar.YEAR, y) calendar.set(Calendar.MONTH, m) if (isStartDate) calendar.set(Calendar.DAY_OF_MONTH, 1) else calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DATE)) val date: Date = calendar.time if (isStartDate) { startDate = date.time } else { endDate = date.time } parent.setText(String.format("%s %d", resources.getStringArray(R.array.month_array)[m], y)) currentPopup?.dismiss() currentPopup = null } } private fun generateTimeSteps(selectedTimeStep: String) { timeSteps.clear() if (startDate == null || endDate == null) return // val diff: Long = endDate!! - startDate!! val add: Long = timeStepRange[selectedTimeStep]!! // val step: Long = diff / add timeStep = add } private fun getReceiptCrossRefData(receipts: List<Receipt>, timeStep: Long) { val receiptIds = arrayListOf<Long>() receipts.forEach {receipt -> receiptIds.add(receipt.receiptId)} Log.d(TAG, "Number of receipts: ${receiptIds.size}") val liveData = receiptProductViewModel.productsInReceipt(receiptIds) liveData.observe(this, object: Observer<List<ReceiptWithProducts>> { override fun onChanged(t: List<ReceiptWithProducts>?) { liveData.removeObserver(this) if (t != null) { populateSpendingData(t, timeStep) } else { Toast.makeText(baseContext, resources.getString(R.string.error_spending_overview_create_failed), Toast.LENGTH_SHORT).show() fetchButton.isClickable = true } } }) } private fun populateSpendingData(crossRef: List<ReceiptWithProducts>, timeStep: Long) { // Clear previous data spendingBlockList.clear() val productBlocks: HashMap<String, ArrayList<Product>> = hashMapOf() var totalProducts = 0 var totalPriceInReceipts = 0f var totalPriceOfProducts = 0f crossRef.forEach {elem -> totalProducts += elem.products.size totalPriceInReceipts += elem.receipt.receiptPrice } Log.d(TAG, "Total products: $totalProducts, price on receipt: $totalPriceInReceipts") val timeSteps: ArrayList<Long> = if (timeStep == timeStepRange["Viikko"]) DateUtils.getStartOfWeeksBetween(startDate!!, endDate!!) else DateUtils.getStartOfMonthsBetween(startDate!!, endDate!!) for (i in timeSteps.indices) { if (i == timeSteps.indices.last) continue val currentDate = timeSteps[i] val upperLimit = timeSteps[i + 1] // Generate map key based on times, will be used for fetching time range specific items val key = "${currentDate}/${upperLimit}" for (ref in crossRef) { if (ref.receipt.receiptDate in currentDate until upperLimit) { if (productBlocks[key] == null) { productBlocks.put(key, arrayListOf<Product>()) productBlocks[key]?.addAll(ref.products) } else { productBlocks[key]?.addAll(ref.products) } } } } var fetchedCount = 0 // Duplicate map is used for products that appear multiple times in a single block // Database sum can't deal with duplicates, so these have to be added here manually val duplicateMap: HashMap<String, ArrayList<DuplicateMapItem>> = hashMapOf() for (kvp in productBlocks) { val params: List<String> = kvp.key.split("/") val begin = params[0].toLong() val end = params[1].toLong() val productIds: List<Long> = kvp.value.map { item -> item.productId } // Populate duplicate map val itemCounts: HashMap<Product, Int> = getProductCounts(kvp.value) for (itemCountPair in itemCounts) { if (itemCountPair.value > 1) { val dupItem = DuplicateMapItem(itemCountPair.key, itemCountPair.value) if (duplicateMap.containsKey(kvp.key)) { duplicateMap[kvp.key]?.add(dupItem) } else { duplicateMap[kvp.key] = arrayListOf(dupItem) } } } val liveData = productViewModel.pricesInCategory(productIds) liveData.observe(this, object: Observer<List<CategoryPricePojo>> { override fun onChanged(list: List<CategoryPricePojo>?) { fetchedCount++ liveData.removeObserver(this) if (list != null) { list.let { // Feed duplicates val duplicates = duplicateMap[kvp.key] val duplicateFixedList: List<CategoryPricePojo> = fixDuplicatesForBlock(it, duplicates) val blockData = SpendingTimeBlock(begin, end, duplicateFixedList) // Update total price blockData.spending.forEach { pojo -> totalPriceOfProducts += pojo.totalPrice } spendingBlockList.add(blockData) if (fetchedCount >= productBlocks.count()) { val sorted = spendingBlockList.sortedWith(Comparator {a: SpendingTimeBlock, b: SpendingTimeBlock -> b.startTime.compareTo(a.startTime) }) spendingBlockList.clear() spendingBlockList.addAll(sorted) recyclerViewAdapter.notifyDataSetChanged() updateWarningText(totalPriceInReceipts, totalPriceOfProducts) } } } else { Toast.makeText(baseContext, resources.getString(R.string.error_spending_overview_create_failed), Toast.LENGTH_SHORT).show() } } }) } // Re-enable fetch button fetchButton.isClickable = true } private fun getProductCounts(productList: ArrayList<Product>): HashMap<Product, Int> { val map: HashMap<Product, Int> = hashMapOf() for (i in productList.indices) { if (map.containsKey(productList[i])) { val currentValue = map[productList[i]] map[productList[i]] = currentValue!! + 1 } else { map[productList[i]] = 1 } } return map } private fun fixDuplicatesForBlock(existing: List<CategoryPricePojo>, duplicates: ArrayList<DuplicateMapItem>?) : List<CategoryPricePojo> { if (duplicates == null) return existing duplicates.forEach { duplicate -> val category = duplicate.product.productCategory val priceAddition = duplicate.product.productPrice * (duplicate.count - 1) existing.forEach { pojo -> if (pojo.category == category) pojo.totalPrice += priceAddition } } return existing } private fun updateWarningText(receiptPrice: Float, productPrice: Float) { if (abs(receiptPrice - productPrice) > 0.05f) { warningTextView.isVisible = true warningTextView.text = resources.getString( R.string.warning_overview_price_mismatch, productPrice, UserConfig.currency, receiptPrice) } else { warningTextView.isVisible = false } } }
0
Kotlin
0
0
e8fc63484c5965db1f459be06aef8ff3e9c73df3
17,720
BudgetHelp
Apache License 2.0
core/src/main/kotlin/materialui/components/gridlist/GridListElementBuilder.kt
subroh0508
167,797,152
false
null
package materialui.components.gridlist import kotlinx.html.Tag import kotlinx.html.TagConsumer import materialui.components.MaterialElementBuilder import materialui.components.getValue import materialui.components.setValue import react.ComponentType class GridListElementBuilder<T: Tag> internal constructor( type: ComponentType<GridListProps>, classMap: List<Pair<Enum<*>, String>>, factory: (TagConsumer<Unit>) -> T ) : MaterialElementBuilder<T, GridListProps>(type, classMap, factory) { val Tag.cellHeight: Any? by materialProps var Tag.cols: Number? by materialProps var Tag.spacing: Number? by materialProps var Tag.style: Any? by materialProps fun Tag.cellHeight(v: String = "auto") { materialProps.cellHeight = v } fun Tag.cellHeight(v: Number) { materialProps.cellHeight = v } }
14
null
27
81
a959a951ace3b9bd49dc5405bea150d4d53cf162
825
kotlin-material-ui
MIT License
payjp-android-cardform/src/test/kotlin/jp/pay/android/testing/PayjpCardFormTestRule.kt
payjp
111,647,224
false
{"Gemfile.lock": 1, "Gradle": 13, "YAML": 3, "Java Properties": 12, "Shell": 5, "Text": 1, "Ignore List": 9, "Batchfile": 1, "Markdown": 2, "Ruby": 2, "Proguard": 2, "XML": 61, "Java": 6, "Kotlin": 161, "HTML": 354, "SVG": 4, "CSS": 2, "JavaScript": 8, "JSON": 1}
/* * * Copyright (c) 2021 PAY, Inc. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package jp.pay.android.testing import jp.pay.android.PayjpCardForm import jp.pay.android.PayjpLogger import jp.pay.android.PayjpTokenBackgroundHandler import jp.pay.android.PayjpTokenService import jp.pay.android.plugin.CardScannerPlugin import org.junit.rules.ExternalResource import java.util.concurrent.Executor /** * Test rule that configure PayjpService */ class PayjpCardFormTestRule( private val tokenService: PayjpTokenService, private val handler: PayjpTokenBackgroundHandler? = null, private val callbackExecutor: Executor? = null, private val cardScannerPlugin: CardScannerPlugin? = null ) : ExternalResource() { override fun before() { PayjpCardForm.configure( logger = PayjpLogger.get(debugEnabled = true), tokenService = tokenService, handler = handler, callbackExecutor = callbackExecutor, cardScannerPlugin = cardScannerPlugin ) } }
1
Kotlin
2
6
6f3cb6184c3def6cae1244fdbdeb8351fb086cf1
2,071
payjp-android
MIT License
src/test/kotlin/no/nav/syfo/narmesteleder/service/BeOmNyNLServiceTest.kt
navikt
258,142,447
false
null
package no.nav.syfo.narmesteleder.service import io.mockk.clearMocks import io.mockk.every import io.mockk.mockk import io.mockk.mockkStatic import no.nav.syfo.model.sykmeldingstatus.ArbeidsgiverStatusDTO import no.nav.syfo.model.sykmeldingstatus.ShortNameDTO import no.nav.syfo.model.sykmeldingstatus.SporsmalOgSvarDTO import no.nav.syfo.model.sykmeldingstatus.SvartypeDTO import no.nav.syfo.model.sykmeldingstatus.SykmeldingStatusKafkaEventDTO import no.nav.syfo.narmesteleder.kafka.NLRequestProducer import no.nav.syfo.narmesteleder.kafka.NLResponseProducer import no.nav.syfo.narmesteleder.model.NarmesteLeder import no.nav.syfo.sykmelding.db.DatabaseInterface import no.nav.syfo.sykmelding.db.hasCheckedNl import org.amshove.kluent.shouldBeEqualTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.time.LocalDate import java.time.OffsetDateTime class BeOmNyNLServiceTest : Spek({ val nlRequestProducer = mockk<NLRequestProducer>(relaxed = true) val nlResponseProducer = mockk<NLResponseProducer>(relaxed = true) val database = mockk<DatabaseInterface>() mockkStatic("no.nav.syfo.sykmelding.db.DatabaseQueriesKt") val beOmNyNLService = BeOmNyNLService(nlRequestProducer, nlResponseProducer, database) afterEachTest { mockkStatic("no.nav.syfo.sykmelding.db.DatabaseQueriesKt") clearMocks(database) } beforeEachTest { every { database.hasCheckedNl(any()) } returns false } describe("BeOmNyNLService") { it("Skal ikke be om ny NL om det er gjort") { every { database.hasCheckedNl(any()) } returns true val sykmeldingStatusKafkaEvent = getSykmeldingStatusKafkaEvent( listOf( SporsmalOgSvarDTO( "Be om ny nærmeste leder?", ShortNameDTO.NY_NARMESTE_LEDER, SvartypeDTO.JA_NEI, "JA" ) ) ) beOmNyNLService.skalBeOmNyNL(sykmeldingStatusKafkaEvent, getNarmesteleder(true)) shouldBeEqualTo false } it("Skal ikke be om ny NL om det ikke er gjort") { every { database.hasCheckedNl(any()) } returns false val sykmeldingStatusKafkaEvent = getSykmeldingStatusKafkaEvent( listOf( SporsmalOgSvarDTO( "Be om ny nærmeste leder?", ShortNameDTO.NY_NARMESTE_LEDER, SvartypeDTO.JA_NEI, "JA" ) ) ) beOmNyNLService.skalBeOmNyNL(sykmeldingStatusKafkaEvent, getNarmesteleder(true)) shouldBeEqualTo true } it("Skal be om ny NL hvis det er svart ja på spørsmål om NL") { val sykmeldingStatusKafkaEvent = getSykmeldingStatusKafkaEvent( listOf( SporsmalOgSvarDTO( "Be om ny nærmeste leder?", ShortNameDTO.NY_NARMESTE_LEDER, SvartypeDTO.JA_NEI, "JA" ) ) ) beOmNyNLService.skalBeOmNyNL( sykmeldingStatusKafkaEvent, getNarmesteleder(forskutterer = false) ) shouldBeEqualTo true } it("Skal be om ny NL hvis det ikke er registrert noen NL") { val sykmeldingStatusKafkaEvent = getSykmeldingStatusKafkaEvent(emptyList()) beOmNyNLService.skalBeOmNyNL(sykmeldingStatusKafkaEvent, null) shouldBeEqualTo true } it("Skal be om ny NL hvis det ikke er svart på om NL forskutterer lønn") { val sykmeldingStatusKafkaEvent = getSykmeldingStatusKafkaEvent( emptyList() ) beOmNyNLService.skalBeOmNyNL( sykmeldingStatusKafkaEvent, getNarmesteleder(forskutterer = null) ) shouldBeEqualTo true } it("Skal ikke be om ny NL hvis NL er registrert og har svart på forskuttering og bruker ikke har bedt om ny NL") { val sykmeldingStatusKafkaEvent = getSykmeldingStatusKafkaEvent( emptyList() ) beOmNyNLService.skalBeOmNyNL( sykmeldingStatusKafkaEvent, getNarmesteleder(forskutterer = false) ) shouldBeEqualTo false } it("Skal ikke be om ny NL hvis det er svart nei på spørsmål om NL") { val sykmeldingStatusKafkaEvent = getSykmeldingStatusKafkaEvent( listOf( SporsmalOgSvarDTO( "Be om ny nærmeste leder?", ShortNameDTO.NY_NARMESTE_LEDER, SvartypeDTO.JA_NEI, "NEI" ) ) ) beOmNyNLService.skalBeOmNyNL(sykmeldingStatusKafkaEvent, null) shouldBeEqualTo false } } }) fun getSykmeldingStatusKafkaEvent(sporsmalOgSvarListe: List<SporsmalOgSvarDTO>): SykmeldingStatusKafkaEventDTO { return SykmeldingStatusKafkaEventDTO( sykmeldingId = "sykmeldingId", arbeidsgiver = ArbeidsgiverStatusDTO("orgnummer", "1234", "orgnavn"), sporsmals = sporsmalOgSvarListe, statusEvent = "SENDT", timestamp = OffsetDateTime.now() ) } fun getNarmesteleder(forskutterer: Boolean?): NarmesteLeder { return NarmesteLeder( epost = "<EMAIL>", orgnummer = "orgnummer", telefonnummer = "99999999", aktivFom = LocalDate.now().minusYears(2), arbeidsgiverForskutterer = forskutterer, navn = "<NAME>", fnr = "fnr" ) }
0
Kotlin
0
0
f80685e2e206d97603f2d1573a5f44724543b453
5,787
syfosmaltinn
MIT License
buildSrc/src/main/kotlin/fr/xgouchet/buildsrc/settings/KtLintConfig.kt
xgouchet
92,030,208
false
null
package fr.xgouchet.buildsrc.settings import org.gradle.api.Project import org.jlleitschuh.gradle.ktlint.KtlintExtension fun Project.ktLintConfig() { extensionConfig<KtlintExtension> { debug.set(false) android.set(true) outputToConsole.set(true) ignoreFailures.set(false) enableExperimentalRules.set(false) additionalEditorconfigFile.set(file("${project.rootDir}/script/config/.editorconfig")) filter { exclude("**/generated/**") include("**/kotlin/**") } } tasks.named("check") { dependsOn("ktlintCheck") } }
6
null
3
83
0ab6c3a673fd8771e9fc02f0676a3a886992a1ef
626
Elmyr
MIT License
app/src/main/java/com/android/taitasciore/chhtest/data/entity/mapper/CoinListMapper.kt
phanghos
137,318,492
false
{"Kotlin": 114821}
package com.android.taitasciore.chhtest.data.entity.mapper import com.android.taitasciore.chhtest.data.entity.CoinListEntity import com.android.taitasciore.chhtest.domain.model.CoinList import javax.inject.Inject open class CoinListMapper @Inject constructor(private val coinMapper: CoinMapper) : Mapper<CoinListEntity?, CoinList> { override fun map(input: CoinListEntity?): CoinList { return CoinList( total = input?.total, data = coinMapper.map(input?.data), currentPage = input?.currentPage, prevPageUrl = input?.prevPageUrl, nextPageUrl = input?.nextPageUrl ) } }
0
Kotlin
0
0
d34428f7cc008c8fa30d9fd5430b2288f56c4327
673
chh-test
MIT License
app/src/main/java/com/pr0gramm/app/services/preloading/PreloadService.kt
Zz9uk3
158,547,370
true
{"Kotlin": 1141144, "Shell": 6640, "IDL": 3434, "Python": 1124}
package com.pr0gramm.app.services.preloading import android.app.IntentService import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.net.Uri import android.os.PowerManager import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.core.content.ContextCompat import com.pr0gramm.app.Duration import com.pr0gramm.app.Instant import com.pr0gramm.app.R import com.pr0gramm.app.feed.FeedItem import com.pr0gramm.app.services.DownloadService import com.pr0gramm.app.services.NotificationService import com.pr0gramm.app.services.UriHelper import com.pr0gramm.app.util.* import com.pr0gramm.app.util.AndroidUtility.toFile import okhttp3.OkHttpClient import okhttp3.Request import org.kodein.di.Kodein import org.kodein.di.KodeinAware import org.kodein.di.erased.instance import java.io.* import java.util.* import java.util.concurrent.TimeUnit /** * This service handles preloading and resolving of preloaded images. */ class PreloadService : IntentService("PreloadService"), KodeinAware { override val kodein: Kodein by lazy { applicationContext.kodein } private val httpClient: OkHttpClient by instance() private val preloadManager: PreloadManager by instance() private val notificationService: NotificationService by instance() private val powerManager: PowerManager by lazy { getSystemService(Context.POWER_SERVICE) as PowerManager } private val notificationManager by lazy { NotificationManagerCompat.from(this) } @Volatile private var canceled: Boolean = false private var jobId: Long = 0 private val interval = DownloadService.Interval(500) private lateinit var preloadCache: File private val notification by lazy { notificationService.beginPreloadNotification() .setContentTitle(getString(R.string.preload_ongoing)) .setSmallIcon(android.R.drawable.stat_sys_download) .setOngoing(true) .setTicker("") } override fun onCreate() { super.onCreate() // send out the initial notification and bring the service into foreground mode! startForeground(NotificationService.Types.Preload.id, notification.build()) preloadCache = File(cacheDir, "preload").apply { if (mkdirs()) { logger.info("preload directory created at {}", this) } } } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { if (intent?.getLongExtra(EXTRA_CANCEL, -1) == jobId) { canceled = true return Service.START_NOT_STICKY } return super.onStartCommand(intent, flags, startId) } override fun onHandleIntent(intent: Intent?) { val items = parseFeedItemsFromIntent(intent) if (intent == null || items.isEmpty()) return jobId = System.currentTimeMillis() canceled = false val cancelIntent = PendingIntent.getService(this, 0, Intent(this, PreloadService::class.java).putExtra(EXTRA_CANCEL, jobId), PendingIntent.FLAG_UPDATE_CURRENT) // update notification show { setProgress(100 * items.size, 0, false) addAction(R.drawable.ic_close_24dp, getString(R.string.cancel), cancelIntent) setContentIntent(cancelIntent) } val creation = Instant.now() val uriHelper = UriHelper.of(this) // create a wake lock val wakeLock = powerManager.newWakeLock( PowerManager.PARTIAL_WAKE_LOCK, PreloadService::class.java.name) val allowOnlyOnMobile = !intent.getBooleanExtra(EXTRA_ALLOW_ON_MOBILE, false) try { logger.info("Acquire wake lock for at most 10 minutes") wakeLock.use(10, TimeUnit.MINUTES) { var statsFailed = 0 var statsDownloaded = 0 var idx = 0 while (idx < items.size && !canceled) { if (allowOnlyOnMobile && AndroidUtility.isOnMobile(this)) break val item = items[idx] try { val mediaUri = uriHelper.media(item) val mediaIsLocal = "file" == mediaUri.scheme val mediaFile = if (mediaIsLocal) toFile(mediaUri) else cacheFileForUri(mediaUri) val thumbUri = uriHelper.thumbnail(item) val thumbIsLocal = "file" == thumbUri.scheme val thumbFile = if (thumbIsLocal) toFile(thumbUri) else cacheFileForUri(thumbUri) // update the notification maybeShow { setProgress(items.size, idx, false) } // prepare the entry that will be put into the database later val entry = PreloadManager.PreloadItem(item.id, creation, mediaFile, thumbFile) if (!mediaIsLocal) download(2 * idx, 2 * items.size, mediaUri, entry.media) if (!thumbIsLocal) download(2 * idx + 1, 2 * items.size, thumbUri, entry.thumbnail) preloadManager.store(entry) statsDownloaded += 1 } catch (ioError: IOException) { statsFailed += 1 logger.warn("Could not preload image id=" + item.id, ioError) } idx++ } // doing cleanup doCleanup(createdBefore = Instant.now() - Duration.days(1)) // setting end message showEndMessage(statsDownloaded, statsFailed) } } catch (error: Throwable) { if (error.rootCause !is IOException) { AndroidUtility.logToCrashlytics(error) } notification.setContentTitle(getString(R.string.preload_failed)) } finally { logger.info("Preloading finished") // clear the action button notification.mActions.clear() show { setSmallIcon(android.R.drawable.stat_sys_download_done) setSubText(null) setProgress(0, 0, false) setOngoing(false) setContentIntent(null) } stopForeground(false) } } private fun parseFeedItemsFromIntent(intent: Intent?): List<FeedItem> { val feed = intent?.extras?.getParcelableArray(EXTRA_LIST_OF_ITEMS) return feed?.mapNotNull { it as? FeedItem } ?: listOf() } private fun showEndMessage(downloaded: Int, failed: Int) { val contentText = ArrayList<String>() contentText.add(getString(R.string.preload_sub_downloaded, downloaded)) if (failed > 0) { contentText.add(getString(R.string.preload_sub_failed, failed)) } if (canceled) { contentText.add(getString(R.string.preload_canceled)) } show { setProgress(0, 0, true) setContentTitle(getString(R.string.preload_finished)) setContentText(contentText.joinToString(", ")) } } /** * Cleaning old files before the given threshold. */ private fun doCleanup(createdBefore: Instant) { show { setContentText(getString(R.string.preload_cleanup)) setProgress(1, 0, true) } preloadManager.deleteBefore(createdBefore) } private fun download(index: Int, total: Int, uri: Uri, targetFile: File) { // if the file exists, we dont need to download it again if (targetFile.exists()) { logger.info("File {} already exists", targetFile) if (!targetFile.setLastModified(System.currentTimeMillis())) logger.warn("Could not touch file {}", targetFile) return } val tempFile = File(targetFile.path + ".tmp") try { download(uri, tempFile) { progress -> val msg: String val progressCurrent = (100 * (index + progress)).toInt() val progressTotal = 100 * total if (canceled) { msg = getString(R.string.preload_sub_finished) } else { msg = getString(R.string.preload_fetching, uri.path) } maybeShow { setContentText(msg).setProgress(progressTotal, progressCurrent, false) } } if (!tempFile.renameTo(targetFile)) throw IOException("Could not rename file") } catch (error: Throwable) { if (!tempFile.delete()) logger.warn("Could not remove temporary file") throw error } } private inline fun show(config: NotificationCompat.Builder.() -> Unit) { notification.config() notificationManager.notify(NotificationService.Types.Preload.id, notification.build()) } private fun maybeShow(config: NotificationCompat.Builder.() -> Unit) { interval.doIfTime { show(config) } } private fun download(uri: Uri, targetFile: File, progress: (Float) -> Unit) { logger.info("Start downloading {} to {}", uri, targetFile) val request = Request.Builder().get().url(uri.toString()).build() val response = httpClient.newCall(request).execute() response.body()?.let { body -> val contentLength = body.contentLength() body.byteStream().use { inputStream -> FileOutputStream(targetFile).use { outputStream -> if (contentLength < 0) { progress(0.0f) inputStream.copyTo(outputStream) progress(1.0f) } else { copyWithProgress(progress, contentLength, inputStream, outputStream) } } } } } /** * Copies from the input stream to the output stream. * The progress is written to the given observable. */ private fun copyWithProgress( progress: (Float) -> Unit, contentLength: Long, inputStream: InputStream, outputStream: OutputStream) { var totalCount: Long = 0 readStream(inputStream) { buffer, count -> outputStream.write(buffer, 0, count) totalCount += count.toLong() progress(totalCount.toFloat() / contentLength) } } /** * Name of the cache file for the given [Uri]. */ private fun cacheFileForUri(uri: Uri): File { val filename = uri.toString().replaceFirst("https?://".toRegex(), "").replace("[^0-9a-zA-Z.]+".toRegex(), "_") return File(preloadCache, filename) } companion object { private val logger = logger("PreloadService") private const val EXTRA_LIST_OF_ITEMS = "PreloadService.listOfItems" private const val EXTRA_CANCEL = "PreloadService.cancel" private const val EXTRA_ALLOW_ON_MOBILE = "PreloadService.allowOnMobile" fun preload(context: Context, items: List<FeedItem>, allowOnMobile: Boolean) { val intent = Intent(context, PreloadService::class.java) intent.putExtra(EXTRA_ALLOW_ON_MOBILE, allowOnMobile) intent.putExtra(EXTRA_LIST_OF_ITEMS, items.toTypedArray()) ContextCompat.startForegroundService(context, intent) } } }
0
Kotlin
0
0
c173fa90bfef3266b80fece6fc67909cd90eaf0b
11,835
Pr0
MIT License
core-api/api/src/main/java/love/forte/simbot/api/message/results/Result.kt
simple-robot
554,852,615
false
null
/* * * * Copyright (c) 2021. 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:JvmMultifileClass @file:JvmName("Results") package love.forte.simbot.api.message.results import love.forte.simbot.api.message.containers.OriginalDataContainer import love.forte.simbot.api.sender.Getter /** * * **返回值** 。 * * 一般可以代表在 [获取器][Getter] 中所得到的信息的值。 * * @author ForteScarlet <<EMAIL>> * @date 2020/9/4 * @since */ public interface Result : OriginalDataContainer { /** * 空的伴生对象。 */ companion object Empty : Result { override val originalData: String get() = "EmptyResult()" } } /** * 存在多个内容的**返回值** 。 * * 一般可以代表在 [获取器][Getter] 中所得到的信息的值。 * */ public interface MultipleResults<T : Result> : Result, Iterable<T> { /** 得到结果集合。可能会是空的,但不应为null。 */ val results: List<T> /** * 习惯用法, 得到 [results] 的长度。 */ fun size(): Int = results.size /** * 获取一个迭代器 */ override operator fun iterator(): Iterator<T> = results.iterator() /** * 结果集是否为空 */ fun isEmpty(): Boolean = results.isEmpty() /** * 将 [results] 转化为 [java.util.stream.Stream] */ fun stream(): java.util.stream.Stream<T> = results.stream() /** * 空的伴生对象。 */ companion object Empty : MultipleResults<Nothing> { override val originalData: String get() = "EmptyMultipleResults()" override val results: List<Nothing> get() = emptyList() } } /** * [MultipleResults].[size][MultipleResults.size]. * @since 2.0.0 */ public inline val <T : Result> MultipleResults<T>.size: Int get() = results.size /** * 复数返回值类型之一。区别在于此为一个节点,每个节点都能继续向下获取剩余元素。 * */ public interface NodeResult<T> : MultipleResults<NodeResult<T>> { /** * 当前元素。 */ val value: T /** * 此节点元素下的其他元素。 */ override val results: List<NodeResult<T>> } /** * 得到一个没有子节点的单节点result。 */ public fun <T> singletonNodeResult(value: T): NodeResult<T> = SingletonNodeResult(value) private data class SingletonNodeResult<T>(override val value: T) : NodeResult<T> { override val originalData: String get() = "SingletonNodeResult($value)" override fun toString(): String = originalData override val results: List<NodeResult<T>> get() = emptyList() } /** * 类似于 [love.forte.common.utils.Carrier] 的 Result实例,内部存在一个 [value] 值。 * * 但是此类不提供carrier中那些 orElse 之类的方法。 * */ public data class CarrierResult<T : Any?> internal constructor(val value: T) : Result { override val originalData: String = "Result($value)" override fun toString(): String = originalData companion object { private val TrueResult = CarrierResult(true) private val FalseResult = CarrierResult(false) private val NullResult = CarrierResult(null) @JvmStatic @Suppress("UNCHECKED_CAST") fun <T : Any?> valueOf(value: T): CarrierResult<T> { return when (value) { null -> NullResult as CarrierResult<T> true -> TrueResult as CarrierResult<T> false -> FalseResult as CarrierResult<T> else -> CarrierResult(value) } } } } public fun <T: Any?> T.toCarrierResult(): CarrierResult<T> = CarrierResult.valueOf(this)
0
Kotlin
0
3
c5d7c9ca8c81b2bddc250090739d7c7d0c110328
3,581
simple-robot-v2
Apache License 2.0
buildSrc/src/main/java/Compose.kt
hassan0shaban
289,748,566
false
null
import Versions.compose_version object Compose { const val composJUnitTest = "androidx.compose.ui:ui-test-junit4:${compose_version}" const val composUiTooling = "androidx.compose.ui:ui-tooling:$compose_version" const val composeAndroidX = "androidx.compose.ui:ui:$compose_version" const val composeDialog = "io.github.vanpra.compose-material-dialogs:datetime:${Versions.material_compose}" const val composeMaterial = "androidx.compose.material:material:$compose_version" const val composePreview = "androidx.compose.ui:ui-tooling-preview:${compose_version}" const val composeData = "androidx.compose.ui:ui-tooling-data:${compose_version}" const val composeActivity = "androidx.activity:activity-compose:1.3.1" const val composeLivedata = "androidx.compose.runtime:runtime-livedata:1.1.0-alpha02" const val composeNavigation = "androidx.navigation:navigation-compose:2.4.0-alpha10" }
0
Kotlin
0
0
94b13cdec71a77bb0e2167e2027e66bdf99ba09d
932
Insta
Apache License 2.0
core/src/main/java/com/nowiwr01p/core/datastore/cities/data/MeetingStatus.kt
nowiwr01w
584,138,480
false
null
package com.nowiwr01p.core.datastore.cities.data enum class MeetingStatus(val type: String) { WAITING_FOR_PEOPLE("waiting"), IN_PROGRESS("running"), ENDED("ended") }
0
Kotlin
1
3
0ebdf8f0cc072cf1f07810a6c36e710f373bfc7f
178
Protest
MIT License
app/src/main/java/com/androiddevs/mvvmnewsapp/models/Source.kt
Behnam12872
753,072,926
false
{"Kotlin": 30459}
package com.androiddevs.mvvmnewsapp.models data class Source( val id: String?=null, val name: String )
0
Kotlin
0
0
c94c466f2b298ad1273a4cc44e9520afe73a40f5
111
NewsApp
MIT License