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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
colorpicker/src/main/java/vadiole/colorpicker/ColorPickerDialog.kt | vadiole | 359,756,768 | false | null | package vadiole.colorpicker
import android.app.Dialog
import android.os.Bundle
import androidx.annotation.ColorInt
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
import androidx.core.graphics.ColorUtils
import androidx.core.os.bundleOf
import androidx.fragment.app.DialogFragment
import kotlin.properties.Delegates
/**
* A subclass of DialogFragment with color picker dialog.
*/
class ColorPickerDialog internal constructor() : DialogFragment() {
companion object {
private const val ACTION_OK_KEY = "key_action_ok"
private const val ACTION_CANCEL_KEY = "key_action_cancel"
private const val INITIAL_COLOR_KEY = "key_initial_color"
private const val COLOR_MODEL_NAME_KEY = "key_color_model_name"
private const val COLOR_MODEL_SWITCH_KEY = "key_color_model_switch"
@JvmStatic
private fun newInstance(
@StringRes actionOk: Int,
@StringRes actionCancel: Int,
@ColorInt initialColor: Int,
colorModel: ColorModel,
colorModelSwitchEnabled: Boolean,
): ColorPickerDialog {
val fragment = ColorPickerDialog()
val initialColorCorrectAlpha = if (colorModel != ColorModel.ARGB) {
ColorUtils.setAlphaComponent(initialColor, 255)
} else {
initialColor
}
fragment.arguments = makeArgs(
actionOk,
actionCancel,
initialColorCorrectAlpha,
colorModel,
colorModelSwitchEnabled
)
return fragment
}
@JvmStatic
private fun makeArgs(
@StringRes actionOk: Int,
@StringRes actionCancel: Int,
@ColorInt initialColor: Int,
colorModel: ColorModel,
colorModelSwitchEnabled: Boolean,
) = bundleOf(
ACTION_OK_KEY to actionOk,
ACTION_CANCEL_KEY to actionCancel,
INITIAL_COLOR_KEY to initialColor,
COLOR_MODEL_NAME_KEY to colorModel.name,
COLOR_MODEL_SWITCH_KEY to colorModelSwitchEnabled,
)
}
/**
* Builder for a color picker dialog
*/
class Builder {
@ColorInt
private var initialColor: Int = ColorPickerView.defaultColor
private var colorModel: ColorModel = ColorPickerView.defaultColorModel
private var colorModelSwitchEnabled = true
@StringRes
private var actionOkStringRes: Int = android.R.string.ok
@StringRes
private var actionCancelStringRes: Int = android.R.string.cancel
private var selectColorListener: OnSelectColorListener? = null
private var switchColorModelListenerListener: OnSwitchColorModelListener? = null
/**
* Set initial color for a color picker dialog.
* Default - Color.GRAY.
* @param initialColor the color that will using as default in color picker dialog.
*/
fun setInitialColor(@ColorInt initialColor: Int): Builder {
this.initialColor = initialColor
return this
}
/**
* Set string resource for positive button.
* Default - android.R.string.ok (OK).
* @param stringId the String resource reference for positive button.
*/
fun setButtonOkText(@StringRes stringId: Int): Builder {
actionOkStringRes = stringId
return this
}
/**
* Set string resource for negative button.
* Default - android.R.string.cancel (Cancel).
* @param stringId the String resource reference for negative button.
*/
fun setButtonCancelText(@StringRes stringId: Int): Builder {
actionCancelStringRes = stringId
return this
}
/**
* Set color mode for a color picker dialog.
* @param colorModel the colorMode for the color picker dialog
*
* Can be one of:
* @see ColorModel.ARGB - alpha, red, green, blue.
* @see ColorModel.RGB - red, green, blue
* @see ColorModel.HSV - hue, saturation, value
*/
fun setColorModel(colorModel: ColorModel): Builder {
this.colorModel = colorModel
return this
}
/**
* Sets whether the color model can be switched.
*
* **Note:** it will work only if color model is ColorModel.RGB or ColorModel.HSV.
* @param enabled is switching enabled.
*/
fun setColorModelSwitchEnabled(enabled: Boolean): Builder {
colorModelSwitchEnabled = enabled
return this
}
/**
* Set callback for a color picker dialog to return color, lambda edition.
*
* @param callback the callback to return color from color picker dialog.
*/
fun onColorSelected(callback: (color: Int) -> Unit): Builder {
this.selectColorListener = object : OnSelectColorListener {
override fun onColorSelected(color: Int) {
callback(color)
}
}
return this
}
/**
* Set callback for a color picker dialog to return color.
*
* @param callback the callback to return color from color picker dialog.
*/
fun onColorSelected(callback: OnSelectColorListener): Builder {
this.selectColorListener = callback
return this
}
/**
* Set callback for a color picker dialog to return new color model, lambda edition.
*
* @param callback the callback to return new color model from color picker dialog.
*/
fun onColorModelSwitched(callback: (colorModel: ColorModel) -> Unit): Builder {
this.switchColorModelListenerListener = object : OnSwitchColorModelListener {
override fun onColorModelSwitched(colorModel: ColorModel) {
callback(colorModel)
}
}
return this
}
/**
* Set callback for a color picker dialog to return new color model.
*
* @param callback the callback to return new color model from color picker dialog.
*/
fun onColorModelSwitched(callback: OnSwitchColorModelListener): Builder {
this.switchColorModelListenerListener = callback
return this
}
/**
* Creates an [ColorPickerDialog] with the arguments supplied to this builder.
*
* Calling this method does not display the dialog. If no additional
* processing is needed, [show] may be called instead to both
* create and display the dialog.
*/
fun create(): ColorPickerDialog {
requireNotNull(selectColorListener) { "You must call onColorSelected() before call create()" }
val fragment = newInstance(
actionOkStringRes,
actionCancelStringRes,
initialColor,
colorModel,
colorModelSwitchEnabled
)
fragment.onSelectColorListener = selectColorListener
fragment.onSwitchColorModelListener = switchColorModelListenerListener
return fragment
}
}
private var onSelectColorListener: OnSelectColorListener? = null
private var onSwitchColorModelListener: OnSwitchColorModelListener? = null
var pickerView: ColorPickerView by Delegates.notNull()
/**
* Set callback for a color picker dialog to return color, lambda edition.
* You should call this method in case your activity/fragment was restored.
*
* NOTE: find dialog instance by
* ```
* // In Activity
* supportFragmentManager.findFragmentByTag("your_tag_from_show()_method") as ColorPickerDialog?
* // In Fragment
* childFragmentManager.findFragmentByTag("your_tag_from_show()_method") as ColorPickerDialog?
* ```
* @param callback the callback to return color from color picker dialog.
*/
fun setOnSelectColorListener(callback: (color: Int) -> Unit) {
this.onSelectColorListener = object : OnSelectColorListener {
override fun onColorSelected(color: Int) {
callback(color)
}
}
}
/**
* Set callback for a color picker dialog to return color.
* You should call this method in case your activity/fragment was restored.
*
* NOTE: find dialog instance by
* ```
* // In Activity
* supportFragmentManager.findFragmentByTag("your_tag_from_show()_method") as ColorPickerDialog?
* // In Fragment
* childFragmentManager.findFragmentByTag("your_tag_from_show()_method") as ColorPickerDialog?
* ```
* @param callback the callback to return color from color picker dialog.
*/
fun setOnSelectColorListener(callback: OnSelectColorListener) {
this.onSelectColorListener = callback
}
/**
* Set callback for a color picker dialog to return new color model, lambda edition.
* You should call this method in case your activity/fragment was restored.
*
* NOTE: find dialog instance by
* ```
* // In Activity
* supportFragmentManager.findFragmentByTag("your_tag_from_show()_method") as ColorPickerDialog?
* // In Fragment
* childFragmentManager.findFragmentByTag("your_tag_from_show()_method") as ColorPickerDialog?
* ```
* @param callback the callback to return new color model from color picker dialog.
*/
fun setOnSwitchColorModelListener(callback: (colorModel: ColorModel) -> Unit) {
this.onSwitchColorModelListener = object : OnSwitchColorModelListener {
override fun onColorModelSwitched(colorModel: ColorModel) {
callback(colorModel)
}
}
}
/**
* Set callback for a color picker dialog to return new color model.
* You should call this method in case your activity/fragment was restored.
*
* NOTE: find dialog instance by
* ```
* // In Activity
* supportFragmentManager.findFragmentByTag("your_tag_from_show()_method") as ColorPickerDialog?
* // In Fragment
* childFragmentManager.findFragmentByTag("your_tag_from_show()_method") as ColorPickerDialog?
* ```
* @param callback the callback to return new color model from color picker dialog.
*/
fun setOnSwitchColorModelListener(callback: OnSwitchColorModelListener) {
this.onSwitchColorModelListener = callback
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val bundle = savedInstanceState ?: requireArguments()
val actionOk = bundle.getInt(ACTION_OK_KEY)
val actionCancel = bundle.getInt(ACTION_CANCEL_KEY)
pickerView = ColorPickerView(
requireContext(),
actionOk,
actionCancel,
bundle.getInt(INITIAL_COLOR_KEY),
ColorModel.fromName(bundle.getString(COLOR_MODEL_NAME_KEY)),
bundle.getBoolean(COLOR_MODEL_SWITCH_KEY),
onSwitchColorModelListener
)
pickerView.enableButtonBar(
object : ColorPickerView.ButtonBarListener {
override fun onNegativeButtonClick() = dismiss()
override fun onPositiveButtonClick(color: Int) {
onSelectColorListener?.onColorSelected(color)
dismiss()
}
}
)
return AlertDialog.Builder(requireContext())
.setView(pickerView)
.create()
}
override fun onSaveInstanceState(outState: Bundle) {
val bundle = makeArgs(
pickerView.actionOkRes,
pickerView.actionCancelRes,
pickerView.currentColor,
pickerView.colorModel,
pickerView.colorModelSwitchEnabled
)
outState.putAll(bundle)
super.onSaveInstanceState(outState)
}
override fun onDestroyView() {
onSelectColorListener = null
onSwitchColorModelListener = null
super.onDestroyView()
}
}
| 3 | Kotlin | 4 | 35 | c2026d1d0fb750e522dd1f49bd7920ae95de71f4 | 12,311 | colorpicker | Apache License 2.0 |
fxgl/src/main/kotlin/com/almasb/fxgl/app/Engine.kt | AlmasB | 32,761,091 | false | {"Java": 1808557, "Kotlin": 1802895, "CSS": 45751, "JavaScript": 6195, "HTML": 3049, "C++": 2908, "kvlang": 134} | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (<EMAIL>).
* See LICENSE for details.
*/
package com.almasb.fxgl.app
import com.almasb.fxgl.core.EngineService
import com.almasb.fxgl.core.Inject
import com.almasb.fxgl.core.collection.PropertyMap
import com.almasb.fxgl.core.concurrent.Async
import com.almasb.fxgl.core.reflect.ReflectionUtils.*
import com.almasb.fxgl.core.serialization.Bundle
import com.almasb.fxgl.logging.Logger
import javafx.util.Duration
/**
* FXGL engine is mostly a collection of services, all controlled
* via callbacks driven by the main loop.
*
* @author <NAME> (<EMAIL>)
*/
internal class Engine(val settings: ReadOnlyGameSettings) {
private val log = Logger.get(javaClass)
private val loop = LoopRunner(settings.ticksPerSecond) { loop(it) }
val tpf: Double
get() = loop.tpf
val cpuNanoTime: Long
get() = loop.cpuNanoTime
private val services = arrayListOf<EngineService>()
private val servicesCache = hashMapOf<Class<out EngineService>, EngineService>()
internal val environmentVars = HashMap<String, Any>()
init {
logVersion()
}
private fun logVersion() {
val jVersion = System.getProperty("java.version", "?")
val fxVersion = System.getProperty("javafx.version", "?")
val javaVendorName = System.getProperty("java.vendor", "?")
val operatingSystemName = System.getProperty("os.name", "?")
val operatingSystemVersion = System.getProperty("os.version", "?")
val operatingSystemArchitecture = System.getProperty("os.arch", "?")
val version = settings.runtimeInfo.version
val build = settings.runtimeInfo.build
log.info("FXGL-$version ($build) on ${settings.platform} (J:$jVersion FX:$fxVersion)")
log.debug("JRE Vendor Name: $javaVendorName")
log.debug("Running on OS: $operatingSystemName version $operatingSystemVersion")
log.debug("Architecture: $operatingSystemArchitecture")
log.info("Source code and latest versions at: https://github.com/AlmasB/FXGL")
log.info(" Join the FXGL chat at: https://gitter.im/AlmasB/FXGL")
}
fun <T : EngineService> getService(serviceClass: Class<T>): T {
if (servicesCache.containsKey(serviceClass))
return servicesCache[serviceClass] as T
return (services.find { serviceClass.isAssignableFrom(it.javaClass) }?.also { servicesCache[serviceClass] = it }
?: throw IllegalArgumentException("Engine does not have service: $serviceClass")) as T
}
fun initServices() {
initEnvironmentVars()
settings.engineServices.forEach {
services += (newInstance(it))
}
services.forEach {
injectDependenciesIntoService(it)
}
services.forEach {
it.onInit()
}
Async.schedule({ logEnvironmentVarsAndServices() }, Duration.seconds(3.0))
}
private fun initEnvironmentVars() {
log.debug("Initializing environment variables")
settings.javaClass.declaredMethods.filter { it.name.startsWith("is") || it.name.startsWith("get") || it.name.endsWith("Property") }.forEach {
environmentVars[it.name.removePrefix("get").decapitalize()] = it.invoke(settings)
}
}
private fun injectDependenciesIntoService(service: EngineService) {
findFieldsByAnnotation(service, Inject::class.java).forEach { field ->
val injectKey = field.getDeclaredAnnotation(Inject::class.java).value
if (injectKey !in environmentVars) {
throw IllegalArgumentException("Cannot inject @Inject($injectKey). No value present for $injectKey")
}
inject(field, service, environmentVars[injectKey])
}
findFieldsByTypeRecursive(service, EngineService::class.java).forEach { field ->
val provider = services.find { field.type.isAssignableFrom(it.javaClass) }
?: throw IllegalStateException("No provider found for ${field.type}")
inject(field, service, provider)
}
}
private fun logEnvironmentVarsAndServices() {
log.debug("Logging environment variables")
environmentVars.toSortedMap().forEach { (key, value) ->
log.debug("$key: $value")
}
log.debug("Logging services")
services.forEach {
log.debug("${it.javaClass}")
}
}
private fun loop(tpf: Double) {
services.forEach { it.onUpdate(tpf) }
}
fun onGameUpdate(tpf: Double) {
services.forEach { it.onGameUpdate(tpf) }
}
fun onGameReady(vars: PropertyMap) {
services.forEach { it.onGameReady(vars) }
}
/**
* Notifies the services that the loop is starting and starts the loop.
* This needs to be called on the JavaFX thread.
*/
fun startLoop() {
services.forEach { it.onMainLoopStarting() }
loop.start()
}
fun stopLoop() {
loop.stop()
}
fun stopLoopAndExitServices() {
loop.stop()
services.forEach { it.onExit() }
}
fun pauseLoop() {
services.forEach { it.onMainLoopPausing() }
loop.pause()
}
fun resumeLoop() {
loop.resume()
services.forEach { it.onMainLoopResumed() }
}
fun write(bundle: Bundle) {
settings.write(bundle)
services.forEach { it.write(bundle) }
}
fun read(bundle: Bundle) {
settings.read(bundle)
services.forEach { it.read(bundle) }
}
} | 138 | Java | 546 | 4,315 | c0eaf4b0af29cf062867a37f3424a4ac37e8dcca | 5,627 | FXGL | MIT License |
backend.native/tests/runtime/workers/worker_threadlocal_no_leak.kt | JetBrains | 58,957,623 | false | null | /*
* Copyright 2010-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.
*/
@file:OptIn(kotlin.experimental.ExperimentalNativeApi::class, ObsoleteWorkersApi::class)
import kotlin.native.concurrent.*
import kotlin.native.Platform
@ThreadLocal
var x = Any()
fun main() {
Platform.isMemoryLeakCheckerActive = true
val worker = Worker.start()
worker.execute(TransferMode.SAFE, {}) {
println(x) // Make sure x is initialized
}.result
worker.requestTermination().result
}
| 166 | null | 625 | 7,100 | 9fb0a75ab17e9d8cddd2c3d1802a1cdd83774dfa | 575 | kotlin-native | Apache License 2.0 |
attribution/src/main/java/com/affise/attribution/events/subscription/SubscriptionEnteredBillingRetry.kt | affise | 496,592,599 | false | null | package com.affise.attribution.events.subscription
import org.json.JSONObject
/**
* Event TrialInRetry use [data] of event and [userData]
*/
class TrialInRetryEvent @JvmOverloads constructor(
data: JSONObject? = null,
userData: String? = null
) : BaseSubscriptionEvent(data, userData) {
/**
* Type of event
*/
override val type = SubscriptionEventName.AFFISE_SUBSCRIPTION_ENTERED_BILLING_RETRY.eventName
/**
* Subtype of event
*/
override val subtype = SubscriptionSubType.AFFISE_SUB_TRIAL_IN_RETRY.typeName
}
/**
* Event OfferInRetry use [data] of event and [userData]
*/
class OfferInRetryEvent @JvmOverloads constructor(
data: JSONObject? = null,
userData: String? = null
) : BaseSubscriptionEvent(data, userData) {
/**
* Type of event
*/
override val type = SubscriptionEventName.AFFISE_SUBSCRIPTION_ENTERED_BILLING_RETRY.eventName
/**
* Subtype of event
*/
override val subtype = SubscriptionSubType.AFFISE_SUB_OFFER_IN_RETRY.typeName
}
/**
* Event SubscriptionInRetry use [data] of event and [userData]
*/
class SubscriptionInRetryEvent @JvmOverloads constructor(
data: JSONObject? = null,
userData: String? = null
) : BaseSubscriptionEvent(data, userData) {
/**
* Type of event
*/
override val type = SubscriptionEventName.AFFISE_SUBSCRIPTION_ENTERED_BILLING_RETRY.eventName
/**
* Subtype of event
*/
override val subtype = SubscriptionSubType.AFFISE_SUB_SUBSCRIPTION_IN_RETRY.typeName
} | 0 | null | 0 | 5 | ab7d393c6583208e33cef9e10e01ba9dd752bbcb | 1,542 | sdk-android | MIT License |
injectk_dagger_hilt_test/src/main/java/com/mozhimen/injectk/dagger/hilt/test/vms/MainViewModel.kt | mozhimen | 798,115,184 | false | {"Kotlin": 23436} | package com.mozhimen.injectk.dagger.hilt.test.vms
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.mozhimen.kotlin.elemk.androidx.lifecycle.bases.BaseViewModel
import com.mozhimen.injectk.dagger.hilt.test.commons.IGetValueListener
import com.mozhimen.injectk.dagger.hilt.test.helpers.CacheRepository
import com.mozhimen.injectk.dagger.hilt.test.helpers.RemoteRepository
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* @ClassName MainViewModel
* @Description TODO
* @Author Mozhimen & <NAME>
* @Date 2023/6/7 11:27
* @Version 1.0
*/
class MainViewModel @AssistedInject constructor(
private val _cacheRepository: CacheRepository,
private val _remoteRepository: RemoteRepository,
private val _getValueListener: IGetValueListener,
@Assisted
private val _strTest: String
) : BaseViewModel() {
fun getCache(): String = _cacheRepository.getCache()
fun getRemote(): String = _remoteRepository.getRemote()
private val _msfValue = MutableStateFlow(_getValueListener.onGetValue())
val sfValue: StateFlow<String> = _msfValue
@AssistedFactory
interface Factory {
fun create(strTest: String): MainViewModel
}
companion object {
fun provideMainViewModelFactory(factory: Factory, strTest: String): ViewModelProvider.Factory {
return object : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return factory.create(strTest) as T
}
}
}
}
private val _liveTest = MutableLiveData(_strTest)
val liveTest: LiveData<String?> get() = _liveTest
} | 0 | Kotlin | 0 | 0 | a8742505a07231da0269ff6bb9ac0dbf2c6c961d | 1,957 | AInjectKit | MIT License |
src/main/kotlin/com/nibado/projects/advent/y2017/Day14.kt | nielsutrecht | 47,550,570 | false | null | package com.nibado.projects.advent.y2017
import com.nibado.projects.advent.*
import com.nibado.projects.advent.Point
object Day14 : Day {
private val rows = (0..127).map { "amgozmfv-$it" }
private val square : List<String> by lazy { rows.map { hash(it) }.map { toBinary(it) } }
override fun part1() = square.sumBy { it.count { it == '1' } }.toString()
override fun part2(): String {
val points = (0 .. 127).flatMap { x -> (0 .. 127 ).map { y -> Point(x, y) } }.toMutableSet()
val visited = points.filter { square[it.y][it.x] == '0'}.toMutableSet()
points.removeAll(visited)
var count = 0
while(!points.isEmpty()) {
count++
fill(visited, points, points.first())
}
return count.toString()
}
private fun fill(visited: MutableSet<Point>, points: MutableSet<Point>, current: Point) {
visited += current
points -= current
current.neighborsHv().filter { points.contains(it) }.forEach { fill(visited, points, it) }
}
private fun hash(input: String): String {
val chars = input.toCharArray().map { it.toInt() } + listOf(17, 31, 73, 47, 23)
return (0..15).map { Day10.knot(chars, 64).subList(it * 16, it * 16 + 16) }.map { xor(it) }.toHex()
}
} | 1 | Kotlin | 0 | 16 | b4221cdd75e07b2860abf6cdc27c165b979aa1c7 | 1,301 | adventofcode | MIT License |
user-error-api/src/main/kotlin/net/plshark/usererror/user/UserCreate.kt | twinklehawk | 138,668,802 | false | null | package net.plshark.usererror.user
data class UserCreate(val username: String, val password: String)
| 10 | null | 1 | 1 | de43c003235a141076722eb45640dea1202f9809 | 102 | bad-users | Apache License 2.0 |
DaggerSingleModuleApp/app/src/main/java/com/github/yamamotoj/daggersinglemoduleapp/package19/Foo01910.kt | yamamotoj | 163,851,411 | false | null | package com.github.yamamotoj.module4.package19
import javax.inject.Inject
class Foo01910 @Inject constructor(){
fun method0() { Foo01909().method5() }
fun method1() { method0() }
fun method2() { method1() }
fun method3() { method2() }
fun method4() { method3() }
fun method5() { method4() }
}
| 0 | Kotlin | 0 | 9 | 2a771697dfebca9201f6df5ef8441578b5102641 | 317 | android_multi_module_experiment | Apache License 2.0 |
src/test/kotlin/com/example/demo/service/impl/MemoServiceIntegrationTests.kt | rubytomato | 128,201,361 | false | null | package com.example.demo.service.impl
import com.example.demo.service.MemoService
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.data.domain.PageRequest
import org.springframework.test.context.junit4.SpringRunner
/**
* 結合テスト
*/
@RunWith(SpringRunner::class)
@SpringBootTest
class MemoServiceIntegrationTests {
@Autowired
lateinit var sut: MemoService
@Test
fun findById() {
val actual = sut.findById(1)
assertThat(actual).`as`("actualは必ず検索できる").isNotNull()
actual?.let {
assertThat(it.id).isEqualTo(1)
}
}
@Test
fun findAll() {
val page = PageRequest.of(0, 3)
val actual = sut.findAll(page)
assertThat(actual).hasSize(3)
}
} | 1 | null | 1 | 5 | 69fed570a51ee0ab852876bd57c481b90f9f237e | 940 | demo-kotlin-spring2 | MIT License |
app/src/main/java/com/project/findhere/AddActivity.kt | yukkohzq | 385,481,000 | false | null | package com.project.findhere
import android.app.Activity
import android.app.DatePickerDialog
import android.content.ContentValues.TAG
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.provider.Settings
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import com.google.android.material.button.MaterialButton
import com.google.android.material.textfield.TextInputEditText
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.storage.FirebaseStorage
import com.google.firebase.storage.StorageReference
import com.project.findhere.models.FindPost
import com.project.findhere.models.FoundPost
import com.project.findhere.models.User
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import java.util.jar.Manifest
class AddActivity : AppCompatActivity() {
lateinit var imageUri: Uri
lateinit var outputImage: File
private var signedInUser: User? = null
private lateinit var signedInUserId: String
private lateinit var tvDatePicker: TextView
private lateinit var btnDatePicker: Button
private lateinit var storageReference: StorageReference
private lateinit var fireStoreDb: FirebaseFirestore
private lateinit var firebaseAuth: FirebaseAuth
private val takePhoto = 1
private val fromAlbum = 2
private val CAMERA_PERMISSION_REQ = 1000
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
storageReference = FirebaseStorage.getInstance().reference
firebaseAuth = FirebaseAuth.getInstance()
val selectPosition = intent.getSerializableExtra("TabSelected") as Int
Log.d("SelectedPosision", "${selectPosition}")
//get user&id
fireStoreDb = FirebaseFirestore.getInstance()
fireStoreDb.collection("users")
.document(firebaseAuth.currentUser?.uid as String)
.get()
.addOnSuccessListener { userSnapshot ->
signedInUser = userSnapshot.toObject(User::class.java)
Log.i(TAG, "signed in user: $signedInUser")
}
.addOnFailureListener { exception ->
Log.i(TAG, "Failure fetching signed in user", exception)
}
signedInUserId = firebaseAuth.currentUser?.uid as String
//
//add backButton
val button: MaterialButton = findViewById(R.id.add_backButton)
button.setOnClickListener() {
onBackPressed()
}//
//addPhotoPicker
val takePhotoBtn: Button = findViewById(R.id.add_button_takePhoto)
takePhotoBtn.setOnClickListener {
if (checkSelfPermission(android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
handleCameraBtnClick()
}
else{
requestPermissions(arrayOf(android.Manifest.permission.CAMERA),CAMERA_PERMISSION_REQ)
}
}
val fromAlbumBtn: Button = findViewById(R.id.add_button_fromAlbum)
fromAlbumBtn.setOnClickListener {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
startActivityForResult(intent, fromAlbum)
}//
//add DatePicker
tvDatePicker = findViewById(R.id.add_tvDate)
btnDatePicker = findViewById(R.id.add_btnDatePicker)
val myCalendar = Calendar.getInstance()
val datePicker = DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
myCalendar.set(Calendar.YEAR, year)
myCalendar.set(Calendar.MONTH, month)
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth)
updateLable(myCalendar)
}
btnDatePicker.setOnClickListener {
DatePickerDialog(
this,
datePicker,
myCalendar.get(Calendar.YEAR),
myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)
).show()
}//
//add submit button
val btnSubmit: MaterialButton = findViewById(R.id.add_submit)
btnSubmit.setOnClickListener {
if (selectPosition == 0) {
handleFoundBtnClick()
} else {
handleFindBtnClick()
}
}//
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
when(requestCode){
CAMERA_PERMISSION_REQ -> {
if(grantResults[0] == PackageManager.PERMISSION_GRANTED){
handleCameraBtnClick()
}
else{
Log.d("AddActivity","CAMERA DENIED")
Toast.makeText(this,"未允许使用相机",Toast.LENGTH_SHORT).show()
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private fun handleCameraBtnClick() {
outputImage = File(externalCacheDir, "output_image.jpg")
if (outputImage.exists()) {
outputImage.delete()
}
outputImage.createNewFile()
imageUri = FileProvider.getUriForFile(this, "com.project.findhere", outputImage)
val intent = Intent("android.media.action.IMAGE_CAPTURE")
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
startActivityForResult(intent, takePhoto)
}
private fun handleFoundBtnClick() {
val imageView: ImageView = findViewById(R.id.add_imageView)
val tvDate: TextView = findViewById(R.id.add_tvDate)
if (tvDate.text.isBlank()) {
Toast.makeText(this, "日期不能为空", Toast.LENGTH_SHORT).show()
return
}
val tvPlace: TextInputEditText = findViewById(R.id.add_PlaceET)
if (tvPlace.text?.isBlank() == true) {
Toast.makeText(this, "地点不能为空", Toast.LENGTH_SHORT).show()
return
}
val tvContent: EditText = findViewById(R.id.add_ContentET)
if (tvContent.text.isBlank()) {
Toast.makeText(this, "描述不能为空", Toast.LENGTH_SHORT).show()
return
}
val tvName: TextInputEditText = findViewById(R.id.add_NameET)
if (tvName.text?.isBlank() == true) {
Toast.makeText(this, "物品名称不能为空", Toast.LENGTH_SHORT).show()
return
}
val btnSubmit: MaterialButton = findViewById(R.id.add_submit)
btnSubmit.isEnabled = false
val photoReference =
storageReference.child("images/${System.currentTimeMillis()}-photo.jpg")
// upload photo to firebase
photoReference.putFile(imageUri)
.continueWithTask { photoUploadTask ->
Log.i(TAG, "uploaded bytes: ${photoUploadTask.result?.bytesTransferred}")
//retrieve image url of the uploaded image
photoReference.downloadUrl
}.continueWithTask { downloadUrlTask ->
// create a post object with the image URL and add that to the posts collection
val post = FoundPost(
signedInUser,
signedInUserId,
System.currentTimeMillis(),
tvDate.text.toString(),
tvName.text.toString(),
downloadUrlTask.result.toString(),
tvPlace.text.toString(),
tvContent.text.toString()
)
fireStoreDb.collection("foundposts").add(post)
}.addOnCompleteListener { postCreationTask ->
btnSubmit.isEnabled = true
if (!postCreationTask.isSuccessful) {
Log.e(TAG, "Exception during Firebase operations", postCreationTask.exception)
Toast.makeText(this, "上传失败", Toast.LENGTH_SHORT).show()
}
tvContent.text.clear()
tvPlace.text?.clear()
imageView.setImageResource(0)
Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
private fun handleFindBtnClick() {
val imageView: ImageView = findViewById(R.id.add_imageView)
val tvDate: TextView = findViewById(R.id.add_tvDate)
if (tvDate.text.isBlank()) {
Toast.makeText(this, "日期不能为空", Toast.LENGTH_SHORT).show()
return
}
val tvPlace: TextInputEditText = findViewById(R.id.add_PlaceET)
if (tvPlace.text?.isBlank() == true) {
Toast.makeText(this, "地点不能为空", Toast.LENGTH_SHORT).show()
return
}
val tvContent: EditText = findViewById(R.id.add_ContentET)
if (tvContent.text.isBlank()) {
Toast.makeText(this, "描述不能为空", Toast.LENGTH_SHORT).show()
return
}
val tvName: TextInputEditText = findViewById(R.id.add_NameET)
if (tvName.text?.isBlank() == true) {
Toast.makeText(this, "物品名称不能为空", Toast.LENGTH_SHORT).show()
return
}
val btnSubmit: MaterialButton = findViewById(R.id.add_submit)
btnSubmit.isEnabled = false
val photoReference =
storageReference.child("images/${System.currentTimeMillis()}-photo.jpg")
// upload photo to firebase
photoReference.putFile(imageUri)
.continueWithTask { photoUploadTask ->
Log.i(TAG, "uploaded bytes: ${photoUploadTask.result?.bytesTransferred}")
//retrieve image url of the uploaded image
photoReference.downloadUrl
}.continueWithTask { downloadUrlTask ->
// create a post object with the image URL and add that to the posts collection
val post = FindPost(
signedInUser,
signedInUserId,
System.currentTimeMillis(),
tvDate.text.toString(),
tvName.text.toString(),
downloadUrlTask.result.toString(),
tvPlace.text.toString(),
tvContent.text.toString()
)
fireStoreDb.collection("findposts").add(post)
}.addOnCompleteListener { postCreationTask ->
btnSubmit.isEnabled = true
if (!postCreationTask.isSuccessful) {
Log.e(TAG, "Exception during Firebase operations", postCreationTask.exception)
Toast.makeText(this, "上传失败", Toast.LENGTH_SHORT).show()
}
tvContent.text.clear()
tvPlace.text?.clear()
imageView.setImageResource(0)
Toast.makeText(this, "上传成功", Toast.LENGTH_SHORT).show()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
takePhoto -> {
if (resultCode == Activity.RESULT_OK) {
val bitmap =
BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri))
val imageView: ImageView = findViewById(R.id.add_imageView)
imageView.setImageBitmap(rotateIfRequired(bitmap))
}
}
fromAlbum -> {
if (resultCode == Activity.RESULT_OK && data != null) {
data.data?.let { uri ->
val bitmap = getBitmapFromUri(uri)
val imageView: ImageView = findViewById(R.id.add_imageView)
imageView.setImageBitmap(bitmap)
}
}
}
}
}
private fun rotateIfRequired(bitmap: Bitmap): Bitmap {
val exif = ExifInterface(outputImage.path)
val orientation =
exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
return when (orientation) {
ExifInterface.ORIENTATION_ROTATE_90 -> rotateBitmap(bitmap, 90)
ExifInterface.ORIENTATION_ROTATE_180 -> rotateBitmap(bitmap, 180)
ExifInterface.ORIENTATION_ROTATE_270 -> rotateBitmap(bitmap, 270)
else -> bitmap
}
}
private fun rotateBitmap(bitmap: Bitmap, degree: Int): Bitmap {
val matrix = Matrix()
matrix.postRotate(degree.toFloat())
val rotatedBitmap =
Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
bitmap.recycle()
return rotatedBitmap
}
private fun getBitmapFromUri(uri: Uri) = contentResolver.openFileDescriptor(uri, "r")?.use {
BitmapFactory.decodeFileDescriptor(it.fileDescriptor)
}
private fun updateLable(myCalendar: Calendar) {
val myFormat = "yyyy-MM-dd"
val sdf = SimpleDateFormat(myFormat, Locale.CHINA)
tvDatePicker.setText(sdf.format(myCalendar.time))
}
} | 0 | Kotlin | 0 | 1 | 2f3c7e96172e2dbf2ccee7647a1f7b039156da11 | 13,740 | Findhere | MIT License |
feature_search/src/main/java/com/pimenta/bestv/search/domain/UrlEncoderTextUseCase.kt | marcuspimenta | 132,016,354 | false | null | /*
*
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.andtv.flicknplay.search.domain
import io.reactivex.Single
import java.net.URLEncoder
import javax.inject.Inject
/**
*
*/
private const val enc = "UTF-8"
class UrlEncoderTextUseCase @Inject constructor() {
operator fun invoke(text: String): Single<String> =
Single.fromCallable { URLEncoder.encode(text, enc) }
}
| 5 | null | 20 | 54 | 63b92f876dd7d4571d3824e723e67c1872d25cd3 | 905 | BESTV | Apache License 2.0 |
src/jvmTest/kotlin/io/grule/parser/RecursiveParserTest.kt | 7hens | 376,845,987 | false | null | package io.grule.parser
import org.junit.Test
import kotlin.test.assertEquals
class RecursiveParserTest {
@Test
fun itMe() {
RepeatGrammar().apply {
val source = "0 1 2 3 4 5 6"
println("================")
println(source)
println("X + Num self { it + me }")
val e by parser { X + N self { it + me } }
val astNode = e.parse(tokenStream(source))
println(astNode.toStringExp())
println(astNode.toString())
println(astNode.toStringTree())
assertEquals("(0 (1 (2 (3 (4 (5 6))))))", astNode.toStringExp())
assertEquals(
"e(e(N(0)) e(e(N(1)) e(e(N(2)) e(e(N(3)) e(e(N(4)) e(e(N(5)) e(N(6))))))))",
astNode.toString()
)
}
}
@Test
fun itOpMe() {
RepeatGrammar().apply {
val source = "x * 1 / 2 - 3 + 4 / 5"
println("================")
println(source)
println("X + \"x\" or X + Num self { it + Op + me }")
val e by parser { X + "x" or X + N self { it + O + me } }
val astNode = e.parse(tokenStream(source))
println(astNode.toStringExp())
println(astNode.toString())
println(astNode.toStringTree())
assertEquals("(x * (1 / (2 - (3 + (4 / 5)))))", astNode.toStringExp())
assertEquals(
"e(e(x) O(*) e(e(N(1)) O(/) e(e(N(2)) O(-) e(e(N(3)) O(+) e(e(N(4)) O(/) e(N(5)))))))",
astNode.toString()
)
}
}
@Test
fun meIt() {
RepeatGrammar().apply {
val source = "0 1 2 3"
println("================")
println(source)
println("X + Num self { me + it }")
val e by parser { X + N self { me + it } }
val astNode = e.parse(tokenStream(source))
println(astNode.toStringExp())
println(astNode.toString())
println(astNode.toStringTree())
assertEquals("(((0 1) 2) 3)", astNode.toStringExp())
assertEquals("e(e(e(e(N(0)) e(N(1))) e(N(2))) e(N(3)))", astNode.toString())
}
}
@Test
fun meOpIt() {
RepeatGrammar().apply {
val source = "0 * 1 / x"
println("================")
println(source)
println("X + \"x\" or X + Num self { me + Op + it }")
val e by parser { X + "x" or X + N self { me + O + it } }
val astNode = e.parse(tokenStream(source))
println(astNode.toStringExp())
println(astNode.toString())
println(astNode.toStringTree())
assertEquals("((0 * 1) / x)", astNode.toStringExp())
assertEquals("e(e(e(N(0)) O(*) e(N(1))) O(/) e(x))", astNode.toString())
}
}
@Test
fun meOp_meNum() {
RepeatGrammar().apply {
val source = "0 + 1 2 3"
println("================")
println(source)
println("X + Num self { me + Op } self { me + Num }")
val e by parser { X + N self { me + O } self { me + N } }
val astNode = e.parse(tokenStream(source))
println(astNode.toStringExp())
println(astNode.toString())
println(astNode.toStringTree())
assertEquals("((((0 +) 1) 2) 3)", astNode.toStringExp())
assertEquals("e(e(e(e(e(N(0)) O(+)) N(1)) N(2)) N(3))", astNode.toString())
}
}
@Test
fun meItOrMeOp() {
RepeatGrammar().apply {
val source = "0 + 1 2 - 3"
println("================")
println(source)
println("X + Num self { me + it or me + Op }")
val e by parser { X + N self { me + it or me + O } }
val astNode = e.parse(tokenStream(source))
println(astNode.toStringExp())
println(astNode.toString())
println(astNode.toStringTree())
assertEquals("(((((0 +) 1) 2) -) 3)", astNode.toStringExp())
assertEquals("e(e(e(e(e(e(N(0)) O(+)) e(N(1))) e(N(2))) O(-)) e(N(3)))", astNode.toString())
}
}
@Test
fun meOp_meIt() {
RepeatGrammar().apply {
val source = "0 * 1 + 2 * 3 - 4"
println("================")
println(source)
println(" X + N self { me + O } self { me + it }")
val e by parser { X + N self { me + O } self { me + it } }
val astNode = e.parse(tokenStream(source))
println(astNode.toStringExp())
println(astNode.toString())
println(astNode.toStringTree())
assertEquals("(((((0 *) (1 +)) (2 *)) (3 -)) 4)", astNode.toStringExp())
assertEquals(
"e(e(e(e(e(e(N(0)) O(*)) e(e(N(1)) O(+))) e(e(N(2)) O(*))) e(e(N(3)) O(-))) e(N(4)))",
astNode.toString()
)
}
}
@Test
fun meOpIt_binary() {
RepeatGrammar().apply {
val source = "0 * 1 + 2 * 3 - 4 / x"
println("================")
println(source)
println("X + Num or X + \"x\" self { me + Op + it }")
val e by parser { X + N or X + "x" self { me + O + it } }
val b by parser { e.flat().binary(O) }
val astNode = b.parse(tokenStream(source))
println(astNode.toStringExp())
println(astNode.toString())
println(astNode.toStringTree())
assertEquals("(((0 * 1) + (2 * 3)) - (4 / x))", astNode.toStringExp())
assertEquals(
"b(e(e(e(e(N(0)) O(*) e(N(1))) O(+) e(e(N(2)) O(*) e(N(3)))) O(-) e(e(N(4)) O(/) e(x))))",
astNode.toString()
)
}
}
@Test
fun meXIt_meXIt() {
RepeatGrammar().apply {
val source = "1 + 2 * 3 * 4 + 5"
println("--------------------------------------")
println(source)
println("X + Num self { me + \"*\" + it } self { me + \"+\" + it }")
val e by parser { X + N self { me + "*" + it } self { me + "+" + it } }
val m by parser { X + e }
val astNode = m.parse(tokenStream(source))
println(astNode.toStringExp())
println(astNode.toString())
println(astNode.toStringTree())
assertEquals("((1 + ((2 * 3) * 4)) + 5)", astNode.toStringExp())
assertEquals(
"m(e(e(e(N(1)) + e(e(e(N(2)) * e(N(3))) * e(N(4)))) + e(N(5))))",
astNode.toString()
)
}
}
@Test
fun numOpMe() {
RepeatGrammar().apply {
val source = "0 * 1 + 2 * 3 - 4 / x"
println("================")
println(source)
println("{ X + \"x\" or X + Num self { X + Num + Op + me } }")
val e by parser { X + "x" or X + N self { X + N + O + me } }
val astNode = e.parse(tokenStream(source))
println(astNode.toStringExp())
println(astNode.toString())
println(astNode.toStringTree())
assertEquals("(0 * (1 + (2 * (3 - (4 / x)))))", astNode.toStringExp())
assertEquals(
"e(N(0) O(*) e(N(1) O(+) e(N(2) O(*) e(N(3) O(-) e(N(4) O(/) e(x))))))",
astNode.toString()
)
}
}
} | 0 | Kotlin | 0 | 1 | 3c00cfd151e78515a93f20a90369e43dd3b75f73 | 7,442 | grule | Apache License 2.0 |
multipaysdk/src/main/java/com/inventiv/multipaysdk/util/Validator.kt | multinetinventiv | 332,757,520 | false | null | package com.inventiv.multipaysdk.util
import android.util.Patterns
import com.inventiv.multipaysdk.MultiPaySdk
import com.inventiv.multipaysdk.R
import com.inventiv.multipaysdk.data.model.type.ValidationErrorType
internal object Validator {
const val INPUT_TYPE_EMAIL = 0
const val INPUT_TYPE_GSM = 1
const val INPUT_TYPE_UNDEFINED = 2
const val NAME_INPUT_MIN_LENGTH = 2
private const val PASSWORD_MIN = 8
private const val PASSWORD_MAX = 20
private const val MASKED_LENGTH_PHONE = 16
private const val MASKED_PREFIX_PHONE = "0"
fun getInputType(str: String): Int {
return when {
str.isEmpty() -> {
INPUT_TYPE_UNDEFINED
}
atLeastOneAlpha(str) -> {
INPUT_TYPE_EMAIL
}
else -> {
INPUT_TYPE_GSM
}
}
}
private fun atLeastOneAlpha(str: String): Boolean {
return str.matches(".*[a-zA-Z]+.*".toRegex())
}
fun validEmail(email: String): Boolean {
return (email.isNotEmpty() && Patterns.EMAIL_ADDRESS.matcher(email).matches())
}
fun validPassword(password: String): Boolean {
return (password.isNotEmpty()
&& password.length >= PASSWORD_MIN && password.length <= PASSWORD_MAX)
}
fun validGsmWithMask(gsm: String): Boolean {
return (gsm.isNotEmpty()
&& gsm.length == MASKED_LENGTH_PHONE && gsm.startsWith(MASKED_PREFIX_PHONE))
}
fun getValidationError(type: ValidationErrorType): String {
when {
type === ValidationErrorType.NAME -> {
return MultiPaySdk.getComponent().getString(R.string.validation_name_multipay_sdk)
}
type === ValidationErrorType.SURNAME -> {
return MultiPaySdk.getComponent()
.getString(R.string.validation_surname_multipay_sdk)
}
type === ValidationErrorType.EMAIL -> {
return MultiPaySdk.getComponent().getString(R.string.validation_email_multipay_sdk)
}
type === ValidationErrorType.GSM -> {
return MultiPaySdk.getComponent().getString(R.string.validation_gsm_multipay_sdk)
}
type === ValidationErrorType.EMAIL_GSM -> {
return MultiPaySdk.getComponent()
.getString(R.string.validation_email_or_gsm_multipay_sdk)
}
else -> return StringUtils.EMPTY
}
}
} | 0 | Kotlin | 0 | 0 | a13e2f5faa0fcb9cc8479d83b8cdfcbbb3bb2462 | 2,524 | MultiPay-Android-Sdk | Apache License 2.0 |
modules/wasm-binary/src/commonMain/kotlin/tree/instructions/MinInstruction.kt | wasmium | 761,480,110 | false | {"Kotlin": 352107, "JavaScript": 200} | package org.wasmium.wasm.binary.tree.instructions
import org.wasmium.wasm.binary.tree.Opcode
import org.wasmium.wasm.binary.visitors.FunctionBodyVisitor
public class MinInstruction(public override val opcode: Opcode) : NoneInstruction {
override fun accept(functionBodyVisitor: FunctionBodyVisitor) {
functionBodyVisitor.visitMinInstruction(opcode)
}
}
| 0 | Kotlin | 0 | 1 | f7ddef76630278616d221e7c8251adf0f11b9587 | 371 | wasmium-wasm-binary | Apache License 2.0 |
compiler/testData/asJava/lightClasses/ideRegression/ImplementingCharSequenceAndNumber.kt | JakeWharton | 99,388,807 | false | null | // p1.Container
package p1
class Container {
class MyString : CharSequence {
override val length: Int
get() = 0
override fun chars(): IntStream = error("")
override fun codePoints(): IntStream = error("")
override fun get(index: Int): Char = 'c'
override fun subSequence(startIndex: Int, endIndex: Int): CharSequence = MyString()
}
class MyNumber : Number {
override fun toByte(): Byte {
TODO("not implemented")
}
override fun toChar(): Char {
TODO("not implemented")
}
override fun toDouble(): Double {
TODO("not implemented")
}
override fun toFloat(): Float {
TODO("not implemented")
}
override fun toInt(): Int {
TODO("not implemented")
}
override fun toLong(): Long {
TODO("not implemented")
}
override fun toShort(): Short {
TODO("not implemented")
}
}
} | 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 1,035 | kotlin | Apache License 2.0 |
ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/OnMapAndViewReadyListener.kt | googlemaps-samples | 34,364,279 | false | null | /*
* Copyright 2018 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.kotlindemos
import android.annotation.SuppressLint
import android.os.Build
import android.view.View
import android.view.ViewTreeObserver.OnGlobalLayoutListener
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
/**
* Helper class that will delay triggering the OnMapReady callback until both the GoogleMap and the
* View having completed initialization. This is only necessary if a developer wishes to immediately
* invoke any method on the GoogleMap that also requires the View to have finished layout
* (ie. anything that needs to know the View's true size like snapshotting).
*/
class OnMapAndViewReadyListener(
private val mapFragment: SupportMapFragment,
private val toBeNotified: OnGlobalLayoutAndMapReadyListener
) : OnGlobalLayoutListener,
OnMapReadyCallback {
private val mapView: View? = mapFragment.view
private var isViewReady = false
private var isMapReady = false
private var map: GoogleMap? = null
/** A listener that needs to wait for both the GoogleMap and the View to be initialized. */
interface OnGlobalLayoutAndMapReadyListener {
fun onMapReady(googleMap: GoogleMap?)
}
init {
registerListeners()
}
private fun registerListeners() {
// View layout.
mapView?.let {
if (it.width != 0 && it.height != 0) {
// View has already completed layout.
isViewReady = true
} else {
// Map has not undergone layout, register a View observer.
it.viewTreeObserver.addOnGlobalLayoutListener(this)
}
}
// GoogleMap. Note if the GoogleMap is already ready it will still fire the callback later.
mapFragment.getMapAsync(this)
}
override fun onMapReady(googleMap: GoogleMap) {
// NOTE: The GoogleMap API specifies the listener is removed just prior to invocation.
map = googleMap ?: return
isMapReady = true
fireCallbackIfReady()
}
// We use the new method when supported
@Suppress("DEPRECATION")
@SuppressLint("NewApi") // We check which build version we are using.
override fun onGlobalLayout() {
// Remove our listener.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
mapView?.viewTreeObserver?.removeGlobalOnLayoutListener(this)
} else {
mapView?.viewTreeObserver?.removeOnGlobalLayoutListener(this)
}
isViewReady = true
fireCallbackIfReady()
}
private fun fireCallbackIfReady() {
if (isViewReady && isMapReady) {
toBeNotified.onMapReady(map)
}
}
}
| 53 | null | 5 | 2,416 | 00c5b8c0e0e767773fb7991e2080bd5bc7007645 | 3,394 | android-samples | Apache License 2.0 |
core/design-system/src/main/java/dev/enesky/core/design_system/annotation/PreviewUiMode.kt | enesky | 708,119,546 | false | null | /*
* Copyright 2023
* Designed and developed by <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.enesky.core.design_system.annotation
import android.content.res.Configuration
import androidx.compose.ui.tooling.preview.Preview
/**
* Created by <NAME> on 18/11/2023
*/
@Preview(
name = "Light Theme",
uiMode = Configuration.UI_MODE_NIGHT_NO,
showBackground = true,
backgroundColor = 0xFFDFE6E9,
)
@Preview(
name = "Dark Theme",
uiMode = Configuration.UI_MODE_NIGHT_YES,
showBackground = true,
backgroundColor = 0xFF2B323F,
)
annotation class PreviewUiMode
| 28 | null | 0 | 9 | 1341678e0974fc0e0292836e9a8571da679150d9 | 1,161 | Doodle | Apache License 2.0 |
packages/default-storage/android/src/test/java/com/reactnativecommunity/asyncstorage/next/StorageTest.kt | react-native-async-storage | 169,431,434 | false | null | package abi49_0_0.com.reactnativecommunity.asyncstorage.next
import androidx.room.Room
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import org.json.JSONObject
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import kotlin.random.Random
@ExperimentalCoroutinesApi
@RunWith(AndroidJUnit4::class)
class AsyncStorageAccessTest {
private lateinit var asyncStorage: AsyncStorageAccess
private lateinit var database: StorageDb
@Before
fun setup() {
database = Room.inMemoryDatabaseBuilder(
InstrumentationRegistry.getInstrumentation().context, StorageDb::class.java
).allowMainThreadQueries().build()
asyncStorage = StorageSupplier(database)
}
@After
fun tearDown() {
database.close()
}
@Test
fun performsBasicGetSetRemoveOperations() = runBlocking {
val entriesCount = 10
val entries = createRandomEntries(entriesCount)
val keys = entries.map { it.key }
assertThat(asyncStorage.getValues(keys)).hasSize(0)
asyncStorage.setValues(entries)
assertThat(asyncStorage.getValues(keys)).hasSize(entriesCount)
val indicesToRemove = (1..4).map { Random.nextInt(0, entriesCount) }.distinct()
val toRemove = entries.filterIndexed { index, _ -> indicesToRemove.contains(index) }
asyncStorage.removeValues(toRemove.map { it.key })
val currentEntries = asyncStorage.getValues(keys)
assertThat(currentEntries).hasSize(entriesCount - toRemove.size)
}
@Test
fun readsAllKeysAndClearsDb() = runBlocking {
val entries = createRandomEntries(8)
val keys = entries.map { it.key }
asyncStorage.setValues(entries)
val dbKeys = asyncStorage.getKeys()
assertThat(dbKeys).isEqualTo(keys)
asyncStorage.clear()
assertThat(asyncStorage.getValues(keys)).hasSize(0)
}
@Test
fun mergesDeeplyTwoValues() = runBlocking {
val initialEntry = Entry("key", VALUE_INITIAL)
val overrideEntry = Entry("key", VALUE_OVERRIDES)
asyncStorage.setValues(listOf(initialEntry))
asyncStorage.mergeValues(listOf(overrideEntry))
val current = asyncStorage.getValues(listOf("key"))[0]
assertThat(current.value).isEqualTo(VALUE_MERGED)
}
@Test
fun updatesExistingValues() = runBlocking {
val key = "test_key"
val value = "test_value"
val entries = listOf(Entry(key, value))
assertThat(asyncStorage.getValues(listOf(key))).hasSize(0)
asyncStorage.setValues(entries)
assertThat(asyncStorage.getValues(listOf(key))).isEqualTo(entries)
val modifiedEntries = listOf(Entry(key, "updatedValue"))
asyncStorage.setValues(modifiedEntries)
assertThat(asyncStorage.getValues(listOf(key))).isEqualTo(modifiedEntries)
}
// Test Helpers
private fun createRandomEntries(count: Int = Random.nextInt(10)): List<Entry> {
val entries = mutableListOf<Entry>()
for (i in 0 until count) {
entries.add(Entry("key$i", "value$i"))
}
return entries
}
private val VALUE_INITIAL = JSONObject(
"""
{
"key":"value",
"key2":"override",
"key3":{
"key4":"value4",
"key6":{
"key7":"value7",
"key8":"override"
}
}
}
""".trimMargin()
).toString()
private val VALUE_OVERRIDES = JSONObject(
"""
{
"key2":"value2",
"key3":{
"key5":"value5",
"key6":{
"key8":"value8"
}
}
}
"""
).toString()
private val VALUE_MERGED = JSONObject(
"""
{
"key":"value",
"key2":"value2",
"key3":{
"key4":"value4",
"key6":{
"key7":"value7",
"key8":"value8"
},
"key5":"value5"
}
}
""".trimMargin()
).toString()
}
| 627 | null | 467 | 4,720 | bb41ee1574862798ac106843bae6843774d78f8d | 4,215 | async-storage | MIT License |
compiler/testData/diagnostics/tests/backingField/FieldShadow.fir.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} | class My {
// No initialization needed because no backing field
val two: Int
get() {
val field = 2
return field
}
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 164 | kotlin | Apache License 2.0 |
src/main/kotlin/com/skillw/fightsystem/internal/manager/PersonalManagerImpl.kt | Skillw | 591,845,487 | false | {"Kotlin": 162033, "JavaScript": 15586} | package com.skillw.fightsystem.internal.manager
import com.skillw.fightsystem.api.manager.PersonalManager
import com.skillw.fightsystem.internal.feature.personal.PersonalData
import com.skillw.pouvoir.api.script.ScriptTool
import com.skillw.pouvoir.internal.feature.database.PouvoirContainer
import com.skillw.pouvoir.util.player
import org.bukkit.entity.Player
import java.util.*
object PersonalManagerImpl : PersonalManager() {
override val key = "PersonalManager"
override val priority: Int = 12
override val subPouvoir = com.skillw.fightsystem.FightSystem
override val enable: Boolean
get() = FSConfig.isPersonalEnable
override fun onDisable() {
this.forEach {
val player = it.key.player() ?: return
pushData(player)
}
}
override fun get(key: UUID): PersonalData {
if (super.get(key) == null) {
this[key] = PersonalData(key)
}
return if (!enable) {
super.get(key)?.run {
if (default) {
this
} else {
default()
this
}
}!!
} else super.get(key)!!
}
override fun pushData(player: Player) {
val name = player.name
if (enable)
PouvoirContainer.container[name, "personal-data"] = this[player.uniqueId].toString()
}
override fun pullData(player: Player): PersonalData? {
val name = player.name
return if (enable)
PersonalData.fromStr(PouvoirContainer.container[name, "personal-data"] ?: return null, player.uniqueId)
else PersonalData(player.uniqueId)
}
override fun hasData(player: Player): Boolean {
return (ScriptTool.get(player, "personal-data") ?: "null") != "null"
}
}
| 0 | Kotlin | 4 | 6 | 84a1273549df31573acb4e8ae32d46923ebc23d1 | 1,833 | FightSystem | MIT License |
demo/src/main/java/com/backbase/deferredresources/demo/DemoPagerAdapter.kt | morristech | 320,873,386 | true | {"Kotlin": 177397, "Java": 7833, "Shell": 1308} | package com.backbase.deferredresources.demo
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.recyclerview.widget.RecyclerView
import com.backbase.deferredresources.DeferredColor
import com.backbase.deferredresources.DeferredDrawable
import com.backbase.deferredresources.DeferredFormattedPlurals
import com.backbase.deferredresources.DeferredText
class DemoPagerAdapter : RecyclerView.Adapter<DemoPagerAdapter.DeferredResourceViewHolder>() {
private val formattedPluralsResource = DeferredFormattedPlurals.Resource(R.plurals.horses)
private val oval by lazy {
GradientDrawable(
GradientDrawable.Orientation.BL_TR,
intArrayOf(Color.parseColor("#00ff00"), Color.parseColor("#000fff"))
).apply {
gradientType = GradientDrawable.RADIAL_GRADIENT
cornerRadius = 0.8f
shape = GradientDrawable.OVAL
}
}
fun getPageName(position: Int): CharSequence = when (position) {
0 -> "Colors"
1 -> "Plurals resource"
2 -> "Drawables"
else -> throw IllegalArgumentException("Position $position in adapter with size $itemCount")
}
override fun getItemCount(): Int = ViewType.values().size
override fun getItemViewType(position: Int): Int = when (position) {
0 -> ViewType.COLORS.ordinal
1 -> ViewType.PLURALS.ordinal
2 -> ViewType.DRAWABLES.ordinal
else -> throw IndexOutOfBoundsException("Position $position in adapter with size $itemCount")
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeferredResourceViewHolder {
val view = when (ViewType.values()[viewType]) {
ViewType.COLORS -> DeferredColorsView(parent.context)
ViewType.PLURALS -> DeferredPluralsView(parent.context)
ViewType.DRAWABLES -> DeferredDrawablesView(parent.context)
}.apply {
layoutParams = LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
}
return DeferredResourceViewHolder(view)
}
override fun onBindViewHolder(holder: DeferredResourceViewHolder, position: Int) {
when (val view = holder.root) {
is DeferredColorsView -> {
view.display(
DeferredColor.Attribute(R.attr.colorSecondary),
DeferredText.Constant("Secondary")
)
view.display(
DeferredColor.Resource(R.color.backbase_red),
DeferredText.Constant("Backbase red")
)
view.display(
DeferredColor.Constant(Color.WHITE),
DeferredText.Constant("White")
)
}
is DeferredPluralsView -> when (position) {
1 -> view.display(formattedPluralsResource)
}
is DeferredDrawablesView -> {
view.display(DeferredDrawable.Constant(oval), DeferredText.Constant("Constant: "))
view.display(DeferredDrawable.Resource(R.drawable.oval), DeferredText.Constant("Resource: "))
view.display(
DeferredDrawable.Attribute(android.R.attr.homeAsUpIndicator),
DeferredText.Constant("Attribute: ")
)
}
}
}
class DeferredResourceViewHolder(
val root: DeferredResourceView
) : RecyclerView.ViewHolder(root)
private enum class ViewType {
COLORS, PLURALS, DRAWABLES
}
}
| 0 | null | 0 | 0 | 6b9c418c325639830ebfb43bcef0d6c0da5be2e2 | 3,712 | DeferredResources | Apache License 2.0 |
src/main/kotlin/in/obvious/mobius/creator/util/DependencyHandler.kt | obvious | 250,562,058 | false | null | package `in`.obvious.mobius.creator.util
import com.android.ide.common.repository.GradleCoordinate
import com.android.tools.idea.projectsystem.getModuleSystem
import com.intellij.openapi.module.ModuleUtil
import com.intellij.psi.PsiDirectory
class DependencyHandler(directory: PsiDirectory) {
private val module = ModuleUtil.findModuleForFile(directory.virtualFile, directory.project)
// TODO (SM): Support adding test gradle dependencies
fun addDependency(artifact: Artifact) {
val parsedCoordinate = GradleCoordinate.parseCoordinateString("${artifact.artifactId}:+")
module?.getModuleSystem()?.registerDependency(parsedCoordinate)
}
}
| 0 | Kotlin | 0 | 9 | 4edd73f8ae7590e21c6894e2708bf3e6e4f8bd59 | 657 | mobius-creator | MIT License |
app/src/main/java/com/kylecorry/trail_sense/tools/paths/ui/commands/ImportPathsCommand.kt | kylecorry31 | 215,154,276 | false | null | package com.kylecorry.trail_sense.tools.paths.ui.commands
import android.content.Context
import androidx.lifecycle.LifecycleOwner
import com.kylecorry.andromeda.alerts.Alerts
import com.kylecorry.andromeda.core.coroutines.BackgroundMinimumState
import com.kylecorry.andromeda.core.coroutines.onDefault
import com.kylecorry.andromeda.core.coroutines.onIO
import com.kylecorry.andromeda.core.filterIndices
import com.kylecorry.andromeda.fragments.inBackground
import com.kylecorry.andromeda.gpx.GPXData
import com.kylecorry.andromeda.gpx.GPXWaypoint
import com.kylecorry.andromeda.pickers.CoroutinePickers
import com.kylecorry.trail_sense.R
import com.kylecorry.trail_sense.shared.UserPreferences
import com.kylecorry.trail_sense.shared.io.ImportService
import com.kylecorry.trail_sense.tools.paths.domain.FullPath
import com.kylecorry.trail_sense.tools.paths.domain.IPathService
import com.kylecorry.trail_sense.tools.paths.domain.Path
import com.kylecorry.trail_sense.tools.paths.domain.PathGroup
import com.kylecorry.trail_sense.tools.paths.domain.PathMetadata
import com.kylecorry.trail_sense.tools.paths.domain.PathPoint
import com.kylecorry.trail_sense.tools.paths.domain.PathSimplificationQuality
import com.kylecorry.trail_sense.tools.paths.infrastructure.persistence.IPathPreferences
import com.kylecorry.trail_sense.tools.paths.infrastructure.persistence.PathService
class ImportPathsCommand(
private val context: Context,
private val lifecycleOwner: LifecycleOwner,
private val gpxService: ImportService<GPXData>,
private val pathService: IPathService = PathService.getInstance(context),
private val prefs: IPathPreferences = UserPreferences(context).navigation
) {
private val style = prefs.defaultPathStyle
fun execute(parentId: Long?) {
lifecycleOwner.inBackground(BackgroundMinimumState.Created) {
val gpx = gpxService.import() ?: return@inBackground
val paths = mutableListOf<FullPath>()
// Get the tracks and routes from the GPX
paths.addAll(getTracks(gpx))
paths.addAll(getRoutes(gpx))
// Let the user select the paths to import
val selectedPathIndices = CoroutinePickers.items(
context,
context.getString(R.string.import_btn),
paths.map {
it.path.name ?: context.getString(android.R.string.untitled)
},
paths.indices.toList()
) ?: return@inBackground
Alerts.withLoading(context, context.getString(R.string.importing)) {
// Import the selected paths
val selectedPaths = paths.filterIndices(selectedPathIndices)
importPaths(selectedPaths, parentId)
// Let the user know the import was successful
Alerts.toast(
context, context.resources.getQuantityString(
R.plurals.paths_imported,
selectedPathIndices.size,
selectedPathIndices.size
)
)
}
}
}
private suspend fun getRoutes(gpx: GPXData): List<FullPath> = onDefault {
// Groups are a Trail Sense concept, so routes don't have groups
val paths = mutableListOf<FullPath>()
for (route in gpx.routes) {
val path = Path(0, route.name, style, PathMetadata.empty)
paths.add(FullPath(path, route.points.toPathPoints()))
}
paths
}
private suspend fun getTracks(gpx: GPXData): List<FullPath> = onDefault {
val paths = mutableListOf<FullPath>()
for (track in gpx.tracks) {
for ((points) in track.segments) {
val path = Path(0, track.name, style, PathMetadata.empty)
val parent = track.group?.let {
PathGroup(0, it)
}
paths.add(FullPath(path, points.toPathPoints(), parent))
}
}
paths
}
private fun List<GPXWaypoint>.toPathPoints(): List<PathPoint> {
return map {
PathPoint(0, 0, it.coordinate, it.elevation, it.time)
}
}
private suspend fun importPaths(
paths: List<FullPath>, parentId: Long?
) = onIO {
val shouldSimplify = prefs.simplifyPathOnImport
val groupNames = paths.mapNotNull { it.parent?.name }.distinct()
val groupIdMap = mutableMapOf<String, Long>()
for (groupName in groupNames) {
val id = pathService.addGroup(PathGroup(0, groupName, parentId))
groupIdMap[groupName] = id
}
for (path in paths) {
val parent = if (path.parent != null) {
groupIdMap[path.parent.name]
} else {
parentId
}
// Create the path
val pathToCreate = path.path.copy(parentId = parent)
val pathId = pathService.addPath(pathToCreate)
// Add the waypoints to the path
pathService.addWaypointsToPath(path.points, pathId)
// Simplify the path
if (shouldSimplify) {
pathService.simplifyPath(
pathId,
PathSimplificationQuality.High
)
}
}
}
} | 456 | null | 66 | 989 | 41176d17b498b2dcecbbe808fbe2ac638e90d104 | 5,360 | Trail-Sense | MIT License |
rpglib/src/main/kotlin/com/naosim/rpglib/android/fieldviewmodel/WebFieldViewModelImpl.kt | naosim | 65,505,136 | false | {"JavaScript": 817270, "Kotlin": 67806, "Java": 4165, "HTML": 1637, "Shell": 42} | package com.naosim.rpglib.android.fieldviewmodel
import android.util.Log
import android.webkit.ConsoleMessage
import android.webkit.WebChromeClient
import android.webkit.WebView
import com.naosim.rpglib.model.value.field.*
import com.naosim.rpglib.model.viewmodel.fieldviewmodel.FieldViewModel
import org.json.JSONArray
import org.json.JSONObject
class WebFieldViewModelImpl(
val webView: WebView,
override val onload: (FieldViewModel) -> Unit,
override val onstep: (FieldViewModel, PositionAndDirection) -> Unit
): FieldViewModel {
init {
webView.setWebChromeClient(object : WebChromeClient() {
override fun onConsoleMessage(cm: ConsoleMessage): Boolean {
if(cm.message().contains("###")) {
Log.e("WebFieldViewModelImpl", cm.message())
val args = cm.message().split("###")
val methodName = args[0]
if (methodName == "onload") {
onload.invoke(this@WebFieldViewModelImpl)
} else if (methodName == "position") {
val obj = JSONObject(args[1])
val position = Position(
FieldNameImpl(obj.getString("fieldName")),
X(obj.getInt("x")),
Y(obj.getInt("y"))
)
onstep.invoke(this@WebFieldViewModelImpl, PositionAndDirection(
position,
createDirection(obj.getString("direction"))
))
}
return true
} else {
Log.e("console${cm.lineNumber()}", cm.message())
}
return false
}
})
}
override fun getPositionAndDirection(callback: (PositionAndDirection) -> Unit) {
webView.evaluateJavascript("fromNative.getPosition()") {
val v = JSONObject(it)
val position = Position(
FieldNameImpl(v.getString("fieldName")!!),
X(v.getInt("x")),
Y(v.getInt("y"))
)
callback.invoke(
PositionAndDirection(
position,
createDirection(v.getString("direction"))
)
)
}
}
override fun gotoPosition(pos: Position) {
val json = JSONObject()
json.put("fieldName", pos.fieldName.value)
json.put("x", pos.x.value)
json.put("y", pos.y.value)
Log.e("WebFieldViewModelImpl", json.toString())
webView.evaluateJavascript("fromNative.gotoPosition(${json.toString()})"){}
}
override fun updateFieldLayer(fieldLayer: FieldLayer) {
val json = JSONObject()
json.put("fieldName", fieldLayer.fieldName.value)
json.put("fieldLayerName", fieldLayer.fieldLayerName.value)
json.put("fieldData", JSONArray(fieldLayer.fieldData.value))
json.put("fieldCollisionData", if(fieldLayer.fieldCollisionData != null) JSONArray(fieldLayer.fieldCollisionData.value) else null)
Log.e("WebFieldViewModelImpl", json.toString())
webView.evaluateJavascript("fromNative.updateFieldLayer(${json.toString()})"){}
}
override fun runFieldEffect(fieldEffect: FieldEffect, callback: () -> Unit) {
throw UnsupportedOperationException("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onButtonDown(arrowButtonType: ArrowButtonType) {
webView.evaluateJavascript("fromNative.onButtonDown(\"${arrowButtonType.name}\")"){}
Log.e("WebFieldViewModelImpl", "onButtonDown " + arrowButtonType.name)
}
override fun onButtonUp(arrowButtonType: ArrowButtonType) {
webView.evaluateJavascript("fromNative.onButtonUp(\"${arrowButtonType.name}\")"){}
Log.e("WebFieldViewModelImpl", "onButtonUp " + arrowButtonType.name)
}
/*
override fun call(input: I, callback: (I) -> Unit) {
modelConverter?.let {
val inputJSON = it.encode(input)
webView.evaluateJavascript("fromNative.call(${inputJSON})"){
it?.let {
val json = JSONObject(it)
callback([email protected](json))
}
}
}
}
*/
}
| 0 | JavaScript | 0 | 0 | a26dd7ff3da98dd82eabbff50bd2098974743655 | 4,516 | RPGSample | MIT License |
app/src/main/java/com/example/commontask/view/mappers/ForecastCommonMapper.kt | Arhs92 | 136,605,425 | false | {"Java": 2710649, "Kotlin": 43646, "CSS": 9707, "HTML": 2131} | package com.example.commontask.view.mappers
import java.text.SimpleDateFormat
import java.util.*
object ForecastCommonMapper {
fun getWeatherDescription(icon: String): String = when (icon) {
"clear-day", "clear-night" -> "clear sky"
"rain" -> "rain"
"snow" -> "snow"
"sleet" -> "sleet"
"wind" -> "wind"
"fog" -> "fog"
"cloudy" -> "cloudy"
"partly-cloudy-day", "partly-cloudy-night" -> "partly cloudy day"
"hail" -> "hail"
"thunderstorm" -> "thunderstorm"
"tornado" -> "tornado"
else -> "Μη-Αναγνωρίσιμο Φαινόμενο"
}
fun calculateWind(w: Double?): String {
return if (w != null) {
"%.2f".format(w) + " m/s"
} else {
"NA"
}
}
fun calculateHumidity(h: Double?): String {
return if (h != null) {
val humidity = h.times(100)
"%.0f".format(humidity) + " %"
} else {
"NA"
}
}
// f1 = low, f2 = high
fun fahrenheitToCelsius(f1: Double?, f2: Double? = null): String {
return if (f2 == null) {
if (f1 != null) {
val temperature = (f1 - 32) * 0.5556
if ("%.0f".format(temperature) == "-0") {
"0°C"
} else {
"%.0f".format(temperature) + "°C"
}
} else {
"NA"
}
} else {
if (f1 != null) {
val temperatureLow = (f1 - 32) * 0.5556
val temperatureHigh = (f2 - 32) * 0.5556
if ("%.0f".format(temperatureLow) == "-0") {
"0°" + " | " + "%.0f".format(temperatureHigh) + "°"
} else if ("%.0f".format(temperatureHigh) == "-0") {
"%.0f".format(temperatureLow) + "°" + " | " + "0°"
} else if ("%.0f".format(temperatureLow) == "-0" && "%.0f".format(temperatureHigh) == "-0") {
"0°" + " | " + "0°"
} else {
"%.0f".format(temperatureLow) + "°" + " | " + "%.0f".format(temperatureHigh) + "°"
}
} else {
"NA"
}
}
}
fun getListItemDay(unixTime: Long): String {
val date = Date(unixTime * 1000L) // *1000 is to convert seconds to milliseconds
val sdf = SimpleDateFormat("E", Locale.getDefault())
return sdf.format(date)
}
fun getIcon(condition: String?, timeStamp: Long? = null): String {
val cal = Calendar.getInstance()
var hour = cal.get(Calendar.HOUR_OF_DAY)
if (timeStamp != null) {
val date = Date(timeStamp * 1000L)
val sdf = SimpleDateFormat("H", Locale.getDefault())
hour = sdf.format(date).toInt()
}
val isNight = hour < 6 || hour > 18
return if (isNight) {
ForecastCommonMapper.nightConditionToIcon(condition)
} else {
ForecastCommonMapper.dayConditionToIcon(condition)
}
}
fun dayConditionToIcon(condition: String?): String {
return when (condition) {
"clear-day", "clear-night" -> "ic_weather_set_1_36"
"rain" -> "ic_weather_set_1_40"
"snow" -> "ic_weather_set_1_43"
"sleet" -> "ic_weather_set_1_42"
"wind" -> "ic_weather_set_1_24"
"fog" -> "ic_weather_set_1_19"
"cloudy" -> "ic_weather_set_1_26"
"partly-cloudy-day", "partly-cloudy-night" -> "ic_weather_set_1_34"
"hail" -> "ic_weather_set_1_18"
"thunderstorm" -> "ic_weather_set_1_35"
"tornado" -> "ic_weather_set_1_20"
else -> "ic_weather_set_1_32"
}
}
private fun nightConditionToIcon(condition: String?): String = when (condition) {
"clear-day", "clear-night" -> "ic_weather_set_1_31"
"rain" -> "ic_weather_set_1_45"
"snow" -> "ic_weather_set_1_46"
"sleet" -> "ic_weather_set_1_05"
"wind" -> "ic_weather_set_1_24"
"fog" -> "ic_weather_set_1_21"
"cloudy" -> "ic_weather_set_1_27"
"partly-cloudy-night", "partly-cloudy-day" -> "ic_weather_set_1_34"
"hail" -> "ic_weather_set_1_18"
"thunderstorm" -> "ic_weather_set_1_00"
"tornado" -> "ic_weather_set_1_20"
else -> "ic_weather_set_1_31"
}
fun timestampToDate(timeStamp: Long): String {
val date = Date(timeStamp * 1000L) // *1000 is to convert seconds to milliseconds
//val sdf = SimpleDateFormat("E, MMM dd, yyyy", Locale.getDefault())
val sdf = SimpleDateFormat("E, MMM dd", Locale.getDefault())
return sdf.format(date)
}
fun timestampToHour(timeStamp: Long): String {
val date = Date(timeStamp * 1000L)
val sdf = SimpleDateFormat("HH:mm", Locale.getDefault())
return sdf.format(date).toLowerCase()
}
} | 1 | null | 1 | 1 | 6d4ff919debe04b09fbabe8fd4b40dc933cb90f6 | 4,993 | AppLea | Apache License 2.0 |
easing/src/commonMain/kotlin/co/touchlab/composeanimations/easing/Circ.kt | touchlab | 392,801,626 | false | {"Kotlin": 56518, "Swift": 551} | package co.touchlab.composeanimations.easing
import androidx.compose.animation.core.Easing
import kotlin.math.pow
import kotlin.math.sqrt
// https://easings.net/#easeInCirc
object EaseInCirc : Easing {
override fun transform(fraction: Float): Float =
1 - sqrt(1 - fraction.pow(2))
}
// https://easings.net/#easeOutCirc
object EaseOutCirc : Easing {
override fun transform(fraction: Float): Float =
sqrt(1 - (fraction - 1).pow(2))
}
// https://easings.net/#easeInOutCirc
object EaseInOutCirc : Easing {
override fun transform(fraction: Float): Float = if (fraction < 0.5f) {
(1 - sqrt(1 - (2 * fraction).pow(2))) / 2
} else {
(sqrt(1 - (-2 * fraction + 2).pow(2)) + 1) / 2
}
}
| 0 | Kotlin | 1 | 48 | b14e1c2ec270eff99bb5d2c6141e7a3e1ff7d649 | 732 | compose-animations | Apache License 2.0 |
github/src/main/kotlin/gropius/sync/github/config/MongoConfig.kt | ccims | 487,996,394 | false | {"Kotlin": 958426, "TypeScript": 437791, "MDX": 55477, "JavaScript": 25165, "HTML": 17174, "CSS": 4796, "Shell": 2363} | package gropius.sync.github.config
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.convert.converter.Converter
import org.springframework.data.mongodb.core.convert.MongoCustomConversions
import java.time.OffsetDateTime
import java.time.ZoneOffset
import java.util.*
/**
* Custom configuration for the mongodb driver implementing custom conversion for offsetdatetime
*/
@Configuration
class MongoConfig {
/**
* Bean providing custom converter
* @return resulting converter list
*/
@Bean
fun customConversions(): MongoCustomConversions {
return MongoCustomConversions(
listOf(
OffsetDateTimeReadConverter(),
OffsetDateTimeWriteConverter()
)
)
}
/**
* MongoDB write type converter
*/
internal class OffsetDateTimeWriteConverter : Converter<OffsetDateTime, Date?> {
override fun convert(source: OffsetDateTime): Date? {
return Date.from(source.toInstant().atZone(ZoneOffset.UTC).toInstant())
}
}
/**
* MongoDB read type converter
*/
internal class OffsetDateTimeReadConverter : Converter<Date, OffsetDateTime?> {
override fun convert(source: Date): OffsetDateTime? {
return source.toInstant()?.atOffset(ZoneOffset.UTC)
}
}
} | 3 | Kotlin | 1 | 0 | de0ece42541db960a08e1448cf0bd5afd65c996a | 1,425 | gropius-backend | MIT License |
core/src/test/kotlin/core/model/HandlerMethodComparatorTest.kt | gitter-badger | 152,720,407 | false | {"YAML": 10, "Maven POM": 14, "Text": 1, "Ignore List": 1, "Markdown": 1, "XML": 5, "Kotlin": 90, "INI": 4, "Java": 21} | /*
* Lamblin
* Copyright 2018 <NAME>
* Licensed under Apache 2.0: https://github.com/BorislavShekerov/lamblin/blob/master/LICENSE
*/
package core.model
import com.lamblin.core.model.HandlerMethod
import com.lamblin.core.model.HandlerMethodComparator
import com.lamblin.core.model.HandlerMethodParameter
import com.lamblin.core.model.HttpMethod
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
class HandlerMethodComparatorTest {
private val handlerMethodComparator = HandlerMethodComparator()
@Test
fun `shorter path should take precedence`() {
val handleMethod1 = createHandlerMethod("/path")
val handleMethod2 = createHandlerMethod("/path/longer")
assertThat(handlerMethodComparator.compare(handleMethod1, handleMethod2)).isEqualTo(-1)
}
@Test
fun `when 2 paths of the same length are compared, the one with less path params is chosen`() {
val handleMethod1 = createHandlerMethod("/path/result")
val handleMethod2 = createHandlerMethod("/path/{param}")
assertThat(handlerMethodComparator.compare(handleMethod1, handleMethod2)).isEqualTo(-1)
}
@Test
fun `when the 2 paths are the same, the one with more query params takes precedence`() {
val handleMethod1 = createHandlerMethod(
"/path/result?param1=query1",
mapOf(
"param1" to HandlerMethodParameter(
annotationMappedName = "param1",
name = "param1",
required = true,
type = String::class.java)))
val handleMethod2 = createHandlerMethod(
"/path/result?param1=query1¶m2=param2",
mapOf(
"param1" to HandlerMethodParameter(
annotationMappedName = "param1",
name = "param1",
required = true,
type = String::class.java),
"param2" to HandlerMethodParameter(
annotationMappedName = "param2",
name = "param2",
required = true,
type = String::class.java)))
assertThat(handlerMethodComparator.compare(handleMethod1, handleMethod2)).isEqualTo(1)
}
@Test
fun `should be equal when same path, no query and path params`() {
val handleMethod1 = createHandlerMethod("/path")
val handleMethod2 = createHandlerMethod("/path")
assertThat(handlerMethodComparator.compare(handleMethod1, handleMethod2)).isEqualTo(0)
}
@Test
fun `should be equal when same path, and path params`() {
val handleMethod1 = createHandlerMethod("/path/{param}")
val handleMethod2 = createHandlerMethod("/path/{param}")
assertThat(handlerMethodComparator.compare(handleMethod1, handleMethod2)).isEqualTo(0)
}
@Test
fun `should be equal when same path,query and path params`() {
val handleMethod1 = createHandlerMethod(
"/path/{param}?query=query",
mapOf(
"query" to HandlerMethodParameter(
annotationMappedName = "query",
name = "query",
required = true,
type = String::class.java))
)
val handleMethod2 = createHandlerMethod(
"/path/{param}?query=query",
mapOf(
"query" to HandlerMethodParameter(
annotationMappedName = "query",
name = "query",
required = true,
type = String::class.java)))
assertThat(handlerMethodComparator.compare(handleMethod1, handleMethod2)).isEqualTo(0)
}
@Test
fun `should be equal when same path, and query params, no path param`() {
val handleMethod1 = createHandlerMethod(
"/path?query=query",
mapOf(
"query" to HandlerMethodParameter(
annotationMappedName = "query",
name = "query",
required = true,
type = String::class.java)))
val handleMethod2 = createHandlerMethod(
"/path?query=query",
mapOf(
"query" to HandlerMethodParameter(
annotationMappedName = "query",
name = "query",
required = true,
type = String::class.java)))
assertThat(handlerMethodComparator.compare(handleMethod1, handleMethod2)).isEqualTo(0)
}
@Test
fun `path with query param should take precedence when comparing to equivalent path-param-based paths`() {
val handleMethod1 = createHandlerMethod(
"/path/{param}?query=query",
mapOf(
"query" to HandlerMethodParameter(
annotationMappedName = "query",
name = "query",
required = true,
type = String::class.java)))
val handleMethod2 = createHandlerMethod("/path/{param}")
assertThat(handlerMethodComparator.compare(handleMethod1, handleMethod2)).isEqualTo(-1)
}
private fun createHandlerMethod(
path: String,
params: Map<String, HandlerMethodParameter> = mapOf()
) =
HandlerMethod(
path,
HttpMethod.GET,
params,
method = HandlerMethodComparatorTest::class.java.declaredMethods.first(),
controllerClass = HandlerMethodComparatorTest::class.java)
}
| 1 | null | 1 | 1 | c0b5a12d7696b172ddeccef39f7c15663c1b2b3d | 5,601 | lamblin | Apache License 2.0 |
src/main/kotlin/server/routing/RoutingMap.kt | spbu-math-cs | 698,589,492 | false | {"Kotlin": 145510} | package server.routing
import db.DBOperator
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.plugins.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import org.json.JSONObject
import server.logger
import server.utils.handleHTTPRequestException
import java.io.File
fun Route.requestsMap() {
get("/api/textures") {
try {
val textures = DBOperator.getAllTextures()
call.respond(HttpStatusCode.OK, JSONObject()
.put("type", "ok")
.put("result", textures.map { mapOf("id" to it.id.toString(), "filepath" to it.pathToFile) })
.toString()
)
logger.info("Successful GET /api/textures request from: ${call.request.origin.remoteAddress}")
} catch (e: Exception) {
handleHTTPRequestException(call, "GET /api/textures", e)
}
}
get("/api/textures/{id}") {
val textureID = call.parameters["id"]?.toUIntOrNull() ?: 0u
try {
val textureFile = File(
DBOperator.getTextureByID(textureID)?.pathToFile
?: throw IllegalArgumentException("Texture #$textureID does not exist")
)
call.response.status(HttpStatusCode.OK)
call.response.header(
HttpHeaders.ContentDisposition,
ContentDisposition.Attachment
.withParameter(ContentDisposition.Parameters.FileName, textureFile.name)
.toString()
)
call.respondFile(textureFile)
logger.info("Successful GET /api/textures/$textureID request from: ${call.request.origin.remoteAddress}")
} catch (e: Exception) {
handleHTTPRequestException(call, "GET /api/textures/$textureID", e)
}
}
get("/api/tilesets") {
try {
val tilesets = DBOperator.getAllTilesets()
call.respond(HttpStatusCode.OK, JSONObject()
.put("type", "ok")
.put("result", tilesets.map { mapOf("id" to it.id.toString(), "filepath" to it.pathToJson) })
.toString()
)
logger.info("Successful GET /api/tilesets request from: ${call.request.origin.remoteAddress}")
} catch (e: Exception) {
handleHTTPRequestException(call, "GET /api/tilesets", e)
}
}
get("/api/tilesets/{id}") {
val tilesetID = call.parameters["id"]?.toUIntOrNull() ?: 0u
try {
val tilesetFile = File(
DBOperator.getTilesetByID(tilesetID)?.pathToJson
?: throw IllegalArgumentException("Tileset #$tilesetID does not exist")
)
call.response.status(HttpStatusCode.OK)
call.respond(tilesetFile.readText())
logger.info("Successful GET /api/tilesets/$tilesetID request from: ${call.request.origin.remoteAddress}")
} catch (e: Exception) {
handleHTTPRequestException(call, "GET /api/tilesets/$tilesetID", e)
}
}
get("/api/maps") {
try {
val maps = DBOperator.getAllMaps()
call.respond(HttpStatusCode.OK, JSONObject()
.put("type", "ok")
.put("result", maps.map { mapOf("id" to it.id.toString(), "filepath" to it.pathToJson) })
.toString()
)
logger.info("Successful GET /api/maps request from: ${call.request.origin.remoteAddress}")
} catch (e: Exception) {
handleHTTPRequestException(call, "GET /api/maps", e)
}
}
get("/api/maps/{id}") {
val mapID = call.parameters["id"]?.toUIntOrNull() ?: 0u
try {
val mapFile = File(
DBOperator.getMapByID(mapID)?.pathToJson
?: throw IllegalArgumentException("Map #$mapID does not exist")
)
call.response.status(HttpStatusCode.OK)
call.respond(mapFile.readText())
logger.info("Successful GET /api/maps/$mapID request from: ${call.request.origin.remoteAddress}")
} catch (e: Exception) {
handleHTTPRequestException(call, "GET /api/maps/$mapID", e)
}
}
}
| 7 | Kotlin | 1 | 3 | d7e63d8f732b0a8af9f4a951edda1ec8e2623005 | 4,242 | RollPlayer-backend | Apache License 2.0 |
recommend/src/main/java/com/allever/lib/recommend/Recommend.kt | devallever | 244,091,663 | false | null | package com.allever.app.kotlin.coroutine.retrofit
import androidx.annotation.Keep
@Keep
class Recommend {
var id: Int = 0
var type: Int = 0
var name: String = ""
var iconResId: Int = 0
var desc: String = ""
var size: String = ""
var channel: String = ""
var pkg: String = ""
var url: String = ""
var googleUrl = ""
var xiaomiUrl = ""
var tag: String = ""
var version: String = ""
var iconUrl: String = ""
} | 0 | null | 9 | 40 | 8d11947254b39fff7ec7aa8d7a623ce41b5250f5 | 464 | TranslationTextOpenSource | Apache License 2.0 |
feature/lightbox/view/implementation/src/main/kotlin/com/savvasdalkitsis/uhuruphotos/feature/lightbox/view/implementation/navigation/LightboxNavigationTarget.kt | savvasdalkitsis | 485,908,521 | false | null | /*
Copyright 2023 Savvas Dalkitsis
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.savvasdalkitsis.uhuruphotos.feature.lightbox.view.implementation.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import com.savvasdalkitsis.uhuruphotos.feature.lightbox.view.api.navigation.LightboxNavigationRoute
import com.savvasdalkitsis.uhuruphotos.feature.lightbox.view.implementation.ui.Lightbox
import com.savvasdalkitsis.uhuruphotos.feature.lightbox.view.implementation.viewmodel.LightboxViewModel
import com.savvasdalkitsis.uhuruphotos.foundation.navigation.api.NavigationTarget
import com.savvasdalkitsis.uhuruphotos.foundation.navigation.api.NavigationTargetBuilder
import com.savvasdalkitsis.uhuruphotos.foundation.ui.api.theme.ThemeMode
import kotlinx.coroutines.flow.MutableStateFlow
import se.ansman.dagger.auto.AutoBindIntoSet
import javax.inject.Inject
@AutoBindIntoSet
class LightboxNavigationTarget @Inject constructor(
private val navigationTargetBuilder: NavigationTargetBuilder,
) : NavigationTarget {
override suspend fun NavGraphBuilder.create(navHostController: NavHostController) = with(navigationTargetBuilder) {
navigationTarget(
themeMode = MutableStateFlow(ThemeMode.DARK_MODE),
route = LightboxNavigationRoute::class,
viewModel = LightboxViewModel::class,
) { state, actions ->
Lightbox(state, actions)
}
}
}
| 48 | Kotlin | 15 | 245 | 4246c45d76b1371f45492ec38aaa954f71aab363 | 1,953 | uhuruphotos-android | Apache License 2.0 |
src/main/kotlin/no/nav/omsorgspenger/ApplicationContext.kt | navikt | 300,249,592 | false | null | package no.nav.omsorgspenger
import io.ktor.client.*
import io.ktor.client.engine.okhttp.*
import no.nav.helse.dusseldorf.ktor.health.HealthCheck
import no.nav.helse.dusseldorf.oauth2.client.AccessTokenClient
import no.nav.helse.dusseldorf.oauth2.client.ClientSecretAccessTokenClient
import no.nav.k9.rapid.river.Environment
import no.nav.k9.rapid.river.RapidsStateListener
import no.nav.k9.rapid.river.csvTilSet
import no.nav.k9.rapid.river.hentRequiredEnv
import no.nav.omsorgspenger.joark.DokarkivClient
import no.nav.omsorgspenger.joark.SafGateway
import no.nav.omsorgspenger.oppgave.OppgaveClient
import java.net.URI
internal class ApplicationContext(
internal val env: Environment,
internal val dokarkivClient: DokarkivClient,
internal val safGateway: SafGateway,
internal val oppgaveClient: OppgaveClient,
internal val healthChecks: Set<HealthCheck>
) {
internal var rapidsState = RapidsStateListener.RapidsState.initialState()
internal fun start() {}
internal fun stop() {}
internal class Builder(
internal var env: Environment? = null,
internal var httpClient: HttpClient? = null,
internal var accessTokenClient: AccessTokenClient? = null,
internal var dokarkivClient: DokarkivClient? = null,
internal var safGateway: SafGateway? = null,
internal var oppgaveClient: OppgaveClient? = null
) {
internal fun build(): ApplicationContext {
val benyttetEnv = env ?: System.getenv()
val benyttetHttpClient = httpClient ?: HttpClient(OkHttp) {
expectSuccess = false
}
val benyttetAccessTokenClient = accessTokenClient ?: ClientSecretAccessTokenClient(
clientId = benyttetEnv.hentRequiredEnv("AZURE_APP_CLIENT_ID"),
clientSecret = benyttetEnv.hentRequiredEnv("AZURE_APP_CLIENT_SECRET"),
tokenEndpoint = URI(benyttetEnv.hentRequiredEnv("AZURE_OPENID_CONFIG_TOKEN_ENDPOINT"))
)
val benyttetDokarkivClient = dokarkivClient ?: DokarkivClient(
accessTokenClient = benyttetAccessTokenClient,
baseUrl = URI(benyttetEnv.hentRequiredEnv("DOKARKIV_BASE_URL")),
scopes = benyttetEnv.hentRequiredEnv("DOKARKIV_SCOPES").csvTilSet()
)
val benyttetOppgaveClient = oppgaveClient ?: OppgaveClient(
baseUrl = URI(benyttetEnv.hentRequiredEnv("OPPGAVE_BASE_URL")),
scopes = benyttetEnv.hentRequiredEnv("OPPGAVE_SCOPES").csvTilSet(),
accessTokenClient = benyttetAccessTokenClient,
httpClient = benyttetHttpClient
)
val benyttetSafGateway = safGateway ?: SafGateway(
accessTokenClient = benyttetAccessTokenClient,
baseUrl = URI(benyttetEnv.hentRequiredEnv("SAF_BASE_URL")),
scopes = benyttetEnv.hentRequiredEnv("SAF_SCOPES").csvTilSet()
)
return ApplicationContext(
env = benyttetEnv,
dokarkivClient = benyttetDokarkivClient,
healthChecks = setOf(
benyttetDokarkivClient,
benyttetOppgaveClient,
benyttetSafGateway
),
oppgaveClient = benyttetOppgaveClient,
safGateway = benyttetSafGateway
)
}
}
} | 9 | Kotlin | 0 | 0 | ab1ab35759d3e6a2c5c43c094e5ba8182ff6c93c | 3,422 | omsorgspenger-journalforing | MIT License |
compiler/testData/diagnostics/tests/lateinit/local/localLateinit.kt | JakeWharton | 99,388,807 | false | null | // !LANGUAGE: +LateinitLocalVariables
fun test() {
lateinit var s: String
s = ""
s.length
} | 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 104 | kotlin | Apache License 2.0 |
compiler/testData/diagnostics/tests/lateinit/local/localLateinit.kt | JakeWharton | 99,388,807 | false | null | // !LANGUAGE: +LateinitLocalVariables
fun test() {
lateinit var s: String
s = ""
s.length
} | 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 104 | kotlin | Apache License 2.0 |
plugins/android-idea-plugin/tests/org/jetbrains/kotlin/android/AbstractParserResultEqualityTest.kt | erokhins | 10,382,997 | true | {"Markdown": 33, "XML": 666, "Ant Build System": 45, "Ignore List": 7, "Git Attributes": 1, "Kotlin": 21040, "Java": 4546, "Protocol Buffer": 7, "Text": 4675, "JavaScript": 63, "JAR Manifest": 3, "Roff": 46, "Roff Manpage": 11, "INI": 17, "HTML": 154, "Groovy": 23, "Java Properties": 14, "Maven POM": 49, "Gradle": 74, "CSS": 2, "Proguard": 1, "JFlex": 2, "Shell": 11, "Batchfile": 10, "ANTLR": 1} | /*
* Copyright 2010-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android
import com.intellij.openapi.module.ModuleManager
import org.jetbrains.kotlin.android.synthetic.idea.TestConst
import org.jetbrains.kotlin.android.synthetic.idea.res.IDESyntheticFileGenerator
import org.jetbrains.kotlin.android.synthetic.res.CliSyntheticFileGenerator
import kotlin.test.assertEquals
public abstract class AbstractParserResultEqualityTest : KotlinAndroidTestCase() {
public fun doTest(path: String) {
val project = myFixture.getProject()
project.putUserData(TestConst.TESTDATA_PATH, path)
val resDirs = getResourceDirs(path).map {
myFixture.copyDirectoryToProject(it.name, it.name)
"$path${it.name}/"
}
val cliParser = CliSyntheticFileGenerator(project, "$path../AndroidManifest.xml", resDirs)
val ideParser = IDESyntheticFileGenerator(ModuleManager.getInstance(project).getModules()[0])
val cliResult = cliParser.getSyntheticFiles().joinToString("\n\n")
val ideResult = ideParser.getSyntheticFiles().joinToString("\n\n")
assertEquals(cliResult, ideResult)
}
override fun getTestDataPath(): String? {
return KotlinAndroidTestCaseBase.getPluginTestDataPathBase() + "/parserResultEquality/" + getTestName(true) + "/"
}
} | 0 | Java | 0 | 1 | ff00bde607d605c4eba2d98fbc9e99af932accb6 | 1,902 | kotlin | Apache License 2.0 |
app/src/androidTest/java/com/vishalgaur/shoppingapp/data/source/FakeProductsRepository.kt | i-vishi | 358,205,394 | false | null | package com.vishalgaur.shoppingapp.data.source
import android.net.Uri
import androidx.core.net.toUri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.vishalgaur.shoppingapp.data.Product
import com.vishalgaur.shoppingapp.data.Result
import com.vishalgaur.shoppingapp.data.Result.Error
import com.vishalgaur.shoppingapp.data.Result.Success
import com.vishalgaur.shoppingapp.data.source.repository.ProductsRepoInterface
import com.vishalgaur.shoppingapp.data.utils.StoreDataStatus
import kotlinx.coroutines.runBlocking
import java.util.*
import kotlin.collections.LinkedHashMap
class FakeProductsRepository : ProductsRepoInterface {
var productsServiceData: LinkedHashMap<String, Product> = LinkedHashMap()
private val imagesStorage = mutableListOf<String>()
private val observableProducts = MutableLiveData<Result<List<Product>>>()
override suspend fun refreshProducts(ownerId: String): StoreDataStatus {
observableProducts.value = Success(productsServiceData.values.toList())
return StoreDataStatus.DONE
}
override fun observeProducts(): LiveData<Result<List<Product>>?> {
runBlocking { refreshProducts() }
return observableProducts
}
override fun observeProductsByOwner(ownerId: String): LiveData<Result<List<Product>>?> {
runBlocking { refreshProducts() }
return Transformations.map(observableProducts) { products ->
when (products) {
is Result.Loading -> Result.Loading
is Error -> Error(products.exception)
is Success -> {
val pros = products.data.filter { it.owner == ownerId }
Success(pros)
}
}
}
}
override suspend fun getAllProductsByOwner(ownerId: String): Result<List<Product>> {
productsServiceData.values.let { pros ->
val res = pros.filter { it.owner == ownerId }
return Success(res)
}
}
override suspend fun getProductById(productId: String, forceUpdate: Boolean): Result<Product> {
productsServiceData[productId]?.let {
return Success(it)
}
return Error(Exception("Product Not Found!"))
}
override suspend fun insertProduct(newProduct: Product): Result<Boolean> {
productsServiceData[newProduct.productId] = newProduct
return Success(true)
}
override suspend fun insertImages(imgList: List<Uri>): List<String> {
val result = mutableListOf<String>()
imgList.forEach { uri ->
val uniId = UUID.randomUUID().toString()
val fileName = uniId + uri.lastPathSegment?.split("/")?.last()
val res = uri.toString() + fileName
imagesStorage.add(res)
result.add(res)
}
return result
}
override suspend fun updateProduct(product: Product): Result<Boolean> {
productsServiceData[product.productId] = product
return Success(true)
}
override suspend fun updateImages(newList: List<Uri>, oldList: List<String>): List<String> {
val urlList = mutableListOf<String>()
newList.forEach { uri ->
if (!oldList.contains(uri.toString())) {
val uniId = UUID.randomUUID().toString()
val fileName = uniId + uri.lastPathSegment?.split("/")?.last()
val res = uri.toString() + fileName
imagesStorage.add(res)
urlList.add(res)
} else {
urlList.add(uri.toString())
}
}
oldList.forEach { imgUrl ->
if (!newList.contains(imgUrl.toUri())) {
imagesStorage.remove(imgUrl)
}
}
return urlList
}
override suspend fun deleteProductById(productId: String): Result<Boolean> {
productsServiceData.remove(productId)
refreshProducts()
return Success(true)
}
} | 1 | null | 47 | 97 | 1768ebf52bb9ae27fe7eca9e92b999cbcd7113f6 | 3,497 | shopping-android-app | MIT License |
src/commonMain/generated/kotlin/ch/tutteli/kbox/Tuple2Like.kt | robstoll | 79,735,987 | false | null | // --------------------------------------------------------------------------------------------------------------------
// automatically generated, don't modify here but in:
// gradle/code-generation/src/main/kotlin/code-generation.generate.gradle.kts
// --------------------------------------------------------------------------------------------------------------------
package ch.tutteli.kbox
/**
* Represents a tuple like data structure which has 2 components.
*
* @since 2.1.0
*/
interface Tuple2Like<A1, A2> {
/**
* Returns the 1st component of this Tuple2Like data structure.
*
* @since 2.1.0
*/
operator fun component1(): A1
/**
* Returns the 2nd component of this Tuple2Like data structure.
*
* @since 2.1.0
*/
operator fun component2(): A2
/**
* Turns this class into a [Pair].
*
* @since 2.1.0
*/
fun toTuple(): Pair<A1, A2> = Pair(
component1(),
component2()
)
}
| 1 | null | 3 | 8 | 9546196cfb0ee0c6b672b9d0e61ceaa034b4121b | 986 | kbox | Apache License 2.0 |
extension/src/main/java/vip/frendy/extension/base/BaseSwipeBackFragmentActivity.kt | frendyxzc | 106,224,204 | false | {"Java": 125513, "Kotlin": 38449} | package vip.frendy.extension.base
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import vip.frendy.extension.R
/**
* Created by frendy on 2017/10/11.
*/
abstract class BaseFragmentActivity: BaseActivity() {
protected var currentFragment: Fragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_base_fragment)
}
protected fun setDefaultFragment(fragment: Fragment) {
// 开启Fragment事务
val fragmentTransaction = supportFragmentManager.beginTransaction()
// 使用fragment的布局替代frame_layout的控件并提交事务
fragmentTransaction.replace(R.id.frame_layout, fragment).commit()
currentFragment = fragment
}
protected fun switchFragment(fragment: Fragment) {
if (fragment !== currentFragment) {
if (!fragment.isAdded) {
supportFragmentManager.beginTransaction().hide(currentFragment)
.add(R.id.frame_layout, fragment).commit()
} else {
supportFragmentManager.beginTransaction().hide(currentFragment)
.show(fragment).commit()
}
currentFragment = fragment
}
}
override fun onResume() {
super.onResume()
currentFragment?.onResume()
}
override fun onPause() {
super.onPause()
currentFragment?.onPause()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
super.onActivityResult(requestCode, resultCode, data)
currentFragment?.onActivityResult(requestCode, resultCode, data)
}
override fun onDestroy() {
super.onDestroy()
}
} | 1 | null | 1 | 1 | a6ef1a6cc58166f18318f01aa7634c52a1343bb4 | 1,783 | KExtension | MIT License |
app/src/main/java/com/developerspace/webrtcsample/legacy/MainActivity.kt | nur-shuvo | 693,727,158 | false | {"Kotlin": 249872} | package com.developerspace.webrtcsample.legacy
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import com.developerspace.webrtcsample.R
import com.developerspace.webrtcsample.legacy.activeUsers.ui.ActiveUserActivity
import com.developerspace.webrtcsample.compose.ui.util.UserUpdateRemoteUtil
import com.firebase.ui.auth.AuthUI
import com.google.android.material.button.MaterialButton
import com.google.firebase.auth.ktx.auth
import com.google.firebase.database.ktx.database
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.ktx.Firebase
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
val db = Firebase.firestore
private val realTimeDb = Firebase.database
private val auth = Firebase.auth
private var start_meeting: MaterialButton?= null
private var meeting_id: EditText?= null
private var join_meeting: MaterialButton?= null
private var only_chat: Button?= null
private var active_users: Button?= null
private var sign_out: Button?= null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_start)
start_meeting = findViewById(R.id.start_meeting)
meeting_id = findViewById(R.id.meeting_id)
join_meeting = findViewById(R.id.join_meeting)
only_chat = findViewById(R.id.only_chat)
active_users = findViewById(R.id.active_users)
sign_out = findViewById(R.id.sign_out)
Constants.isIntiatedNow = true
Constants.isCallEnded = true
start_meeting?.setOnClickListener {
if (meeting_id?.text.toString().trim().isNullOrEmpty())
meeting_id?.error = "Please enter meeting id"
else {
db.collection("calls")
.document(meeting_id?.text.toString())
.get()
.addOnSuccessListener {
if (it["type"] == "OFFER" || it["type"] == "ANSWER" || it["type"] == "END_CALL") {
meeting_id?.error = "Please enter new meeting ID"
} else {
val intent = Intent(this@MainActivity, RTCActivity::class.java)
intent.putExtra("meetingID", meeting_id?.text.toString())
intent.putExtra("isJoin", false)
startActivity(intent)
}
}
.addOnFailureListener {
meeting_id?.error = "Please enter new meeting ID"
}
}
}
join_meeting?.setOnClickListener {
if (meeting_id?.text.toString().trim().isNullOrEmpty())
meeting_id?.error = "Please enter meeting id"
else {
val intent = Intent(this@MainActivity, RTCActivity::class.java)
intent.putExtra("meetingID", meeting_id?.text.toString())
intent.putExtra("isJoin", true)
startActivity(intent)
}
}
only_chat?.setOnClickListener {
// Need to think the flow
// val intent = Intent(this@MainActivity, ChatMainActivity::class.java)
// startActivity(intent)
}
active_users?.setOnClickListener {
val intent = Intent(this@MainActivity, ActiveUserActivity::class.java)
startActivity(intent)
}
sign_out?.setOnClickListener {
signOut()
}
// Coming to mainActivity indicates user is online now
UserUpdateRemoteUtil().makeUserOnlineRemote(Firebase.database, Firebase.auth)
}
private fun getPhotoUrl(): String? {
val user = auth.currentUser
return user?.photoUrl?.toString()
}
private fun getUserName(): String? {
val user = auth.currentUser
return if (user != null) {
user.displayName
} else ChatMainActivity.ANONYMOUS
}
private fun signOut() {
AuthUI.getInstance().signOut(this).addOnSuccessListener {
gotoSignInActivity()
}
}
private fun gotoSignInActivity() {
startActivity(Intent(this, SignInActivity::class.java))
finish()
}
override fun onDestroy() {
// user is offline now
UserUpdateRemoteUtil().makeUserOfflineRemote(Firebase.database, Firebase.auth)
super.onDestroy()
}
companion object {
const val ONLINE_USER_LIST_CHILD = "onlineuserlist"
}
} | 5 | Kotlin | 0 | 1 | 33aa99b42433f718629e4896c5c16f0f878a38b1 | 4,725 | SwapMind | MIT License |
src/main/kotlin/TestingControl.kt | cs125-illinois | 277,361,183 | false | null | package edu.illinois.cs.cs125.jenisol.core
import java.lang.RuntimeException
sealed class TestingControlException : RuntimeException()
class SkipTest : TestingControlException()
class BoundComplexity : TestingControlException() | 0 | Kotlin | 0 | 1 | 0643c0ce6f4035f0ecff31688ee78089b91295f1 | 229 | jenisol | MIT License |
favorite/src/main/java/com/masscode/animesuta/favorite/FavoriteModule.kt | agustiyann | 299,888,684 | false | null | package com.masscode.animesuta.favorite
import org.koin.android.viewmodel.dsl.viewModel
import org.koin.dsl.module
val favoriteModule = module {
viewModel { FavoriteViewModel(get()) }
} | 0 | Kotlin | 10 | 55 | 0a51677ddcd69eb9f8c2f9c8da62518c894d06ce | 191 | Android-Clean-Architecture | Apache License 2.0 |
posts/src/main/java/com/karntrehan/posts/details/model/DetailsDataContract.kt | karntrehan | 93,308,442 | false | null | package com.karntrehan.posts.details.model
import com.karntrehan.posts.commons.data.local.Comment
import com.mpaani.core.networking.Outcome
import io.reactivex.Flowable
import io.reactivex.subjects.PublishSubject
interface DetailsDataContract {
interface Repository {
val commentsFetchOutcome: PublishSubject<Outcome<List<Comment>>>
fun fetchCommentsFor(postId: Int?)
fun refreshComments(postId: Int)
fun saveCommentsForPost(comments: List<Comment>)
fun handleError(error: Throwable)
}
interface Local {
fun getCommentsForPost(postId: Int): Flowable<List<Comment>>
fun saveComments(comments: List<Comment>)
}
interface Remote {
fun getCommentsForPost(postId: Int): Flowable<List<Comment>>
}
} | 0 | null | 98 | 611 | b22ec155b9ddf831a7670cf216187dde3b0264af | 784 | Posts | Apache License 2.0 |
demo/demo/src/jsMain/kotlin/zakadabar/demo/frontend/pages/ship/SearchForm.kt | kondorj | 355,137,640 | true | {"Kotlin": 577495, "HTML": 828, "JavaScript": 820, "Shell": 253} | /*
* Copyright © 2020, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.demo.frontend.pages.ship
import zakadabar.demo.data.PortDto
import zakadabar.demo.data.SeaDto
import zakadabar.demo.data.ship.SearchShipsQuery
import zakadabar.demo.data.speed.SpeedDto
import zakadabar.demo.resources.Strings
import zakadabar.stack.frontend.builtin.button.ZkButton
import zakadabar.stack.frontend.builtin.form.ZkForm
import zakadabar.stack.frontend.util.io
import zakadabar.stack.frontend.util.marginBottom
import zakadabar.stack.frontend.util.marginRight
class SearchForm(
val runQuery: (dto: SearchShipsQuery) -> Unit
) : ZkForm<SearchShipsQuery>() {
override fun onCreate() {
io {
// As this form is a query and is intended to be part of a page
// we don't use the "build" function from ZkForm.
// Also, we set fieldGrid parameter of the section to false.
// That means we can build the content of the section freely.
+ column {
+ section(Strings.filters, fieldGrid = false) {
style {
margin = "0px" // override margin, so we can align it with the table
}
+ row {
+ fieldGrid {
+ dto::name
+ select(dto::speed) { SpeedDto.all().by { it.description } }
} marginRight 24
+ fieldGrid {
+ select(dto::sea) { SeaDto.all().by { it.name } }
+ select(dto::port) { PortDto.all().by { it.name } }
}
} marginBottom 12
+ row {
+ ZkButton(Strings.runQuery) { runQuery(dto) }
}
}
}
}
}
} | 0 | null | 0 | 0 | 2379c0fb031f04a230e753a9afad6bd260f6a0b2 | 1,956 | zakadabar-stack | Apache License 2.0 |
src/main/kotlin/org/rooftop/netx/api/TransactionManager.kt | rooftop-MSA | 751,298,974 | false | {"Kotlin": 169884, "Java": 8573} | package org.rooftop.netx.api
import reactor.core.publisher.Mono
interface TransactionManager {
fun <T : Any> start(undo: T): Mono<String>
fun <T : Any, S : Any> start(undo: T, event: S): Mono<String>
fun <T : Any> syncStart(undo: T): String
fun <T : Any, S : Any> syncStart(undo: T, event: S): String
fun <T : Any> join(transactionId: String, undo: T): Mono<String>
fun <T : Any, S : Any> join(transactionId: String, undo: T, event: S): Mono<String>
fun <T : Any> syncJoin(transactionId: String, undo: T): String
fun <T : Any, S : Any> syncJoin(transactionId: String, undo: T, event: S): String
fun exists(transactionId: String): Mono<String>
fun syncExists(transactionId: String): String
fun commit(transactionId: String): Mono<String>
fun <T : Any> commit(transactionId: String, event: T): Mono<String>
fun syncCommit(transactionId: String): String
fun <T : Any> syncCommit(transactionId: String, event: T): String
fun rollback(transactionId: String, cause: String): Mono<String>
fun <T : Any> rollback(transactionId: String, cause: String, event: T): Mono<String>
fun syncRollback(transactionId: String, cause: String): String
fun <T : Any> syncRollback(transactionId: String, cause: String, event: T): String
}
| 10 | Kotlin | 0 | 5 | 80e8758fa6d22744ea95afec2743351de41fcce3 | 1,308 | Netx | Apache License 2.0 |
app/src/main/java/com/koma/video/search/SearchAdapter.kt | komamj | 135,701,576 | false | {"Kotlin": 177378} | /*
* Copyright 2018 koma_mj
*
* 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.koma.video.search
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.PopupMenu
import android.support.v7.widget.RecyclerView
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ForegroundColorSpan
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.koma.video.R
import com.koma.video.data.enities.VideoEntry
import com.koma.video.play.PlayActivity
import com.koma.video.util.GlideApp
class SearchAdapter constructor(private val context: Context) :
RecyclerView.Adapter<SearchAdapter.SearchVH>() {
private val data = ArrayList<VideoEntry>()
private var keyWord = ""
fun updateData(newData: List<VideoEntry>, newKeyWord: String) {
keyWord = newKeyWord
data.clear()
data.addAll(newData)
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SearchVH {
return SearchVH(
LayoutInflater.from(context).inflate(
R.layout.video_item, parent,
false
)
)
}
override fun onBindViewHolder(holder: SearchVH, position: Int) {
val videoEntry = data[position]
bind(holder, videoEntry)
}
private fun bind(holder: SearchAdapter.SearchVH, entry: VideoEntry) {
GlideApp.with(context)
.asBitmap()
.placeholder(ColorDrawable(Color.GRAY))
.thumbnail(0.1f)
.load(entry.uri)
.into(holder.image)
val spannableStringBuilder = SpannableStringBuilder(entry.displayName)
val foregroundColorSpan =
ForegroundColorSpan(ContextCompat.getColor(context, R.color.colorAccent))
val start = entry.displayName.toLowerCase().indexOf(keyWord)
val end = start + keyWord.length
spannableStringBuilder.setSpan(
foregroundColorSpan,
start,
end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
holder.name.text = spannableStringBuilder
holder.duration.text = entry.formatDuration
}
override fun getItemCount(): Int {
return data.size
}
inner class SearchVH(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
val image: ImageView
val duration: TextView
val name: TextView
init {
itemView.setOnClickListener(this)
image = itemView.findViewById(R.id.iv_video)
name = itemView.findViewById(R.id.tv_name)
duration = itemView.findViewById(R.id.tv_duration)
(itemView.findViewById(R.id.iv_more) as ImageView).setOnClickListener(this)
}
override fun onClick(view: View) {
when (view.id) {
R.id.iv_more -> {
val popupMenu = PopupMenu(view.context, view)
popupMenu.menuInflater.inflate(R.menu.item_video_menu, popupMenu.menu)
popupMenu.show()
}
else -> {
val intent = Intent(context, PlayActivity::class.java)
intent.putExtra(PlayActivity.KEY_MEDIA_ID, data[adapterPosition].id)
context.startActivity(intent)
}
}
}
}
} | 0 | Kotlin | 1 | 1 | be4142c9126b0e74cd1d8d1dcaae5285505294d8 | 4,164 | Video | Apache License 2.0 |
app/src/main/java/com/chillibits/pmapp/widget/WidgetProviderSmall.kt | chillibits | 115,863,331 | false | null | /*
* Copyright © <NAME> 2017 - 2020. All rights reserved
*/
package com.chillibits.pmapp.widget
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.Context
import android.content.Intent
import android.os.Build
import android.view.View
import android.widget.RemoteViews
import com.chillibits.pmapp.service.SyncService
import com.chillibits.pmapp.tool.Constants
import com.chillibits.pmapp.tool.StorageUtils
import com.chillibits.pmapp.tool.Tools
import com.mrgames13.jimdo.feinstaubapp.R
class WidgetProviderSmall : AppWidgetProvider() {
// Utils packages
private lateinit var su: StorageUtils
// Variables as objects
private lateinit var context: Context
override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, app_widget_id: IntArray) {
super.onUpdate(context, appWidgetManager, app_widget_id)
initialize(context)
val rv = RemoteViews(context.packageName, R.layout.widget_small)
for (widget_id in app_widget_id) {
// Refresh button
val refresh = Intent(context, javaClass)
refresh.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
refresh.putExtra(Constants.WIDGET_EXTRA_SMALL_WIDGET_ID, widget_id)
val refreshPi = PendingIntent.getBroadcast(context, 0, refresh, 0)
rv.setOnClickPendingIntent(R.id.widget_refresh, refreshPi)
// Update data
updateData(context, rv, widget_id)
}
}
override fun onReceive(context: Context, intent: Intent) {
super.onReceive(context, intent)
initialize(context)
val rv = RemoteViews(context.packageName, R.layout.widget_small)
if (intent.action == AppWidgetManager.ACTION_APPWIDGET_UPDATE && intent.hasExtra(Constants.WIDGET_SMALL_EXTRA_SENSOR_ID)) {
// Get WidgetID
val widgetId = su.getInt("Widget_Small_" + intent.getStringExtra(Constants.WIDGET_SMALL_EXTRA_SENSOR_ID)!!, AppWidgetManager.INVALID_APPWIDGET_ID)
if (widgetId != AppWidgetManager.INVALID_APPWIDGET_ID) updateData(context, rv, widgetId)
} else if (intent.action == AppWidgetManager.ACTION_APPWIDGET_UPDATE && intent.hasExtra(Constants.WIDGET_EXTRA_LARGE_WIDGET_ID)) {
val widgetId = intent.getIntExtra(Constants.WIDGET_EXTRA_SMALL_WIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID)
AppWidgetManager.getInstance(context).updateAppWidget(widgetId, rv)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(Intent(context, SyncService::class.java))
} else {
context.startService(Intent(context, SyncService::class.java))
}
}
}
private fun initialize(context: Context) {
this.context = context
su = StorageUtils(context)
}
private fun updateData(context: Context, rv: RemoteViews, widgetId: Int) {
try {
// Load sensors
val sensor = su.getSensor(su.getString("Widget_Small_$widgetId"))
// Get last record from the db
val lastRecord = su.getLastRecord(sensor!!.chipID)
if (lastRecord != null) {
rv.run {
setTextViewText(R.id.name, sensor.name)
setTextViewText(R.id.p1, context.getString(R.string.value1) + ": " + Tools.round(lastRecord.p1, 1).toString() + " µg/m³")
setTextViewText(R.id.p2, context.getString(R.string.value2) + ": " + Tools.round(lastRecord.p2, 1).toString() + " µg/m³")
setProgressBar(R.id.progress, 40, lastRecord.p1.toInt(), false)
setViewVisibility(R.id.data_container, View.VISIBLE)
setViewVisibility(R.id.no_data, View.GONE)
}
} else {
rv.setViewVisibility(R.id.data_container, View.GONE)
rv.setViewVisibility(R.id.no_data, View.VISIBLE)
}
AppWidgetManager.getInstance(context).updateAppWidget(widgetId, rv)
} catch (ignored: Exception) {}
}
} | 24 | Kotlin | 5 | 9 | fafdf73e03f2ea67769bf67cc0433997d516d66c | 4,183 | particulate-matter-app | MIT License |
samples/SkijaInjectSample/src/main/kotlin/SkijaInjectSample/App.kt | tchigher | 328,241,573 | true | {"Kotlin": 31622, "C++": 18275, "Objective-C": 8557} | package SkijaInjectSample
import org.jetbrains.skiko.SkiaWindow
import java.awt.event.MouseEvent
import javax.swing.WindowConstants
import javax.swing.event.MouseInputAdapter
import org.jetbrains.skija.*
import org.jetbrains.skiko.SkiaRenderer
import java.awt.event.MouseMotionAdapter
import kotlin.math.cos
import kotlin.math.sin
import org.jetbrains.skija.paragraph.FontCollection
import org.jetbrains.skija.paragraph.ParagraphBuilder
import org.jetbrains.skija.paragraph.ParagraphStyle
import org.jetbrains.skija.paragraph.TextStyle
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.KeyEvent
import java.awt.Toolkit
import javax.swing.JFrame
import javax.swing.JMenu
import javax.swing.JMenuBar
import javax.swing.JMenuItem
import javax.swing.JOptionPane
import javax.swing.KeyStroke
fun main(args: Array<String>) {
createWindow("First window")
}
fun createWindow(title: String) {
var mouseX = 0
var mouseY = 0
val window = SkiaWindow()
window.defaultCloseOperation = WindowConstants.EXIT_ON_CLOSE
window.title = title
// Create menu.
val menuBar = JMenuBar()
val menu = JMenu("File")
menuBar.add(menu)
val miFullscreenState = JMenuItem("Is fullscreen mode")
val ctrlI = KeyStroke.getKeyStroke(KeyEvent.VK_I, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())
miFullscreenState.setAccelerator(ctrlI)
miFullscreenState.addActionListener(object : ActionListener {
override fun actionPerformed(actionEvent: ActionEvent?) {
println("${window.title} is in fullscreen mode: ${window.layer.fullscreen}")
}
})
val miToggleFullscreen = JMenuItem("Toggle fullscreen")
val ctrlF = KeyStroke.getKeyStroke(KeyEvent.VK_F, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())
miToggleFullscreen.setAccelerator(ctrlF)
miToggleFullscreen.addActionListener(object : ActionListener {
override fun actionPerformed(actionEvent: ActionEvent?) {
window.layer.fullscreen = !window.layer.fullscreen
}
})
menu.add(miToggleFullscreen)
menu.add(miFullscreenState)
window.setJMenuBar(menuBar)
val state = State()
state.text = title
window.layer.renderer = Renderer {
renderer, w, h -> displayScene(renderer, w, h, mouseX, mouseY, state)
}
window.layer.addMouseMotionListener(object : MouseMotionAdapter() {
override fun mouseMoved(event: MouseEvent) {
mouseX = event.x
mouseY = event.y
window.display()
}
})
// MANDATORY: set window size before calling setVisible(true)
window.setSize(800, 600)
window.setVisible(true)
}
class Renderer(val displayScene: (Renderer, Int, Int) -> Unit): SkiaRenderer {
val typeface = Typeface.makeFromFile("fonts/JetBrainsMono-Regular.ttf")
val font = Font(typeface, 40f)
val paint = Paint().apply {
setColor(0xff9BC730L.toInt())
setMode(PaintMode.FILL)
setStrokeWidth(1f)
}
var canvas: Canvas? = null
override fun onInit() {
}
override fun onDispose() {
}
override fun onReshape(width: Int, height: Int) {
}
override fun onRender(canvas: Canvas, width: Int, height: Int) {
this.canvas = canvas
displayScene(this, width, height)
}
}
class State {
var frame: Int = 0
var text: String = "Hello Skija"
}
fun displayScene(renderer: Renderer, width: Int, height: Int, xpos: Int, ypos: Int, state: State) {
val canvas = renderer.canvas!!
val watchFill = Paint().setColor(0xFFFFFFFF.toInt())
val watchStroke = Paint().setColor(0xFF000000.toInt()).setMode(PaintMode.STROKE).setStrokeWidth(1f)
val watchStrokeAA = Paint().setColor(0xFF000000.toInt()).setMode(PaintMode.STROKE).setStrokeWidth(1f)
val watchFillHover = Paint().setColor(0xFFE4FF01.toInt())
for (x in 0 .. (width - 50) step 50) {
for (y in 0 .. (height - 50) step 50) {
val hover = xpos > x + 0 && xpos < x + 50 && ypos > y + 0 && ypos < y + 50
val fill = if (hover) watchFillHover else watchFill
val stroke = if (x > width / 2) watchStrokeAA else watchStroke
canvas.drawOval(Rect.makeXYWH(x + 5f, y + 5f, 40f, 40f), fill)
canvas.drawOval(Rect.makeXYWH(x + 5f, y + 5f, 40f, 40f), stroke)
var angle = 0f
while (angle < 2f * Math.PI) {
canvas.drawLine(
(x + 25 - 17 * sin(angle)),
(y + 25 + 17 * cos(angle)),
(x + 25 - 20 * sin(angle)),
(y + 25 + 20 * cos(angle)),
stroke
)
angle += (2.0 * Math.PI / 12.0).toFloat()
}
val time = System.currentTimeMillis() % 60000 +
(x.toFloat() / width * 5000).toLong() +
(y.toFloat() / width * 5000).toLong()
val angle1 = (time.toFloat() / 5000 * 2f * Math.PI).toFloat()
canvas.drawLine(x + 25f, y + 25f,
x + 25f - 15f * sin(angle1),
y + 25f + 15 * cos(angle1),
stroke)
val angle2 = (time / 60000 * 2f * Math.PI).toFloat()
canvas.drawLine(x + 25f, y + 25f,
x + 25f - 10f * sin(angle2),
y + 25f + 10f * cos(angle2),
stroke)
}
}
val text = "${state.text} ${state.frame++}!"
canvas.drawString(text, xpos.toFloat(), ypos.toFloat(), renderer.font, renderer.paint)
val fontCollection = FontCollection()
.setDefaultFontManager(FontMgr.getDefault())
val style = ParagraphStyle()
val paragraph = ParagraphBuilder(style, fontCollection)
.pushStyle(TextStyle().setColor(0xFF000000.toInt()))
.addText("Text")
.popStyle()
.build()
paragraph.layout(Float.POSITIVE_INFINITY)
paragraph.paint(canvas, 0f, 0f)
}
| 0 | null | 0 | 0 | 5c7a7ff6b2ab08ab53ebc8651df2b1a7fd6d8e56 | 6,034 | skiko | Apache License 2.0 |
domain/src/main/java/com/example/domain/usecase/GetBookmarkedNewsUseCase.kt | yoo-sudo | 693,298,176 | false | {"Kotlin": 34155} | package com.example.domain.usecase
import com.example.domain.model.News
import com.example.domain.repo.BookmarkedNewsRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class GetBookmarkedNewsUseCase @Inject constructor(
private val repository: BookmarkedNewsRepository
) {
suspend fun execute():Flow<List<News>>{
return repository.getBookmarkedNews()
}
} | 0 | Kotlin | 0 | 0 | e3516fc2ab55e30ab1dc33ad359d4ba0801b25fc | 401 | NewsApp | Apache License 2.0 |
app/src/main/java/com/krm/tmdb/ui/fragments/search/FragmentSearch.kt | cadet29manikandan | 242,054,653 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 95, "XML": 116, "Java": 38} | package com.krm.tmdb.ui.fragments.search
import android.os.Bundle
import androidx.recyclerview.widget.GridLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.krm.tmdb.data.model.ObjectsSearch
import com.krm.tmdb.ui.activities.base.BaseFragment
import com.krm.tmdb.ui.adapters.RecyclerAdapterSearch
import com.krm.tmdb.utils.ConstStrings
import com.krm.tmdb.utils.ConstFun.openActivityPeople
import com.google.gson.JsonArray
import com.krm.tmdb.R
import com.pawegio.kandroid.hide
import com.pawegio.kandroid.show
import kotlinx.android.synthetic.main.fragment_search.*
import javax.inject.Inject
import javax.inject.Named
class FragmentSearch : BaseFragment(), InterfaceSearch.View, RecyclerAdapterSearch.OnItemSearchClickListener {
@Inject lateinit var interactor: InteractorSearch<InterfaceSearch.View>
@Inject lateinit var adapterSearch: RecyclerAdapterSearch
@field:Named(ConstStrings.COUNT3) @Inject lateinit var lManagerCount3: GridLayoutManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
getActivityComponent()!!.inject(this)
interactor.onAttach(this)
}
override fun onDetach() {
interactor.onDetach()
super.onDetach()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
inflater.inflate(R.layout.fragment_search,container,false)
override fun setSearch(query:String){
if (query.isEmpty())showEdtEmpty()
else interactor.getDataSearch(query)
}
override fun resultData(data: ObjectsSearch){
if (data.results.size() == 0) hiddenLoadingNotData()
else {
setDataSearch(data.results)
hiddenLoading()
}
}
override fun setDataSearch(json: JsonArray) {
adapterSearch.addItem(json)
list_search.apply {
layoutManager = lManagerCount3
adapter = adapterSearch
recycledViewPool.clear()
}
adapterSearch.notifyDataSetChanged()
adapterSearch.setOnItemMovieClickListener(this)
}
override fun onItemSearchClicked(id: Int, title: String, type: String, image: String,v:View) {
if (type== ConstStrings.PERSON) getBaseActivity().openActivityPeople(id,title,v)
else getBaseActivity().setMaximizeDraggable(id,title,type,image)
}
override fun showLoading() {
//progress_search.show()
}
private fun showEdtEmpty() {
txt_view_search.show()
//progress_search.hide()
list_search.hide()
connect_search.hide()
txt_no_data.hide()
}
override fun hiddenLoading() {
list_search.show()
txt_view_search.hide()
//progress_search.hide()
connect_search.hide()
txt_no_data.hide()
}
override fun hiddenLoadingFailed() {
txt_view_search.hide()
//progress_search.hide()
list_search.hide()
txt_no_data.hide()
connect_search.show()
}
override fun hiddenLoadingNotData() {
txt_view_search.hide()
//progress_search.hide()
list_search.hide()
connect_search.hide()
txt_no_data.show()
}
} | 0 | Kotlin | 0 | 0 | 3fba5c2fd1029b013c0a09db72899b743cc1800b | 3,338 | TMDB | Apache License 2.0 |
plugins/space/src/main/kotlin/com/intellij/space/vcs/review/list/SpaceReviewListFactory.kt | haarlemmer | 392,603,002 | 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.space.vcs.review.list
import circlet.code.api.CodeReviewListItem
import circlet.platform.client.BatchResult
import com.intellij.ide.DataManager
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.progress.util.ProgressWindow
import com.intellij.space.ui.LoadableListVmImpl
import com.intellij.space.ui.bindScroll
import com.intellij.space.ui.toLoadable
import com.intellij.space.vcs.review.SpaceReviewDataKeys
import com.intellij.ui.CollectionListModel
import com.intellij.ui.ListUtil
import com.intellij.ui.PopupHandler
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import com.intellij.vcs.log.ui.frame.ProgressStripe
import java.awt.Component
import javax.swing.JComponent
import javax.swing.JScrollPane
internal object SpaceReviewListFactory {
fun create(parentDisposable: Disposable, listVm: SpaceReviewsListVm): JComponent {
val listModel: CollectionListModel<CodeReviewListItem> = CollectionListModel()
val reviewsList: SpaceReviewsList = SpaceReviewsList(listModel, listVm.lifetime).apply {
installPopup(this)
}
val scrollableList: JScrollPane = ScrollPaneFactory.createScrollPane(reviewsList,
ScrollPaneFactory.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneFactory.HORIZONTAL_SCROLLBAR_NEVER).apply {
border = JBUI.Borders.empty()
verticalScrollBar.isOpaque = true
UIUtil.putClientProperty(verticalScrollBar, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, false)
}
listVm.reviews.forEach(listVm.lifetime) { xList ->
listModel.removeAll()
xList.batches.forEach(listVm.lifetime) { batchResult: BatchResult<CodeReviewListItem> ->
when (batchResult) {
is BatchResult.More -> listModel.add(batchResult.items)
is BatchResult.Reset -> listModel.removeAll()
}
}
}
bindScroll(listVm.lifetime, scrollableList, LoadableListVmImpl(listVm.isLoading, listVm.reviews.toLoadable()), reviewsList)
DataManager.registerDataProvider(scrollableList) { dataId ->
if (SpaceReviewDataKeys.REVIEWS_LIST_VM.`is`(dataId)) listVm else null
}
val progressStripe = ProgressStripe(
scrollableList,
parentDisposable,
ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS
)
listVm.isLoading.forEach(listVm.lifetime) { isLoading ->
if (isLoading) {
progressStripe.startLoading()
}
else {
progressStripe.stopLoading()
}
}
return progressStripe
}
private fun installPopup(list: SpaceReviewsList) {
val actionManager = ActionManager.getInstance()
val popupHandler = object : PopupHandler() {
override fun invokePopup(comp: Component, x: Int, y: Int) {
if (ListUtil.isPointOnSelection(list, x, y)) {
val actionGroup = actionManager.getAction("com.intellij.space.vcs.review.list.popup") as ActionGroup
val popupMenu = actionManager.createActionPopupMenu("Circlet.Reviews.List.Popup", actionGroup)
popupMenu.setTargetComponent(list)
popupMenu.component.show(comp, x, y)
}
}
}
list.addMouseListener(popupHandler)
}
} | 1 | null | 1 | 1 | de80b70f5507f0110de89a95d72b8f902ca72b3e | 3,623 | intellij-community | Apache License 2.0 |
VehicleUI/src/main/java/com/drivequant/drivekit/vehicle/ui/odometer/fragment/OdometerHistoryDetailFragment.kt | DriveQuantPublic | 216,339,559 | false | {"Kotlin": 1650199, "Java": 8753} | package com.drivequant.drivekit.vehicle.ui.odometer.fragment
import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.text.InputType
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.drivequant.drivekit.common.ui.DriveKitUI
import com.drivequant.drivekit.common.ui.extension.normalText
import com.drivequant.drivekit.common.ui.extension.setDKStyle
import com.drivequant.drivekit.common.ui.extension.smallText
import com.drivequant.drivekit.vehicle.ui.R
import com.drivequant.drivekit.vehicle.ui.databinding.DkFragmentOdometerHistoryDetailBinding
import com.drivequant.drivekit.vehicle.ui.odometer.viewmodel.OdometerHistoryDetailViewModel
import com.drivequant.drivekit.vehicle.ui.vehicles.utils.VehicleUtils
import com.google.android.material.textfield.TextInputEditText
class OdometerHistoryDetailFragment : Fragment() {
private var vehicleId: String? = null
private var historyId: Int = -1
private lateinit var viewModel: OdometerHistoryDetailViewModel
private var _binding: DkFragmentOdometerHistoryDetailBinding? = null
private val binding get() = _binding!! // This property is only valid between onCreateView and onDestroyView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
vehicleId = it.getString("vehicleIdTag")
historyId = it.getInt("historyIdTag")
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
vehicleId?.let {
outState.putString("vehicleIdTag", it)
}
outState.putInt("historyIdTag", historyId)
super.onSaveInstanceState(outState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = DkFragmentOdometerHistoryDetailBinding.inflate(inflater, container, false)
binding.root.setDKStyle(Color.WHITE)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
(savedInstanceState?.getString("vehicleIdTag"))?.let {
vehicleId = it
}
(savedInstanceState?.getInt("historyIdTag"))?.let {
historyId = it
}
vehicleId?.let { vehicleId ->
context?.let { context ->
viewModel = ViewModelProvider(this,
OdometerHistoryDetailViewModel.OdometerHistoryDetailViewModelFactory(vehicleId,
historyId))[OdometerHistoryDetailViewModel::class.java]
if (!viewModel.canEditOrAddHistory()) {
R.string.dk_tag_vehicles_odometer_histories_detail
} else {
if (historyId == -1) {
R.string.dk_tag_vehicles_odometer_histories_add
} else {
R.string.dk_tag_vehicles_odometer_histories_edit
}
}.let {
DriveKitUI.analyticsListener?.trackScreen(getString(it), javaClass.simpleName)
}
initVehicle(context, vehicleId)
initMileageRecord(context)
onValidateButtonClicked(context)
onDeleteOdometerHistory()
onDistanceClicked(context)
onCancelButtonClicked()
binding.vehicleItem.setBackgroundColor(DriveKitUI.colors.neutralColor())
viewModel.odometerActionObserver.observe(viewLifecycleOwner) {
updateProgressVisibility(false)
Toast.makeText(context, it.first, Toast.LENGTH_LONG).show()
if (it.second) {
val intentData = Intent()
activity?.let { activity ->
activity.apply {
setResult(Activity.RESULT_OK, intentData)
finish()
}
}
}
}
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun initVehicle(context: Context, vehicleId: String) {
binding.spinnerItem.textViewItemDisplayName.apply {
smallText(ContextCompat.getColor(context, com.drivequant.drivekit.common.ui.R.color.dkGrayColor))
text = viewModel.getVehicleFormattedName(context)
}
VehicleUtils().getVehicleDrawable(context, vehicleId)?.let { drawable ->
Glide.with(context)
.load(drawable)
.apply(RequestOptions.circleCropTransform())
.placeholder(drawable)
.into(binding.spinnerItem.imageItem)
}
}
private fun initMileageRecord(context: Context) {
binding.editTextDistance.apply {
if (viewModel.canEditOrAddHistory()) {
setEditTextTitle(viewModel.getHistoryDistance(context), DriveKitUI.colors.complementaryFontColor())
} else {
setEditTextTitle(viewModel.getHistoryDistance(context))
}
}
binding.editTextDate.setEditTextTitle(viewModel.getHistoryUpdateDate())
binding.textViewHistoryDetailTitle.apply {
setText(R.string.dk_vehicle_odometer_odometer_history_detail_title)
normalText(DriveKitUI.colors.secondaryColor())
}
}
private fun onValidateButtonClicked(context: Context) {
binding.buttonValidateReference.apply {
visibility = if (viewModel.canEditOrAddHistory()) View.VISIBLE else View.GONE
setOnClickListener {
if (viewModel.showMileageDistanceErrorMessage()) {
Toast.makeText(
context,
R.string.dk_vehicle_odometer_history_error,
Toast.LENGTH_SHORT
).show()
} else {
updateProgressVisibility(true)
if (viewModel.canEditHistory()) {
viewModel.updateOdometerHistory()
} else {
viewModel.addOdometerHistory()
}
}
}
}
}
private fun onCancelButtonClicked() {
binding.buttonCancelAction.apply {
visibility = if (viewModel.canEditOrAddHistory()) View.VISIBLE else View.GONE
setOnClickListener {
activity?.let {
val intentData = Intent()
it.setResult(Activity.RESULT_CANCELED, intentData)
it.finish()
}
}
}
}
private fun onDistanceClicked(context: Context) {
binding.editTextDistance.apply {
setOnClickListener {
if (viewModel.canEditOrAddHistory()) {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflater.inflate(com.drivequant.drivekit.common.ui.R.layout.dk_alert_dialog_edit_value, null)
val builder = androidx.appcompat.app.AlertDialog.Builder(context, com.drivequant.drivekit.common.ui.R.style.DKAlertDialog)
builder.setView(view)
val alertDialog = builder.create()
val titleTextView = view.findViewById<TextView>(com.drivequant.drivekit.common.ui.R.id.text_view_title)
val editText = view.findViewById<TextInputEditText>(com.drivequant.drivekit.common.ui.R.id.edit_text_field)
titleTextView.apply {
setText(R.string.dk_vehicle_odometer_mileage_kilometer)
normalText(DriveKitUI.colors.fontColorOnSecondaryColor())
setBackgroundColor(DriveKitUI.colors.primaryColor())
}
editText.apply {
inputType = InputType.TYPE_CLASS_NUMBER
if (viewModel.canAddHistory()) {
this.hint = getString(R.string.dk_vehicle_odometer_mileage_kilometer)
this.typeface = DriveKitUI.primaryFont(context)
} else {
this.setText(viewModel.getFormattedMileageDistance(context, false))
}
}
alertDialog.apply {
setCancelable(true)
setButton(
DialogInterface.BUTTON_POSITIVE,
getString(com.drivequant.drivekit.common.ui.R.string.dk_common_validate)
) { dialog, _ ->
viewModel.mileageDistance = if (editText.editableText.toString().isBlank()) 0.0 else editText.editableText.toString().toDouble()
this@OdometerHistoryDetailFragment.binding.editTextDistance.setEditTextTitle(viewModel.getFormattedMileageDistance(context))
dialog.dismiss()
}
setOnKeyListener { _, keyCode, _ -> keyCode == KeyEvent.KEYCODE_BACK }
show()
getButton(AlertDialog.BUTTON_POSITIVE)?.apply {
typeface = DriveKitUI.primaryFont(context)
}
}
}
}
}
}
private fun onDeleteOdometerHistory() {
binding.buttonDeleteReference.apply {
normalText(DriveKitUI.colors.secondaryColor())
setText(com.drivequant.drivekit.common.ui.R.string.dk_common_delete)
visibility = if (viewModel.canDeleteHistory()) View.VISIBLE else View.GONE
setOnClickListener {
updateProgressVisibility(true)
viewModel.deleteOdometerHistory()
}
}
}
private fun updateProgressVisibility(displayProgress: Boolean) {
binding.progressCircular.visibility = if (displayProgress) {
View.VISIBLE
} else {
View.GONE
}
}
companion object {
fun newInstance(vehicleId: String, historyId: Int) =
OdometerHistoryDetailFragment().apply {
arguments = Bundle().apply {
putString("vehicleIdTag", vehicleId)
putInt("historyIdTag", historyId)
}
}
}
}
| 1 | Kotlin | 3 | 9 | e7956263157c49aae8d6f993a558ea77d9658ee6 | 11,173 | drivekit-ui-android | Apache License 2.0 |
app/src/main/java/com/puntogris/recap/feature_recap/domain/model/Recap.kt | puntogris | 398,389,151 | false | null | package com.puntogris.recap.feature_recap.domain.model
import android.os.Parcelable
import androidx.annotation.Keep
import com.google.firebase.Timestamp
import kotlinx.parcelize.Parcelize
@Keep
@Parcelize
data class Recap(
var id: String = "",
var uid: String = "",
var username: String = "",
var title: String = "",
var rating: Int = 0,
var season: Int = 0,
var episode: Int = 0,
var type: String = "",
var language: String = "",
var body: String = "",
var status: String = RecapStatus.PENDING,
var category: String = "",
var image: String = "",
var deepLink: String = "",
var created: Timestamp = Timestamp.now(),
val reviewers: List<String> = emptyList()
) : Parcelable
fun Recap.isPending() = status == RecapStatus.PENDING
fun Recap.isApproved() = status == RecapStatus.APPROVED
fun Recap.isRejected() = status == RecapStatus.REJECTED
| 0 | Kotlin | 0 | 0 | 960f3f6f3c876289cfc6e7edc76778af05dcdcd0 | 922 | recap | MIT License |
src/main/java/io/javalin/plugin/openapi/dsl/DocumentedRequestBody.kt | gaecom | 225,545,176 | false | null | package io.javalin.plugin.openapi.dsl
import io.swagger.v3.oas.models.Components
import io.swagger.v3.oas.models.parameters.RequestBody
class DocumentedRequestBody(
val content: List<DocumentedContent>
)
fun RequestBody.applyDocumentedRequestBody(documentedRequestBody: DocumentedRequestBody) {
if (documentedRequestBody.content.isNotEmpty()) {
updateContent {
documentedRequestBody.content.forEach { applyDocumentedContent(it) }
}
}
}
fun Components.applyDocumentedRequestBody(documentedRequestBody: DocumentedRequestBody) {
documentedRequestBody.content.forEach { applyDocumentedContent(it) }
}
| 0 | null | 0 | 1 | 5031c0da0e0ddf61acf3204e969912d56a5e4888 | 649 | javalin | Apache License 2.0 |
core/design/src/main/java/com/weather/core/design/theme/Color.kt | aarash709 | 605,957,736 | false | {"Kotlin": 261029} | package com.weather.core.design.theme
import androidx.compose.ui.graphics.Color
val White = Color(0xFFF0F0F0)
val Gray900 = Color(0xFF0F0F0F)
val Gray800 = Color(0xFF141414)
val Gray200 = Color(0xFFD2D2D2)
val Gray100 = Color(0XFFe6e6e6)
val Blue = Color(0xFF2131CC)
val Black = Color(0xFF0A0A0A)
val Yellow = Color(0XFFFDDD5E)
| 0 | Kotlin | 0 | 2 | 510bc2f8eed164ac477b6c327c408698a5af18b0 | 331 | Weather | Apache License 2.0 |
src/test/kotlin/no/nav/syfo/testutil/KOppfolgingsplanLPSNAVGenerator.kt | navikt | 290,982,864 | false | null | package no.nav.syfo.testutil
import no.nav.syfo.domain.PersonIdentNumber
import no.nav.syfo.oppfolgingsplan.avro.KOppfolgingsplanLPSNAV
import no.nav.syfo.testutil.UserConstants.ARBEIDSTAKER_FNR
import no.nav.syfo.testutil.UserConstants.VIRKSOMHETSNUMMER
import java.time.LocalDate
import java.util.*
fun generateKOppfolgingsplanLPSNAV(personIdentNumber: PersonIdentNumber): KOppfolgingsplanLPSNAV {
return KOppfolgingsplanLPSNAV(
UUID.randomUUID().toString(),
personIdentNumber.value,
VIRKSOMHETSNUMMER.value,
true,
LocalDate.now().toEpochDay().toInt()
)
}
val generateKOppfolgingsplanLPSNAV =
KOppfolgingsplanLPSNAV(
UUID.randomUUID().toString(),
ARBEIDSTAKER_FNR.value,
VIRKSOMHETSNUMMER.value,
true,
LocalDate.now().toEpochDay().toInt()
)
val generateKOppfolgingsplanLPSNAV2 =
KOppfolgingsplanLPSNAV(
UUID.randomUUID().toString(),
ARBEIDSTAKER_FNR.value,
VIRKSOMHETSNUMMER.value,
true,
LocalDate.now().toEpochDay().toInt()
)
val generateKOppfolgingsplanLPSNAVNoBehovforForBistand =
KOppfolgingsplanLPSNAV(
UUID.randomUUID().toString(),
ARBEIDSTAKER_FNR.value,
VIRKSOMHETSNUMMER.value,
false,
LocalDate.now().toEpochDay().toInt()
)
| 0 | Kotlin | 0 | 0 | f03038805a3d4838f38d63eea9e61c51bce0b130 | 1,332 | ispersonoppgave | MIT License |
service/src/main/kotlin/io/provenance/explorer/domain/extensions/MessageTranslationExtensions.kt | provenance-io | 332,035,574 | false | {"Kotlin": 1062465, "PLpgSQL": 316369, "Shell": 679, "Python": 642} | package io.provenance.explorer.domain.extensions
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.ArrayNode
import com.fasterxml.jackson.databind.node.ObjectNode
import com.google.protobuf.Message
import com.google.protobuf.util.JsonFormat
import io.provenance.explorer.JSON_NODE_FACTORY
import io.provenance.explorer.OBJECT_MAPPER
import io.provenance.explorer.domain.core.isMAddress
val protoTypesToCheckForMetadata = listOf(
"/provenance.metadata.v1.MsgWriteScopeRequest",
"/provenance.metadata.v1.MsgDeleteScopeRequest",
"/provenance.metadata.v1.MsgWriteRecordSpecificationRequest",
"/provenance.metadata.v1.MsgDeleteRecordSpecificationRequest",
"/provenance.metadata.v1.MsgWriteScopeSpecificationRequest",
"/provenance.metadata.v1.MsgDeleteScopeSpecificationRequest",
"/provenance.metadata.v1.MsgWriteContractSpecificationRequest",
"/provenance.metadata.v1.MsgDeleteContractSpecificationRequest",
"/provenance.metadata.v1.MsgAddScopeDataAccessRequest",
"/provenance.metadata.v1.MsgDeleteScopeDataAccessRequest",
"/provenance.metadata.v1.MsgAddScopeOwnerRequest",
"/provenance.metadata.v1.MsgDeleteScopeOwnerRequest",
"/provenance.metadata.v1.MsgWriteSessionRequest",
"/provenance.metadata.v1.MsgWriteRecordRequest",
"/provenance.metadata.v1.MsgDeleteRecordRequest",
"/provenance.metadata.v1.MsgAddContractSpecToScopeSpecRequest",
"/provenance.metadata.v1.MsgDeleteContractSpecFromScopeSpecRequest"
)
val protoTypesFieldsToCheckForMetadata = listOf(
"scopeId",
"specificationId",
"recordId",
"sessionId",
"contractSpecificationId",
"scopeSpecificationId",
"contractSpecIds",
"scopeSpecId",
"contractSpecId",
"recordSpecId"
)
val protoTypesToCheckForSmartContract = listOf(
"/cosmwasm.wasm.v1beta1.MsgInstantiateContract",
"/cosmwasm.wasm.v1beta1.MsgExecuteContract",
"/cosmwasm.wasm.v1beta1.MsgMigrateContract",
"/cosmwasm.wasm.v1.MsgInstantiateContract",
"/cosmwasm.wasm.v1.MsgExecuteContract",
"/cosmwasm.wasm.v1.MsgMigrateContract"
)
val protoTypesFieldsToCheckForSmartContract = listOf(
"initMsg",
"msg",
"migrateMsg"
)
fun Message.toObjectNode(protoPrinter: JsonFormat.Printer) =
OBJECT_MAPPER.readTree(protoPrinter.print(this))
.let { node ->
node.get("@type")?.asText()?.let { proto ->
if (protoTypesToCheckForMetadata.contains(proto))
protoTypesFieldsToCheckForMetadata.forEach { fromBase64ToMAddress(node, it) }
if (protoTypesToCheckForSmartContract.contains(proto))
protoTypesFieldsToCheckForSmartContract.forEach { fromBase64ToObject(node, it) }
}
(node as ObjectNode).remove("@type")
node
}
fun Message.toObjectNodeNonTxMsg(protoPrinter: JsonFormat.Printer, fieldNames: List<String>) =
OBJECT_MAPPER.readTree(protoPrinter.print(this))
.let { node ->
fieldNames.forEach { fromBase64ToObject(node, it) }
node
}
fun Message.toObjectNodeMAddressValues(protoPrinter: JsonFormat.Printer, fieldNames: List<String>) =
OBJECT_MAPPER.readTree(protoPrinter.print(this))
.let { node ->
fieldNames.forEach { fromBase64ToMAddress(node, it) }
node
}
fun fromBase64ToObject(jsonNode: JsonNode, fieldName: String) {
var found = false
if (jsonNode.has(fieldName)) {
val newValue = jsonNode.get(fieldName).asText().fromBase64()
(jsonNode as ObjectNode).replace(fieldName, OBJECT_MAPPER.readTree(newValue))
found = true // stop after first find
}
if (!found) {
jsonNode.forEach { fromBase64ToMAddress(it, fieldName) }
}
}
fun fromBase64ToMAddress(jsonNode: JsonNode, fieldName: String) {
var found = false
if (jsonNode.has(fieldName)) {
when {
jsonNode.get(fieldName).isTextual -> {
val value = jsonNode.get(fieldName).asText()
if (!value.isMAddress())
(jsonNode as ObjectNode).replace(
fieldName,
JSON_NODE_FACTORY.textNode(value.fromBase64ToMAddress().toString())
)
}
jsonNode.get(fieldName).isArray -> {
val oldArray = (jsonNode.get(fieldName) as ArrayNode)
val newArray = JSON_NODE_FACTORY.arrayNode()
oldArray.forEach {
val value = it.asText().fromBase64ToMAddress().toString()
newArray.add(JSON_NODE_FACTORY.textNode(value))
}
(jsonNode as ObjectNode).replace(fieldName, newArray)
}
}
found = true
}
if (!found) {
jsonNode.forEach { fromBase64ToMAddress(it, fieldName) }
}
}
| 29 | Kotlin | 3 | 6 | 4a181cb18f45b6b30e75c2536272709e7f6155ba | 4,896 | explorer-service | Apache License 2.0 |
app/src/main/java/com/lukaslechner/coroutineusecasesonandroid/playground/fundamentals/8_suspending_coroutines.kt | ahuamana | 627,986,788 | false | null | package com.lukaslechner.coroutineusecasesonandroid.playground.fundamentals
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.runBlocking
fun main() = runBlocking {
println("Main starts: ${Thread.currentThread().name}")
joinAll(
async {
suspendingCoroutine(1, 500)
},
async {
suspendingCoroutine(2, 300)
},
async {
repeat(5) {
println("other task is workin on ${Thread.currentThread().name}")
delay(100)
}
suspendingCoroutine(3, 100)
}
)
println("Main ends: ${Thread.currentThread().name}")
}
suspend fun suspendingCoroutine(number:Int, delay:Long){
println("Coroutine starts: $number starts work on ${Thread.currentThread().name}")
delay(delay)
println("Coroutine ends: $number ends work on ${Thread.currentThread().name}")
} | 0 | Kotlin | 0 | 0 | 931ce884b8c70355e38e007141aab58687ed1909 | 973 | KotlinCorutinesExpert | Apache License 2.0 |
platform/platform-impl/src/com/intellij/ui/layout/Row.kt | androidports | 115,100,208 | true | {"Java": 168074327, "Python": 25851822, "Kotlin": 6237300, "Groovy": 3448233, "HTML": 1962706, "C": 214338, "C++": 180382, "CSS": 172743, "JavaScript": 148969, "Lex": 148787, "XSLT": 113040, "Jupyter Notebook": 93222, "Shell": 60321, "NSIS": 57796, "Batchfile": 51257, "Roff": 37534, "Objective-C": 27309, "TeX": 25473, "AMPL": 20665, "TypeScript": 9469, "J": 5050, "PHP": 2699, "Makefile": 2352, "Thrift": 1846, "CoffeeScript": 1759, "CMake": 1675, "Ruby": 1217, "Perl": 962, "Smalltalk": 906, "C#": 696, "AspectJ": 182, "Visual Basic": 77, "HLSL": 57, "Erlang": 10} | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui.layout
import com.intellij.BundleBase
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.fileChooser.FileChooserDescriptor
import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.ClickListener
import com.intellij.ui.TextFieldWithHistoryWithBrowseButton
import com.intellij.ui.components.Label
import com.intellij.ui.components.Link
import com.intellij.ui.components.Panel
import com.intellij.ui.components.textFieldWithHistoryWithBrowseButton
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.UIUtil.ComponentStyle
import com.intellij.util.ui.UIUtil.FontColor
import java.awt.Component
import java.awt.event.ActionEvent
import java.awt.event.MouseEvent
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.JLabel
abstract class Row() {
abstract var enabled: Boolean
abstract var visible: Boolean
abstract var subRowsEnabled: Boolean
abstract var subRowsVisible: Boolean
abstract val subRows: List<Row>
protected abstract val builder: LayoutBuilderImpl
fun label(text: String, gapLeft: Int = 0, style: ComponentStyle? = null, fontColor: FontColor? = null, bold: Boolean = false) {
Label(text, style, fontColor, bold)(gapLeft = gapLeft)
}
fun link(text: String, style: ComponentStyle? = null, action: () -> Unit) {
val result = Link(text, action = action)
style?.let { UIUtil.applyStyle(it, result) }
result()
}
fun button(text: String, actionListener: (event: ActionEvent) -> Unit) {
val button = JButton(BundleBase.replaceMnemonicAmpersand(text))
button.addActionListener(actionListener)
button()
}
fun textFieldWithBrowseButton(browseDialogTitle: String,
value: String? = null,
project: Project? = null,
fileChooserDescriptor: FileChooserDescriptor = FileChooserDescriptorFactory.createSingleFileNoJarsDescriptor(),
historyProvider: (() -> List<String>)? = null,
fileChoosen: ((chosenFile: VirtualFile) -> String)? = null): TextFieldWithHistoryWithBrowseButton {
val component = textFieldWithHistoryWithBrowseButton(project, browseDialogTitle, fileChooserDescriptor, historyProvider, fileChoosen)
value?.let { component.text = it }
component()
return component
}
fun gearButton(vararg actions: AnAction) {
val label = JLabel()
label.icon = AllIcons.General.Gear
object : ClickListener() {
override fun onClick(e: MouseEvent, clickCount: Int): Boolean {
JBPopupFactory.getInstance()
.createActionGroupPopup(null, DefaultActionGroup(*actions), DataContext { dataId ->
when (dataId) {
PlatformDataKeys.CONTEXT_COMPONENT.name -> label
else -> null
}
}, true, null, 10)
.showUnderneathOf(label)
return true
}
}.installOn(label)
label()
}
fun hint(text: String) {
label(text, style = ComponentStyle.SMALL, fontColor = FontColor.BRIGHTER, gapLeft = 3 * HORIZONTAL_GAP)
}
fun panel(title: String, wrappedComponent: Component, vararg constraints: CCFlags) {
val panel = Panel(title)
panel.add(wrappedComponent)
panel(*constraints)
}
abstract operator fun JComponent.invoke(vararg constraints: CCFlags, gapLeft: Int = 0, growPolicy: GrowPolicy? = null)
inline fun right(init: Row.() -> Unit) {
alignRight()
init()
}
protected abstract fun alignRight()
inline fun row(label: String, init: Row.() -> Unit): Row {
val row = createRow(label)
row.init()
return row
}
inline fun row(init: Row.() -> Unit): Row {
val row = createRow(null)
row.init()
return row
}
protected abstract fun createRow(label: String?): Row
@Deprecated(message = "Nested row is prohibited", level = DeprecationLevel.ERROR)
fun row(label: JLabel? = null, init: Row.() -> Unit) {
}
@Deprecated(message = "Nested noteRow is prohibited", level = DeprecationLevel.ERROR)
fun noteRow(text: String) {
}
}
enum class GrowPolicy {
SHORT_TEXT
} | 6 | Java | 0 | 4 | 6e4f7135c5843ed93c15a9782f29e4400df8b068 | 5,158 | intellij-community | Apache License 2.0 |
faux-api/src/main/kotlin/io/polymorphicpanda/faux/state/state.kt | raniejade | 109,104,219 | false | null | package io.polymorphicpanda.faux.state
import io.polymorphicpanda.faux.entity.Context
import io.polymorphicpanda.faux.runtime.Descriptor
import io.polymorphicpanda.faux.runtime.Faux
import io.polymorphicpanda.faux.service.Service
import kotlinx.coroutines.experimental.channels.ProducerScope
import kotlinx.coroutines.experimental.channels.ReceiveChannel
data class Progress(val progress: Double, val description: String)
interface GlobalContext: Context
abstract class State {
inline fun <reified T: Service> service() = lazy { Faux.getService<T>() }
val stateManager by service<StateManager>()
suspend open fun ProducerScope<Progress>.init() { }
open fun dispose() { }
open fun update(duration: Double, context: GlobalContext) { }
}
interface StateDescriptor<T: State>: Descriptor<T>
interface StateManager: Service {
fun set(descriptor: StateDescriptor<*>): ReceiveChannel<Progress>
fun push(descriptor: StateDescriptor<*>): ReceiveChannel<Progress>
fun peek(): StateDescriptor<*>
fun pop(): StateDescriptor<*>
}
abstract class TransitionState<T: State>: State() {
abstract val nextState: StateDescriptor<T>
var progressChannel: ReceiveChannel<Progress>? = null
suspend override fun ProducerScope<Progress>.init() {
progressChannel = stateManager.set(nextState)
}
override final fun update(duration: Double, context: GlobalContext) {
try {
if (progressChannel != null) {
progressChannel!!.poll()?.let { progress ->
onUpdate(progress)
}
} else {
onTransitionError()
}
} catch (throwable: Throwable) {
onError(throwable)
}
}
protected abstract fun onUpdate(progress: Progress)
protected abstract fun onError(throwable: Throwable)
protected abstract fun onTransitionError()
}
| 0 | Kotlin | 0 | 0 | d204efdb3f602ecdd9bf9aae159d900bd5ac4f8e | 1,905 | faux | MIT License |
src/main/java/pl/edu/amu/wmi/erykandroidcommon/recycler/grouping/GroupedRecyclerFragment.kt | dagi12 | 107,324,186 | false | null | package pl.edu.amu.wmi.erykandroidcommon.recycler.grouping
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import pl.edu.amu.wmi.erykandroidcommon.base.BaseFragment
import pl.edu.amu.wmi.erykandroidcommon.recycler.AbstractViewHolder
abstract class GroupedRecyclerFragment<in T : ListItem, P : View, in U : AbstractViewHolder<P>> : BaseFragment() {
protected fun initRecyclerView(recyclerView: RecyclerView) {
recyclerView.layoutManager = LinearLayoutManager(recyclerView.context)
val groupedRecyclerAdapter = instantiateAdapter()
recyclerView.adapter = groupedRecyclerAdapter
}
protected abstract fun instantiateAdapter(): GroupedRecyclerAdapter<T, P, U>
}
| 1 | null | 1 | 1 | 0715d59c3c208df668dc116171ece78a6cf9dd2c | 774 | eryk-android-common | Apache License 2.0 |
lang/src/org/partiql/lang/ast/ast.kt | pcholakov | 200,474,830 | true | {"Kotlin": 1943709, "HTML": 99272, "Java": 13314, "TSQL": 158} | /*
* Copyright 2019 Amazon.com, Inc. or its affiliates. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at:
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
* language governing permissions and limitations under the License.
*/
package org.partiql.lang.ast
import com.amazon.ion.*
import org.partiql.lang.util.*
import java.util.*
/**
* The only nodes that inherit directly from ExprNode should just be generic expressions that can be used any
* place a value is allowed.
*/
sealed class ExprNode : HasMetas {
fun copy(newMetas: MetaContainer? = null): ExprNode {
// This looks like duplication but really isn't: each branch executes a different compiler-generated `copy` function.
val metas = newMetas ?: this.metas
return when (this) {
is Literal -> {
copy(metas = metas)
}
is LiteralMissing -> {
copy(metas = metas)
}
is VariableReference -> {
copy(metas = metas)
}
is NAry -> {
copy(metas = metas)
}
is CallAgg -> {
copy(metas = metas)
}
is Typed -> {
copy(metas = metas)
}
is Path -> {
copy(metas = metas)
}
is SimpleCase -> {
copy(metas = metas)
}
is SearchedCase -> {
copy(metas = metas)
}
is Select -> {
copy(metas = metas)
}
is Struct -> {
copy(metas = metas)
}
is ListExprNode -> {
copy(metas = metas)
}
is Bag -> {
copy(metas = metas)
}
}
}
}
//********************************
// Basic arithmetic expressions.
//********************************
/** Represents a literal value. */
data class Literal(
val ionValue: IonValue,
override val metas: MetaContainer
) : ExprNode() {
init {
ionValue.clone().makeReadOnly()
}
}
/** Represents the literal value `MISSING`. */
data class LiteralMissing(
override val metas: MetaContainer
) : ExprNode()
/**
* A variable reference, which contains a [SymbolicName] and the [CaseSensitivity] that should be used to determine when
* resolving the variable's binding.
*/
data class VariableReference(
val id: String,
val case: CaseSensitivity,
val scopeQualifier: ScopeQualifier = ScopeQualifier.UNQUALIFIED,
override val metas: MetaContainer
) : ExprNode() {
/**
* Respects case sensitivity when comparing against another [VariableReference].
*/
override fun equals(other: Any?): Boolean =
if(other !is VariableReference) { false }
else {
id.compareTo(other.id, case == CaseSensitivity.INSENSITIVE) == 0
&& case == other.case
&& scopeQualifier == other.scopeQualifier
&& metas == other.metas
}
override fun hashCode(): Int =
Arrays.hashCode(
arrayOf(
when(case) {
CaseSensitivity.SENSITIVE -> id
CaseSensitivity.INSENSITIVE -> id.toLowerCase()
},
case,
scopeQualifier,
metas))
}
/**
* Represents an n-ary expression. See [NAryOp] for the types of expressions
* that can be represented with an instance of [NAry].
*/
data class NAry(
val op: NAryOp,
val args: List<ExprNode>,
override val metas: MetaContainer
) : ExprNode()
/**
* Represents a call to an aggregate function.
*/
data class CallAgg(
val funcExpr: ExprNode,
val setQuantifier: SetQuantifier,
val arg: ExprNode,
override val metas: MetaContainer
) : ExprNode()
/** Represents a "typed expression", i.e. `CAST` and `IS`. */
data class Typed(
val op: TypedOp,
val expr: ExprNode,
val type: DataType,
override val metas: MetaContainer
) : ExprNode()
//********************************
// Path expressions
//********************************
/** Represents a path expression, i.e. `foo.bar`, `foo[*].bar`, etc. */
data class Path(
val root: ExprNode,
val components: List<PathComponent>,
override val metas: MetaContainer
) : ExprNode()
//********************************
// Simple CASE
//********************************
/** For `CASE foo WHEN <value> THEN <expr> ELSE <else> END` */
data class SimpleCase(
val valueExpr: ExprNode,
val whenClauses: List<SimpleCaseWhen>,
val elseExpr: ExprNode?,
override val metas: MetaContainer) : ExprNode()
/** Represents a case of a [SimpleCase]. */
data class SimpleCaseWhen(
val valueExpr: ExprNode,
val thenExpr: ExprNode
)
//********************************
// Searched CASE
//********************************
/** For `CASE WHEN <conditionExpr> THEN <thenExpr> ELSE <elseExpr> END`. */
data class SearchedCase(
val whenClauses: List<SearchedCaseWhen>,
val elseExpr: ExprNode?,
override val metas: MetaContainer
) : ExprNode()
/** Represents a case of a [SearchedCase]. */
data class SearchedCaseWhen(
val condition: ExprNode,
val thenExpr: ExprNode
)
//********************************
// Select Expression
//********************************
/**
* Represents a `SELECT` statements as well as the `PIVOT` and `SELECT VALUE`, variants.
*/
data class Select(
val setQuantifier: SetQuantifier = SetQuantifier.ALL,
val projection: SelectProjection,
val from: FromSource,
val where: ExprNode? = null,
val groupBy: GroupBy? = null,
val having: ExprNode? = null,
val limit: ExprNode? = null,
override val metas: MetaContainer
) : ExprNode()
/**
* SymbolicName does have a semantic meaning and primarily exists so that any identifier in the query may
* have `Meta` associated with it that is independent of the parent node which imbues its meaning.
*
* In the following example:
*
* ```
* SELECT 1 + 1 AS bar FROM ...
* ^ ^
* 1 2
* ```
*
* `1 + 1 AS bar` (#1) becomes a `SelectListItemExpr` with `1 + 1` as its expression and `bar` (#2) as its `asAlias`.
* It would be ideal to point users to the location of bar specifically in the case of errors related to the alias
* and to the location of the expression for errors related to the expression. Having SymbolicName allows for
* this.
*/
data class SymbolicName(
val name: String,
override val metas: MetaContainer
) : HasMetas
/**
* A path component can be:
* - An identifier
* - An expression with an optional alias
* - An unpivot operator (i.e. the `*` in `a.*.c`)
* - A wildcard operator (i.e. the `[*]` in `a[*].b`
* The [PathComponent] base class is used to constrain the types of child nodes that are allowed
* in a [Path] expression.
*/
sealed class PathComponent
/**
* Represents a path component that is an expression, i.e. '''['bar']''' in '''foo['bar']'''.
* Also represents ```a.b``` using a literal string `b` as [expr].
* [case] indicates the case-sensitivity of the lookup, but this is ignored in the event that [expr] evaluates
* a value that is not a string.
*/
data class PathComponentExpr(val expr: ExprNode, val case: CaseSensitivity) : PathComponent() {
companion object {
private fun getStringValueIfCaseInsensitiveLiteral(component: PathComponentExpr): String? =
when {
component.case == CaseSensitivity.INSENSITIVE
&& component.expr is Literal
&& component.expr.ionValue.type == IonType.STRING -> {
component.expr.ionValue.stringValue()
}
else -> null
}
}
override fun equals(other: Any?): Boolean =
when (other as? PathComponentExpr) {
null -> false
else -> {
val myStringValue = getStringValueIfCaseInsensitiveLiteral(this)
val otherStringValue = getStringValueIfCaseInsensitiveLiteral(other)
when {
myStringValue == null && otherStringValue == null -> {
// Neither component is a case insensitive string literal, standard equality applies
val (otherExpr, otherCase) = other
expr.equals(otherExpr) && case == otherCase
}
else ->
when {
myStringValue == null || otherStringValue == null ->
// Only one of the components was a case insensitive literal, so they are not equal
false
else ->
// Both components are case insensitive literals, perform case insensitive comparison
myStringValue.equals(otherStringValue, true)
}
}
}
}
override fun hashCode(): Int =
Arrays.hashCode(arrayOf(getStringValueIfCaseInsensitiveLiteral(this)?.toLowerCase() ?: expr, case))
}
/** Represents an unpivot path component, i.e. `*` in `foo.*.bar` */
data class PathComponentUnpivot(override val metas: MetaContainer) : PathComponent(), HasMetas
/** Represents a wildcard path component, i.e. `[*]` in `foo[*].bar`. */
data class PathComponentWildcard(override val metas: MetaContainer) : PathComponent(), HasMetas
sealed class SelectProjection
/** For `SELECT <SelectListItem> [, <SelectListItem>]...` and `SELECT *` cases */
data class SelectProjectionList(
val items: List<SelectListItem>
) : SelectProjection()
/** For `SELECT VALUE <expr>` */
data class SelectProjectionValue(
val expr: ExprNode
) : SelectProjection()
/** For `PIVOT <expr> AS <asName> AT <atName>` */
data class SelectProjectionPivot(
val valueExpr: ExprNode,
val nameExpr: ExprNode
) : SelectProjection()
/**
* A [SelectListItem] node can be:
* - An expression with an optional alias
* - A select-all expression (i.e. the `*` in `SELECT * FROM foo`)
* The [SelectListItem] base class is used to constrain the types of child nodes that are
* allowed in a [Select] expression's select list.
*
* This is intentionally not a subtype of [ExprNode] because things like the select-all expression (`*`) and
* expressions with aliases are not allowed any place an [ExprNode] is allowed.
*/
sealed class SelectListItem
/** Represents `<expr> [AS alias]` in a select list.*/
data class SelectListItemExpr(
val expr: ExprNode,
val asName: SymbolicName? = null
) : SelectListItem()
/** Represents `<expr>.*` in a select list. */
data class SelectListItemProjectAll(val expr: ExprNode) : SelectListItem()
/** Represents an `*` that is not part of a path expression in a select list, i.e. `SELECT * FROM foo`. */
data class SelectListItemStar(override val metas: MetaContainer) : SelectListItem(), HasMetas
/**
* A [FromSource] node can be:
* - A n-ary expression with optional `AS` and `AT` aliases
* - A qualified join (i.e. inner, left, right, outer)
* - An unpviot:
* Note: a `CROSS JOIN` is modeled as an `INNER JOIN` with a condition of `true`.
* Note: `FromSource`s that are separated by commas are modeled as an INNER JOIN with a condition of `true`.
*/
sealed class FromSource
/** Represents `<expr> [AS <correlation>]` within a FROM clause. */
data class FromSourceExpr(
val expr: ExprNode,
val asName: SymbolicName? = null,
val atName: SymbolicName? = null
) : FromSource()
/** Represents `<leftRef> [INNER | OUTER | LEFT | RIGHT] JOIN <rightRef> ON <condition>`. */
data class FromSourceJoin(
val joinOp: JoinOp,
val leftRef: FromSource,
val rightRef: FromSource,
val condition: ExprNode,
override val metas: MetaContainer
) : FromSource(), HasMetas
/** Represents `SELECT ... FROM UNPIVOT <fromSource> [AS <asName>] [AT <atName>]`.
*
* Note: although this is almost the same as [FromSourceExpr], it has to be kept in its own distinct
* data class because [FromSourceExpr] has no metas of its own, instead relying on [FromSourceExpr.expr] to store
* metas. However, [FromSourceUnpivot] must have its own metas because it a transform on the value resulting from
* [FromSourceUnpivot.expr]--and thus it changes its data type. (When supported, type information will be stored
* as meta nodes.)
*/
data class FromSourceUnpivot(
val expr: ExprNode,
val asName: SymbolicName?,
val atName: SymbolicName?,
override val metas: MetaContainer
) : FromSource(), HasMetas
fun FromSource.metas() =
when(this) {
is FromSourceExpr -> this.expr.metas
is FromSourceJoin -> this.metas
is FromSourceUnpivot -> this.expr.metas
}
/** For `GROUP [ PARTIAL ] BY <item>... [ GROUP AS <gropuName> ]`. */
data class GroupBy(
val grouping: GroupingStrategy,
val groupByItems: List<GroupByItem>,
val groupName: SymbolicName? = null
)
data class GroupByItem(
val expr: ExprNode,
val asName: SymbolicName? = null
)
//********************************
// Constructors
//********************************
/** Represents a field in a struct constructor. */
data class StructField(
val name: ExprNode,
val expr: ExprNode
)
/** Represents a struct constructor. */
data class Struct(
val fields: List<StructField>,
override val metas: MetaContainer
) : ExprNode()
/**
* Represents a list constructor.
* Note: `ExprNode` suffix in name disambiguates from [kotlin.collections.List].
*/
data class ListExprNode(
val values: List<ExprNode>,
override val metas: MetaContainer
) : ExprNode()
/** Represents a bag constructor. */
data class Bag(
val bag: List<ExprNode>,
override val metas: MetaContainer
) : ExprNode()
/**
* Represents a data type reference such as `INT` or `VARCHAR(50)`.
*/
data class DataType(
val sqlDataType: SqlDataType,
val args: List<Long>,
override val metas: MetaContainer
) : HasMetas
//********************************
// Node attributes
//********************************
/** Indicates case sensitivity of variable references. */
enum class CaseSensitivity(private val symbol: String) {
SENSITIVE("case_sensitive"),
INSENSITIVE("case_insensitive");
companion object {
fun fromSymbol(s: String) : CaseSensitivity = when (s) {
"case_sensitive" -> SENSITIVE
"case_insensitive" -> INSENSITIVE
else -> throw IllegalArgumentException("Unrecognized CaseSensitivity $s")
}
}
fun toSymbol() = symbol
}
/** Indicates if all rows in a select query are to be returned or only distinct rows. */
enum class SetQuantifier {
ALL, DISTINCT
}
/**
* Different types of n-ary operations.
* [minArity] and [maxArity] are to be used during AST validation.
* [symbol] is used to look up an [NAryOp] instance from the token text and must be unique among
* all instances of [NAryOp].
*/
enum class NAryOp(val arityRange: IntRange, val symbol: String) {
/** Add, but when arity is 1 then this just returns the value of its argument. */
ADD(1..Int.MAX_VALUE, "+"),
/** Subtract, but when when arity is 1, then this is assumed to be 0 - <arg1>. */
SUB(1..Int.MAX_VALUE, "-"),
/** Multiply */
MUL(2..Int.MAX_VALUE, "*"),
/** Divide */
DIV(2..Int.MAX_VALUE, "/"),
/** Modulus */
MOD(2..Int.MAX_VALUE, "%"),
/** Equivalent */
EQ(2..Int.MAX_VALUE, "="),
/** Less-than */
LT(2..Int.MAX_VALUE, "<"),
/** Less-than-or-equal.*/
LTE(2..Int.MAX_VALUE, "<="),
/** Greater-than. */
GT(2..Int.MAX_VALUE, ">"),
/** Greater-than-or-equal. */
GTE(2..Int.MAX_VALUE, ">="),
/** Not Equals. */
NE(2..Int.MAX_VALUE, "<>"),
/** Like. */
LIKE(2..3, "like"),
/** Between expression..i.e. `<expr1> BETWEEN <expr2> AND <expr3>`*/
BETWEEN(3..3, "between"),
/** IN expression, i.e. `<expr1> IN <containerExpr> ` */
IN(2..Int.MAX_VALUE, "in"),
/** Logical not */
NOT(1..1, "not"),
/** Logical `and`. */
AND(2..Int.MAX_VALUE, "and"),
/** Logical `or` */
OR(2..Int.MAX_VALUE, "or"),
/** String concatenation. */
STRING_CONCAT(2..Int.MAX_VALUE, "||"),
/** A function call. */
CALL(0..Int.MAX_VALUE, "call"),
// The following are capable of being parsed by [SqlParser] but are not currently being consumed by
// [EvaluatingCompiler]. Additionally, they are not well defined in README-AST.md, which does not
// seem to agree with what is defined for these in the PartiQL spec. For instance, the spec references an
// ORDERED keyword, but this keyword is never used in relation to these operations in the source or README-AST.md.
// As a result, these definitions are a "best guess" that will likely need to be modified when it comes time
// to support these operators.
INTERSECT(2..Int.MAX_VALUE, "intersect"),
INTERSECT_ALL(2..Int.MAX_VALUE, "intersect_all"),
EXCEPT(2..Int.MAX_VALUE, "except"),
EXCEPT_ALL(2..Int.MAX_VALUE, "except_all"),
UNION(2..Int.MAX_VALUE, "union"),
UNION_ALL(2..Int.MAX_VALUE, "union_all"),
CONCAT(2..Int.MAX_VALUE, "concat");
companion object {
/** Map of [NAryOp] keyed by the operation's text. */
private val OP_SYMBOL_TO_OP_LOOKUP =
NAryOp.values()
.map { Pair(it.symbol, it) }
.toMap()
fun forSymbol(symbol: String): NAryOp? = OP_SYMBOL_TO_OP_LOOKUP[symbol]
}
}
/** Different types of type expressions. */
enum class TypedOp(val text: String) {
CAST("cast"),
IS("is")
}
/** Type of join operation. */
enum class JoinOp {
/** INNER JOIN. */
INNER,
/** A LEFT OUTER JOIN. */
LEFT,
/** A RIGHT OUTER JOIN. */
RIGHT,
/** A FULL OUTER JOIN. */
OUTER
}
/** Grouping strategy. */
enum class GroupingStrategy {
/** Represents `GROUP BY` (no partial). */
FULL,
/** Represents `GROUP PARTIAL BY`.*/
PARTIAL
}
/**
* Indicates strategy for binding lookup within scopes.
*/
enum class ScopeQualifier {
/** For variable references *not* prefixed with '@'. */
UNQUALIFIED,
/** For variable references prefixed with '@'. */
LEXICAL,
}
/**
* The core PartiQL data types.
*/
enum class SqlDataType(val typeName: String, val arityRange: IntRange) {
MISSING("missing", 0..0), // PartiQL
NULL("null", 0..0), // Ion
BOOLEAN("boolean", 0..0), // Ion & SQL-99
SMALLINT("smallint", 0..0), // SQL-92
INTEGER("integer", 0..0), // Ion & SQL-92
FLOAT("float", 0..1), // Ion & SQL-92
REAL("real", 0..0), // SQL-92
DOUBLE_PRECISION("double_precision", 0..0), // SQL-92
DECIMAL("decimal", 0..2), // Ion & SQL-92
NUMERIC("numeric", 0..2), // SQL-92
TIMESTAMP("timestamp", 0..0), // Ion & SQL-92
CHARACTER("character", 0..1), // SQL-92
CHARACTER_VARYING("character_varying", 0..1), // SQL-92
STRING("string", 0..0), // Ion
SYMBOL("symbol", 0..0), // Ion
CLOB("clob", 0..0), // Ion
BLOB("blob", 0..0), // Ion
STRUCT("struct", 0..0), // Ion
TUPLE("tuple", 0..0), // PartiQL
LIST("list", 0..0), // Ion
SEXP("sexp", 0..0), // Ion
BAG("bag", 0..0); // PartiQL
companion object {
private val DATA_TYPE_NAME_TO_TYPE_LOOKUP =
SqlDataType.values()
.map { Pair(it.typeName, it) }
.toMap()
fun forTypeName(typeName: String): SqlDataType? = DATA_TYPE_NAME_TO_TYPE_LOOKUP[typeName]
}
}
| 0 | Kotlin | 0 | 0 | a0ac8750a330c8f27897e3ef094e2830d9c6544b | 20,221 | partiql-lang-kotlin | Apache License 2.0 |
simplified-profiles/src/main/java/org/nypl/simplified/profiles/ProfilesDatabase.kt | ThePalaceProject | 367,082,997 | false | null | package org.nypl.simplified.profiles
import android.content.Context
import com.google.common.base.Preconditions
import com.io7m.jfunctional.Option
import com.io7m.jfunctional.OptionType
import com.io7m.junreachable.UnreachableCodeException
import io.reactivex.subjects.Subject
import org.joda.time.LocalDateTime
import org.nypl.simplified.accounts.api.AccountAuthenticationCredentialsStoreType
import org.nypl.simplified.accounts.api.AccountBundledCredentialsType
import org.nypl.simplified.accounts.api.AccountEvent
import org.nypl.simplified.accounts.api.AccountProviderType
import org.nypl.simplified.accounts.database.api.AccountsDatabaseFactoryType
import org.nypl.simplified.accounts.registry.api.AccountProviderRegistryType
import org.nypl.simplified.analytics.api.AnalyticsEvent
import org.nypl.simplified.analytics.api.AnalyticsType
import org.nypl.simplified.books.formats.api.BookFormatSupportType
import org.nypl.simplified.files.DirectoryUtilities
import org.nypl.simplified.profiles.api.ProfileAnonymousDisabledException
import org.nypl.simplified.profiles.api.ProfileAnonymousEnabledException
import org.nypl.simplified.profiles.api.ProfileCreateDuplicateException
import org.nypl.simplified.profiles.api.ProfileCreateInvalidException
import org.nypl.simplified.profiles.api.ProfileDatabaseException
import org.nypl.simplified.profiles.api.ProfileID
import org.nypl.simplified.profiles.api.ProfileNoneCurrentException
import org.nypl.simplified.profiles.api.ProfileNonexistentException
import org.nypl.simplified.profiles.api.ProfileType
import org.nypl.simplified.profiles.api.ProfilesDatabaseType
import org.nypl.simplified.profiles.api.ProfilesDatabaseType.AnonymousProfileEnabled.ANONYMOUS_PROFILE_DISABLED
import org.nypl.simplified.profiles.api.ProfilesDatabaseType.AnonymousProfileEnabled.ANONYMOUS_PROFILE_ENABLED
import org.slf4j.LoggerFactory
import java.io.File
import java.io.IOException
import java.util.Collections
import java.util.SortedMap
import java.util.UUID
import java.util.concurrent.ConcurrentSkipListMap
import javax.annotation.concurrent.GuardedBy
/**
* The default implementation of the [ProfilesDatabaseType] interface.
*/
internal class ProfilesDatabase internal constructor(
private val accountBundledCredentials: AccountBundledCredentialsType,
private val accountEvents: Subject<AccountEvent>,
private val accountProviders: AccountProviderRegistryType,
private val accountCredentialsStore: AccountAuthenticationCredentialsStoreType,
private val accountsDatabases: AccountsDatabaseFactoryType,
private val bookFormatSupport: BookFormatSupportType,
private val analytics: AnalyticsType,
private val anonymousProfileEnabled: ProfilesDatabaseType.AnonymousProfileEnabled,
private val context: Context,
private val directory: File,
private val profiles: ConcurrentSkipListMap<ProfileID, Profile>
) : ProfilesDatabaseType {
private val logger = LoggerFactory.getLogger(ProfilesDatabase::class.java)
private val profilesReadOnly: SortedMap<ProfileID, ProfileType>
private val profileCurrentLock: Any = Any()
@GuardedBy("profileCurrentLock")
private var profileCurrent: ProfileID? = null
/**
* Perform an unchecked (but safe) cast of the given map type. The cast is safe because
* `V <: VB`.
*/
private fun <K, VB, V : VB> castMap(m: SortedMap<K, V>): SortedMap<K, VB> {
return m as SortedMap<K, VB>
}
init {
this.profilesReadOnly = castMap(Collections.unmodifiableSortedMap(this.profiles))
this.profileCurrent = null
for (profile in this.profiles.values) {
profile.setOwner(this)
}
}
internal val defaultAccountProvider: AccountProviderType =
this.accountProviders.defaultProvider
override fun anonymousProfileEnabled(): ProfilesDatabaseType.AnonymousProfileEnabled {
return this.anonymousProfileEnabled
}
@Throws(ProfileAnonymousDisabledException::class)
override fun anonymousProfile(): ProfileType {
return when (this.anonymousProfileEnabled) {
ANONYMOUS_PROFILE_ENABLED ->
this.profiles[ProfilesDatabases.ANONYMOUS_PROFILE_ID]!!
ANONYMOUS_PROFILE_DISABLED ->
throw ProfileAnonymousDisabledException("The anonymous profile is not enabled")
}
}
override fun directory(): File {
return this.directory
}
override fun profiles(): SortedMap<ProfileID, ProfileType> {
return this.profilesReadOnly
}
@Throws(ProfileDatabaseException::class)
override fun createProfile(
accountProvider: AccountProviderType,
displayName: String
): ProfileType {
if (displayName.isEmpty()) {
throw ProfileCreateInvalidException("Display name cannot be empty")
}
val existing = this.findProfileWithDisplayName(displayName)
if (existing.isSome) {
throw ProfileCreateDuplicateException("Display name is already used by an existing profile")
}
val next = ProfileID(UUID.randomUUID())
Preconditions.checkArgument(
!this.profiles.containsKey(next),
"Profile ID %s cannot have been used", next
)
val profile =
ProfilesDatabases.createProfileActual(
context = this.context,
analytics = this.analytics,
accountBundledCredentials = this.accountBundledCredentials,
accountEvents = this.accountEvents,
accountProviders = this.accountProviders,
accountsDatabases = this.accountsDatabases,
accountCredentialsStore = this.accountCredentialsStore,
accountProvider = accountProvider,
bookFormatSupport = this.bookFormatSupport,
directory = this.directory,
displayName = displayName,
id = next
)
this.profiles[profile.id] = profile
profile.setOwner(this)
logProfileCreated(profile)
return profile
}
override fun findProfileWithDisplayName(displayName: String): OptionType<ProfileType> {
for (profile in this.profiles.values) {
if (profile.displayName == displayName) {
return Option.some(profile)
}
}
return Option.none()
}
@Throws(ProfileNonexistentException::class, ProfileAnonymousEnabledException::class)
override fun setProfileCurrent(profile: ProfileID) {
return when (this.anonymousProfileEnabled) {
ANONYMOUS_PROFILE_ENABLED -> {
throw ProfileAnonymousEnabledException(
"The anonymous profile is enabled; cannot set the current profile"
)
}
ANONYMOUS_PROFILE_DISABLED -> {
if (!this.profiles.containsKey(profile)) {
throw ProfileNonexistentException("Profile does not exist")
}
this.setCurrentProfile(profile)
}
}
}
internal fun setCurrentProfile(profile: ProfileID) {
this.logger.debug("setCurrentProfile: {}", profile)
synchronized(this.profileCurrentLock) {
this.profileCurrent = profile
}
}
override fun currentProfile(): OptionType<ProfileType> {
return synchronized(this.profileCurrentLock) {
when (this.anonymousProfileEnabled) {
ANONYMOUS_PROFILE_ENABLED -> {
try {
Option.some(this.anonymousProfile())
} catch (e: ProfileAnonymousDisabledException) {
throw UnreachableCodeException(e)
}
}
ANONYMOUS_PROFILE_DISABLED -> {
Option.of<ProfileID>(this.profileCurrent).map { id -> this.profiles[id] }
}
}
}
}
@Throws(ProfileNoneCurrentException::class)
override fun currentProfileUnsafe(): ProfileType {
return this.currentProfileGet()
}
@Throws(ProfileNoneCurrentException::class)
private fun currentProfileGet(): Profile {
synchronized(this.profileCurrentLock) {
val id = this.profileCurrent
if (id != null) {
return this.profiles[id]!!
}
throw ProfileNoneCurrentException("No profile is current")
}
}
@Throws(IOException::class)
internal fun deleteProfile(profile: Profile) {
synchronized(this.profileCurrentLock) {
this.profiles.remove(profile.id)
if (this.profileCurrent == profile.id) {
this.profileCurrent = null
}
DirectoryUtilities.directoryDelete(profile.directory)
}
}
private fun logProfileCreated(profile: Profile) {
this.analytics.publishEvent(
AnalyticsEvent.ProfileCreated(
timestamp = LocalDateTime.now(),
credentials = null,
profileUUID = profile.id.uuid,
displayName = profile.displayName,
birthDate = profile.preferences().dateOfBirth?.show(),
attributes = profile.description().attributes.attributes
)
)
}
}
| 109 | null | 4 | 8 | 82dee2e0f39a74afc5a429d0124e20f77b1eac13 | 8,568 | android-core | Apache License 2.0 |
app/src/main/java/com/leonra/versions/list/VersionListFragment.kt | LeonRa | 347,512,789 | false | null | package com.leonra.versions.list
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.leonra.versions.databinding.FragmentVersionListBinding
import com.leonra.versions.model.Version
import com.leonra.versions.model.VersionRepository
/**
* A list of all of our Android [Version]s.
*/
class VersionListFragment : Fragment() {
private var _binding: FragmentVersionListBinding? = null
private val binding get() = requireNotNull(_binding)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentVersionListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val versionAdapter = VersionListAdapter()
binding.recyclerView.run {
adapter = versionAdapter
addItemDecoration(DividerItemDecoration(context, RecyclerView.VERTICAL))
}
versionAdapter.submitList(VersionRepository.getAll())
}
// TODO: Hook up this callback
private fun onVersionClicked(version: Version) = findNavController().navigate(
VersionListFragmentDirections.actionVersionListToSecondFragment(
label = version.codename,
apiLevel = version.apiLevel,
)
)
}
| 0 | Kotlin | 0 | 0 | cb6728227a5cc548c0bbad6c0a172d5f9f2d1b26 | 1,688 | AndroidVersions | Apache License 2.0 |
detekt-formatting/src/main/kotlin/io/gitlab/arturbosch/detekt/formatting/FormattingProvider.kt | detekt | 71,729,669 | false | null | package io.gitlab.arturbosch.detekt.formatting
import com.pinterest.ktlint.rule.engine.core.api.Rule
import com.pinterest.ktlint.rule.engine.core.api.RuleId
import com.pinterest.ktlint.rule.engine.core.api.RuleSetId
import io.gitlab.arturbosch.detekt.api.ActiveByDefault
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Configuration
import io.gitlab.arturbosch.detekt.api.RuleSet
import io.gitlab.arturbosch.detekt.api.RuleSetProvider
import io.gitlab.arturbosch.detekt.formatting.wrappers.AnnotationOnSeparateLine
import io.gitlab.arturbosch.detekt.formatting.wrappers.AnnotationSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.ArgumentListWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.BinaryExpressionWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.BlankLineBeforeDeclaration
import io.gitlab.arturbosch.detekt.formatting.wrappers.BlockCommentInitialStarAlignment
import io.gitlab.arturbosch.detekt.formatting.wrappers.ChainMethodContinuation
import io.gitlab.arturbosch.detekt.formatting.wrappers.ChainWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.ClassName
import io.gitlab.arturbosch.detekt.formatting.wrappers.ClassSignature
import io.gitlab.arturbosch.detekt.formatting.wrappers.CommentSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.CommentWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.ConditionWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.ContextReceiverMapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.EnumEntryNameCase
import io.gitlab.arturbosch.detekt.formatting.wrappers.EnumWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.Filename
import io.gitlab.arturbosch.detekt.formatting.wrappers.FinalNewline
import io.gitlab.arturbosch.detekt.formatting.wrappers.FunKeywordSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.FunctionExpressionBody
import io.gitlab.arturbosch.detekt.formatting.wrappers.FunctionLiteral
import io.gitlab.arturbosch.detekt.formatting.wrappers.FunctionName
import io.gitlab.arturbosch.detekt.formatting.wrappers.FunctionReturnTypeSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.FunctionSignature
import io.gitlab.arturbosch.detekt.formatting.wrappers.FunctionStartOfBodySpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.FunctionTypeModifierSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.FunctionTypeReferenceSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.IfElseBracing
import io.gitlab.arturbosch.detekt.formatting.wrappers.IfElseWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.ImportOrdering
import io.gitlab.arturbosch.detekt.formatting.wrappers.Indentation
import io.gitlab.arturbosch.detekt.formatting.wrappers.KdocWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.MaximumLineLength
import io.gitlab.arturbosch.detekt.formatting.wrappers.MixedConditionOperators
import io.gitlab.arturbosch.detekt.formatting.wrappers.ModifierListSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.ModifierOrdering
import io.gitlab.arturbosch.detekt.formatting.wrappers.MultiLineIfElse
import io.gitlab.arturbosch.detekt.formatting.wrappers.MultilineExpressionWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.MultilineLoop
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoBlankLineBeforeRbrace
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoBlankLineInList
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoBlankLinesInChainedMethodCalls
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoConsecutiveBlankLines
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoConsecutiveComments
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoEmptyClassBody
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoEmptyFile
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoEmptyFirstLineInClassBody
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoEmptyFirstLineInMethodBlock
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoLineBreakAfterElse
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoLineBreakBeforeAssignment
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoMultipleSpaces
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoSemicolons
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoSingleLineBlockComment
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoTrailingSpaces
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoUnitReturn
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoUnusedImports
import io.gitlab.arturbosch.detekt.formatting.wrappers.NoWildcardImports
import io.gitlab.arturbosch.detekt.formatting.wrappers.NullableTypeSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.PackageName
import io.gitlab.arturbosch.detekt.formatting.wrappers.ParameterListSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.ParameterListWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.ParameterWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.PropertyName
import io.gitlab.arturbosch.detekt.formatting.wrappers.PropertyWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundAngleBrackets
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundColon
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundComma
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundCurly
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundDot
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundDoubleColon
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundKeyword
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundOperators
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundParens
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundRangeOperator
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingAroundUnaryOperator
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingBetweenDeclarationsWithAnnotations
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingBetweenDeclarationsWithComments
import io.gitlab.arturbosch.detekt.formatting.wrappers.SpacingBetweenFunctionNameAndOpeningParenthesis
import io.gitlab.arturbosch.detekt.formatting.wrappers.StatementWrapping
import io.gitlab.arturbosch.detekt.formatting.wrappers.StringTemplate
import io.gitlab.arturbosch.detekt.formatting.wrappers.StringTemplateIndent
import io.gitlab.arturbosch.detekt.formatting.wrappers.TrailingCommaOnCallSite
import io.gitlab.arturbosch.detekt.formatting.wrappers.TrailingCommaOnDeclarationSite
import io.gitlab.arturbosch.detekt.formatting.wrappers.TryCatchFinallySpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.TypeArgumentComment
import io.gitlab.arturbosch.detekt.formatting.wrappers.TypeArgumentListSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.TypeParameterComment
import io.gitlab.arturbosch.detekt.formatting.wrappers.TypeParameterListSpacing
import io.gitlab.arturbosch.detekt.formatting.wrappers.UnnecessaryParenthesesBeforeTrailingLambda
import io.gitlab.arturbosch.detekt.formatting.wrappers.ValueArgumentComment
import io.gitlab.arturbosch.detekt.formatting.wrappers.ValueParameterComment
import io.gitlab.arturbosch.detekt.formatting.wrappers.Wrapping
/**
* This rule set provides wrappers for rules implemented by ktlint - https://ktlint.github.io/.
*
* **Note: The `formatting` rule set is not included in the detekt-cli or Gradle plugin.**
*
* To enable this rule set, add `detektPlugins "io.gitlab.arturbosch.detekt:detekt-formatting:$version"`
* to your gradle `dependencies` or reference the `detekt-formatting`-jar with the `--plugins` option
* in the command line interface.
*
* Note: Issues reported by this rule set can only be suppressed on file level (`@file:Suppress("detekt.rule")`).
*/
@ActiveByDefault(since = "1.0.0")
class FormattingProvider : RuleSetProvider {
override val ruleSetId = RuleSet.Id("formatting")
@Suppress("LongMethod")
override fun instance() = RuleSet(
ruleSetId,
listOf(
// Wrappers for standard rules. Enabled by default.
::AnnotationOnSeparateLine,
::AnnotationSpacing,
::ArgumentListWrapping,
::BlankLineBeforeDeclaration,
::BlockCommentInitialStarAlignment,
::ChainWrapping,
::ClassName,
::CommentSpacing,
::CommentWrapping,
::ContextReceiverMapping,
::EnumEntryNameCase,
::EnumWrapping,
::Filename,
::FinalNewline,
::FunctionName,
::FunKeywordSpacing,
::FunctionReturnTypeSpacing,
::FunctionSignature,
::FunctionStartOfBodySpacing,
::FunctionTypeReferenceSpacing,
::IfElseBracing,
::IfElseWrapping,
::ImportOrdering,
::Indentation,
::KdocWrapping,
::MaximumLineLength,
::ModifierListSpacing,
::ModifierOrdering,
::MultiLineIfElse,
::MultilineExpressionWrapping,
::NoBlankLineBeforeRbrace,
::NoBlankLineInList,
::NoBlankLinesInChainedMethodCalls,
::NoConsecutiveBlankLines,
::NoConsecutiveComments,
::NoEmptyClassBody,
::NoEmptyFile,
::NoEmptyFirstLineInClassBody,
::NoEmptyFirstLineInMethodBlock,
::NoLineBreakAfterElse,
::NoLineBreakBeforeAssignment,
::NoMultipleSpaces,
::NoSemicolons,
::NoSingleLineBlockComment,
::NoTrailingSpaces,
::NoUnitReturn,
::NoUnusedImports,
::NoWildcardImports,
::NullableTypeSpacing,
::PackageName,
::ParameterListSpacing,
::ParameterListWrapping,
::ParameterWrapping,
::PropertyName,
::PropertyWrapping,
::SpacingAroundAngleBrackets,
::SpacingAroundColon,
::SpacingAroundComma,
::SpacingAroundCurly,
::SpacingAroundDot,
::SpacingAroundDoubleColon,
::SpacingAroundKeyword,
::SpacingAroundOperators,
::SpacingAroundParens,
::SpacingAroundRangeOperator,
::SpacingAroundUnaryOperator,
::SpacingBetweenDeclarationsWithAnnotations,
::SpacingBetweenDeclarationsWithComments,
::SpacingBetweenFunctionNameAndOpeningParenthesis,
::StatementWrapping,
::StringTemplate,
::StringTemplateIndent,
::TrailingCommaOnCallSite, // standard rule but not enabled by default
::TrailingCommaOnDeclarationSite, // standard rule but not enabled by default
::TryCatchFinallySpacing,
::TypeArgumentComment,
::TypeArgumentListSpacing,
::TypeParameterComment,
::TypeParameterListSpacing,
::UnnecessaryParenthesesBeforeTrailingLambda,
::ValueArgumentComment,
::ValueParameterComment,
::Wrapping,
// Wrappers for experimental rules. Disabled by default.
::BinaryExpressionWrapping,
::ChainMethodContinuation,
::ClassSignature,
::ConditionWrapping,
::FunctionExpressionBody,
::FunctionLiteral,
::FunctionTypeModifierSpacing,
::MixedConditionOperators,
::MultilineLoop,
).sorted()
)
companion object {
@Configuration("if android style guides should be preferred")
val android by ruleSetConfig(false)
@Configuration("if rules should auto correct style violation")
val autoCorrect by ruleSetConfig(true)
}
}
/**
* Return a list of [FormattingRule] that respects
* [Rule.VisitorModifier.RunAsLateAsPossible] and [Rule.VisitorModifier.RunAfterRule].
* Algorithm is based on [com.pinterest.ktlint.rule.engine.internal.RuleProviderSorter].
*/
internal fun List<(Config) -> FormattingRule>.sorted(): List<(Config) -> FormattingRule> {
val sortedRules = mutableListOf<(Config) -> FormattingRule>()
val sortedRuleIds = mutableSetOf<RuleId>()
val unprocessedRules = this
.map { it to it(Config.empty) }
.sortedWith(defaultRuleOrderComparator())
.toMutableList()
// Initially the list only contains the rules without any VisitorModifiers
unprocessedRules
.filter { (_, rule) -> !rule.runAsLateAsPossible && rule.hasNoRunAfterRules() }
.forEach { (provider, rule) ->
sortedRules.add(provider)
sortedRuleIds.add(rule.wrappingRuleId)
}
unprocessedRules.removeAll { (provider, _) -> provider in sortedRules }
// Then we add the rules that have a RunAsLateAsPossible modifier
// and we obey the RunAfterRule modifiers as well.
while (unprocessedRules.isNotEmpty()) {
val (provider, rule) =
checkNotNull(
unprocessedRules
.firstOrNull { (_, rule) ->
rule
.runAfterRules()
.all { it.ruleId in sortedRuleIds }
}
) {
"Can not complete sorting of rule providers as next item can not be determined."
}
sortedRuleIds.add(rule.wrappingRuleId)
sortedRules.add(provider)
unprocessedRules.removeAll { (provider, _) -> provider in sortedRules }
}
return sortedRules
}
private fun defaultRuleOrderComparator() =
// The sort order below should guarantee a stable order of the rule between multiple invocations of KtLint given
// the same set of input parameters. There should be no dependency on data ordering outside this class.
compareBy<Pair<(Config) -> FormattingRule, FormattingRule>> { (_, rule) ->
if (rule.runAsLateAsPossible) 1 else 0
}.thenBy { (_, rule) ->
if (rule.wrappingRuleId.ruleSetId == RuleSetId.STANDARD) 0 else 1
}.thenBy { (_, rule) -> rule.wrappingRuleId.value }
internal val FormattingRule.wrappingRuleId
get() = wrapping.ruleId
internal val FormattingRule.visitorModifiers
get() = wrapping.visitorModifiers
internal val FormattingRule.runAsLateAsPossible
get() = Rule.VisitorModifier.RunAsLateAsPossible in visitorModifiers
private fun FormattingRule.runAfterRules() =
visitorModifiers.filterIsInstance<Rule.VisitorModifier.RunAfterRule>()
private fun FormattingRule.hasNoRunAfterRules() =
visitorModifiers.filterIsInstance<Rule.VisitorModifier.RunAfterRule>().isEmpty()
| 190 | null | 772 | 6,253 | c5d7ed3da2824534d0e15f8404ad4f1c59fb553c | 14,943 | detekt | Apache License 2.0 |
src/main/kotlin/net/json/jsonm/JsonMatcher.kt | xhuang2020 | 808,859,041 | false | {"Kotlin": 44674, "ANTLR": 2239} | package net.json.jsonm
import net.json.jsonm.antlr4.JsonmParser
class JsonMatcher internal constructor(private val jsonMatch: JsonmParser.JsonMatchContext) {
init { validate(jsonMatch) }
companion object {
private fun validate(jsonMatch: JsonmParser.JsonMatchContext) {
jsonMatch.objectMatch()?.let { validate(it) }
jsonMatch.arrayMatch()?.let { validate(it) }
}
private fun validate(obj: JsonmParser.ObjectMatchContext) {
val pairs = obj.pairMatch().sortedWith(::pairMatchCompare)
for (i in pairs.indices) {
if (pairs[i].keyMatch().NEGATION() != null) {
if (pairs[i].valueMatch().WILDCARD() == null) {
throw JsonMatchValidationException(
"Negative key '${pairs[i].keyMatch().text}' must have the wild card value in the object ${obj.locateInJson()}"
)
}
}
if (i > 0) {
if (pairMatchCompare(pairs[i-1], pairs[i]) == 0 ||
pairs[i-1].keyMatch().STRING() != null && pairs[i].keyMatch().STRING() != null &&
pairs[i-1].keyMatch().STRING().text == pairs[i].keyMatch().STRING().text) {
throw JsonMatchValidationException(
"Duplicated keys '${pairs[i-1].keyMatch().text}', '${pairs[i].keyMatch().text}' in the object ${obj.locateInJson()}"
)
}
}
}
for (pair in pairs) {
pair.valueMatch().singleValueMatch().forEach { value: JsonmParser.SingleValueMatchContext ->
validate(value)
}
}
}
private fun validate(array: JsonmParser.ArrayMatchContext) {
if (!array.arrayEntryMatch().isNullOrEmpty()) {
array.arrayEntryMatch().forEach { entry: JsonmParser.ArrayEntryMatchContext ->
entry.valueMatch().singleValueMatch().forEach { value: JsonmParser.SingleValueMatchContext ->
validate(value)
}
}
val wildCardIndex = array.arrayEntryMatch().indexOfFirst {
it.valueMatch().WILDCARD() != null
}
if (wildCardIndex >= 0 && wildCardIndex < array.arrayEntryMatch().lastIndex) {
throw JsonMatchValidationException(
"wildcard entry match must be the last one in the array ${array.locateInJson()}"
)
}
}
}
private fun validate(value: JsonmParser.SingleValueMatchContext) {
value.objectMatch()?.let { validate(it) }
value.arrayMatch()?.let { validate(it) }
}
infix fun String.matchJson(jsonStr: String): MatchResult {
val jsonMatcher = JsonmReader.fromString(this).readAsJsonMatcher()
val json = JsonmReader.fromString(jsonStr).readAsJson()
return jsonMatcher.match(json)
}
}
fun match(json: Json): MatchResult = match(jsonMatch, json.json)
} | 0 | Kotlin | 0 | 0 | 774f5ea9eabcce7c829665f1aefcb54bdf7498db | 3,222 | json-m | MIT License |
app/src/main/java/com/cdmp/rickmorty/data/RickMortyApi.kt | carlosdmp | 178,059,225 | false | {"Kotlin": 39638, "Java": 1114} | package com.cdmp.rickmorty.data
import androidx.annotation.WorkerThread
import com.cdmp.rickmorty.data.entity.CharacterList
import com.cdmp.rickmorty.data.service.RickMortyService
import retrofit2.Response
import java.lang.RuntimeException
class RickMortyApi(private val service: RickMortyService) {
@WorkerThread
suspend fun fetchCharacters(page: Int) = service.getCharacters(page)
} | 0 | Kotlin | 0 | 0 | d06b37ed10a48bcc75c9fa542ce543f3bf6014d8 | 396 | CoroutinesTestApp | Apache License 2.0 |
app/src/main/java/com/example/rootcheck/SPUtils.kt | mytangyh | 698,863,851 | false | {"Kotlin": 232382, "Java": 18246, "C++": 8362, "CMake": 1864, "HTML": 526} | package com.example.rootcheck
import android.content.Context
class SPUtils{
companion object{
fun saveString(context: Context,spName:String,key: String, value: String) {
val editor = MyApplication.applicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE).edit()
editor.putString(key, value)
editor.commit()
}
fun saveString(context:Context,key: String, value: String){
saveString(context,"sptest",key,value)
}
fun getString(context: Context, spName: String, key: String, defaultValue: String?): String? {
val sp = MyApplication.applicationContext().getSharedPreferences(spName, Context.MODE_PRIVATE)
return sp.getString(key, defaultValue)
}
fun getString(context: Context,key: String):String?{
return getString(context,"sptest",key,null)
}
}
// 同样的方式,你可以添加更多的方法来保存和获取其他类型的数据,例如Boolean,Float,Long等。
} | 0 | Kotlin | 0 | 3 | 7760c038b6232c4b4c91eca49ba5a409fed2d0a5 | 983 | RootDetect | MIT License |
presentation/src/main/kotlin/app/web/drjackycv/presentation/main/MainActivity.kt | Drjacky | 256,785,326 | false | null | package app.web.drjackycv.presentation.main
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.lifecycle.lifecycleScope
import androidx.navigation.NavController
import androidx.navigation.findNavController
import app.web.drjackycv.domain.extension.allowReads
import app.web.drjackycv.presentation.R
import app.web.drjackycv.presentation.base.preference.Settings
import app.web.drjackycv.presentation.databinding.ActivityMainBinding
import app.web.drjackycv.presentation.datastore.DataStoreManager
import app.web.drjackycv.presentation.extension.setOnReactiveClickListener
import app.web.drjackycv.presentation.extension.viewBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.collect
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
private val binding by viewBinding(ActivityMainBinding::inflate)
private val navController: NavController by lazy {
findNavController(R.id.activityMainChooseHostFragment)
}
private var uiStateJob: Job? = null
@Inject
lateinit var dataStoreManager: DataStoreManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
setupUI()
}
override fun onSupportNavigateUp() = navController.navigateUp()
override fun onStop() {
uiStateJob?.cancel()
super.onStop()
}
override fun onBackPressed() {
if (isTaskRoot
&& supportFragmentManager.primaryNavigationFragment?.childFragmentManager?.backStackEntryCount == 0
&& supportFragmentManager.backStackEntryCount == 0
) {
finishAfterTransition()
} else {
super.onBackPressed()
}
}
override fun onDestroy() {
if (isTaskRoot && isFinishing) {
finishAfterTransition()
}
super.onDestroy()
}
private fun setupUI() {
lifecycleScope.launchWhenStarted {
dataStoreManager.themeMode.collect { mode ->
setNightMode(mode)
}
}
}
private fun setNightMode(mode: Int) {
allowReads {
uiStateJob = lifecycleScope.launchWhenStarted {
dataStoreManager.setThemeMode(mode)
}
}
when (mode) {
AppCompatDelegate.MODE_NIGHT_NO -> {
binding.activityMainSwitchThemeFab.setImageResource(R.drawable.ic_mode_night_no_black)
binding.activityMainSwitchThemeFab.setOnReactiveClickListener {
setNightMode(AppCompatDelegate.MODE_NIGHT_YES)
}
}
AppCompatDelegate.MODE_NIGHT_YES -> {
binding.activityMainSwitchThemeFab.setImageResource(R.drawable.ic_mode_night_yes_black)
binding.activityMainSwitchThemeFab.setOnReactiveClickListener {
setNightMode(Settings.MODE_NIGHT_DEFAULT)
}
}
else -> {
binding.activityMainSwitchThemeFab.setImageResource(R.drawable.ic_mode_night_default_black)
binding.activityMainSwitchThemeFab.setOnReactiveClickListener {
setNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
}
}
if (AppCompatDelegate.getDefaultNightMode() != mode)
AppCompatDelegate.setDefaultNightMode(mode)
}
} | 9 | null | 92 | 566 | 1edb7911f1450555210db4f96734ef189895a912 | 3,559 | MVVMTemplate | MIT License |
typescript/ts-ast-declarations/src/org/jetbrains/dukat/ast/model/nodes/ReferenceOriginNode.kt | vipyami | 261,616,816 | true | {"Kotlin": 2584052, "WebIDL": 317874, "TypeScript": 125096, "JavaScript": 15185, "ANTLR": 11333} | package org.jetbrains.dukat.ast.model.nodes
enum class ReferenceOriginNode {
IRRELEVANT,
IMPORT,
NAMED_IMPORT
} | 0 | null | 0 | 0 | 61d863946227f59d9b2c7c4e4c463c2558c4e605 | 124 | dukat | Apache License 2.0 |
core_library_android/library/src/main/java/net/apptronic/core/android/viewmodel/ViewBinder.kt | apptronicnet | 264,405,837 | false | null | package net.apptronic.core.android.viewmodel
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.os.Parcelable
import android.util.SparseArray
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import net.apptronic.core.android.viewmodel.view.ViewAdapter
import net.apptronic.core.base.platform.debugError
import net.apptronic.core.context.plugin.extensionDescriptor
import net.apptronic.core.viewmodel.IViewModel
import net.apptronic.core.viewmodel.ViewModel
import net.apptronic.core.viewmodel.ViewModelLifecycle
import net.apptronic.core.viewmodel.navigation.ViewModelItem
private class SavedInstanceState(
val hierarchyState: SparseArray<Parcelable>,
val customState: Bundle
)
private val SavedInstanceStateExtensionDescriptor = extensionDescriptor<SavedInstanceState>()
private val ViewBinderExtensionsDescriptor = extensionDescriptor<ViewBinder<*>>()
/**
* Responsible for creating [View] and binding it to [ViewModel]. Generally implements "View" layer.
*
* There are several methods for usage with [Activity], [Dialog] or generic usage as [View] under
* some [ViewGroup] container.
*/
abstract class ViewBinder<T : IViewModel> : ViewAdapter, BindingContainer {
/**
* Specify layout resource to be used for creation or [View] using default implementation.
* If null - should override each method [onCreateView] to be used for corresponding binding
* or navigator.
*/
@LayoutRes
open var layoutResId: Int? = null
private var viewModelItemReference: ViewModelItem? = null
private var viewModelReference: T? = null
private var viewReference: View? = null
private var bindingsReference: Bindings? = null
private var savedInstanceStateReference: Bundle? = null
private var outStateReference: Bundle? = null
fun <E> viewBinding(builder: (View) -> E): ViewBindingProperty<E> {
return ViewBindingProperty(this, builder)
}
fun <E> getBinding(builder: (View) -> E): E {
return view.getBinding(builder)
}
fun <E> withBinding(builder: (View) -> E, action: E.() -> Unit) {
with(view.getBinding(builder), action)
}
@Deprecated("Grammar mistake in method name")
fun <E> withBinging(builder: (View) -> E, action: E.() -> Unit) = withBinding(builder, action)
val viewModelItem: ViewModelItem
get() {
return viewModelItemReference
?: throw IllegalStateException("No ViewModelItem for $this")
}
val viewModel: T
get() {
return viewModelReference
?: throw IllegalStateException("No viewModel bound for $this")
}
val view: View
get() {
return viewReference
?: throw IllegalStateException("No view bound for $this")
}
val context: Context
get() {
return view.context
}
val savedInstanceState: Bundle?
get() {
return savedInstanceStateReference
}
val outState: Bundle
get() {
return outStateReference
?: throw IllegalStateException("Out state is not ready for $this")
}
private val bindings: Bindings
get() {
return bindingsReference ?: throw IllegalStateException("No bindings for $this")
}
private fun preCheck(viewModel: IViewModel) {
if (viewModel.extensions[ViewBinderExtensionsDescriptor] != null) {
debugError(Error("$viewModel already have bound view!!!"))
}
if (!viewModel.isStateBound()) {
debugError(
Error(
"$viewModel in stage ${
viewModel.context.lifecycle.getActiveStage()
?.getStageName()
}"
)
)
}
}
fun performViewBinding(viewModel: IViewModel, view: View) {
preCheck(viewModel)
performViewBindingInternal(viewModel, view)
}
/**
* Bind [view] to [viewModelReference]
*/
@Suppress("UNCHECKED_CAST")
fun performViewBinding(item: ViewModelItem, view: View) {
preCheck(item.viewModel)
this.viewModelItemReference = item
performViewBindingInternal(item.viewModel, view)
}
private fun performViewBindingInternal(viewModel: IViewModel, view: View) {
this.viewReference = view
this.viewModelReference = viewModel as T
bindingsReference = Bindings(viewModel, this)
val savedState = viewModel.extensions[SavedInstanceStateExtensionDescriptor]
viewModel.extensions.remove(SavedInstanceStateExtensionDescriptor)
savedState?.let {
this.savedInstanceStateReference = it.customState
}
onBindView()
savedState?.let {
view.restoreHierarchyState(it.hierarchyState)
}
onViewStateRestored()
outStateReference = Bundle()
viewModel.extensions[ViewBinderExtensionsDescriptor] = this
viewModel.doOnUnbind {
val hierarchyState = SparseArray<Parcelable>()
view.saveHierarchyState(hierarchyState)
viewModel.extensions[SavedInstanceStateExtensionDescriptor] = SavedInstanceState(
hierarchyState,
outStateReference ?: Bundle()
)
bindings.unbind()
bindingsReference = null
viewModel.extensions.remove(ViewBinderExtensionsDescriptor)
}
}
/**
* Called when [view] is binding to the [viewModel]. At this time [viewModel] lifecycle
* is in stage [ViewModelLifecycle.STAGE_BOUND]
*/
protected abstract fun onBindView()
protected open fun onViewStateRestored() {
// implement by subclasses if needed
}
final override fun onUnbind(action: () -> Unit) {
bindings.onUnbind(action)
}
final override fun add(binding: Binding) {
bindings.add(binding)
}
}
| 2 | Kotlin | 0 | 6 | 5320427ddc9dd2393f01e75564dab126fdeaac72 | 6,084 | core | MIT License |
app/src/main/kotlin/org/emunix/insteadlauncher/presentation/launcher/AppArgumentViewModel.kt | btimofeev | 125,632,007 | false | null | /*
* Copyright (c) 2021 <NAME> <<EMAIL>>
* Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT).
*/
package org.emunix.insteadlauncher.ui.launcher
import android.net.Uri
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
class AppArgumentViewModel: ViewModel() {
val zipUri: MutableLiveData<Uri?> by lazy { MutableLiveData() }
} | 6 | Java | 6 | 22 | 13e2e650a1368835d0e079e864803892ea0dba83 | 406 | instead-launcher-android | MIT License |
matrix-sdk-android/src/main/java/im/vector/matrix/android/internal/session/group/GroupSummaryUpdater.kt | Dominaezzz | 194,926,838 | true | {"Kotlin": 3115318, "Java": 77793, "HTML": 22258, "Shell": 18973} | /*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.matrix.android.internal.session.group
import android.content.Context
import androidx.work.Constraints
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.zhuinden.monarchy.Monarchy
import im.vector.matrix.android.api.auth.data.Credentials
import im.vector.matrix.android.internal.database.RealmLiveEntityObserver
import im.vector.matrix.android.internal.database.model.GroupEntity
import im.vector.matrix.android.internal.database.query.where
import im.vector.matrix.android.internal.worker.WorkerParamsFactory
import javax.inject.Inject
private const val GET_GROUP_DATA_WORKER = "GET_GROUP_DATA_WORKER"
internal class GroupSummaryUpdater @Inject constructor(private val context: Context,
private val credentials: Credentials,
monarchy: Monarchy) : RealmLiveEntityObserver<GroupEntity>(monarchy) {
override val query = Monarchy.Query<GroupEntity> { GroupEntity.where(it) }
private val workConstraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
override fun processChanges(inserted: List<GroupEntity>, updated: List<GroupEntity>, deleted: List<GroupEntity>) {
val newGroupIds = inserted.map { it.groupId }
val getGroupDataWorkerParams = GetGroupDataWorker.Params(credentials.userId, newGroupIds)
val workData = WorkerParamsFactory.toData(getGroupDataWorkerParams)
val sendWork = OneTimeWorkRequestBuilder<GetGroupDataWorker>()
.setInputData(workData)
.setConstraints(workConstraints)
.build()
WorkManager.getInstance(context)
.beginUniqueWork(GET_GROUP_DATA_WORKER, ExistingWorkPolicy.APPEND, sendWork)
.enqueue()
}
} | 0 | Kotlin | 0 | 0 | d90698fe92732544889c5c149bb778e201e348fe | 2,558 | riotX-android | Apache License 2.0 |
vzd-cli/src/main/kotlin/de/gematik/ti/directory/cli/apo/ApoConfig.kt | gematik | 455,597,084 | false | {"Kotlin": 297462, "HTML": 87329, "TypeScript": 41771, "Shell": 6186, "SCSS": 5370, "JavaScript": 1430, "Makefile": 359, "Batchfile": 89} | package de.gematik.ti.directory.cli.apo
import de.gematik.ti.directory.cli.util.FileObjectStore
import kotlinx.serialization.Serializable
import kotlinx.serialization.decodeFromString
import java.nio.file.Path
@Serializable
data class ApoEnvironmentConfig(
var apiURL: String,
)
@Serializable
class ApoConfig(
val environments: Map<ApoInstance, ApoEnvironmentConfig>,
var apiKeys: Map<ApoInstance, String>,
)
internal class ApoConfigFileStore(customConfigPath: Path? = null) : FileObjectStore<ApoConfig>(
"directory-apo.yaml",
{
ApoConfig(
mapOf(
ApoInstance.test to ApoEnvironmentConfig("https://apovzd-test.app.ti-dienste.de/api/"),
ApoInstance.prod to ApoEnvironmentConfig("https://apovzd.app.ti-dienste.de/api/"),
),
mapOf(
ApoInstance.test to "unknown",
ApoInstance.prod to "unknown",
),
)
},
{ yaml, stringValue -> yaml.decodeFromString(stringValue) },
customConfigPath,
)
| 2 | Kotlin | 1 | 3 | 4b414555bf575116f841fc8a1341b0a56bbca66d | 1,043 | app-vzd-cli | MIT License |
core/src/main/java/com/filkom/core/model/domain/TrashDetail.kt | fahmigutawan | 572,343,810 | false | null | package com.filkom.core.model.domain
import com.filkom.core.model.data.response.base.ObjectImageUrlResponse
data class TrashDetail(
val id:String,
val name:String,
val exchange_value:Int,
val content:String,
val thumbnail: String
)
| 0 | Kotlin | 0 | 0 | 38af1bf62fd2363723abffb692d6b79399c5a26f | 254 | Jetpack-BankSampahRW5 | MIT License |
compass-geolocation-mobile/src/androidMain/kotlin/dev/jordond/compass/geolocation/mobile/internal/LocationManager.kt | jordond | 772,795,864 | false | null | package dev.jordond.compass.geolocation.mobile.internal
import android.content.Context
import android.location.Location
import android.location.LocationManager
import android.os.Looper
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import com.google.android.gms.tasks.CancellationTokenSource
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
internal class LocationManager(
private val context: Context,
) {
private val _locationUpdates = MutableSharedFlow<LocationResult>(
replay = 1,
extraBufferCapacity = 0,
onBufferOverflow = BufferOverflow.DROP_OLDEST,
)
internal val locationUpdates: Flow<LocationResult> = _locationUpdates
private var locationCallback: LocationCallback? = null
private val fusedLocationClient by lazy {
LocationServices.getFusedLocationProviderClient(context)
}
fun locationEnabled(): Boolean {
val locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
|| locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
}
suspend fun currentLocation(priority: Int): Location {
return suspendCancellableCoroutine { continuation ->
val cancellation = CancellationTokenSource()
fusedLocationClient
.getCurrentLocation(priority, cancellation.token)
.addOnSuccessListener { location -> continuation.resume(location) }
.addOnFailureListener { exception -> continuation.resumeWithException(exception) }
continuation.invokeOnCancellation {
cancellation.cancel()
}
}
}
fun startTracking(request: LocationRequest): Flow<LocationResult> {
if (locationCallback != null) return _locationUpdates
val callback = object : LocationCallback() {
override fun onLocationResult(result: LocationResult) {
_locationUpdates.tryEmit(result)
}
}
fusedLocationClient.requestLocationUpdates(request, callback, Looper.getMainLooper())
locationCallback = callback
return _locationUpdates
}
fun stopTracking() {
locationCallback?.let { callback ->
fusedLocationClient.removeLocationUpdates(callback)
locationCallback = null
}
}
}
| 5 | null | 4 | 89 | d0ef39ed66f7af237bbe21ba630dfcdd6f2ff258 | 2,813 | compass | MIT License |
App/app/src/main/java/com/example/winedroid/SplashActivity.kt | MrBoosted00 | 305,794,078 | false | null | package com.example.winedroid
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import com.example.winedroid.ui.login.LoginActivity
import com.example.winedroid.ui.perfil.EditarPerfilFragment
import com.example.winedroid.ui.perfil.PerfilFragment
class SplashActivity : AppCompatActivity() {
// This is the loading time of the splash screen
private val SPLASH_TIME_OUT:Long = 3000 // 1 sec
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash)
Handler().postDelayed({
// This method will be executed once the timer is over
// Start your app main activity
startActivity(Intent(this,
LoginActivity::class.java))
// close this activity
finish()
}, SPLASH_TIME_OUT)
}
} | 0 | Kotlin | 1 | 3 | 59a885f19ec9b29e4318b0d8ad8fa3875f61820b | 949 | ProyectoFinal | MIT License |
libs/ledger/ledger-utxo-data/src/main/kotlin/net/corda/ledger/utxo/data/state/LazyStateAndRefImpl.kt | corda | 346,070,752 | false | {"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.ledger.utxo.data.state
import net.corda.crypto.core.parseSecureHash
import net.corda.ledger.utxo.data.transaction.UtxoOutputInfoComponent
import net.corda.ledger.utxo.data.transaction.UtxoVisibleTransactionOutputDto
import net.corda.utilities.serialization.deserialize
import net.corda.v5.application.serialization.SerializationService
import net.corda.v5.base.annotations.CordaSerializable
import net.corda.v5.base.exceptions.CordaRuntimeException
import net.corda.v5.ledger.utxo.ContractState
import net.corda.v5.ledger.utxo.StateAndRef
import net.corda.v5.ledger.utxo.StateRef
import net.corda.v5.ledger.utxo.TransactionState
import java.lang.Exception
/**
* Lazy [StateRef]. It stores initially the serialized form of the represented state and ref.
* Its purposes are to avoid
* - unnecessary deserializations to perform better
* - deserializations whose required CPKs are not necessarily available.
*
* @constructor Creates a new instance of the [LazyStateAndRefImpl] data class.
* @property serializedStateAndRef A [UtxoVisibleTransactionOutputDto] with the serialized information
*/
@CordaSerializable
data class LazyStateAndRefImpl<out T : ContractState>(
val serializedStateAndRef: UtxoVisibleTransactionOutputDto,
val deserializedStateAndRef: StateAndRef<@UnsafeVariance T>?,
private val serializationService: SerializationService
) : StateAndRef<@UnsafeVariance T> {
val stateAndRef: StateAndRef<@UnsafeVariance T> by lazy(LazyThreadSafetyMode.PUBLICATION) {
deserializedStateAndRef ?: serializedStateAndRef.deserializeToStateAndRef<T>(serializationService)
}
override fun getState(): TransactionState<@UnsafeVariance T> {
return stateAndRef.state
}
override fun getRef(): StateRef {
return stateAndRef.ref
}
/**
* Determines whether the specified object is equal to the current object.
*
* @param other The object to compare with the current object.
* @return Returns true if the specified object is equal to the current object; otherwise, false.
*/
override fun equals(other: Any?): Boolean {
return this === other ||
other != null &&
other is StateAndRef<*> &&
other.ref == ref &&
other.state == state
}
/**
* Serves as the default hash function.
*
* @return Returns a hash code for the current object.
*/
override fun hashCode(): Int {
return serializedStateAndRef.hashCode()
}
}
@Suppress("UNCHECKED_CAST")
private fun <T : ContractState> UtxoVisibleTransactionOutputDto.deserializeToStateAndRef(
serializationService: SerializationService
): StateAndRef<T> {
val info = try {
serializationService.deserialize<UtxoOutputInfoComponent>(info)
} catch (e: Exception) {
throw CordaRuntimeException("Deserialization of $info into UtxoOutputInfoComponent failed.", e)
}
val contractState = try {
serializationService.deserialize<ContractState>(data)
} catch (e: Exception) {
throw CordaRuntimeException("Deserialization of $data into ContractState failed.", e)
}
return StateAndRefImpl(
state = TransactionStateImpl(
contractState as T,
info.notaryName,
info.notaryKey,
info.getEncumbranceGroup()
),
ref = StateRef(parseSecureHash(transactionId), leafIndex)
)
}
| 14 | Kotlin | 27 | 69 | 0766222eb6284c01ba321633e12b70f1a93ca04e | 3,441 | corda-runtime-os | Apache License 2.0 |
app/src/main/java/com/thryan/secondclass/ui/login/LoginViewModel.kt | Thryanii | 649,615,369 | false | null | package com.thryan.secondclass.ui.login
import android.annotation.SuppressLint
import android.content.Context
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController
import com.thryan.secondclass.core.Webvpn
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
@SuppressLint("StaticFieldLeak")
class LoginViewModel(private val context: Context, private val navController: NavHostController) :
ViewModel() {
private val TAG = "LoginViewModel"
val sharedPref = context.getSharedPreferences(
"com.thryan.secondclass.PREFERENCE", Context.MODE_PRIVATE
)
private val _uiState = MutableStateFlow(LoginState("", "", "", false, ""))
val uiState: StateFlow<LoginState> = _uiState.asStateFlow()
private suspend fun update(uiStates: LoginState) = _uiState.emit(uiStates)
fun send(intent: LoginIntent) = viewModelScope.launch { onHandle(intent) }
private suspend fun onHandle(intent: LoginIntent) {
when (intent) {
is LoginIntent.Login -> {
login()
}
is LoginIntent.GetPreference -> {
update(
uiState.value.copy(
account = sharedPref.getString("account", "")!!,
password = sharedPref.getString("password", "")!!
)
)
}
is LoginIntent.UpdateAccount -> {
update(uiState.value.copy(account = intent.account))
}
is LoginIntent.UpdatePassword -> {
update(uiState.value.copy(password = intent.password))
}
is LoginIntent.UpdateSCAccount -> {
update(uiState.value.copy(scAccount = intent.scAccount))
}
is LoginIntent.CloseDialog -> {
update(uiState.value.copy(showDialog = false))
}
}
}
suspend fun login() {
val twfid = sharedPref.getString("twfid", "")
val (account, password, scAccount) = uiState.value
//检查缓存的twfid是否可用
if (!twfid.isNullOrEmpty() && Webvpn.checkLogin(twfid)) {
withContext(Dispatchers.Main) {
navController.navigate("page?twfid=${twfid}&account=${scAccount.ifEmpty { account }}") {
launchSingleTop = true
}
}
} else {
val response = Webvpn.login(account, password)
//登录
if (response.message == "请求成功") {
with(sharedPref.edit()) {
putString("twfid", response.data)
putString("account", account)
putString("password", password)
apply()
}
withContext(Dispatchers.Main) {
navController.navigate("page?twfid=${response.data}&account=${scAccount.ifEmpty { account }}") {
launchSingleTop = true
}
}
} else {
update(uiState.value.copy(showDialog = true, message = response.message))
}
}
}
}
| 0 | Kotlin | 0 | 2 | 311f1ccbb918bb153a769404f64610b057821a08 | 3,377 | SecondClass | MIT License |
compiler/testData/debug/stepping/trait.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} |
// FILE: test.kt
interface A {
fun foo() = 32
fun bar(): Int {
return foo()
}
}
class B : A
fun box() {
(object : A {}).bar()
B().bar()
}
// The dispatch methods added to classes directly implementing
// interfaces with default methods (forwarding to the actual implementation
// on A$DefaultImpls) have the line number of the class declaration.
// EXPECTATIONS JVM_IR
// test.kt:15 box
// test.kt:15 <init>
// test.kt:15 box
// test.kt:15 bar
// test.kt:8 bar
// test.kt:15 foo
// test.kt:5 foo
// test.kt:15 foo
// test.kt:8 bar
// test.kt:15 bar
// test.kt:15 box
// test.kt:16 box
// test.kt:12 <init>
// test.kt:16 box
// test.kt:12 bar
// test.kt:8 bar
// test.kt:12 foo
// test.kt:5 foo
// test.kt:12 foo
// test.kt:8 bar
// test.kt:12 bar
// test.kt:16 box
// test.kt:17 box
// EXPECTATIONS JS_IR
// test.kt:15 box
// test.kt:15 <init>
// test.kt:15 box
// test.kt:8 bar
// test.kt:5 foo
// test.kt:16 box
// test.kt:12 <init>
// test.kt:16 box
// test.kt:8 bar
// test.kt:5 foo
// test.kt:17 box
// EXPECTATIONS WASM
// test.kt:1 $box
// test.kt:15 $box (5, 5, 20)
// test.kt:15 $<no name provided>.<init>
// test.kt:8 $A.bar (15, 8, 15, 8)
// test.kt:5 $A.foo (16, 18, 16, 18)
// test.kt:16 $box (4, 4, 8)
// test.kt:12 $B.<init>
// test.kt:17 $box
| 184 | Kotlin | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 1,296 | kotlin | Apache License 2.0 |
libraries/tools/kotlin-gradle-plugin-api/src/main/kotlin/org/jetbrains/kotlin/gradle/plugin/KotlinCompilation.kt | arrow-kt | 109,678,056 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.gradle.plugin
import org.gradle.api.Named
import org.gradle.api.attributes.HasAttributes
import org.gradle.api.file.FileCollection
import org.gradle.api.tasks.SourceSetOutput
interface KotlinCompilation: Named, HasAttributes, HasKotlinDependencies {
val target: KotlinTarget
val compilationName: String
val kotlinSourceSets: Set<KotlinSourceSet>
val compileDependencyConfigurationName: String
var compileDependencyFiles: FileCollection
val output: SourceSetOutput
val platformType get() = target.platformType
val compileKotlinTaskName: String
val compileAllTaskName: String
companion object {
const val MAIN_COMPILATION_NAME = "main"
const val TEST_COMPILATION_NAME = "test"
}
fun source(sourceSet: KotlinSourceSet)
override fun getName(): String = compilationName
override val relatedConfigurationNames: List<String>
get() = super.relatedConfigurationNames + compileDependencyConfigurationName
}
interface KotlinCompilationToRunnableFiles : KotlinCompilation {
val runtimeDependencyConfigurationName: String
var runtimeDependencyFiles: FileCollection
override val relatedConfigurationNames: List<String>
get() = super.relatedConfigurationNames + runtimeDependencyConfigurationName
}
interface KotlinCompilationWithResources : KotlinCompilation {
val processResourcesTaskName: String
} | 12 | null | 1 | 43 | d2a24985b602e5f708e199aa58ece652a4b0ea48 | 1,600 | kotlin | Apache License 2.0 |
comments-biz/src/commonMain/kotlin/CommentProcessor.kt | crowdproj | 508,567,511 | false | {"Kotlin": 52564, "Dockerfile": 344} | import com.crowdproj.comments.common.CommentContext
import com.crowdproj.comments.common.config.CommentsCorSettings
import com.crowdproj.comments.common.models.CommentCommand
import com.crowdproj.comments.common.models.CommentObjectType
import com.crowdproj.comments.common.models.CommentWorkMode
import com.crowdproj.comments.stubs.CommentStub
class CommentProcessor(private val settings: CommentsCorSettings = CommentsCorSettings()) {
suspend fun exec(ctx: CommentContext){
//TODO: Rewrite temporary stub solution with BIZ
require(ctx.workMode == CommentWorkMode.STUB){
"Currently working only in STUB mode."
}
when (ctx.command) {
CommentCommand.SEARCH -> {
ctx.commentsResponse.addAll(CommentStub.prepareSearchList("d-666-01", CommentObjectType.PRODUCT))
}
else -> {
ctx.commentResponse = CommentStub.get()
}
}
}
} | 0 | Kotlin | 2 | 1 | f8512415eee255492e0f14b43bd007ddf4a96fd6 | 959 | crowdproj-comments | Apache License 2.0 |
matisse/src/main/kotlin/com/zhihu/matisse/SelectionCreator.kt | youuupeng | 206,088,081 | true | {"Kotlin": 151202} | package com.zhihu.matisse
import android.app.Activity
import android.content.pm.ActivityInfo
import androidx.annotation.StyleRes
import com.zhihu.matisse.engine.ImageEngine
import com.zhihu.matisse.filter.Filter
import com.zhihu.matisse.internal.entity.CaptureStrategy
import com.zhihu.matisse.internal.entity.SelectionSpec
import com.zhihu.matisse.listener.OnCheckedListener
import com.zhihu.matisse.listener.OnSelectedListener
import com.zhihu.matisse.ui.MatisseActivity
import org.jetbrains.anko.intentFor
import java.util.*
/**
* Description
* <p>
*
* @author peyo
* @date 9/6/2019
*/
class SelectionCreator constructor(private val matisse: Matisse, mimeTypes: Set<MimeType>, mediaTypeExclusive: Boolean) {
private var mSelectionSpec: SelectionSpec = SelectionSpec.getCleanInstance()
/**
* Constructs a new specification builder on the context.
*
* @param mimeTypes MIME type set to select.
*/
init {
mSelectionSpec.apply {
mimeTypeSet = mimeTypes
this.mediaTypeExclusive = mediaTypeExclusive
orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
}
enum class ScreenOrientation(val value: Int) {
SCREEN_ORIENTATION_UNSPECIFIED(-1),
SCREEN_ORIENTATION_LANDSCAPE(0),
SCREEN_ORIENTATION_PORTRAIT(1),
SCREEN_ORIENTATION_USER(2),
SCREEN_ORIENTATION_BEHIND(3),
SCREEN_ORIENTATION_SENSOR(4),
SCREEN_ORIENTATION_NOSENSOR(5),
SCREEN_ORIENTATION_SENSOR_LANDSCAPE(6),
SCREEN_ORIENTATION_SENSOR_PORTRAIT(7),
SCREEN_ORIENTATION_REVERSE_LANDSCAPE(8),
SCREEN_ORIENTATION_REVERSE_PORTRAIT(9),
SCREEN_ORIENTATION_FULL_SENSOR(10),
SCREEN_ORIENTATION_USER_LANDSCAPE(11),
SCREEN_ORIENTATION_USER_PORTRAIT(12),
SCREEN_ORIENTATION_FULL_USER(13),
SCREEN_ORIENTATION_LOCKED(14);
}
/**
* Whether to show only one media type if choosing medias are only images or videos.
*
* @param showSingleMediaType whether to show only one media type, either images or videos.
* @return {@link SelectionCreator} for fluent API.
* @see SelectionSpec#onlyShowImages()
* @see SelectionSpec#onlyShowVideos()
*/
fun showSingleMediaType(showSingleMediaType: Boolean): SelectionCreator {
mSelectionSpec.showSingleMediaType = showSingleMediaType
return this
}
/**
* Theme for media selecting Activity.
* <p>
* There are two built-in themes:
* 1. com.zhihu.matisse.R.style.Matisse_Zhihu;
* 2. com.zhihu.matisse.R.style.Matisse_Dracula
* you can define a custom theme derived from the above ones or other themes.
*
* @param themeId theme resource id. Default value is com.zhihu.matisse.R.style.Matisse_Zhihu.
* @return {@link SelectionCreator} for fluent API.
*/
fun theme(@StyleRes themeId: Int): SelectionCreator {
mSelectionSpec.themeId = themeId
return this
}
/**
* Show a auto-increased number or a check mark when user select media.
*
* @param countable true for a auto-increased number from 1, false for a check mark. Default
* value is false.
* @return {@link SelectionCreator} for fluent API.
*/
fun countable(countable: Boolean): SelectionCreator {
mSelectionSpec.countable = countable
return this
}
/**
* Maximum selectable count.
*
* @param maxSelectable Maximum selectable count. Default value is 1.
* @return {@link SelectionCreator} for fluent API.
*/
fun maxSelectable(maxSelectable: Int): SelectionCreator {
require(maxSelectable >= 1) { "maxSelectable must be greater than or equal to one" }
check(!(mSelectionSpec.maxImageSelectable > 0 || mSelectionSpec.maxVideoSelectable > 0)) { "already set maxImageSelectable and maxVideoSelectable" }
mSelectionSpec.maxSelectable = maxSelectable
return this
}
/**
* Only useful when {@link SelectionSpec#mediaTypeExclusive} set true and you want to set different maximum
* selectable files for image and video media types.
*
* @param maxImageSelectable Maximum selectable count for image.
* @param maxVideoSelectable Maximum selectable count for video.
* @return {@link SelectionCreator} for fluent API.
*/
fun maxSelectablePerMediaType(maxImageSelectable: Int, maxVideoSelectable: Int): SelectionCreator {
require(!(maxImageSelectable < 1 || maxVideoSelectable < 1)) { "max selectable must be greater than or equal to one" }
mSelectionSpec.maxSelectable = -1
mSelectionSpec.maxImageSelectable = maxImageSelectable
mSelectionSpec.maxVideoSelectable = maxVideoSelectable
return this
}
/**
* Add filter to filter each selecting item.
*
* @param filter {@link Filter}
* @return {@link SelectionCreator} for fluent API.
*/
fun addFilter(filter: Filter): SelectionCreator {
if (mSelectionSpec.filters == null) {
mSelectionSpec.filters = ArrayList()
}
mSelectionSpec.filters!!.add(filter)
return this
}
/**
* Determines whether the photo capturing is enabled or not on the media grid view.
* <p>
* If this value is set true, photo capturing entry will appear only on All Media's page.
*
* @param enable Whether to enable capturing or not. Default value is false;
* @return {@link SelectionCreator} for fluent API.
*/
fun capture(enable: Boolean): SelectionCreator {
mSelectionSpec.capture = enable
return this
}
/**
* Show a original photo check options.Let users decide whether use original photo after select
*
* @param enable Whether to enable original photo or not
* @return {@link SelectionCreator} for fluent API.
*/
fun originalEnable(enable: Boolean): SelectionCreator {
mSelectionSpec.originalable = enable
return this
}
/**
* Determines Whether to hide top and bottom toolbar in PreView mode ,when user tap the picture
*
* @param enable
* @return {@link SelectionCreator} for fluent API.
*/
fun autoHideToolbarOnSingleTap(enable: Boolean): SelectionCreator {
mSelectionSpec.autoHideToobar = enable
return this
}
/**
* Maximum original size,the unit is MB. Only useful when {link@originalEnable} set true
*
* @param size Maximum original size. Default value is Integer.MAX_VALUE
* @return {@link SelectionCreator} for fluent API.
*/
fun maxOriginalSize(size: Int): SelectionCreator {
mSelectionSpec.originalMaxSize = size
return this
}
/**
* Capture strategy provided for the location to save photos including internal and external
* storage and also a authority for {@link androidx.core.content.FileProvider}.
*
* @param captureStrategy {@link CaptureStrategy}, needed only when capturing is enabled.
* @return {@link SelectionCreator} for fluent API.
*/
fun captureStrategy(captureStrategy: CaptureStrategy): SelectionCreator {
mSelectionSpec.captureStrategy = captureStrategy
return this
}
/**
* Set the desired orientation of this activity.
*
* @param orientation An orientation constant as used in {@link ScreenOrientation}.
* Default value is {@link android.content.pm.ActivityInfo#SCREEN_ORIENTATION_PORTRAIT}.
* @return {@link SelectionCreator} for fluent API.
* @see Activity#setRequestedOrientation(int)
*/
fun restrictOrientation(orientation: ScreenOrientation): SelectionCreator {
mSelectionSpec.orientation = orientation.value
return this
}
/**
* Set a fixed span count for the media grid. Same for different screen orientations.
* <p>
* This will be ignored when {@link #gridExpectedSize(int)} is set.
*
* @param spanCount Requested span count.
* @return {@link SelectionCreator} for fluent API.
*/
fun spanCount(spanCount: Int): SelectionCreator {
require(spanCount >= 1) { "spanCount cannot be less than 1" }
mSelectionSpec.spanCount = spanCount
return this
}
/**
* Set expected size for media grid to adapt to different screen sizes. This won't necessarily
* be applied cause the media grid should fill the view container. The measured media grid's
* size will be as close to this value as possible.
*
* @param size Expected media grid size in pixel.
* @return {@link SelectionCreator} for fluent API.
*/
fun gridExpectedSize(size: Int): SelectionCreator {
mSelectionSpec.gridExpectedSize = size
return this
}
/**
* Photo thumbnail's scale compared to the View's size. It should be a float value in (0.0,
* 1.0].
*
* @param scale Thumbnail's scale in (0.0, 1.0]. Default value is 0.5.
* @return {@link SelectionCreator} for fluent API.
*/
fun thumbnailScale(scale: Float): SelectionCreator {
require(!(scale <= 0f || scale > 1f)) { "Thumbnail scale must be between (0.0, 1.0]" }
mSelectionSpec.thumbnailScale = scale
return this
}
/**
* Provide an image engine.
* <p>
* There are two built-in image engines:
* 1. {@link com.zhihu.matisse.engine.impl.GlideEngine}
* 2. {@link com.zhihu.matisse.engine.impl.PicassoEngine}
* And you can implement your own image engine.
*
* @param imageEngine {@link ImageEngine}
* @return {@link SelectionCreator} for fluent API.
*/
fun imageEngine(imageEngine: ImageEngine): SelectionCreator {
mSelectionSpec.imageEngine = imageEngine
return this
}
/**
* Set listener for callback immediately when user select or unselect something.
* <p>
* It's a redundant API with {@link Matisse#obtainResult(Intent)},
* we only suggest you to use this API when you need to do something immediately.
*
* @param listener {@link OnSelectedListener}
* @return {@link SelectionCreator} for fluent API.
*/
fun setOnSelectedListener(listener: OnSelectedListener?): SelectionCreator {
mSelectionSpec.onSelectedListener = listener
return this
}
/**
* Set listener for callback immediately when user check or uncheck original.
*
* @param listener [OnSelectedListener]
* @return [SelectionCreator] for fluent API.
*/
fun setOnCheckedListener(listener: OnCheckedListener?): SelectionCreator {
mSelectionSpec.onCheckedListener = listener
return this
}
/**
* Start to select media and wait for result.
*
* @param requestCode Identity of the request Activity or Fragment.
*/
fun forResult(requestCode: Int) {
val activity = matisse.getActivity() ?: return
val intent = activity.intentFor<MatisseActivity>()
val fragment = matisse.getFragment()
fragment?.startActivityForResult(intent, requestCode)
?: activity.startActivityForResult(intent, requestCode)
}
} | 1 | Kotlin | 1 | 1 | 292456fbbe09cd3a968ba14ef8a49f944ae87d75 | 11,244 | Matisse | Apache License 2.0 |
integration-test-project/project-types/jvm/src/main/kotlin/io/github/virelion/buildata/integration/builder/inner/Level1Class.kt | Virelion | 330,246,253 | false | null | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.virelion.buildata.integration.builder.inner
import io.github.virelion.buildata.Buildable
@Buildable
data class Level3Class(
val value: String
)
| 21 | null | 0 | 7 | 4645c2afcb52b320223c0860286c55d33ca40167 | 755 | buildata | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Elementequal.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup
public val OutlineGroup.Elementequal: ImageVector
get() {
if (_elementequal != null) {
return _elementequal!!
}
_elementequal = Builder(name = "Elementequal", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(19.77f, 11.25f)
horizontalLineTo(15.73f)
curveTo(13.72f, 11.25f, 12.75f, 10.27f, 12.75f, 8.27f)
verticalLineTo(4.23f)
curveTo(12.75f, 2.22f, 13.73f, 1.25f, 15.73f, 1.25f)
horizontalLineTo(19.77f)
curveTo(21.78f, 1.25f, 22.75f, 2.23f, 22.75f, 4.23f)
verticalLineTo(8.27f)
curveTo(22.75f, 10.27f, 21.77f, 11.25f, 19.77f, 11.25f)
close()
moveTo(15.73f, 2.75f)
curveTo(14.55f, 2.75f, 14.25f, 3.05f, 14.25f, 4.23f)
verticalLineTo(8.27f)
curveTo(14.25f, 9.45f, 14.55f, 9.75f, 15.73f, 9.75f)
horizontalLineTo(19.77f)
curveTo(20.95f, 9.75f, 21.25f, 9.45f, 21.25f, 8.27f)
verticalLineTo(4.23f)
curveTo(21.25f, 3.05f, 20.95f, 2.75f, 19.77f, 2.75f)
horizontalLineTo(15.73f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(8.27f, 11.25f)
horizontalLineTo(4.23f)
curveTo(2.22f, 11.25f, 1.25f, 10.36f, 1.25f, 8.52f)
verticalLineTo(3.98f)
curveTo(1.25f, 2.14f, 2.23f, 1.25f, 4.23f, 1.25f)
horizontalLineTo(8.27f)
curveTo(10.28f, 1.25f, 11.25f, 2.14f, 11.25f, 3.98f)
verticalLineTo(8.51f)
curveTo(11.25f, 10.36f, 10.27f, 11.25f, 8.27f, 11.25f)
close()
moveTo(4.23f, 2.75f)
curveTo(2.89f, 2.75f, 2.75f, 3.13f, 2.75f, 3.98f)
verticalLineTo(8.51f)
curveTo(2.75f, 9.37f, 2.89f, 9.74f, 4.23f, 9.74f)
horizontalLineTo(8.27f)
curveTo(9.61f, 9.74f, 9.75f, 9.36f, 9.75f, 8.51f)
verticalLineTo(3.98f)
curveTo(9.75f, 3.12f, 9.61f, 2.75f, 8.27f, 2.75f)
horizontalLineTo(4.23f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(8.27f, 22.75f)
horizontalLineTo(4.23f)
curveTo(2.22f, 22.75f, 1.25f, 21.77f, 1.25f, 19.77f)
verticalLineTo(15.73f)
curveTo(1.25f, 13.72f, 2.23f, 12.75f, 4.23f, 12.75f)
horizontalLineTo(8.27f)
curveTo(10.28f, 12.75f, 11.25f, 13.73f, 11.25f, 15.73f)
verticalLineTo(19.77f)
curveTo(11.25f, 21.77f, 10.27f, 22.75f, 8.27f, 22.75f)
close()
moveTo(4.23f, 14.25f)
curveTo(3.05f, 14.25f, 2.75f, 14.55f, 2.75f, 15.73f)
verticalLineTo(19.77f)
curveTo(2.75f, 20.95f, 3.05f, 21.25f, 4.23f, 21.25f)
horizontalLineTo(8.27f)
curveTo(9.45f, 21.25f, 9.75f, 20.95f, 9.75f, 19.77f)
verticalLineTo(15.73f)
curveTo(9.75f, 14.55f, 9.45f, 14.25f, 8.27f, 14.25f)
horizontalLineTo(4.23f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0f, 16.25f)
horizontalLineTo(15.0f)
curveTo(14.59f, 16.25f, 14.25f, 15.91f, 14.25f, 15.5f)
curveTo(14.25f, 15.09f, 14.59f, 14.75f, 15.0f, 14.75f)
horizontalLineTo(21.0f)
curveTo(21.41f, 14.75f, 21.75f, 15.09f, 21.75f, 15.5f)
curveTo(21.75f, 15.91f, 21.41f, 16.25f, 21.0f, 16.25f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0f, 20.25f)
horizontalLineTo(15.0f)
curveTo(14.59f, 20.25f, 14.25f, 19.91f, 14.25f, 19.5f)
curveTo(14.25f, 19.09f, 14.59f, 18.75f, 15.0f, 18.75f)
horizontalLineTo(21.0f)
curveTo(21.41f, 18.75f, 21.75f, 19.09f, 21.75f, 19.5f)
curveTo(21.75f, 19.91f, 21.41f, 20.25f, 21.0f, 20.25f)
close()
}
}
.build()
return _elementequal!!
}
private var _elementequal: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 6,206 | VuesaxIcons | MIT License |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/outline/Elementequal.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.OutlineGroup
public val OutlineGroup.Elementequal: ImageVector
get() {
if (_elementequal != null) {
return _elementequal!!
}
_elementequal = Builder(name = "Elementequal", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(19.77f, 11.25f)
horizontalLineTo(15.73f)
curveTo(13.72f, 11.25f, 12.75f, 10.27f, 12.75f, 8.27f)
verticalLineTo(4.23f)
curveTo(12.75f, 2.22f, 13.73f, 1.25f, 15.73f, 1.25f)
horizontalLineTo(19.77f)
curveTo(21.78f, 1.25f, 22.75f, 2.23f, 22.75f, 4.23f)
verticalLineTo(8.27f)
curveTo(22.75f, 10.27f, 21.77f, 11.25f, 19.77f, 11.25f)
close()
moveTo(15.73f, 2.75f)
curveTo(14.55f, 2.75f, 14.25f, 3.05f, 14.25f, 4.23f)
verticalLineTo(8.27f)
curveTo(14.25f, 9.45f, 14.55f, 9.75f, 15.73f, 9.75f)
horizontalLineTo(19.77f)
curveTo(20.95f, 9.75f, 21.25f, 9.45f, 21.25f, 8.27f)
verticalLineTo(4.23f)
curveTo(21.25f, 3.05f, 20.95f, 2.75f, 19.77f, 2.75f)
horizontalLineTo(15.73f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(8.27f, 11.25f)
horizontalLineTo(4.23f)
curveTo(2.22f, 11.25f, 1.25f, 10.36f, 1.25f, 8.52f)
verticalLineTo(3.98f)
curveTo(1.25f, 2.14f, 2.23f, 1.25f, 4.23f, 1.25f)
horizontalLineTo(8.27f)
curveTo(10.28f, 1.25f, 11.25f, 2.14f, 11.25f, 3.98f)
verticalLineTo(8.51f)
curveTo(11.25f, 10.36f, 10.27f, 11.25f, 8.27f, 11.25f)
close()
moveTo(4.23f, 2.75f)
curveTo(2.89f, 2.75f, 2.75f, 3.13f, 2.75f, 3.98f)
verticalLineTo(8.51f)
curveTo(2.75f, 9.37f, 2.89f, 9.74f, 4.23f, 9.74f)
horizontalLineTo(8.27f)
curveTo(9.61f, 9.74f, 9.75f, 9.36f, 9.75f, 8.51f)
verticalLineTo(3.98f)
curveTo(9.75f, 3.12f, 9.61f, 2.75f, 8.27f, 2.75f)
horizontalLineTo(4.23f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(8.27f, 22.75f)
horizontalLineTo(4.23f)
curveTo(2.22f, 22.75f, 1.25f, 21.77f, 1.25f, 19.77f)
verticalLineTo(15.73f)
curveTo(1.25f, 13.72f, 2.23f, 12.75f, 4.23f, 12.75f)
horizontalLineTo(8.27f)
curveTo(10.28f, 12.75f, 11.25f, 13.73f, 11.25f, 15.73f)
verticalLineTo(19.77f)
curveTo(11.25f, 21.77f, 10.27f, 22.75f, 8.27f, 22.75f)
close()
moveTo(4.23f, 14.25f)
curveTo(3.05f, 14.25f, 2.75f, 14.55f, 2.75f, 15.73f)
verticalLineTo(19.77f)
curveTo(2.75f, 20.95f, 3.05f, 21.25f, 4.23f, 21.25f)
horizontalLineTo(8.27f)
curveTo(9.45f, 21.25f, 9.75f, 20.95f, 9.75f, 19.77f)
verticalLineTo(15.73f)
curveTo(9.75f, 14.55f, 9.45f, 14.25f, 8.27f, 14.25f)
horizontalLineTo(4.23f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0f, 16.25f)
horizontalLineTo(15.0f)
curveTo(14.59f, 16.25f, 14.25f, 15.91f, 14.25f, 15.5f)
curveTo(14.25f, 15.09f, 14.59f, 14.75f, 15.0f, 14.75f)
horizontalLineTo(21.0f)
curveTo(21.41f, 14.75f, 21.75f, 15.09f, 21.75f, 15.5f)
curveTo(21.75f, 15.91f, 21.41f, 16.25f, 21.0f, 16.25f)
close()
}
path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0f, 20.25f)
horizontalLineTo(15.0f)
curveTo(14.59f, 20.25f, 14.25f, 19.91f, 14.25f, 19.5f)
curveTo(14.25f, 19.09f, 14.59f, 18.75f, 15.0f, 18.75f)
horizontalLineTo(21.0f)
curveTo(21.41f, 18.75f, 21.75f, 19.09f, 21.75f, 19.5f)
curveTo(21.75f, 19.91f, 21.41f, 20.25f, 21.0f, 20.25f)
close()
}
}
.build()
return _elementequal!!
}
private var _elementequal: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 6,206 | VuesaxIcons | MIT License |
app/src/main/java/com/zve/redditassessment/di/PresenterModule.kt | pzverkov | 117,295,101 | false | null | package com.zve.redditassessment.di
import com.zve.redditassessment.api.RedditService
import com.zve.redditassessment.ui.comments.CommentsPresenter
import com.zve.redditassessment.ui.comments.CommentsPresenterImpl
import com.zve.redditassessment.ui.listing.ListingPresenter
import com.zve.redditassessment.ui.listing.ListingPresenterImpl
import javax.inject.Singleton
import dagger.Module
import dagger.Provides
/**
* Created by Peter on 11.01.2018.
*/
@Module(includes = arrayOf(NetworkModule::class))
class PresenterModule {
@Provides
@Singleton
internal fun provideListingPresenter(redditService: RedditService): ListingPresenter {
return ListingPresenterImpl(redditService)
}
@Provides
@Singleton
internal fun provideCommentsPresenter(redditService: RedditService): CommentsPresenter {
return CommentsPresenterImpl(redditService)
}
}
| 1 | null | 1 | 1 | b3209d4cfdf9bcbd5aa7db7fdef0459b9d2b0dbd | 894 | RedditTest | Apache License 2.0 |
feature/story/src/main/kotlin/com/najudoryeong/mineme/feature/story/WriteStoryViewModel.kt | NaJuDoRyeong | 689,891,643 | false | {"Kotlin": 402597} | /*
* Copyright 2023 KDW03
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.najudoryeong.mineme.feature.story
import android.net.Uri
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import java.time.LocalDate
import javax.inject.Inject
@HiltViewModel
class WriteStoryViewModel @Inject constructor(
private val savedStateHandle: SavedStateHandle,
) : ViewModel() {
val allRegions: MutableStateFlow<List<String>> = MutableStateFlow(koreanProvinces)
val allCities: MutableStateFlow<List<String>> = MutableStateFlow(emptyList())
val selectedRegion: MutableStateFlow<String> = MutableStateFlow(koreanProvinces.first())
val selectedCity: MutableStateFlow<String> = MutableStateFlow(koreanCities[koreanProvinces.first()]?.first() ?: "")
val selectedDate: MutableStateFlow<LocalDate> = MutableStateFlow(LocalDate.now())
val selectedImage: MutableStateFlow<List<Uri>> = MutableStateFlow(emptyList())
val storyContent = mutableStateOf("")
init {
viewModelScope.launch {
selectedRegion.collect { region ->
val cities = koreanCities[region] ?: emptyList()
allCities.value = cities
updateCity(cities.first())
}
}
}
fun updateDate(year: Int, month: Int, day: Int) {
selectedDate.value = LocalDate.of(year, month, day)
}
fun updateRegion(newRegion: String) {
selectedRegion.value = newRegion
}
fun updateCity(newCity: String) {
selectedCity.value = newCity
}
fun updateImages(newUris: List<Uri>) {
selectedImage.value = newUris
}
}
val koreanProvinces = listOf(
"서울특별시", "부산광역시", "대구광역시", "인천광역시", "광주광역시", "대전광역시", "울산광역시",
"세종특별자치시", "경기도", "강원도", "충청북도", "충청남도", "전라북도", "전라남도", "경상북도", "경상남도", "제주특별자치도",
)
val koreanCities = mapOf(
"서울특별시" to listOf("강남구", "강동구", "강북구", "강서구", "관악구", "광진구", "구로구", "금천구", "노원구", "도봉구", "동대문구", "동작구", "마포구", "서대문구", "서초구", "성동구", "성북구", "송파구", "양천구", "영등포구", "용산구", "은평구", "종로구", "중구", "중랑구"),
"부산광역시" to listOf("강서구", "금정구", "기장군", "남구", "동구", "동래구", "부산진구", "북구", "사상구", "사하구", "서구", "수영구", "연제구", "영도구", "중구", "해운대구"),
"대구광역시" to listOf("남구", "달서구", "달성군", "동구", "북구", "서구", "수성구", "중구"),
"인천광역시" to listOf("강화군", "계양구", "남동구", "동구", "미추홀구", "부평구", "서구", "연수구", "옹진군", "중구"),
"광주광역시" to listOf("광산구", "남구", "동구", "북구", "서구"),
"대전광역시" to listOf("대덕구", "동구", "서구", "유성구", "중구"),
"울산광역시" to listOf("남구", "동구", "북구", "울주군", "중구"),
"세종특별자치시" to listOf("세종시"),
"경기도" to listOf("가평군", "고양시", "과천시", "광명시", "광주시", "구리시", "군포시", "김포시", "남양주시", "동두천시", "부천시", "성남시", "수원시", "시흥시", "안산시", "안성시", "안양시", "양주시", "양평군", "여주시", "연천군", "오산시", "용인시", "의왕시", "의정부시", "이천시", "파주시", "평택시", "포천시", "하남시", "화성시"),
"강원도" to listOf("강릉시", "고성군", "동해시", "삼척시", "속초시", "양구군", "양양군", "영월군", "원주시", "인제군", "정선군", "철원군", "춘천시", "태백시", "평창군", "홍천군", "화천군", "횡성군"),
"충청북도" to listOf("괴산군", "단양군", "보은군", "영동군", "옥천군", "음성군", "제천시", "증평군", "진천군", "청주시", "충주시"),
"충청남도" to listOf("계룡시", "공주시", "금산군", "논산시", "당진시", "보령시", "부여군", "서산시", "서천군", "아산시", "예산군", "천안시", "청양군", "태안군", "홍성군"),
"전라북도" to listOf("고창군", "군산시", "김제시", "남원시", "무주군", "부안군", "순창군", "완주군", "익산시", "임실군", "장수군", "전주시", "정읍시", "진안군"),
"전라남도" to listOf("강진군", "고흥군", "곡성군", "광양시", "구례군", "나주시", "담양군", "목포시", "무안군", "보성군", "순천시", "신안군", "여수시", "영광군", "영암군", "완도군", "장성군", "장흥군", "진도군", "함평군", "해남군", "화순군"),
"경상북도" to listOf("경산시", "경주시", "고령군", "구미시", "군위군", "김천시", "문경시", "봉화군", "상주시", "성주군", "안동시", "영덕군", "영양군", "영주시", "영천시", "예천군", "울릉군", "울진군", "의성군", "청도군", "청송군", "칠곡군", "포항시"),
"경상남도" to listOf("거제시", "거창군", "고성군", "김해시", "남해군", "밀양시", "사천시", "산청군", "양산시", "의령군", "진주시", "창녕군", "창원시", "통영시", "하동군", "함안군", "함양군", "합천군"),
"제주특별자치도" to listOf("서귀포시", "제주시"),
)
| 2 | Kotlin | 0 | 0 | 7b1b46b14b8af6994cb86cb6ca844266a6429d68 | 4,587 | mineme_AOS_new | Apache License 2.0 |
app/src/main/java/com/moussafir/notesapp/domain/use_case/GetAllNotesUseCase.kt | Nassr-Allah | 516,005,707 | false | {"Kotlin": 47347} | package com.moussafir.notesapp.domain.use_case
import com.moussafir.notesapp.data.repository.NoteRepository
import com.moussafir.notesapp.domain.model.Note
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class GetAllNotesUseCase @Inject constructor(
private val noteRepository: NoteRepository
) {
operator fun invoke(): Flow<List<Note>> {
return noteRepository.getAllNotes()
}
} | 0 | Kotlin | 0 | 2 | c487d5b91cec6cb1a65a2cb08681209772acec78 | 417 | Notes-App | MIT License |
image/src/main/java/com/smarttoolfactory/image/zoom/EnhancedZoomStateImpl.kt | T8RIN | 478,710,402 | false | null | package com.smarttoolfactory.image.zoom
import androidx.compose.animation.core.exponentialDecay
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Rect
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.input.pointer.PointerInputChange
import androidx.compose.ui.input.pointer.util.VelocityTracker
import androidx.compose.ui.unit.IntRect
import androidx.compose.ui.unit.IntSize
import com.smarttoolfactory.image.util.coerceIn
import com.smarttoolfactory.image.util.getCropRect
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.launch
/**
* * State of the enhanced zoom that uses animations and fling
* to animate to bounds or have movement after pointers are up.
* Allows to change zoom, pan, translate, or get current state by
* calling methods on this object. To be hosted and passed to [Modifier.enhancedZoom].
* Also contains [EnhancedZoomData] about current transformation area of Composable and
* visible are of image being zoomed, rotated, or panned. If any animation
* is going on current [isAnimationRunning] is true and [EnhancedZoomData] returns rectangle
* that belongs to end of animation.
*
* @param imageSize size of the image that is zoomed or transformed. Size of the image
* is required to get [Rect] of visible area after current transformation.
* @param initialZoom zoom set initially
* @param minZoom minimum zoom value
* @param maxZoom maximum zoom value
* @param fling when set to true dragging pointer builds up velocity. When last
* pointer leaves Composable a movement invoked against friction till velocity drops down
* to threshold
* @param moveToBounds when set to true if image zoom is lower than initial zoom or
* panned out of image boundaries moves back to bounds with animation.
* ##Note
* Currently rotating back to borders is not available
* @param zoomable when set to true zoom is enabled
* @param pannable when set to true pan is enabled
* @param rotatable when set to true rotation is enabled
* @param limitPan limits pan to bounds of parent Composable. Using this flag prevents creating
* empty space on sides or edges of parent
*/
open class EnhancedZoomState constructor(
val imageSize: IntSize,
initialZoom: Float = 1f,
minZoom: Float = .5f,
maxZoom: Float = 5f,
fling: Boolean = false,
moveToBounds: Boolean = true,
zoomable: Boolean = true,
pannable: Boolean = true,
rotatable: Boolean = false,
limitPan: Boolean = false
) : BaseEnhancedZoomState(
initialZoom = initialZoom,
minZoom = minZoom,
maxZoom = maxZoom,
fling = fling,
moveToBounds = moveToBounds,
zoomable = zoomable,
pannable = pannable,
rotatable = rotatable,
limitPan = limitPan
) {
private val rectDraw: Rect
get() = Rect(
offset = Offset.Zero,
size = Size(size.width.toFloat(), size.height.toFloat())
)
val enhancedZoomData: EnhancedZoomData
get() = EnhancedZoomData(
zoom = animatableZoom.targetValue,
pan = Offset(animatablePanX.targetValue, animatablePanY.targetValue),
rotation = animatableRotation.targetValue,
imageRegion = rectDraw,
visibleRegion = calculateRectBounds()
)
private fun calculateRectBounds(): IntRect {
val width = size.width
val height = size.height
val bounds = getBounds()
val zoom = animatableZoom.targetValue
val panX = animatablePanX.targetValue.coerceIn(-bounds.x, bounds.x)
val panY = animatablePanY.targetValue.coerceIn(-bounds.y, bounds.y)
// Offset for interpolating offset from (imageWidth/2,-imageWidth/2) interval
// to (0, imageWidth) interval when
// transform origin is TransformOrigin(0.5f,0.5f)
val horizontalCenterOffset = width * (zoom - 1) / 2f
val verticalCenterOffset = height * (zoom - 1) / 2f
val offsetX = (horizontalCenterOffset - panX)
.coerceAtLeast(0f) / zoom
val offsetY = (verticalCenterOffset - panY)
.coerceAtLeast(0f) / zoom
val offset = Offset(offsetX, offsetY)
return getCropRect(
bitmapWidth = imageSize.width,
bitmapHeight = imageSize.height,
containerWidth = width.toFloat(),
containerHeight = height.toFloat(),
pan = offset,
zoom = zoom,
rectSelection = rectDraw
)
}
}
open class BaseEnhancedZoomState constructor(
initialZoom: Float = 1f,
minZoom: Float = .5f,
maxZoom: Float = 5f,
val fling: Boolean = true,
val moveToBounds: Boolean = true,
zoomable: Boolean = true,
pannable: Boolean = true,
rotatable: Boolean = false,
limitPan: Boolean = false
) : ZoomState(
initialZoom = initialZoom,
initialRotation = 0f,
minZoom = minZoom,
maxZoom = maxZoom,
zoomable = zoomable,
pannable = pannable,
rotatable = rotatable,
limitPan = limitPan
) {
private val velocityTracker = VelocityTracker()
private var doubleTapped = false
open suspend fun onGesture(
centroid: Offset,
pan: Offset,
zoom: Float,
rotation: Float,
mainPointer: PointerInputChange,
changes: List<PointerInputChange>
) = coroutineScope {
doubleTapped = false
updateZoomState(
centroid = centroid,
zoomChange = zoom,
panChange = pan,
rotationChange = rotation
)
// Fling Gesture
if (fling) {
if (changes.size == 1) {
addPosition(mainPointer.uptimeMillis, mainPointer.position)
}
}
}
open suspend fun onGestureStart() = coroutineScope {}
open suspend fun onGestureEnd(onBoundsCalculated: () -> Unit) {
// Gesture end might be called after second tap and we don't want to fling
// or animate back to valid bounds when doubled tapped
if (!doubleTapped) {
if (fling && zoom > 1) {
fling {
// We get target value on start instead of updating bounds after
// gesture has finished
onBoundsCalculated()
}
} else {
onBoundsCalculated()
}
if (moveToBounds) {
resetToValidBounds()
}
}
}
// Double Tap
suspend fun onDoubleTap(
pan: Offset = Offset.Zero,
zoom: Float = 1f,
rotation: Float = 0f,
onAnimationEnd: () -> Unit
) {
doubleTapped = true
if (fling) {
resetTracking()
}
resetWithAnimation(pan = pan, zoom = zoom, rotation = rotation)
onAnimationEnd()
}
// TODO Add resetting back to bounds for rotated state as well
/**
* Resets to bounds with animation and resets tracking for fling animation
*/
private suspend fun resetToValidBounds() {
val zoom = zoom.coerceAtLeast(1f)
val bounds = getBounds()
val pan = pan.coerceIn(-bounds.x..bounds.x, -bounds.y..bounds.y)
resetWithAnimation(pan = pan, zoom = zoom, rotation = rotation)
resetTracking()
}
/*
Fling gesture
*/
private fun addPosition(timeMillis: Long, position: Offset) {
velocityTracker.addPosition(
timeMillis = timeMillis,
position = position
)
}
/**
* Create a fling gesture when user removes finger from scree to have continuous movement
* until [velocityTracker] speed reached to lower bound
*/
private suspend fun fling(onFlingStart: () -> Unit) = coroutineScope {
val velocityTracker = velocityTracker.calculateVelocity()
val velocity = Offset(velocityTracker.x, velocityTracker.y)
var flingStarted = false
launch {
animatablePanX.animateDecay(
velocity.x,
exponentialDecay(absVelocityThreshold = 20f),
block = {
// This callback returns target value of fling gesture initially
if (!flingStarted) {
onFlingStart()
flingStarted = true
}
}
)
}
launch {
animatablePanY.animateDecay(
velocity.y,
exponentialDecay(absVelocityThreshold = 20f),
block = {
// This callback returns target value of fling gesture initially
if (!flingStarted) {
onFlingStart()
flingStarted = true
}
}
)
}
}
private fun resetTracking() {
velocityTracker.resetTracking()
}
}
| 5 | null | 77 | 979 | 7d164a02c463afede47c785f8b182c954abfcde9 | 8,962 | ImageToolbox | Apache License 2.0 |
app/src/main/java/com/octagontechnologies/harrypotter/repo/local/dao/BaseDao.kt | Octagon-Technologies | 809,502,044 | false | {"Kotlin": 61907} | package com.da_chelimo.generate.core.data.repo.local.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
@Dao
abstract class BaseDao<T> {
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract suspend fun insertData(data: T)
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract suspend fun insertData(data: List<T>)
} | 0 | Kotlin | 0 | 0 | ed7c8c9f4f6bff1da7002809d3eb1d70e493d2e8 | 392 | Whisper | MIT License |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/iot/CfnAuthorizerProps.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.iot
import io.cloudshiftdev.awscdk.CfnTag
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.Boolean
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
import kotlin.collections.Map
/**
* Properties for defining a `CfnAuthorizer`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.iot.*;
* CfnAuthorizerProps cfnAuthorizerProps = CfnAuthorizerProps.builder()
* .authorizerFunctionArn("authorizerFunctionArn")
* // the properties below are optional
* .authorizerName("authorizerName")
* .enableCachingForHttp(false)
* .signingDisabled(false)
* .status("status")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .tokenKeyName("tokenKeyName")
* .tokenSigningPublicKeys(Map.of(
* "tokenSigningPublicKeysKey", "tokenSigningPublicKeys"))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html)
*/
public interface CfnAuthorizerProps {
/**
* The authorizer's Lambda function ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-authorizerfunctionarn)
*/
public fun authorizerFunctionArn(): String
/**
* The authorizer name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-authorizername)
*/
public fun authorizerName(): String? = unwrap(this).getAuthorizerName()
/**
* When `true` , the result from the authorizer's Lambda function is cached for clients that use
* persistent HTTP connections.
*
* The results are cached for the time specified by the Lambda function in `refreshAfterInSeconds`
* . This value doesn't affect authorization of clients that use MQTT connections.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-enablecachingforhttp)
*/
public fun enableCachingForHttp(): Any? = unwrap(this).getEnableCachingForHttp()
/**
* Specifies whether AWS IoT validates the token signature in an authorization request.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-signingdisabled)
*/
public fun signingDisabled(): Any? = unwrap(this).getSigningDisabled()
/**
* The status of the authorizer.
*
* Valid values: `ACTIVE` | `INACTIVE`
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-status)
*/
public fun status(): String? = unwrap(this).getStatus()
/**
* Metadata which can be used to manage the custom authorizer.
*
*
* For URI Request parameters use format: ...key1=value1&key2=value2...
*
* For the CLI command-line parameter use format: &&tags "key1=value1&key2=value2..."
*
* For the cli-input-json file use format: "tags": "key1=value1&key2=value2..."
*
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* The key used to extract the token from the HTTP headers.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-tokenkeyname)
*/
public fun tokenKeyName(): String? = unwrap(this).getTokenKeyName()
/**
* The public keys used to validate the token signature returned by your custom authentication
* service.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-tokensigningpublickeys)
*/
public fun tokenSigningPublicKeys(): Any? = unwrap(this).getTokenSigningPublicKeys()
/**
* A builder for [CfnAuthorizerProps]
*/
@CdkDslMarker
public interface Builder {
/**
* @param authorizerFunctionArn The authorizer's Lambda function ARN.
*/
public fun authorizerFunctionArn(authorizerFunctionArn: String)
/**
* @param authorizerName The authorizer name.
*/
public fun authorizerName(authorizerName: String)
/**
* @param enableCachingForHttp When `true` , the result from the authorizer's Lambda function is
* cached for clients that use persistent HTTP connections.
* The results are cached for the time specified by the Lambda function in
* `refreshAfterInSeconds` . This value doesn't affect authorization of clients that use MQTT
* connections.
*/
public fun enableCachingForHttp(enableCachingForHttp: Boolean)
/**
* @param enableCachingForHttp When `true` , the result from the authorizer's Lambda function is
* cached for clients that use persistent HTTP connections.
* The results are cached for the time specified by the Lambda function in
* `refreshAfterInSeconds` . This value doesn't affect authorization of clients that use MQTT
* connections.
*/
public fun enableCachingForHttp(enableCachingForHttp: IResolvable)
/**
* @param signingDisabled Specifies whether AWS IoT validates the token signature in an
* authorization request.
*/
public fun signingDisabled(signingDisabled: Boolean)
/**
* @param signingDisabled Specifies whether AWS IoT validates the token signature in an
* authorization request.
*/
public fun signingDisabled(signingDisabled: IResolvable)
/**
* @param status The status of the authorizer.
* Valid values: `ACTIVE` | `INACTIVE`
*/
public fun status(status: String)
/**
* @param tags Metadata which can be used to manage the custom authorizer.
*
* For URI Request parameters use format: ...key1=value1&key2=value2...
*
* For the CLI command-line parameter use format: &&tags
* "key1=value1&key2=value2..."
*
* For the cli-input-json file use format: "tags": "key1=value1&key2=value2..."
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags Metadata which can be used to manage the custom authorizer.
*
* For URI Request parameters use format: ...key1=value1&key2=value2...
*
* For the CLI command-line parameter use format: &&tags
* "key1=value1&key2=value2..."
*
* For the cli-input-json file use format: "tags": "key1=value1&key2=value2..."
*/
public fun tags(vararg tags: CfnTag)
/**
* @param tokenKeyName The key used to extract the token from the HTTP headers.
*/
public fun tokenKeyName(tokenKeyName: String)
/**
* @param tokenSigningPublicKeys The public keys used to validate the token signature returned
* by your custom authentication service.
*/
public fun tokenSigningPublicKeys(tokenSigningPublicKeys: IResolvable)
/**
* @param tokenSigningPublicKeys The public keys used to validate the token signature returned
* by your custom authentication service.
*/
public fun tokenSigningPublicKeys(tokenSigningPublicKeys: Map<String, String>)
}
private class BuilderImpl : Builder {
private val cdkBuilder: software.amazon.awscdk.services.iot.CfnAuthorizerProps.Builder =
software.amazon.awscdk.services.iot.CfnAuthorizerProps.builder()
/**
* @param authorizerFunctionArn The authorizer's Lambda function ARN.
*/
override fun authorizerFunctionArn(authorizerFunctionArn: String) {
cdkBuilder.authorizerFunctionArn(authorizerFunctionArn)
}
/**
* @param authorizerName The authorizer name.
*/
override fun authorizerName(authorizerName: String) {
cdkBuilder.authorizerName(authorizerName)
}
/**
* @param enableCachingForHttp When `true` , the result from the authorizer's Lambda function is
* cached for clients that use persistent HTTP connections.
* The results are cached for the time specified by the Lambda function in
* `refreshAfterInSeconds` . This value doesn't affect authorization of clients that use MQTT
* connections.
*/
override fun enableCachingForHttp(enableCachingForHttp: Boolean) {
cdkBuilder.enableCachingForHttp(enableCachingForHttp)
}
/**
* @param enableCachingForHttp When `true` , the result from the authorizer's Lambda function is
* cached for clients that use persistent HTTP connections.
* The results are cached for the time specified by the Lambda function in
* `refreshAfterInSeconds` . This value doesn't affect authorization of clients that use MQTT
* connections.
*/
override fun enableCachingForHttp(enableCachingForHttp: IResolvable) {
cdkBuilder.enableCachingForHttp(enableCachingForHttp.let(IResolvable.Companion::unwrap))
}
/**
* @param signingDisabled Specifies whether AWS IoT validates the token signature in an
* authorization request.
*/
override fun signingDisabled(signingDisabled: Boolean) {
cdkBuilder.signingDisabled(signingDisabled)
}
/**
* @param signingDisabled Specifies whether AWS IoT validates the token signature in an
* authorization request.
*/
override fun signingDisabled(signingDisabled: IResolvable) {
cdkBuilder.signingDisabled(signingDisabled.let(IResolvable.Companion::unwrap))
}
/**
* @param status The status of the authorizer.
* Valid values: `ACTIVE` | `INACTIVE`
*/
override fun status(status: String) {
cdkBuilder.status(status)
}
/**
* @param tags Metadata which can be used to manage the custom authorizer.
*
* For URI Request parameters use format: ...key1=value1&key2=value2...
*
* For the CLI command-line parameter use format: &&tags
* "key1=value1&key2=value2..."
*
* For the cli-input-json file use format: "tags": "key1=value1&key2=value2..."
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags Metadata which can be used to manage the custom authorizer.
*
* For URI Request parameters use format: ...key1=value1&key2=value2...
*
* For the CLI command-line parameter use format: &&tags
* "key1=value1&key2=value2..."
*
* For the cli-input-json file use format: "tags": "key1=value1&key2=value2..."
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
/**
* @param tokenKeyName The key used to extract the token from the HTTP headers.
*/
override fun tokenKeyName(tokenKeyName: String) {
cdkBuilder.tokenKeyName(tokenKeyName)
}
/**
* @param tokenSigningPublicKeys The public keys used to validate the token signature returned
* by your custom authentication service.
*/
override fun tokenSigningPublicKeys(tokenSigningPublicKeys: IResolvable) {
cdkBuilder.tokenSigningPublicKeys(tokenSigningPublicKeys.let(IResolvable.Companion::unwrap))
}
/**
* @param tokenSigningPublicKeys The public keys used to validate the token signature returned
* by your custom authentication service.
*/
override fun tokenSigningPublicKeys(tokenSigningPublicKeys: Map<String, String>) {
cdkBuilder.tokenSigningPublicKeys(tokenSigningPublicKeys)
}
public fun build(): software.amazon.awscdk.services.iot.CfnAuthorizerProps = cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.iot.CfnAuthorizerProps,
) : CdkObject(cdkObject), CfnAuthorizerProps {
/**
* The authorizer's Lambda function ARN.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-authorizerfunctionarn)
*/
override fun authorizerFunctionArn(): String = unwrap(this).getAuthorizerFunctionArn()
/**
* The authorizer name.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-authorizername)
*/
override fun authorizerName(): String? = unwrap(this).getAuthorizerName()
/**
* When `true` , the result from the authorizer's Lambda function is cached for clients that use
* persistent HTTP connections.
*
* The results are cached for the time specified by the Lambda function in
* `refreshAfterInSeconds` . This value doesn't affect authorization of clients that use MQTT
* connections.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-enablecachingforhttp)
*/
override fun enableCachingForHttp(): Any? = unwrap(this).getEnableCachingForHttp()
/**
* Specifies whether AWS IoT validates the token signature in an authorization request.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-signingdisabled)
*/
override fun signingDisabled(): Any? = unwrap(this).getSigningDisabled()
/**
* The status of the authorizer.
*
* Valid values: `ACTIVE` | `INACTIVE`
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-status)
*/
override fun status(): String? = unwrap(this).getStatus()
/**
* Metadata which can be used to manage the custom authorizer.
*
*
* For URI Request parameters use format: ...key1=value1&key2=value2...
*
* For the CLI command-line parameter use format: &&tags
* "key1=value1&key2=value2..."
*
* For the cli-input-json file use format: "tags": "key1=value1&key2=value2..."
*
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* The key used to extract the token from the HTTP headers.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-tokenkeyname)
*/
override fun tokenKeyName(): String? = unwrap(this).getTokenKeyName()
/**
* The public keys used to validate the token signature returned by your custom authentication
* service.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iot-authorizer.html#cfn-iot-authorizer-tokensigningpublickeys)
*/
override fun tokenSigningPublicKeys(): Any? = unwrap(this).getTokenSigningPublicKeys()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): CfnAuthorizerProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.iot.CfnAuthorizerProps):
CfnAuthorizerProps = CdkObjectWrappers.wrap(cdkObject) as? CfnAuthorizerProps ?:
Wrapper(cdkObject)
internal fun unwrap(wrapped: CfnAuthorizerProps):
software.amazon.awscdk.services.iot.CfnAuthorizerProps = (wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.iot.CfnAuthorizerProps
}
}
| 1 | null | 0 | 4 | a18731816a3ec710bc89fb8767d2ab71cec558a6 | 16,264 | kotlin-cdk-wrapper | Apache License 2.0 |
lib/src/integrationTest/kotlin/com/lemonappdev/konsist/core/verify/koproviderassert/deprecated/DeprecatedKoProviderAssertOnSequenceTest.kt | LemonAppDev | 621,181,534 | false | null | package com.lemonappdev.konsist.core.verify.koproviderassert
import com.lemonappdev.konsist.TestSnippetProvider
import com.lemonappdev.konsist.api.declaration.KoFileDeclaration
import com.lemonappdev.konsist.api.provider.KoAnnotationProvider
import com.lemonappdev.konsist.api.provider.KoNameProvider
import com.lemonappdev.konsist.api.provider.KoPrimaryConstructorProvider
import com.lemonappdev.konsist.api.provider.KoPropertyProvider
import com.lemonappdev.konsist.api.provider.modifier.KoModifierProvider
import com.lemonappdev.konsist.core.exception.KoCheckFailedException
import com.lemonappdev.konsist.core.exception.KoPreconditionFailedException
import com.lemonappdev.konsist.core.verify.assert
import com.lemonappdev.konsist.core.verify.assertNot
import org.amshove.kluent.shouldContain
import org.amshove.kluent.shouldThrow
import org.amshove.kluent.withMessage
import org.junit.jupiter.api.Test
class KoDeclarationAssertForProviderListTest {
@Test
fun `provider-assert-test-method-name`() {
// given
val sut = getSnippetFile("provider-assert-test-method-name")
.declarations()
.filterIsInstance<KoNameProvider>()
// then
try {
sut.assert { false }
} catch (e: Exception) {
e.message?.shouldContain("Assert 'provider-assert-test-method-name' has failed. Invalid declarations (2)") ?: throw e
}
}
@Test
fun `provider-assert-fails-when-declaration-list-is-empty`() {
// given
val sut = getSnippetFile("provider-assert-fails-when-declaration-list-is-empty")
.declarations()
.filterNot { it is KoFileDeclaration }
.filterIsInstance<KoNameProvider>()
// when
val func = {
sut.assert { true }
}
// then
func shouldThrow KoPreconditionFailedException::class withMessage
"Declaration list is empty. Please make sure that list of declarations contain items before calling the 'assert' method."
}
@Test
fun `provider-assert-not-fails-when-declaration-list-is-empty`() {
// given
val sut = getSnippetFile("provider-assert-not-fails-when-declaration-list-is-empty")
.declarations()
.filterNot { it is KoFileDeclaration }
.filterIsInstance<KoNameProvider>()
// when
val func = {
sut.assertNot { false }
}
// then
func shouldThrow KoPreconditionFailedException::class withMessage
"Declaration list is empty. Please make sure that list of declarations contain items before calling the 'assertNot' method."
}
@Test
fun `assert-passes`() {
// given
val sut = getSnippetFile("assert-passes")
.declarations()
.filterIsInstance<KoAnnotationProvider>()
// then
sut.assert { it.hasAnnotations() }
}
@Test
fun `assert-fails`() {
// given
val sut = getSnippetFile("assert-fails")
.declarations()
.filterIsInstance<KoAnnotationProvider>()
// when
val func = {
sut.assert { it.hasAnnotations() }
}
// then
func shouldThrow KoCheckFailedException::class
}
@Test
fun `assert-not-passes`() {
// given
val sut = getSnippetFile("assert-not-passes")
.declarations()
.filterIsInstance<KoAnnotationProvider>()
// then
sut.assertNot { it.hasAnnotations() }
}
@Test
fun `assert-not-fails`() {
// given
val sut = getSnippetFile("assert-not-fails")
.declarations()
.filterIsInstance<KoAnnotationProvider>()
// when
val func = {
sut.assertNot { it.hasAnnotations() }
}
// then
func shouldThrow KoCheckFailedException::class
}
@Test
fun `assert-passes-when-expression-is-nullable`() {
// given
val sut = getSnippetFile("assert-passes-when-expression-is-nullable")
.declarations()
.filterIsInstance<KoPrimaryConstructorProvider>()
// then
sut.assert { it.primaryConstructor?.hasParameterNamed("sampleParameter") ?: true }
}
@Test
fun `assert-fails-when-expression-is-nullable`() {
// given
val sut = getSnippetFile("assert-fails-when-expression-is-nullable")
.declarations()
.filterIsInstance<KoPrimaryConstructorProvider>()
// when
val func = {
sut.assert { it.primaryConstructor?.hasParameterNamed("sampleParameter") ?: true }
}
// then
func shouldThrow KoCheckFailedException::class
}
@Test
fun `assert-not-passes-when-expression-is-nullable`() {
// given
val sut = getSnippetFile("assert-not-passes-when-expression-is-nullable")
.declarations()
.filterIsInstance<KoPrimaryConstructorProvider>()
// then
sut.assertNot { it.primaryConstructor?.hasParameterNamed("otherParameter") ?: false }
}
@Test
fun `assert-not-fails-when-expression-is-nullable`() {
// given
val sut = getSnippetFile("assert-not-fails-when-expression-is-nullable")
.declarations()
.filterIsInstance<KoPrimaryConstructorProvider>()
// when
val func = {
sut.assertNot { it.primaryConstructor?.hasParameterNamed("sampleParameter") ?: false }
}
// then
func shouldThrow KoCheckFailedException::class
}
@Test
fun `assert-suppress-by-konsist-and-name-at-file-level-when-all-declarations-are-KoAnnotationProvider`() {
// given
val sut =
getSnippetFile("assert-suppress-by-konsist-and-name-at-file-level-when-all-declarations-are-KoAnnotationProvider")
.declarations(includeNested = true)
.filterIsInstance<KoModifierProvider>()
// then
sut.assert { it.hasModifiers() }
}
@Test
fun `assert-suppress-by-name-at-file-level-when-all-declarations-are-KoAnnotationProvider`() {
// given
val sut =
getSnippetFile("assert-suppress-by-name-at-file-level-when-all-declarations-are-KoAnnotationProvider")
.declarations(includeNested = true)
.filterIsInstance<KoModifierProvider>()
// then
sut.assert { it.hasModifiers() }
}
@Test
fun `assert-suppress-by-konsist-and-name-at-declaration-parent-level-when-all-declarations-are-KoAnnotationProvider`() {
// given
val sut =
getSnippetFile("assert-suppress-by-konsist-and-name-at-declaration-parent-level-when-all-declarations-are-KoAnnotationProvider")
.declarations(includeNested = true)
.filterIsInstance<KoModifierProvider>()
// then
sut.assert { it.hasModifiers() }
}
@Test
fun `assert-suppress-by-name-at-declaration-parent-level-when-all-declarations-are-KoAnnotationProvider`() {
// given
val sut =
getSnippetFile("assert-suppress-by-name-at-declaration-parent-level-when-all-declarations-are-KoAnnotationProvider")
.declarations(includeNested = true)
.filterIsInstance<KoModifierProvider>()
// then
sut.assert { it.hasModifiers() }
}
@Test
fun `assert-suppress-by-konsist-and-name-at-declaration-level-when-all-declarations-are-KoAnnotationProvider`() {
// given
val sut =
getSnippetFile("assert-suppress-by-konsist-and-name-at-declaration-level-when-all-declarations-are-KoAnnotationProvider")
.declarations(includeNested = true)
.filterIsInstance<KoModifierProvider>()
// then
sut.assert { it.hasModifiers() }
}
@Test
fun `assert-suppress-by-name-at-declaration-level-when-all-declarations-are-KoAnnotationProvider`() {
// given
val sut =
getSnippetFile("assert-suppress-by-name-at-declaration-level-when-all-declarations-are-KoAnnotationProvider")
.declarations(includeNested = true)
.filterIsInstance<KoModifierProvider>()
// then
sut.assert { it.hasModifiers() }
}
@Test
fun `assert-suppress-by-konsist-and-name-at-declaration-parent-level-when-it-is-not-KoAnnotationProvider`() {
// given
val sut =
getSnippetFile("assert-suppress-by-konsist-and-name-at-declaration-parent-level-when-it-is-not-KoAnnotationProvider")
.declarations(includeNested = true)
.filterIsInstance<KoPropertyProvider>()
// then
sut.assert { it.containsProperty("otherProperty") }
}
@Test
fun `assert-suppress-by-name-at-declaration-parent-level-when-it-is-not-KoAnnotationProvider`() {
// given
val sut =
getSnippetFile("assert-suppress-by-name-at-declaration-parent-level-when-it-is-not-KoAnnotationProvider")
.declarations(includeNested = true)
.filterIsInstance<KoPropertyProvider>()
// then
sut.assert { it.containsProperty("otherProperty") }
}
@Test
fun `assert-suppress-by-konsist-and-name-at-file-level-when-it-is-not-KoAnnotationProvider`() {
// given
val sut =
getSnippetFile("assert-suppress-by-konsist-and-name-at-file-level-when-it-is-not-KoAnnotationProvider")
.declarations(includeNested = true)
.filterIsInstance<KoPropertyProvider>()
// then
sut.assert { it.containsProperty("otherProperty") }
}
@Test
fun `assert-suppress-by-name-at-file-level-when-it-is-not-KoAnnotationProvider`() {
// given
val sut =
getSnippetFile("assert-suppress-by-name-at-file-level-when-it-is-not-KoAnnotationProvider")
.declarations(includeNested = true)
.filterIsInstance<KoPropertyProvider>()
// then
sut.assert { it.containsProperty("otherProperty") }
}
@Test
fun `assert-suppress-by-konsist-and-name-at-declaration-level-when-it-is-at-not-KoAnnotationProvider-declaration`() {
// given
val sut =
getSnippetFile("assert-suppress-by-konsist-and-name-at-declaration-level-when-it-is-at-not-KoAnnotationProvider-declaration")
.declarations(includeNested = true)
.filterIsInstance<KoPropertyProvider>()
// then
sut.assert { it.containsProperty("otherProperty") }
}
@Test
fun `assert-suppress-by-name-at-declaration-level-when-it-is-at-not-KoAnnotationProvider-declaration`() {
// given
val sut =
getSnippetFile("assert-suppress-by-name-at-declaration-level-when-it-is-at-not-KoAnnotationProvider-declaration")
.declarations(includeNested = true)
.filterIsInstance<KoPropertyProvider>()
// then
sut.assert { it.containsProperty("otherProperty") }
}
@Test
fun `assert-suppress-by-konsist-and-name-at-declaration-parent-level-when-it-is-at-not-KoAnnotationProvider-declaration`() {
// given
val sut =
getSnippetFile(
"assert-suppress-by-konsist-and-name-at-declaration-parent-level-when-it-is-at-not-KoAnnotationProvider-declaration",
)
.declarations(includeNested = true)
.filterIsInstance<KoPropertyProvider>()
// then
sut.assert { it.containsProperty("otherProperty") }
}
@Test
fun `assert-suppress-by-name-at-declaration-parent-level-when-it-is-at-not-KoAnnotationProvider-declaration`() {
// given
val sut =
getSnippetFile("assert-suppress-by-name-at-declaration-parent-level-when-it-is-at-not-KoAnnotationProvider-declaration")
.declarations(includeNested = true)
.filterIsInstance<KoPropertyProvider>()
// then
sut.assert { it.containsProperty("otherProperty") }
}
@Test
fun `assert-suppress-by-konsist-and-name-at-file-level-when-it-is-at-not-KoAnnotationProvider-declaration`() {
// given
val sut =
getSnippetFile("assert-suppress-by-konsist-and-name-at-file-level-when-it-is-at-not-KoAnnotationProvider-declaration")
.declarations(includeNested = true)
.filterIsInstance<KoPropertyProvider>()
// then
sut.assert { it.containsProperty("otherProperty") }
}
@Test
fun `assert-suppress-by-name-at-file-level-when-it-is-at-not-KoAnnotationProvider-declaration`() {
// given
val sut =
getSnippetFile("assert-suppress-by-name-at-file-level-when-it-is-at-not-KoAnnotationProvider-declaration")
.declarations(includeNested = true)
.filterIsInstance<KoPropertyProvider>()
// then
sut.assert { it.containsProperty("otherProperty") }
}
@Test
fun `assert-suppress-with-few-parameters`() {
// given
val sut =
getSnippetFile("assert-suppress-with-few-parameters")
.declarations(includeNested = true)
.filterIsInstance<KoModifierProvider>()
// then
sut.assert { it.hasModifiers() }
}
private fun getSnippetFile(fileName: String) =
TestSnippetProvider.getSnippetKoScope("core/verify/koproviderassert/snippet/", fileName)
}
| 8 | null | 26 | 995 | 603d19e179f59445c5f4707c1528a438e4595136 | 13,616 | konsist | Apache License 2.0 |
src/test/aoc2023/Day24Test.kt | nibarius | 154,152,607 | false | {"Kotlin": 984647} | package test.aoc2023
import aoc2023.Day24
import org.junit.Assert.assertEquals
import org.junit.Test
import resourceAsList
class Day24Test {
private val exampleInput = """
19, 13, 30 @ -2, 1, -2
18, 19, 22 @ -1, -1, -2
20, 25, 34 @ -2, -2, -4
12, 31, 28 @ -1, -2, -1
20, 19, 15 @ 1, -5, -3
""".trimIndent().split("\n")
@Test
fun testPartOneExample1() {
val day24 = Day24(exampleInput)
assertEquals(2, day24.solvePart1(7, 27))
}
@Test
fun partOneRealInput() {
val day24 = Day24(resourceAsList("2023/day24.txt"))
assertEquals(15107, day24.solvePart1())
}
@Test
fun testPartTwoExample1() {
val day24 = Day24(exampleInput)
assertEquals(47, day24.solvePart2())
}
@Test
fun partTwoRealInput() {
val day24 = Day24(resourceAsList("2023/day24.txt"))
assertEquals(856642398547748, day24.solvePart2())
}
} | 0 | Kotlin | 0 | 6 | b55af885eeb0000fb054fe485f401729f018f025 | 960 | aoc | MIT License |
app/src/main/java/com/givekesh/raters/utils/diff/CurrenciesDiffCallBack.kt | jinxul | 311,699,312 | false | null | package com.givekesh.raters.utils.diff
import androidx.recyclerview.widget.DiffUtil
import com.givekesh.raters.data.models.CurrenciesModel
class CurrenciesDiffCallBack(
private val oldList: MutableList<CurrenciesModel>,
private val newList: List<CurrenciesModel>
) : DiffUtil.Callback() {
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
override fun areItemsTheSame(
oldItemPosition: Int,
newItemPosition: Int
): Boolean = oldList[oldItemPosition].alpha3 == newList[newItemPosition].alpha3
override fun areContentsTheSame(
oldItemPosition: Int,
newItemPosition: Int
): Boolean = oldList[oldItemPosition] == newList[newItemPosition]
} | 0 | Kotlin | 0 | 1 | 4d913ff52171f96c9b29d681e14631346bf32135 | 755 | Raters | Apache License 2.0 |
persistence-common/src/main/kotlin/com/github/dean535/excel/convertor/EntityConvertor.kt | chaodai535 | 345,480,058 | false | null | package com.github.dean535.excel.convertor
import com.github.dean535.files.convert.CellConverter
import javax.persistence.EntityManager
class EntityConvertor : CellConverter {
lateinit var em: EntityManager
lateinit var name: String
lateinit var fieldName: String
override fun convert(value: String, obj: Any): Any {
val hql = "SELECT e from $name e where e.${fieldName} = :value"
val entity = kotlin.runCatching { em.createQuery(hql).setParameter("value", value).singleResult }
return if (entity.isSuccess) {
entity.getOrNull()!!
} else {
TODO("if not found, create new one")
}
}
} | 0 | Kotlin | 0 | 0 | 2382998ffaf4125f7e096b8bf820451d921d73a3 | 668 | persistence | Apache License 2.0 |
app/src/main/java/com/example/stufffmanager/logic/Repository.kt | Aliceweizhentian | 856,875,660 | false | {"Kotlin": 43099} | package com.example.stufffmanager.logic
import android.util.Log
import androidx.lifecycle.liveData
import com.example.staffmanager.logic.model.AnnoucementResponse
import com.example.staffmanager.logic.model.LoginRequest
import com.example.staffmanager.logic.model.LoginResponse
import com.example.staffmanager.logic.network.StuffNetwork
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
object Repository {
fun login(loginRequest: LoginRequest) = liveData(Dispatchers.IO) {
val result = try {
val response = StuffNetwork.login(loginRequest)
if(response.success)
{
Log.d("cici","login请求发送并成功")
//这个result会返回参数内的值
Result.success(response)
} else {
Log.d("cici","login请求失败 ${response.toString()}")
Result.failure(RuntimeException("request error is ${response.code}"))
}
}
catch (e:Exception){
Result.failure(RuntimeException("i dont know why"))
}
emit(result)
}
fun getAnnoucement() = liveData(Dispatchers.IO) {
Log.d("cici", "now get announcement")
val result = try {
val response = StuffNetwork.getAnnouncement()
if (response.success) {
Log.d("cici", "announcement请求成功")
Result.success(response)
}
else{
Log.d("cici","announcement请求失败")
Result.failure(RuntimeException("request error is ${response.toString()}"))
}
}catch(e : Exception){
Result.failure(e)
}
emit(result)
}
}
| 0 | Kotlin | 0 | 0 | d0cc719923375648371cd389e4130d9f3349934d | 1,759 | StuffManagerApp | Apache License 2.0 |
gson-support/src/test/java/com/chibatching/kotpref/gsonpref/GsonSupportTest.kt | ligi | 99,931,955 | false | null | package com.chibatching.kotpref.gsonpref
import android.content.Context
import android.content.SharedPreferences
import com.chibatching.kotpref.Kotpref
import com.chibatching.kotpref.KotprefModel
import com.google.gson.Gson
import org.assertj.core.api.Assertions.assertThat
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import java.util.*
@RunWith(RobolectricTestRunner::class)
class GsonSupportTest {
companion object {
fun createDefaultContent(): Content
= Content("default title", "contents write here", createDate(2017, 1, 5))
fun createDate(year: Int, month: Int, day: Int): Date =
Calendar.getInstance().apply {
set(year, month, day)
set(Calendar.HOUR, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}.time
}
class Example : KotprefModel() {
var content by gsonPref(createDefaultContent())
var nullableContent: Content? by gsonNullablePref()
}
lateinit var example: Example
lateinit var context: Context
lateinit var pref: SharedPreferences
@Before
fun setUp() {
context = RuntimeEnvironment.application
Kotpref.init(context)
Kotpref.gson = Gson()
example = Example()
pref = example.preferences
pref.edit().clear().commit()
}
@After
fun tearDown() {
example.clear()
}
@Test
fun gsonPrefDefaultIsDefined() {
assertThat(example.content).isEqualTo(createDefaultContent())
}
@Test
fun setGsonPrefSetCausePreferenceUpdate() {
example.content = Content("new title", "this is new content", createDate(2017, 1, 25))
assertThat(example.content).isEqualTo(Content("new title", "this is new content", createDate(2017, 1, 25)))
assertThat(example.content).isEqualTo(Kotpref.gson?.fromJson(pref.getString("content", ""), Content::class.java))
}
@Test
fun gsonNullablePrefDefaultIsNull() {
assertThat(example.nullableContent).isNull()
}
@Test
fun gsonNullablePrefCausePreferenceUpdate() {
example.nullableContent = Content("nullable content", "this is not null", createDate(2017, 1, 20))
assertThat(example.nullableContent).isEqualTo(Content("nullable content", "this is not null", createDate(2017, 1, 20)))
assertThat(example.nullableContent).isEqualTo(Kotpref.gson?.fromJson(pref.getString("nullableContent", ""), Content::class.java))
}
@Test
fun gsonNullablePrefSetNull() {
fun setNull() {
example.nullableContent = null
}
setNull()
assertThat(example.nullableContent).isNull()
assertThat(example.nullableContent).isEqualTo(Kotpref.gson?.fromJson(pref.getString("nullableContent", ""), Content::class.java))
}
}
| 0 | null | 0 | 1 | ba47e1bb3dc7500bd978f244ba358ffdeb477d79 | 3,064 | Kotpref | Apache License 2.0 |
eth/abi/src/commonMain/kotlin/kosh/eth/abi/dsl/AbiArrayDsl.kt | niallkh | 855,100,709 | false | {"Kotlin": 1845307, "Swift": 768} | package kosh.eth.abi.dsl
import kosh.eth.abi.coder.AbiType
@AbiDsl
public class AbiArrayDsl {
internal lateinit var type: AbiType
private fun set(abiType: AbiType) {
require(::type.isInitialized.not())
type = abiType
}
@AbiDsl
public fun uint256() {
set(AbiType.UInt.UInt256)
}
@AbiDsl
public fun uint32() {
set(AbiType.UInt.UInt32)
}
@AbiDsl
public fun uint8() {
set(AbiType.UInt.UInt8)
}
@AbiDsl
public fun int256() {
set(AbiType.Int.Int256)
}
@AbiDsl
public fun bytes4() {
set(AbiType.FixedBytes.Bytes4)
}
@AbiDsl
public fun bytes32() {
set(AbiType.FixedBytes.Bytes32)
}
@AbiDsl
public fun bytes(size: UInt? = null) {
if (size == null) {
set(AbiType.DynamicBytes)
} else {
set(AbiType.FixedBytes(size))
}
}
@AbiDsl
public fun address() {
set(AbiType.Address)
}
@AbiDsl
public fun string() {
set(AbiType.DynamicString)
}
@AbiDsl
public fun bool() {
set(AbiType.Bool)
}
@AbiDsl
public fun tuple(
typeName: String? = null,
@AbiDsl block: AbiTupleDsl.() -> Unit,
) {
val params = AbiTupleDsl().apply(block)
set(AbiType.Tuple(typeName, params.parameters))
}
@AbiDsl
public fun array(
size: UInt? = null,
@AbiDsl block: AbiArrayDsl.() -> Unit,
) {
val type = AbiArrayDsl().apply(block)
if (size == null) {
set(AbiType.DynamicArray(type.type))
} else {
set(AbiType.FixedArray(size = size, type = type.type))
}
}
}
| 0 | Kotlin | 0 | 3 | 2be90c7ce7775a76d44fac4cae3a6777d6e9c7f7 | 1,729 | kosh | MIT License |
src/net/azib/photos/cast/MainActivity.kt | realdubb | 74,255,356 | true | {"Kotlin": 13768} | package net.azib.photos.cast
import android.content.Intent
import android.content.Intent.ACTION_VIEW
import android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
import android.net.Uri
import android.os.Bundle
import android.support.v4.view.MenuItemCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.app.MediaRouteActionProvider
import android.view.GestureDetector
import android.view.Menu
import android.view.MotionEvent
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import kotlinx.android.synthetic.main.activity_main.*
import java.text.SimpleDateFormat
import java.util.*
class MainActivity : AppCompatActivity() {
lateinit var gestureDetector: GestureDetector
companion object {
lateinit var cast: CastClient
}
override fun onCreate(state: Bundle?) {
super.onCreate(state)
if (resources.getBoolean(R.bool.portrait_only))
requestedOrientation = SCREEN_ORIENTATION_PORTRAIT
setContentView(R.layout.activity_main)
try {
cast.activity = this
}
catch (e: UninitializedPropertyAccessException) {
cast = CastClient(this)
}
path.setAdapter(PhotoDirsSuggestionAdapter(this))
path.setText(state?.getString("path") ?: SimpleDateFormat("yyyy").format(Date()))
path.setOnItemClickListener { parent, view, pos, id -> castPhotos() }
castPhotosButton.setOnClickListener { castPhotos() }
assignCommand(nextButton, "next")
assignCommand(prevButton, "prev")
assignCommand(pauseButton, "pause")
assignCommand(nextMoreButton, "next:10")
assignCommand(prevMoreButton, "prev:10")
assignCommand(markDeleteButton, "mark:delete")
assignCommand(markRedButton, "mark:red")
assignCommand(markYellowButton, "mark:yellow")
assignCommand(markGreenButton, "mark:green")
assignCommand(markBlueButton, "mark:blue")
assignCommand(mark0Button, "mark:0")
assignCommand(mark1Button, "mark:1")
assignCommand(mark2Button, "mark:2")
assignCommand(mark3Button, "mark:3")
assignCommand(mark4Button, "mark:4")
assignCommand(mark5Button, "mark:5")
randomSwitch.setOnClickListener { cast.sendCommand(if (randomSwitch.isChecked) "rnd" else "seq") }
styleSwitch.setOnClickListener { cast.sendCommand(if (styleSwitch.isChecked) "style:cover" else "style:contain") }
gestureDetector = GestureDetector(this, GestureListener())
}
class GestureListener : GestureDetector.SimpleOnGestureListener() {
override fun onDown(e: MotionEvent) = true
override fun onFling(e1: MotionEvent, e2: MotionEvent, velocityX: Float, velocityY: Float): Boolean {
if (Math.abs(velocityX) < Math.abs(velocityY)) return false
if (velocityX > 0)
cast.sendCommand("prev")
else
cast.sendCommand("next")
return true
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
val command = intent.action
if (command != null) cast.sendCommand(command)
}
override fun onSaveInstanceState(state: Bundle) {
super.onSaveInstanceState(state)
state.putString("path", path.text.toString())
}
override fun onTouchEvent(event: MotionEvent): Boolean {
gestureDetector.onTouchEvent(event)
return super.onTouchEvent(event)
}
private fun assignCommand(button: Button, command: String) {
button.setOnClickListener { cast.sendCommand(command) }
}
private fun castPhotos() {
cast.sendCommand((if (randomSwitch.isChecked) "rnd:" else "seq:") + path.text)
path.clearFocus()
(getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(path.windowToken, 0)
}
override fun onResume() {
super.onResume()
cast.startDiscovery()
}
override fun onPause() {
if (isFinishing) cast.stopDiscovery()
super.onPause()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.main, menu)
val mediaRouteMenuItem = menu.findItem(R.id.media_route_menu_item)
val mediaRouteActionProvider = MenuItemCompat.getActionProvider(mediaRouteMenuItem) as MediaRouteActionProvider
// Set the MediaRouteActionProvider selector for device discovery.
mediaRouteActionProvider.routeSelector = cast.mediaRouteSelector
return true
}
fun onMessageReceived(parts: List<String>) {
status.text = parts[0]
if (parts.size == 2)
status.setOnClickListener { startActivity(Intent(ACTION_VIEW, Uri.parse(parts[1]))) }
else
status.isClickable = false
}
}
| 0 | Kotlin | 0 | 0 | a6d684a86d13aa5b9ddd846f498adce5a51a9f8a | 4,563 | synology-cast-photos-android | Apache License 2.0 |
core/src/main/java/br/ufs/nubankchallenge/core/infrastructure/errorhandlers/RestErrorsHandler.kt | ubiratansoares | 111,469,213 | false | null | package br.ufs.nubankchallenge.core.infrastructure.errorhandlers
import br.ufs.nubankchallenge.core.domain.errors.InfrastructureError
import br.ufs.nubankchallenge.core.domain.errors.InfrastructureError.RemoteSystemDown
import br.ufs.nubankchallenge.core.domain.errors.InfrastructureError.UndesiredResponse
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.ObservableTransformer
import retrofit2.HttpException
/**
*
* Created by @ubiratanfsoares
*
*/
class RestErrorsHandler : ObservableTransformer<Any, Any> {
override fun apply(upstream: Observable<Any>): ObservableSource<Any> {
return upstream.onErrorResumeNext(this::handleIfRestError)
}
private fun handleIfRestError(throwable: Throwable): Observable<Any> {
if (isRestError(throwable)) return toInfrastructureError(throwable as HttpException)
return Observable.error(throwable)
}
private fun toInfrastructureError(restError: HttpException): Observable<Any> {
val infraError = mapErrorWith(restError.code())
return Observable.error(infraError)
}
private fun mapErrorWith(code: Int): InfrastructureError {
return when (code) {
in 500..511 -> RemoteSystemDown
else -> UndesiredResponse
}
}
private fun isRestError(throwable: Throwable): Boolean {
return throwable is HttpException
}
} | 0 | Kotlin | 5 | 20 | d0b863a338b04ef40068f005c72b9d8e8335bc26 | 1,415 | nubank-challenge | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.