repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
garmax1/material-flashlight
|
app/src/main/java/co/garmax/materialflashlight/features/modes/SosMode.kt
|
1
|
3409
|
package co.garmax.materialflashlight.features.modes
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.disposables.Disposable
import java.util.concurrent.TimeUnit
/**
* Implement SOS
*/
class SosMode(private val workerScheduler: Scheduler) : ModeBase() {
private var disposableInterval: Disposable? = null
override fun start() {
disposableInterval = Observable.interval(
0,
SOS_PERIOD.toLong(),
TimeUnit.MILLISECONDS,
workerScheduler
)
.doOnNext { setBrightness(MAX_LIGHT_VOLUME) }
.delay(STROBE_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MIN_LIGHT_VOLUME) } // 1 short
.delay(DELAY_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MAX_LIGHT_VOLUME) }
.delay(STROBE_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MIN_LIGHT_VOLUME) } // 1 short
.delay(DELAY_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MAX_LIGHT_VOLUME) }
.delay(STROBE_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MIN_LIGHT_VOLUME) } // 1 short
.delay(DELAY_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MAX_LIGHT_VOLUME) }
.delay(STROBE_LONG.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MIN_LIGHT_VOLUME) } // 1 long
.delay(DELAY_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MAX_LIGHT_VOLUME) }
.delay(STROBE_LONG.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MIN_LIGHT_VOLUME) } // 1 long
.delay(DELAY_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MAX_LIGHT_VOLUME) }
.delay(STROBE_LONG.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MIN_LIGHT_VOLUME) } // 1 long
.delay(DELAY_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MAX_LIGHT_VOLUME) }
.delay(STROBE_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MIN_LIGHT_VOLUME) } // 1 short
.delay(DELAY_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MAX_LIGHT_VOLUME) }
.delay(STROBE_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MIN_LIGHT_VOLUME) } // 1 short
.delay(DELAY_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MAX_LIGHT_VOLUME) }
.delay(STROBE_SHORT.toLong(), TimeUnit.MILLISECONDS)
.doOnNext { setBrightness(MIN_LIGHT_VOLUME) } // 1 short
.delay(DELAY_LONG.toLong(), TimeUnit.MILLISECONDS)
.subscribe { }
}
override fun stop() {
setBrightness(MIN_LIGHT_VOLUME)
disposableInterval?.dispose()
}
override fun checkPermissions(): Boolean {
return true
}
companion object {
private const val STROBE_SHORT = 400
private const val STROBE_LONG = 900
private const val DELAY_SHORT = 400
private const val DELAY_LONG = 2500
private const val SOS_PERIOD =
(STROBE_SHORT * 3 + DELAY_SHORT * 3) * 2 + 2 * DELAY_SHORT + 3 * STROBE_LONG + DELAY_LONG
}
}
|
apache-2.0
|
86a5585e71bb7098bd451ef3ce1ac82d
| 42.164557 | 101 | 0.62511 | 4.309735 | false | false | false | false |
Heiner1/AndroidAPS
|
core/src/test/java/info/nightscout/androidaps/utils/CryptoUtilTest.kt
|
1
|
4215
|
package info.nightscout.androidaps.utils
import info.nightscout.androidaps.TestBase
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.not
import org.junit.Assert
import org.junit.Assume.assumeThat
import org.junit.Test
// https://stackoverflow.com/questions/52344522/joseexception-couldnt-create-aes-gcm-nopadding-cipher-illegal-key-size
// https://stackoverflow.com/questions/47708951/can-aes-256-work-on-android-devices-with-api-level-26
// Java prior to Oracle Java 8u161 does not have policy for 256 bit AES - but Android support it
// when test is run in Vanilla JVM without policy - Invalid key size exception is thrown
fun assumeAES256isSupported(cryptoUtil: CryptoUtil) {
cryptoUtil.lastException?.message?.let { exceptionMessage ->
assumeThat("Upgrade your testing environment Java (OpenJDK or Java 8u161) and JAVA_HOME - AES 256 is supported by Android so this exception should not happen!", exceptionMessage, not(containsString("key size")))
}
}
@Suppress("SpellCheckingInspection")
class CryptoUtilTest : TestBase() {
private var cryptoUtil: CryptoUtil = CryptoUtil(aapsLogger)
@Test
fun testFixedSaltCrypto() {
val salt = byteArrayOf(
-33, -29, 16, -19, 99, -111, -3, 2, 116, 106, 47, 38, -54, 11, -77, 28,
111, -15, -65, -110, 4, -32, -29, -70, -95, -88, -53, 19, 87, -103, 123, -15)
val password = "thisIsFixedPassword"
val payload = "FIXED-PAYLOAD"
val encrypted = cryptoUtil.encrypt(password, salt, payload)
assumeAES256isSupported(cryptoUtil)
Assert.assertNotNull(encrypted)
val decrypted = cryptoUtil.decrypt(password, salt, encrypted!!)
assumeAES256isSupported(cryptoUtil)
Assert.assertEquals(decrypted, payload)
}
@Test
fun testStandardCrypto() {
val salt = cryptoUtil.mineSalt()
val password = "topSikret"
val payload = "{what:payloadYouWantToProtect}"
val encrypted = cryptoUtil.encrypt(password, salt, payload)
assumeAES256isSupported(cryptoUtil)
Assert.assertNotNull(encrypted)
val decrypted = cryptoUtil.decrypt(password, salt, encrypted!!)
assumeAES256isSupported(cryptoUtil)
Assert.assertEquals(decrypted, payload)
}
@Test
fun testHashVector() {
val payload = "{what:payloadYouWantToProtect}"
val hash = cryptoUtil.sha256(payload)
Assert.assertEquals(hash, "a1aafe3ed6cc127e6d102ddbc40a205147230e9cfd178daf108c83543bbdcd13")
}
@Test
fun testHmac() {
val payload = "{what:payloadYouWantToProtect}"
val password = "topSikret"
val expectedHmac = "ea2213953d0f2e55047cae2d23fb4f0de1b805d55e6271efa70d6b85fb692bea" // generated using other HMAC tool
val hash = cryptoUtil.hmac256(payload, password)
Assert.assertEquals(hash, expectedHmac)
}
@Test
fun testPlainPasswordCheck() {
Assert.assertTrue(cryptoUtil.checkPassword("same", "same"))
Assert.assertFalse(cryptoUtil.checkPassword("same", "other"))
}
@Test
fun testHashedPasswordCheck() {
Assert.assertTrue(cryptoUtil.checkPassword("givenSecret", cryptoUtil.hashPassword("givenSecret")))
Assert.assertFalse(cryptoUtil.checkPassword("givenSecret", cryptoUtil.hashPassword("otherSecret")))
Assert.assertTrue(cryptoUtil.checkPassword("givenHashToCheck", "hmac:7fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:a0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1"))
Assert.assertFalse(cryptoUtil.checkPassword("givenMashToCheck", "hmac:7fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:a0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1"))
Assert.assertFalse(cryptoUtil.checkPassword("givenHashToCheck", "hmac:0fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:a0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1"))
Assert.assertFalse(cryptoUtil.checkPassword("givenHashToCheck", "hmac:7fe5f9c7b4b97c5d32d5cfad9d07473543a9938dc07af48a46dbbb49f4f68c12:b0c7cee14312bbe31b51359a67f0d2dfdf46813f319180269796f1f617a64be1"))
}
}
|
agpl-3.0
|
16147d7a106354ee1cb491801702ea3d
| 44.322581 | 219 | 0.74306 | 3.300705 | false | true | false | false |
Heiner1/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/activities/fragments/TreatmentsExtendedBolusesFragment.kt
|
1
|
11979
|
package info.nightscout.androidaps.activities.fragments
import android.annotation.SuppressLint
import android.os.Bundle
import android.util.SparseArray
import android.view.*
import androidx.core.util.forEach
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.fragments.TreatmentsExtendedBolusesFragment.RecyclerViewAdapter.ExtendedBolusesViewHolder
import info.nightscout.androidaps.database.AppRepository
import info.nightscout.androidaps.database.entities.ExtendedBolus
import info.nightscout.androidaps.database.entities.UserEntry.Action
import info.nightscout.androidaps.database.entities.UserEntry.Sources
import info.nightscout.androidaps.database.entities.ValueWithUnit
import info.nightscout.androidaps.database.interfaces.end
import info.nightscout.androidaps.database.transactions.InvalidateExtendedBolusTransaction
import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusFragmentBinding
import info.nightscout.androidaps.databinding.TreatmentsExtendedbolusItemBinding
import info.nightscout.androidaps.events.EventExtendedBolusChange
import info.nightscout.androidaps.extensions.iobCalc
import info.nightscout.androidaps.extensions.isInProgress
import info.nightscout.androidaps.extensions.toVisibility
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.ProfileFunction
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.logging.UserEntryLogger
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.utils.ActionModeHelper
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.kotlin.plusAssign
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class TreatmentsExtendedBolusesFragment : DaggerFragment() {
private val disposable = CompositeDisposable()
private val millsToThePast = T.days(30).msecs()
@Inject lateinit var activePlugin: ActivePlugin
@Inject lateinit var rxBus: RxBus
@Inject lateinit var rh: ResourceHelper
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var fabricPrivacy: FabricPrivacy
@Inject lateinit var profileFunction: ProfileFunction
@Inject lateinit var dateUtil: DateUtil
@Inject lateinit var aapsSchedulers: AapsSchedulers
@Inject lateinit var uel: UserEntryLogger
@Inject lateinit var repository: AppRepository
private var _binding: TreatmentsExtendedbolusFragmentBinding? = null
// This property is only valid between onCreateView and onDestroyView.
private val binding get() = _binding!!
private var menu: Menu? = null
private lateinit var actionHelper: ActionModeHelper<ExtendedBolus>
private var showInvalidated = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
TreatmentsExtendedbolusFragmentBinding.inflate(inflater, container, false).also { _binding = it }.root
@SuppressLint("NotifyDataSetChanged")
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
actionHelper = ActionModeHelper(rh, activity, this)
actionHelper.setUpdateListHandler { binding.recyclerview.adapter?.notifyDataSetChanged() }
actionHelper.setOnRemoveHandler { removeSelected(it) }
setHasOptionsMenu(true)
binding.recyclerview.setHasFixedSize(true)
binding.recyclerview.layoutManager = LinearLayoutManager(view.context)
binding.recyclerview.emptyView = binding.noRecordsText
binding.recyclerview.loadingView = binding.progressBar
}
fun swapAdapter() {
val now = System.currentTimeMillis()
binding.recyclerview.isLoading = true
disposable += if (showInvalidated)
repository
.getExtendedBolusDataIncludingInvalidFromTime(now - millsToThePast, false)
.observeOn(aapsSchedulers.main)
.subscribe { list -> binding.recyclerview.swapAdapter(RecyclerViewAdapter(list), true) }
else
repository
.getExtendedBolusDataFromTime(now - millsToThePast, false)
.observeOn(aapsSchedulers.main)
.subscribe { list -> binding.recyclerview.swapAdapter(RecyclerViewAdapter(list), true) }
}
@Synchronized
override fun onResume() {
super.onResume()
swapAdapter()
disposable += rxBus
.toObservable(EventExtendedBolusChange::class.java)
.observeOn(aapsSchedulers.io)
.debounce(1L, TimeUnit.SECONDS)
.subscribe({ swapAdapter() }, fabricPrivacy::logException)
}
@Synchronized
override fun onPause() {
super.onPause()
actionHelper.finish()
disposable.clear()
}
@Synchronized
override fun onDestroyView() {
super.onDestroyView()
binding.recyclerview.adapter = null // avoid leaks
_binding = null
}
private inner class RecyclerViewAdapter(private var extendedBolusList: List<ExtendedBolus>) : RecyclerView.Adapter<ExtendedBolusesViewHolder>() {
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ExtendedBolusesViewHolder {
val v = LayoutInflater.from(viewGroup.context).inflate(R.layout.treatments_extendedbolus_item, viewGroup, false)
return ExtendedBolusesViewHolder(v)
}
override fun onBindViewHolder(holder: ExtendedBolusesViewHolder, position: Int) {
val extendedBolus = extendedBolusList[position]
holder.binding.ns.visibility = (extendedBolus.interfaceIDs.nightscoutId != null).toVisibility()
holder.binding.ph.visibility = (extendedBolus.interfaceIDs.pumpId != null).toVisibility()
holder.binding.invalid.visibility = extendedBolus.isValid.not().toVisibility()
val newDay = position == 0 || !dateUtil.isSameDayGroup(extendedBolus.timestamp, extendedBolusList[position - 1].timestamp)
holder.binding.date.visibility = newDay.toVisibility()
holder.binding.date.text = if (newDay) dateUtil.dateStringRelative(extendedBolus.timestamp, rh) else ""
if (extendedBolus.isInProgress(dateUtil)) {
holder.binding.time.text = dateUtil.timeString(extendedBolus.timestamp)
holder.binding.time.setTextColor(rh.gac(context, R.attr.activeColor))
} else {
holder.binding.time.text = dateUtil.timeRangeString(extendedBolus.timestamp, extendedBolus.end)
holder.binding.time.setTextColor(holder.binding.insulin.currentTextColor)
}
val profile = profileFunction.getProfile(extendedBolus.timestamp) ?: return
holder.binding.duration.text = rh.gs(R.string.format_mins, T.msecs(extendedBolus.duration).mins())
holder.binding.insulin.text = rh.gs(R.string.formatinsulinunits, extendedBolus.amount)
val iob = extendedBolus.iobCalc(System.currentTimeMillis(), profile, activePlugin.activeInsulin)
holder.binding.iob.text = rh.gs(R.string.formatinsulinunits, iob.iob)
holder.binding.ratio.text = rh.gs(R.string.pump_basebasalrate, extendedBolus.rate)
if (iob.iob != 0.0) holder.binding.iob.setTextColor(rh.gac(context, R.attr.activeColor)) else holder.binding.iob.setTextColor(holder.binding.insulin.currentTextColor)
holder.binding.cbRemove.visibility = (extendedBolus.isValid && actionHelper.isRemoving).toVisibility()
if (actionHelper.isRemoving) {
holder.binding.cbRemove.setOnCheckedChangeListener { _, value ->
actionHelper.updateSelection(position, extendedBolus, value)
}
holder.binding.root.setOnClickListener {
holder.binding.cbRemove.toggle()
actionHelper.updateSelection(position, extendedBolus, holder.binding.cbRemove.isChecked)
}
holder.binding.cbRemove.isChecked = actionHelper.isSelected(position)
}
}
override fun getItemCount() = extendedBolusList.size
inner class ExtendedBolusesViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = TreatmentsExtendedbolusItemBinding.bind(itemView)
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
this.menu = menu
inflater.inflate(R.menu.menu_treatments_extended_bolus, menu)
super.onCreateOptionsMenu(menu, inflater)
}
private fun updateMenuVisibility() {
menu?.findItem(R.id.nav_hide_invalidated)?.isVisible = showInvalidated
menu?.findItem(R.id.nav_show_invalidated)?.isVisible = !showInvalidated
}
override fun onPrepareOptionsMenu(menu: Menu) {
updateMenuVisibility()
return super.onPrepareOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.nav_remove_items -> actionHelper.startRemove()
R.id.nav_show_invalidated -> {
showInvalidated = true
updateMenuVisibility()
ToastUtils.showToastInUiThread(context, rh.gs(R.string.show_invalidated_records))
swapAdapter()
true
}
R.id.nav_hide_invalidated -> {
showInvalidated = false
updateMenuVisibility()
ToastUtils.showToastInUiThread(context, rh.gs(R.string.hide_invalidated_records))
swapAdapter()
true
}
else -> false
}
}
private fun getConfirmationText(selectedItems: SparseArray<ExtendedBolus>): String {
if (selectedItems.size() == 1) {
val bolus = selectedItems.valueAt(0)
return rh.gs(R.string.extended_bolus) + "\n" +
"${rh.gs(R.string.date)}: ${dateUtil.dateAndTimeString(bolus.timestamp)}"
}
return rh.gs(R.string.confirm_remove_multiple_items, selectedItems.size())
}
private fun removeSelected(selectedItems: SparseArray<ExtendedBolus>) {
activity?.let { activity ->
OKDialog.showConfirmation(activity, rh.gs(R.string.removerecord), getConfirmationText(selectedItems), Runnable {
selectedItems.forEach { _, extendedBolus ->
uel.log(
Action.EXTENDED_BOLUS_REMOVED, Sources.Treatments,
ValueWithUnit.Timestamp(extendedBolus.timestamp),
ValueWithUnit.Insulin(extendedBolus.amount),
ValueWithUnit.UnitPerHour(extendedBolus.rate),
ValueWithUnit.Minute(TimeUnit.MILLISECONDS.toMinutes(extendedBolus.duration).toInt())
)
disposable += repository.runTransactionForResult(InvalidateExtendedBolusTransaction(extendedBolus.id))
.subscribe(
{ aapsLogger.debug(LTag.DATABASE, "Removed extended bolus $extendedBolus") },
{ aapsLogger.error(LTag.DATABASE, "Error while invalidating extended bolus", it) })
}
actionHelper.finish()
})
}
}
}
|
agpl-3.0
|
12058218994f8335ab543973eb4da501
| 47.497976 | 178 | 0.705318 | 5.045914 | false | false | false | false |
jainsahab/AndroidSnooper
|
Snooper/src/main/java/com/prateekj/snooper/networksnooper/helper/HttpCallRenderer.kt
|
1
|
1076
|
package com.prateekj.snooper.networksnooper.helper
import androidx.fragment.app.Fragment
import com.prateekj.snooper.networksnooper.activity.HttpCallTab
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.ERROR
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.HEADERS
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.REQUEST
import com.prateekj.snooper.networksnooper.activity.HttpCallTab.RESPONSE
import com.prateekj.snooper.networksnooper.views.HttpCallView
class HttpCallRenderer(private val httpCallView: HttpCallView, private val hasError: Boolean) {
fun getTabs(): List<HttpCallTab> {
return if (hasError) {
listOf(ERROR, REQUEST, HEADERS)
} else listOf(RESPONSE, REQUEST, HEADERS)
}
fun getFragment(position: Int): Fragment {
if (position == 0 && this.hasError)
return httpCallView.getExceptionFragment()
if (position == 0)
return httpCallView.getResponseBodyFragment()
return if (position == 1) httpCallView.getRequestBodyFragment() else httpCallView.getHeadersFragment()
}
}
|
apache-2.0
|
fcff42636f48114501bba3a93aca9876
| 38.888889 | 106 | 0.79368 | 4.409836 | false | false | false | false |
Hexworks/zircon
|
zircon.jvm.examples/src/main/kotlin/org/hexworks/zircon/examples/fragments/table/tableData.kt
|
1
|
15418
|
package org.hexworks.zircon.examples.fragments.table
import org.hexworks.cobalt.databinding.api.extension.toProperty
import kotlin.random.Random
fun Int.randomPersons(): List<Person> =
List(this) { randomPerson() }
fun randomPerson(): Person =
Person(
randomFirstName(),
randomLastName(),
Random.nextInt(18, 80),
Height.values().random(),
randomWage().toProperty()
)
internal fun randomWage() = Random.nextInt(Person.MIN_WAGE, Person.MAX_WAGE)
private fun randomFirstName(): String =
firstNames.random()
private fun randomLastName(): String =
lastNames.random()
// Some names, most of which are credited to https://github.com/imsky/wordlists
private val firstNames: List<String> =
listOf(
"Alice",
"Bob",
"Charlie",
"Donald",
"Alfred",
"Barkley",
"Barrymore",
"Belvedere",
"Bertuccio",
"Brunton",
"Bullimore",
"Cadbury",
"Figaro",
"Jeeves",
"Jenkins",
"Leporello",
"Merriman",
"Passepartout",
"Poole",
"Simonides",
"Callan",
"Roland",
"Saul",
"Jalen",
"Brycen",
"Ryland",
"Lawrence",
"Davis",
"Rowen",
"Zain",
"Ermias",
"Jaime",
"Duke",
"Stetson",
"Alec",
"Yusuf",
"Case",
"Trenton",
"Callen",
"Ariel",
"Jasiah",
"Soren",
"Dennis",
"Donald",
"Keith",
"Izaiah",
"Lewis",
"Kylan",
"Kobe",
"Makai",
"Rayan",
"Ford",
"Zaire",
"Landyn",
"Roy",
"Bo",
"Chris",
"Jamari",
"Ares",
"Mohammad",
"Darius",
"Drake",
"Tripp",
"Marcelo",
"Samson",
"Dustin",
"Layton",
"Gerardo",
"Johan",
"Kaysen",
"Keaton",
"Reece",
"Chandler",
"Lucca",
"Mack",
"Baylor",
"Kannon",
"Marvin",
"Huxley",
"Nixon",
"Tony",
"Cason",
"Mauricio",
"Quentin",
"Erin",
"Eve",
"Kathryn",
"Renata",
"Kayleigh",
"Emmy",
"Celine",
"Francesca",
"Fernanda",
"April",
"Shelby",
"Poppy",
"Colette",
"Meadow",
"Nia",
"Sierra",
"Cheyenne",
"Edith",
"Oaklynn",
"Kennedi",
"Abby",
"Danna",
"Jazlyn",
"Alessia",
"Mikayla",
"Alondra",
"Addilyn",
"Leona",
"Mckinley",
"Carter",
"Maren",
"Sylvia",
"Alejandra",
"Ariya",
"Astrid",
"Adrianna",
"Charli",
"Imani",
"Maryam",
"Christina",
"Stevie",
"Maia",
"Adelina",
"Dream",
"Aisha",
"Alanna",
"Itzel",
"Azalea",
"Katelyn",
"Kylee",
"Leslie",
"Madilynn",
"Myra",
"Virginia",
"Remy"
)
private val lastNames: List<String> =
listOf(
"Abbey",
"Abram",
"Acker",
"Adair",
"Adam",
"Adams",
"Adamson",
"Addison",
"Adkins",
"Aiken",
"Akerman",
"Akers",
"Albert",
"Albertson",
"Albinson",
"Alexander",
"Alfredson",
"Alger",
"Alvin",
"Anderson",
"Andrews",
"Ansel",
"Appleton",
"Archer",
"Armistead",
"Arnold",
"Arrington",
"Arthur",
"Arthurson",
"Ashworth",
"Atkins",
"Atkinson",
"Austin",
"Avery",
"Babcock",
"Bagley",
"Bailey",
"Baker",
"Baldwin",
"Bancroft",
"Banister",
"Banks",
"Banner",
"Barber",
"Barker",
"Barlow",
"Bass",
"Bates",
"Baxter",
"Beake",
"Beasley",
"Beck",
"Beckett",
"Beckham",
"Bell",
"Bellamy",
"Bennett",
"Benson",
"Bentley",
"Benton",
"Bernard",
"Berry",
"Beverley",
"Bird",
"Black",
"Blackburn",
"Bond",
"Bonham",
"Bourke",
"Braddock",
"Bradford",
"Bradley",
"Brand",
"Brandon",
"Breckenridge",
"Brewer",
"Brewster",
"Brigham",
"Bristol",
"Brook",
"Brooke",
"Brown",
"Bryson",
"Buckley",
"Bullard",
"Bullock",
"Burnham",
"Burrell",
"Burton",
"Bush",
"Byrd",
"Cantrell",
"Carl",
"Carlisle",
"Carlyle",
"Carman",
"Carpenter",
"Carter",
"Cartwright",
"Carver",
"Caulfield",
"Causer",
"Chadwick",
"Chamberlain",
"Chance",
"Chandler",
"Chapman",
"Chase",
"Cheshire",
"Chlarke",
"Church",
"Clark",
"Clarkson",
"Clay",
"Clayton",
"Clemens",
"Clifford",
"Clifton",
"Cline",
"Clinton",
"Close",
"Coburn",
"Coke",
"Colbert",
"Cole",
"Coleman",
"Colton",
"Comstock",
"Constable",
"Cook",
"Cooke",
"Cookson",
"Cooper",
"Corey",
"Cornell",
"Courtney",
"Cox",
"Crawford",
"Crewe",
"Croft",
"Cropper",
"Cross",
"Crouch",
"Cummins",
"Curtis",
"Dalton",
"Danell",
"Daniel",
"Darby",
"Darrell",
"Darwin",
"Daubney",
"David",
"Davidson",
"Davies",
"Davis",
"Dawson",
"Day",
"Dean",
"Deering",
"Delaney",
"Denman",
"Dennel",
"Dennell",
"Derby",
"Derrick",
"Devin",
"Devine",
"Dickens",
"Dickenson",
"Dickinson",
"Dickman",
"Donalds",
"Donaldson",
"Downer",
"Draper",
"Dudley",
"Duke",
"Dunn",
"Durand",
"Durant",
"Dustin",
"Dwight",
"Dyer",
"Dyson",
"Eason",
"Easton",
"Eaton",
"Edgar",
"Edison",
"Edwards",
"Edwarson",
"Eliot",
"Eliott",
"Elliott",
"Ellis",
"Ellison",
"Emerson",
"Emmett",
"Endicott",
"Ericson",
"Evanson",
"Evelyn",
"Everett",
"Fairbarn",
"Fairburn",
"Fairchild",
"Fay",
"Fields",
"Fisher",
"Fleming",
"Fletcher",
"Ford",
"Forest",
"Forester",
"Forrest",
"Foss",
"Foster",
"Fox",
"Frank",
"Franklin",
"Freeman",
"Frost",
"Fry",
"Fuller",
"Gardener",
"Gardner",
"Garfield",
"Garland",
"Garner",
"Garnet",
"Garrard",
"Garrett",
"Garry",
"Geary",
"Gibbs",
"Gibson",
"Gilbert",
"Giles",
"Gilliam",
"Gladwin",
"Glover",
"Goddard",
"Goode",
"Goodwin",
"Granger",
"Grant",
"Gray",
"Green",
"Greene",
"Griffin",
"Gully",
"Hackett",
"Hadaway",
"Haden",
"Haggard",
"Haight",
"Hailey",
"Haley",
"Hall",
"Hallman",
"Hamilton",
"Hamm",
"Hancock",
"Hanley",
"Hanson",
"Hardy",
"Harford",
"Hargrave",
"Harlan",
"Harley",
"Harlow",
"Harman",
"Harper",
"Hart",
"Harvey",
"Hathaway",
"Hawk",
"Hawking",
"Hawkins",
"Hayes",
"Haywood",
"Heath",
"Hedley",
"Henderson",
"Henry",
"Henson",
"Herbert",
"Herman",
"Hewitt",
"Hibbert",
"Hicks",
"Hightower",
"Hill",
"Hilton",
"Hobbes",
"Hobbs",
"Hobson",
"Hodges",
"Hodson",
"Holmes",
"Holt",
"Hooker",
"Hooper",
"Hope",
"Hopper",
"Horn",
"Horne",
"Horton",
"House",
"Howard",
"Howe",
"Hudson",
"Hughes",
"Hull",
"Hume",
"Hunt",
"Hunter",
"Hurst",
"Huxley",
"Huxtable",
"Ingram",
"Irvin",
"Irvine",
"Irving",
"Irwin",
"Ivers",
"Jack",
"Jackson",
"Jacobs",
"Jacobson",
"James",
"Jameson",
"Jamison",
"Janson",
"Jardine",
"Jarrett",
"Jarvis",
"Jefferson",
"Jeffries",
"Jekyll",
"Jenkins",
"Jepson",
"Jerome",
"Jinks",
"Johns",
"Johnson",
"Jones",
"Jordan",
"Judd",
"Kay",
"Keen",
"Kelsey",
"Kemp",
"Kendall",
"Kendrick",
"Kerry",
"Kersey",
"Key",
"Kidd",
"King",
"Kingsley",
"Kingston",
"Kinsley",
"Kipling",
"Kirby",
"Knight",
"Lacy",
"Lamar",
"Landon",
"Lane",
"Langley",
"Larson",
"Lawson",
"Leach",
"Leavitt",
"Lee",
"Leigh",
"Leon",
"Levitt",
"Lewin",
"Lincoln",
"Lindsay",
"Linton",
"Little",
"Loman",
"London",
"Long",
"Lovell",
"Lowell",
"Lowry",
"Lucas",
"Lyndon",
"Lynn",
"Lyon",
"Madison",
"Mann",
"Mark",
"Marley",
"Marlow",
"Marshall",
"Martel",
"Martin",
"Mason",
"Massey",
"Masters",
"Masterson",
"Mathers",
"Matthews",
"May",
"Mayes",
"Maynard",
"Meadows",
"Mercer",
"Merchant",
"Merrill",
"Merritt",
"Michael",
"Michaels",
"Michaelson",
"Mills",
"Mitchell",
"Moore",
"Morris",
"Myers",
"Nathanson",
"Neville",
"Newell",
"Newman",
"Newport",
"Nichols",
"Nicholson",
"Nielson",
"Niles",
"Nixon",
"Noel",
"Norman",
"Oakley",
"Odell",
"Ogden",
"Oliver",
"Oliverson",
"Olson",
"Osborne",
"Otis",
"Overton",
"Page",
"Parker",
"Parsons",
"Patrick",
"Patton",
"Paulson",
"Payne",
"Pearce",
"Pearson",
"Penny",
"Perkins",
"Perry",
"Peters",
"Peyton",
"Philips",
"Pickering",
"Pierce",
"Pierson",
"Piper",
"Pitts",
"Platt",
"Poole",
"Pope",
"Porcher",
"Porter",
"Potter",
"Pound",
"Powers",
"Prescott",
"Pressley",
"Preston",
"Pryor",
"Purcell",
"Putnam",
"Quigley",
"Quincy",
"Radcliff",
"Raines",
"Ramsey",
"Randall",
"Ray",
"Reed",
"Reeve",
"Rey",
"Reynolds",
"Rhodes",
"Richards",
"Rider",
"Ridley",
"Roach",
"Robbins",
"Robert",
"Roberts",
"Robertson",
"Rogers",
"Rogerson",
"Rollins",
"Roscoe",
"Ross",
"Rowe",
"Rowland",
"Royce",
"Roydon",
"Rush",
"Russell",
"Ryder",
"Sadler",
"Salvage",
"Sampson",
"Samson",
"Samuel",
"Sanders",
"Sandford",
"Sanford",
"Sargent",
"Savage",
"Sawyer",
"Scarlett",
"Seaver",
"Sergeant",
"Shelby",
"Shine",
"Simmons",
"Simon",
"Simons",
"Simonson",
"Simpkin",
"Simpson",
"Sims",
"Sinclair",
"Skinner",
"Slater",
"Smalls",
"Smedley",
"Smith",
"Snelling",
"Snider",
"Sniders",
"Snyder",
"Spalding",
"Sparks",
"Spear",
"Spears",
"Spence",
"Spencer",
"Spooner",
"Spurling",
"Stacy",
"Stafford",
"Stamp",
"Stanton",
"Statham",
"Steed",
"Steele",
"Stephens",
"Stephenson",
"Stern",
"Stone",
"Strange",
"Strickland",
"Stringer",
"Stroud",
"Strudwick",
"Styles",
"Summerfield",
"Summers",
"Sumner",
"Sutton",
"Sydney",
"Tailor",
"Tanner",
"Tash",
"Tasker",
"Tate",
"Taylor",
"Teel",
"Tennyson",
"Terrell",
"Terry",
"Thacker",
"Thatcher",
"Thomas",
"Thompson",
"Thorne",
"Thorpe",
"Timberlake",
"Townsend",
"Tracy",
"Travers",
"Travis",
"Trent",
"Trevis",
"Truman",
"Tucker",
"Tuft",
"Turnbull",
"Turner",
"Tyler",
"Tyrell",
"Tyson",
"Underhill",
"Underwood",
"Upton",
"Vance",
"Vernon",
"Victor",
"Vincent",
"Walker",
"Wallace",
"Walsh",
"Walton",
"Warner",
"Warren",
"Warwick",
"Washington",
"Waters",
"Wayne",
"Weaver",
"Webb",
"Webster",
"Wells",
"Wembley",
"West",
"Wheeler",
"Whitaker",
"White",
"Whitney",
"Whittle",
"Wickham",
"Wilcox",
"Wilkie",
"Wilkins",
"Willard",
"Williams",
"Williamson",
"Willis",
"Wilson",
"Winchester",
"Winfield",
"Winship",
"Winslow",
"Winston",
"Winthrop",
"Witherspoon",
"Wolf",
"Wolfe",
"Womack",
"Woodcock",
"Woodham",
"Woodward",
"Wortham",
"Wray",
"Wright",
"Wyatt",
"Wyndham",
"Yates",
"York",
"Young"
)
|
apache-2.0
|
e2e7ae77b2a02c9cf53915c92b35f2e0
| 17.421744 | 79 | 0.358737 | 3.43156 | false | false | false | false |
JetBrains/ideavim
|
vim-engine/src/main/kotlin/com/maddyhome/idea/vim/vimscript/model/commands/Command.kt
|
1
|
8150
|
/*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.vimscript.model.commands
import com.maddyhome.idea.vim.api.ExecutionContext
import com.maddyhome.idea.vim.api.VimCaret
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.api.injector
import com.maddyhome.idea.vim.command.CommandFlags
import com.maddyhome.idea.vim.command.OperatorArguments
import com.maddyhome.idea.vim.common.TextRange
import com.maddyhome.idea.vim.diagnostic.vimLogger
import com.maddyhome.idea.vim.ex.ExException
import com.maddyhome.idea.vim.ex.MissingArgumentException
import com.maddyhome.idea.vim.ex.MissingRangeException
import com.maddyhome.idea.vim.ex.NoArgumentAllowedException
import com.maddyhome.idea.vim.ex.NoRangeAllowedException
import com.maddyhome.idea.vim.ex.ranges.LineRange
import com.maddyhome.idea.vim.ex.ranges.Ranges
import com.maddyhome.idea.vim.helper.Msg
import com.maddyhome.idea.vim.helper.exitVisualMode
import com.maddyhome.idea.vim.helper.inVisualMode
import com.maddyhome.idea.vim.helper.mode
import com.maddyhome.idea.vim.helper.noneOfEnum
import com.maddyhome.idea.vim.helper.subMode
import com.maddyhome.idea.vim.helper.vimStateMachine
import com.maddyhome.idea.vim.vimscript.model.Executable
import com.maddyhome.idea.vim.vimscript.model.ExecutionResult
import com.maddyhome.idea.vim.vimscript.model.VimLContext
import java.util.*
sealed class Command(var commandRanges: Ranges, val commandArgument: String) : Executable {
override lateinit var vimContext: VimLContext
abstract val argFlags: CommandHandlerFlags
protected open val optFlags: EnumSet<CommandFlags> = noneOfEnum()
private val logger = vimLogger<Command>()
abstract class ForEachCaret(ranges: Ranges, argument: String = "") : Command(ranges, argument) {
abstract fun processCommand(
editor: VimEditor,
caret: VimCaret,
context: ExecutionContext,
operatorArguments: OperatorArguments
): ExecutionResult
}
abstract class SingleExecution(ranges: Ranges, argument: String = "") : Command(ranges, argument) {
abstract fun processCommand(
editor: VimEditor,
context: ExecutionContext,
operatorArguments: OperatorArguments,
): ExecutionResult
}
@Throws(ExException::class)
override fun execute(editor: VimEditor, context: ExecutionContext): ExecutionResult {
checkRanges()
checkArgument()
if (editor.inVisualMode && Flag.SAVE_VISUAL !in argFlags.flags) {
editor.exitVisualMode()
}
if (argFlags.access == Access.WRITABLE && !editor.isDocumentWritable()) {
logger.info("Trying to modify readonly document")
return ExecutionResult.Error
}
val operatorArguments = OperatorArguments(
editor.vimStateMachine.isOperatorPending,
0,
editor.mode,
editor.subMode,
)
val runCommand = { runCommand(editor, context, operatorArguments) }
return when (argFlags.access) {
Access.WRITABLE -> injector.application.runWriteAction(runCommand)
Access.READ_ONLY -> injector.application.runReadAction(runCommand)
Access.SELF_SYNCHRONIZED -> runCommand.invoke()
}
}
private fun runCommand(editor: VimEditor, context: ExecutionContext, operatorArguments: OperatorArguments): ExecutionResult {
var result: ExecutionResult = ExecutionResult.Success
when (this) {
is ForEachCaret -> {
editor.forEachNativeCaret(
{ caret ->
if (result is ExecutionResult.Success) {
result = processCommand(editor, caret, context, operatorArguments)
}
},
true
)
}
is SingleExecution -> result = processCommand(editor, context, operatorArguments)
}
return result
}
private fun checkRanges() {
if (RangeFlag.RANGE_FORBIDDEN == argFlags.rangeFlag && commandRanges.size() != 0) {
injector.messages.showStatusBarMessage(injector.messages.message(Msg.e_norange))
throw NoRangeAllowedException()
}
if (RangeFlag.RANGE_REQUIRED == argFlags.rangeFlag && commandRanges.size() == 0) {
injector.messages.showStatusBarMessage(injector.messages.message(Msg.e_rangereq))
throw MissingRangeException()
}
if (RangeFlag.RANGE_IS_COUNT == argFlags.rangeFlag) {
commandRanges.setDefaultLine(1)
}
}
private fun checkArgument() {
if (ArgumentFlag.ARGUMENT_FORBIDDEN == argFlags.argumentFlag && commandArgument.isNotBlank()) {
injector.messages.showStatusBarMessage(injector.messages.message(Msg.e_argforb))
throw NoArgumentAllowedException()
}
if (ArgumentFlag.ARGUMENT_REQUIRED == argFlags.argumentFlag && commandArgument.isBlank()) {
injector.messages.showStatusBarMessage(injector.messages.message(Msg.e_argreq))
throw MissingArgumentException()
}
}
enum class RangeFlag {
/**
* Indicates that a range must be specified with this command
*/
RANGE_REQUIRED,
/**
* Indicates that a range is optional for this command
*/
RANGE_OPTIONAL,
/**
* Indicates that a range can't be specified for this command
*/
RANGE_FORBIDDEN,
/**
* Indicates that the command takes a count, not a range - effects default
* Works like RANGE_OPTIONAL
*/
RANGE_IS_COUNT
}
enum class ArgumentFlag {
/**
* Indicates that an argument must be specified with this command
*/
ARGUMENT_REQUIRED,
/**
* Indicates that an argument is optional for this command
*/
ARGUMENT_OPTIONAL,
/**
* Indicates that an argument can't be specified for this command
*/
ARGUMENT_FORBIDDEN
}
enum class Access {
/**
* Indicates that this is a command that modifies the editor
*/
WRITABLE,
/**
* Indicates that this command does not modify the editor
*/
READ_ONLY,
/**
* Indicates that this command handles writability by itself
*/
SELF_SYNCHRONIZED
}
enum class Flag {
/**
* This command should not exit visual mode.
*
* Vim exits visual mode before command execution, but in this case :action will work incorrect.
* With this flag visual mode will not be exited while command execution.
*/
SAVE_VISUAL
}
data class CommandHandlerFlags(
val rangeFlag: RangeFlag,
val argumentFlag: ArgumentFlag,
val access: Access,
val flags: Set<Flag>,
)
fun flags(rangeFlag: RangeFlag, argumentFlag: ArgumentFlag, access: Access, vararg flags: Flag) =
CommandHandlerFlags(rangeFlag, argumentFlag, access, flags.toSet())
fun getLine(editor: VimEditor): Int = commandRanges.getLine(editor)
fun getLine(editor: VimEditor, caret: VimCaret): Int = commandRanges.getLine(editor, caret)
fun getCount(editor: VimEditor, defaultCount: Int, checkCount: Boolean): Int {
val count = if (checkCount) countArgument else -1
val res = commandRanges.getCount(editor, count)
return if (res == -1) defaultCount else res
}
fun getCount(editor: VimEditor, caret: VimCaret, defaultCount: Int, checkCount: Boolean): Int {
val count = commandRanges.getCount(editor, caret, if (checkCount) countArgument else -1)
return if (count == -1) defaultCount else count
}
fun getLineRange(editor: VimEditor): LineRange = commandRanges.getLineRange(editor, -1)
fun getLineRange(editor: VimEditor, caret: VimCaret, checkCount: Boolean = false): LineRange {
return commandRanges.getLineRange(editor, caret, if (checkCount) countArgument else -1)
}
fun getTextRange(editor: VimEditor, checkCount: Boolean): TextRange {
val count = if (checkCount) countArgument else -1
return commandRanges.getTextRange(editor, count)
}
fun getTextRange(editor: VimEditor, caret: VimCaret, checkCount: Boolean): TextRange {
return commandRanges.getTextRange(editor, caret, if (checkCount) countArgument else -1)
}
private val countArgument: Int
get() = commandArgument.toIntOrNull() ?: -1
}
|
mit
|
b126d3a2cd26b2d55213556a6302ab39
| 32.265306 | 127 | 0.718037 | 4.41974 | false | false | false | false |
wordpress-mobile/WordPress-Android
|
WordPress/src/main/java/org/wordpress/android/ui/bloggingreminders/EpilogueBuilder.kt
|
1
|
3826
|
package org.wordpress.android.ui.bloggingreminders
import org.wordpress.android.R.drawable
import org.wordpress.android.R.string
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersItem.Caption
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersItem.EmphasizedText
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersItem.HighEmphasisText
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersItem.Illustration
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersItem.Title
import org.wordpress.android.ui.bloggingreminders.BloggingRemindersViewModel.UiState.PrimaryButton
import org.wordpress.android.ui.utils.HtmlMessageUtils
import org.wordpress.android.ui.utils.ListItemInteraction
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.ListFormatterUtils
import org.wordpress.android.util.LocaleManagerWrapper
import java.time.DayOfWeek
import java.time.format.TextStyle
import javax.inject.Inject
class EpilogueBuilder @Inject constructor(
private val dayLabelUtils: DayLabelUtils,
private val localeManagerWrapper: LocaleManagerWrapper,
private val listFormatterUtils: ListFormatterUtils,
private val htmlMessageUtils: HtmlMessageUtils
) {
fun buildUiItems(
bloggingRemindersModel: BloggingRemindersUiModel?
): List<BloggingRemindersItem> {
val enabledDays = bloggingRemindersModel?.enabledDays ?: setOf()
val title = when {
enabledDays.isEmpty() -> UiStringRes(string.blogging_reminders_epilogue_not_set_title)
else -> UiStringRes(string.blogging_reminders_epilogue_title)
}
val body = when (enabledDays.size) {
ZERO -> UiStringRes(string.blogging_reminders_epilogue_body_no_reminders)
SEVEN_DAYS -> UiStringText(
htmlMessageUtils.getHtmlMessageFromStringFormatResId(
string.blogging_reminders_epilogue_body_everyday_with_time,
bloggingRemindersModel?.getNotificationTime()
)
)
else -> {
val numberOfTimes = (dayLabelUtils.buildLowercaseNTimesLabel(bloggingRemindersModel) ?: "").toBold()
val selectedDays = listFormatterUtils.formatList(enabledDays.print().map { it.toBold() })
UiStringText(
htmlMessageUtils.getHtmlMessageFromStringFormatResId(
string.blogging_reminders_epilogue_body_days_with_time,
numberOfTimes,
selectedDays,
bloggingRemindersModel?.getNotificationTime().toString().toBold()
)
)
}
}
return listOf(
Illustration(drawable.img_illustration_bell_yellow_96dp),
Title(title),
HighEmphasisText(EmphasizedText(body, false)),
Caption(UiStringRes(string.blogging_reminders_epilogue_caption))
)
}
fun buildPrimaryButton(
onDone: () -> Unit
): PrimaryButton {
return PrimaryButton(
UiStringRes(string.blogging_reminders_done),
enabled = true,
ListItemInteraction.create(onDone)
)
}
private fun Set<DayOfWeek>.print(): List<String> {
return this.sorted().map {
it.getDisplayName(TextStyle.FULL, localeManagerWrapper.getLocale())
}
}
private fun String.toBold(): String {
return this.let { "<b>$it</b>" }
}
companion object {
private const val ZERO = 0
private const val SEVEN_DAYS = 7
}
}
|
gpl-2.0
|
ff1fd4b3da8329510cc6df482ad18a21
| 40.139785 | 116 | 0.669367 | 5.108144 | false | false | false | false |
KotlinNLP/SimpleDNN
|
src/test/kotlin/core/functionalities/activations/HardTanhSpec.kt
|
1
|
1635
|
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package core.functionalities.activations
import com.kotlinnlp.simplednn.core.functionalities.activations.HardTanh
import com.kotlinnlp.simplednn.simplemath.ndarray.dense.DenseNDArrayFactory
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertTrue
/**
*
*/
class HardTanhSpec: Spek({
describe("an HardTanh activation function") {
val activationFunction = HardTanh
val array = DenseNDArrayFactory.arrayOf(doubleArrayOf(0.0, 0.1, 0.01, -0.1, -0.01, 1.0, 10.0, -1.0, -10.0))
val activatedArray = activationFunction.f(array)
context("f") {
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(
0.0, 0.1, 0.01, -0.1, -0.01, 1.0, 1.0, -1.0, -1.0
))
it("should return the expected values") {
assertTrue { expectedArray.equals(activatedArray, tolerance = 1.0e-08) }
}
}
context("dfOptimized") {
val dfArray = activationFunction.dfOptimized(activatedArray)
val expectedArray = DenseNDArrayFactory.arrayOf(doubleArrayOf(
1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0
))
it("should return the expected values") {
assertTrue { expectedArray.equals(dfArray, tolerance = 1.0e-08) }
}
}
}
})
|
mpl-2.0
|
90763935d4a3c75286da0a8432caaa11
| 31.058824 | 111 | 0.656269 | 3.665919 | false | false | false | false |
WhisperSystems/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/keyboard/sticker/StickerSearchRepository.kt
|
2
|
2006
|
package org.thoughtcrime.securesms.keyboard.sticker
import android.content.Context
import androidx.annotation.WorkerThread
import org.thoughtcrime.securesms.components.emoji.EmojiUtil
import org.thoughtcrime.securesms.database.DatabaseFactory
import org.thoughtcrime.securesms.database.EmojiSearchDatabase
import org.thoughtcrime.securesms.database.StickerDatabase
import org.thoughtcrime.securesms.database.StickerDatabase.StickerRecordReader
import org.thoughtcrime.securesms.database.model.StickerRecord
private const val RECENT_LIMIT = 24
private const val EMOJI_SEARCH_RESULTS_LIMIT = 20
class StickerSearchRepository(context: Context) {
private val emojiSearchDatabase: EmojiSearchDatabase = DatabaseFactory.getEmojiSearchDatabase(context)
private val stickerDatabase: StickerDatabase = DatabaseFactory.getStickerDatabase(context)
@WorkerThread
fun search(query: String): List<StickerRecord> {
if (query.isEmpty()) {
return StickerRecordReader(stickerDatabase.getRecentlyUsedStickers(RECENT_LIMIT)).readAll()
}
val maybeEmojiQuery: List<StickerRecord> = findStickersForEmoji(query)
val searchResults: List<StickerRecord> = emojiSearchDatabase.query(query, EMOJI_SEARCH_RESULTS_LIMIT)
.map { findStickersForEmoji(it) }
.flatten()
return maybeEmojiQuery + searchResults
}
@WorkerThread
private fun findStickersForEmoji(emoji: String): List<StickerRecord> {
val searchEmoji: String = EmojiUtil.getCanonicalRepresentation(emoji)
return EmojiUtil.getAllRepresentations(searchEmoji)
.filterNotNull()
.map { candidate -> StickerRecordReader(stickerDatabase.getStickersByEmoji(candidate)).readAll() }
.flatten()
}
}
private fun StickerRecordReader.readAll(): List<StickerRecord> {
val stickers: MutableList<StickerRecord> = mutableListOf()
use { reader ->
var record: StickerRecord? = reader.next
while (record != null) {
stickers.add(record)
record = reader.next
}
}
return stickers
}
|
gpl-3.0
|
50432c3b899d084d77400636aaf5aaba
| 35.472727 | 105 | 0.783649 | 4.477679 | false | false | false | false |
GunoH/intellij-community
|
java/java-analysis-impl/src/com/intellij/workspaceModel/ide/legacyBridge/impl/java/LanguageLevelModuleExtensionBridge.kt
|
2
|
3102
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.ide.legacyBridge.impl.java
import com.intellij.openapi.roots.LanguageLevelModuleExtensionImpl
import com.intellij.openapi.roots.ModuleExtension
import com.intellij.pom.java.LanguageLevel
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.findModuleEntity
import com.intellij.workspaceModel.ide.java.languageLevel
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridge
import com.intellij.workspaceModel.ide.legacyBridge.ModuleExtensionBridgeFactory
import com.intellij.workspaceModel.storage.VersionedEntityStorage
import com.intellij.workspaceModel.storage.MutableEntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.addJavaModuleSettingsEntity
import com.intellij.workspaceModel.storage.bridgeEntities.modifyEntity
class LanguageLevelModuleExtensionBridge private constructor(private val module: ModuleBridge,
private val entityStorage: VersionedEntityStorage,
private val diff: MutableEntityStorage?) : LanguageLevelModuleExtensionImpl(), ModuleExtensionBridge {
private var changed = false
private val moduleEntity
get() = module.findModuleEntity(entityStorage.current)
override fun setLanguageLevel(languageLevel: LanguageLevel?) {
if (diff == null) error("Cannot modify data via read-only extensions")
val moduleEntity = moduleEntity ?: error("Cannot find entity for $module")
val javaSettings = moduleEntity.javaSettings
if (javaSettings != null) {
diff.modifyEntity(javaSettings) {
this.languageLevel = languageLevel
}
}
else if (languageLevel != null) {
diff.addJavaModuleSettingsEntity(inheritedCompilerOutput = true, excludeOutput = true, compilerOutput = null,
compilerOutputForTests = null, languageLevelId = languageLevel.name, module = moduleEntity,
source = moduleEntity.entitySource)
}
}
override fun getLanguageLevel(): LanguageLevel? {
return moduleEntity?.javaSettings?.languageLevel
}
override fun isChanged(): Boolean = changed
override fun getModifiableModel(writable: Boolean): ModuleExtension {
throw UnsupportedOperationException("This method must not be called for extensions backed by workspace model")
}
override fun commit() = Unit
override fun dispose() = Unit
companion object : ModuleExtensionBridgeFactory<LanguageLevelModuleExtensionBridge> {
override fun createExtension(module: ModuleBridge,
entityStorage: VersionedEntityStorage,
diff: MutableEntityStorage?): LanguageLevelModuleExtensionBridge {
return LanguageLevelModuleExtensionBridge(module, entityStorage, diff)
}
}
}
|
apache-2.0
|
58acbf7038f624cda11aa976a8ce7106
| 50.716667 | 163 | 0.740812 | 5.931166 | false | false | false | false |
GunoH/intellij-community
|
platform/script-debugger/debugger-ui/src/DebugProcessImpl.kt
|
7
|
9507
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.debugger
import com.intellij.execution.DefaultExecutionResult
import com.intellij.execution.ExecutionResult
import com.intellij.execution.process.ProcessHandler
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.BrowserHyperlinkListener
import com.intellij.util.Url
import com.intellij.util.io.socketConnection.ConnectionStatus
import com.intellij.xdebugger.DefaultDebugProcessHandler
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.breakpoints.XBreakpointHandler
import com.intellij.xdebugger.breakpoints.XLineBreakpoint
import com.intellij.xdebugger.evaluation.XDebuggerEditorsProvider
import com.intellij.xdebugger.frame.XSuspendContext
import com.intellij.xdebugger.impl.XDebugSessionImpl
import com.intellij.xdebugger.stepping.XSmartStepIntoHandler
import org.jetbrains.concurrency.Promise
import org.jetbrains.debugger.connection.RemoteVmConnection
import org.jetbrains.debugger.connection.VmConnection
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
import java.util.concurrent.atomic.AtomicBoolean
import javax.swing.event.HyperlinkListener
interface MultiVmDebugProcess {
val mainVm: Vm?
val activeOrMainVm: Vm?
val collectVMs: List<Vm>
get() {
val mainVm = mainVm ?: return emptyList()
val result = mutableListOf<Vm>()
fun addRecursively(vm: Vm) {
if (vm.attachStateManager.isAttached) {
result.add(vm)
vm.childVMs.forEach { addRecursively(it) }
}
}
addRecursively(mainVm)
return result
}
}
abstract class DebugProcessImpl<out C : VmConnection<*>>(session: XDebugSession,
val connection: C,
private val editorsProvider: XDebuggerEditorsProvider,
private val smartStepIntoHandler: XSmartStepIntoHandler<*>? = null,
protected val executionResult: ExecutionResult? = null) : XDebugProcess(session), MultiVmDebugProcess {
@Volatile var lastStep: StepAction? = null
@Volatile protected var lastCallFrame: CallFrame? = null
@Volatile protected var isForceStep: Boolean = false
@Volatile protected var disableDoNotStepIntoLibraries: Boolean = false
// todo: file resolving: check that urlToFileCache still needed
protected val urlToFileCache: ConcurrentMap<Url, VirtualFile> = ConcurrentHashMap()
private val connectedListenerAdded = AtomicBoolean()
private val breakpointsInitiated = AtomicBoolean()
private val _breakpointHandlers: Array<XBreakpointHandler<*>> by lazy(LazyThreadSafetyMode.NONE) { createBreakpointHandlers() }
protected val realProcessHandler: ProcessHandler?
get() = executionResult?.processHandler
final override fun getSmartStepIntoHandler(): XSmartStepIntoHandler<*>? = smartStepIntoHandler
final override fun getBreakpointHandlers(): Array<out XBreakpointHandler<*>> = when (connection.state.status) {
ConnectionStatus.DISCONNECTED, ConnectionStatus.DETACHED, ConnectionStatus.CONNECTION_FAILED -> XBreakpointHandler.EMPTY_ARRAY
else -> _breakpointHandlers
}
final override fun getEditorsProvider(): XDebuggerEditorsProvider = editorsProvider
val vm: Vm?
get() = connection.vm
final override val mainVm: Vm?
get() = connection.vm
final override val activeOrMainVm: Vm?
get() = (session.suspendContext?.activeExecutionStack as? ExecutionStackView)?.suspendContext?.vm ?: mainVm
val childConnections: MutableList<VmConnection<*>> = mutableListOf()
init {
if (session is XDebugSessionImpl && executionResult is DefaultExecutionResult) {
session.addRestartActions(*executionResult.restartActions)
}
connection.stateChanged {
when (it.status) {
ConnectionStatus.DISCONNECTED, ConnectionStatus.DETACHED -> {
if (it.status == ConnectionStatus.DETACHED) {
if (realProcessHandler != null) {
// here must we must use effective process handler
processHandler.detachProcess()
}
}
getSession().stop()
}
ConnectionStatus.CONNECTION_FAILED -> {
getSession().reportMessage(it.message, MessageType.ERROR, BrowserHyperlinkListener.INSTANCE)
getSession().stop()
}
else -> getSession().rebuildViews()
}
}
}
protected abstract fun createBreakpointHandlers(): Array<XBreakpointHandler<*>>
private fun updateLastCallFrame(vm: Vm) {
lastCallFrame = vm.suspendContextManager.context?.topFrame
}
final override fun checkCanPerformCommands(): Boolean = activeOrMainVm != null
override fun isValuesCustomSorted(): Boolean = true
final override fun startStepOver(context: XSuspendContext?) {
val vm = context.vm
updateLastCallFrame(vm)
continueVm(vm, StepAction.OVER)
}
val XSuspendContext?.vm: Vm
get() = (this as? SuspendContextView)?.activeVm ?: mainVm!!
final override fun startForceStepInto(context: XSuspendContext?) {
isForceStep = true
enableBlackboxing(false, context.vm)
startStepInto(context)
}
final override fun startStepInto(context: XSuspendContext?) {
val vm = context.vm
updateLastCallFrame(vm)
continueVm(vm, StepAction.IN)
}
final override fun startStepOut(context: XSuspendContext?) {
val vm = context.vm
updateLastCallFrame(vm)
continueVm(vm, StepAction.OUT)
}
// some VM (firefox for example) doesn't implement step out correctly, so, we need to fix it
protected open fun isVmStepOutCorrect(): Boolean = true
override fun resume(context: XSuspendContext?) {
continueVm(context.vm, StepAction.CONTINUE)
}
open fun resume(vm: Vm) {
continueVm(vm, StepAction.CONTINUE)
}
/**
* You can override this method to avoid SuspendContextManager implementation, but it is not recommended.
*/
protected open fun continueVm(vm: Vm, stepAction: StepAction): Promise<*>? {
val suspendContextManager = vm.suspendContextManager
if (stepAction === StepAction.CONTINUE) {
if (suspendContextManager.context == null) {
// on resumed we ask session to resume, and session then call our "resume", but we have already resumed, so, we don't need to send "continue" message
return null
}
lastStep = null
lastCallFrame = null
urlToFileCache.clear()
enableBlackboxing(true, vm)
}
else {
lastStep = stepAction
}
return suspendContextManager.continueVm(stepAction)
}
protected open fun enableBlackboxing(state: Boolean, vm: Vm) {
disableDoNotStepIntoLibraries = !state
}
protected fun setOverlay(context: SuspendContext<*>) {
val vm = mainVm
if (context.vm == vm) {
vm.suspendContextManager.setOverlayMessage(ScriptDebuggerBundle.message("notification.content.paused.in.debugger"))
}
}
final override fun startPausing() {
activeOrMainVm!!.suspendContextManager.suspend()
.onError(RejectErrorReporter(session, ScriptDebuggerBundle.message("notification.content.cannot.pause")))
}
final override fun getCurrentStateMessage(): String = connection.state.message
final override fun getCurrentStateHyperlinkListener(): HyperlinkListener? = connection.state.messageLinkListener
override fun doGetProcessHandler(): ProcessHandler = executionResult?.processHandler ?: object : DefaultDebugProcessHandler() { override fun isSilentlyDestroyOnClose() = true }
fun saveResolvedFile(url: Url, file: VirtualFile) {
urlToFileCache.putIfAbsent(url, file)
}
open fun getLocationsForBreakpoint(breakpoint: XLineBreakpoint<*>): List<Location> = getLocationsForBreakpoint(activeOrMainVm!!, breakpoint)
open fun getLocationsForBreakpoint(vm: Vm, breakpoint: XLineBreakpoint<*>): List<Location> = throw UnsupportedOperationException()
override fun isLibraryFrameFilterSupported(): Boolean = true
// todo make final (go plugin compatibility)
override fun checkCanInitBreakpoints(): Boolean {
if (connection.state.status == ConnectionStatus.CONNECTED) {
return true
}
if (connectedListenerAdded.compareAndSet(false, true)) {
connection.stateChanged {
if (it.status == ConnectionStatus.CONNECTED) {
initBreakpoints()
}
}
}
return false
}
protected fun initBreakpoints() {
if (breakpointsInitiated.compareAndSet(false, true)) {
doInitBreakpoints()
}
}
protected open fun doInitBreakpoints() {
mainVm?.let(::beforeInitBreakpoints)
runReadAction { session.initBreakpoints() }
}
protected open fun beforeInitBreakpoints(vm: Vm) {
}
protected fun addChildVm(vm: Vm, childConnection: RemoteVmConnection<*>) {
mainVm?.childVMs?.add(vm)
childConnection.stateChanged {
if (it.status == ConnectionStatus.CONNECTION_FAILED || it.status == ConnectionStatus.DISCONNECTED || it.status == ConnectionStatus.DETACHED) {
mainVm?.childVMs?.remove(vm)
childConnections.remove(childConnection)
}
}
childConnections.add(childConnection)
mainVm?.debugListener?.childVmAdded(vm)
}
}
|
apache-2.0
|
36cf711b4e9d1d44ca629ea439a4a10a
| 35.848837 | 178 | 0.724098 | 4.94641 | false | false | false | false |
walleth/kethereum
|
erc681/src/main/kotlin/org/kethereum/erc681/ERC681Parser.kt
|
1
|
1814
|
package org.kethereum.erc681
import org.kethereum.erc831.ERC831
import org.kethereum.model.EthereumURI
import org.kethereum.uri.common.CommonEthereumURIData
import org.kethereum.uri.common.parseCommonURI
import java.math.BigDecimal
import java.math.BigInteger
private val scientificNumberRegEx = Regex("^[0-9]+(\\.[0-9]+)?(e[0-9]+)?$")
fun EthereumURI.toERC681() = parseCommonURI().toERC681()
fun ERC831.toERC681() = parseCommonURI().toERC681()
fun CommonEthereumURIData.toERC681() = let { commonURI ->
ERC681().apply {
scheme = commonURI.scheme
prefix = commonURI.prefix
chainId = commonURI.chainId
function = commonURI.function
address = commonURI.address
valid = commonURI.valid
fun String?.toBigInteger(): BigInteger? {
if (this == null) {
return null
}
if (!scientificNumberRegEx.matches(this)) {
valid = false
return null
}
return when {
contains("e") -> {
val split = split("e")
BigDecimal(split.first()).multiply(BigDecimal.TEN.pow(split[1].toIntOrNull() ?: 1)).toBigInteger()
}
contains(".") -> {
valid = false
null
}
else -> BigInteger(this)
}
}
val queryAsMap = commonURI.query.toMap() // should be improved https://github.com/walleth/kethereum/issues/25
gas = queryAsMap["gas"].toBigInteger()
value = queryAsMap["value"]?.split("-")?.first()?.toBigInteger()
functionParams = commonURI.query.filter { it.first != "gas" && it.first != "value" }
}
}
fun parseERC681(url: String) = EthereumURI(url).toERC681()
|
mit
|
f1f4cb966c333b35dc1256c27fd4523f
| 30.293103 | 118 | 0.577729 | 4.248244 | false | false | false | false |
pdvrieze/kotlinsql
|
sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/dml/impl/_BaseSelect.kt
|
1
|
3041
|
/*
* Copyright (c) 2021.
*
* This file is part of kotlinsql.
*
* This file is licenced to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You should have received a copy of the license with the source distribution.
* Alternatively, 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.pdvrieze.kotlinsql.dml.impl
import io.github.pdvrieze.kotlinsql.ddl.Column
import io.github.pdvrieze.kotlinsql.ddl.columns.PreparedStatementHelper
import io.github.pdvrieze.kotlinsql.dml.Select
abstract class _BaseSelect(override vararg val columns: Column<*, *, *>) : Select {
override val select: Select get() = this
override fun toSQL(): String = toSQL(createTablePrefixMap())
override fun toSQL(prefixMap: Map<String, String>?): String {
return when {
prefixMap != null -> toSQLMultipleTables(prefixMap)
else -> columns.joinToString("`, `",
"SELECT `",
"` FROM ${columns[0].table._name}") { it.name }
}
}
override fun setParams(statementHelper: PreparedStatementHelper, first: Int) = first
private fun tableNames() = columns.map { it.table._name }.toSortedSet()
private fun toSQLMultipleTables(prefixMap: Map<String, String>): String {
return buildString {
append("SELECT ")
columns.joinTo(this, ", ") { column -> column.name(prefixMap) }
append(" FROM ")
prefixMap.entries.joinTo(this, ", `", "`") { pair -> "${pair.key}` AS ${pair.value}" }
}
}
override fun createTablePrefixMap(): Map<String, String>? {
val tableNames = tableNames()
fun uniquePrefix(string: String, usedPrefixes: Set<String>): String {
for (i in 1..(string.length - 1)) {
string.substring(0, i).let {
if (it !in usedPrefixes) return it
}
}
for (i in 1..Int.MAX_VALUE) {
(string + i.toString()).let {
if (it !in usedPrefixes) return it
}
}
throw IllegalArgumentException("No unique prefix could be found")
}
if (tableNames.size <= 1) return null
return tableNames.let {
val seen = mutableSetOf<String>()
it.associateTo(sortedMapOf<String, String>()) { name ->
name to uniquePrefix(name, seen).apply {
seen.add(this)
}
}
}
}
}
|
apache-2.0
|
e08d57e03f4e9ad3d4565d82250c0382
| 34.788235 | 101 | 0.587964 | 4.566066 | false | false | false | false |
jk1/intellij-community
|
platform/script-debugger/debugger-ui/src/VariableView.kt
|
2
|
19864
|
// Copyright 2000-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 file.
package org.jetbrains.debugger
import com.intellij.icons.AllIcons
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.pom.Navigatable
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.util.SmartList
import com.intellij.util.ThreeState
import com.intellij.xdebugger.XExpression
import com.intellij.xdebugger.XSourcePositionWrapper
import com.intellij.xdebugger.frame.*
import com.intellij.xdebugger.frame.presentation.XKeywordValuePresentation
import com.intellij.xdebugger.frame.presentation.XNumericValuePresentation
import com.intellij.xdebugger.frame.presentation.XStringValuePresentation
import com.intellij.xdebugger.frame.presentation.XValuePresentation
import org.jetbrains.concurrency.*
import org.jetbrains.debugger.values.*
import java.util.*
import java.util.concurrent.atomic.AtomicBoolean
import java.util.regex.Pattern
import javax.swing.Icon
fun VariableView(variable: Variable, context: VariableContext): VariableView = VariableView(variable.name, variable, context)
class VariableView(override val variableName: String, private val variable: Variable, private val context: VariableContext) : XNamedValue(variableName), VariableContext {
@Volatile private var value: Value? = null
// lazy computed
private var _memberFilter: MemberFilter? = null
@Volatile private var remainingChildren: List<Variable>? = null
@Volatile private var remainingChildrenOffset: Int = 0
override fun watchableAsEvaluationExpression(): Boolean = context.watchableAsEvaluationExpression()
override val viewSupport: DebuggerViewSupport
get() = context.viewSupport
override val parent: VariableContext = context
override val memberFilter: Promise<MemberFilter>
get() = context.viewSupport.getMemberFilter(this)
override val evaluateContext: EvaluateContext
get() = context.evaluateContext
override val scope: Scope?
get() = context.scope
override val vm: Vm?
get() = context.vm
override fun computePresentation(node: XValueNode, place: XValuePlace) {
value = variable.value
if (value != null) {
computePresentation(value!!, node)
return
}
if (variable !is ObjectProperty || variable.getter == null) {
// it is "used" expression (WEB-6779 Debugger/Variables: Automatically show used variables)
evaluateContext.evaluate(variable.name)
.onSuccess(node) {
if (it.wasThrown) {
setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(it.value, null), null, node)
}
else {
value = it.value
computePresentation(it.value, node)
}
}
.onError(node) { setEvaluatedValue(viewSupport.transformErrorOnGetUsedReferenceValue(null, it.message), it.message, node) }
return
}
node.setPresentation(null, object : XValuePresentation() {
override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) {
renderer.renderValue("\u2026")
}
}, false)
node.setFullValueEvaluator(object : XFullValueEvaluator(" (invoke getter)") {
override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) {
var valueModifier = variable.valueModifier
var nonProtoContext = context
while (nonProtoContext is VariableView && nonProtoContext.variableName == PROTOTYPE_PROP) {
valueModifier = nonProtoContext.variable.valueModifier
nonProtoContext = nonProtoContext.parent
}
valueModifier!!.evaluateGet(variable, evaluateContext)
.onSuccess(node) {
callback.evaluated("")
setEvaluatedValue(it, null, node)
}
}
}.setShowValuePopup(false))
}
private fun setEvaluatedValue(value: Value?, error: String?, node: XValueNode) {
if (value == null) {
node.setPresentation(AllIcons.Debugger.Db_primitive, null, error ?: "Internal Error", false)
}
else {
this.value = value
computePresentation(value, node)
}
}
private fun computePresentation(value: Value, node: XValueNode) {
when (value.type) {
ValueType.OBJECT, ValueType.NODE -> context.viewSupport.computeObjectPresentation((value as ObjectValue), variable, context, node, icon)
ValueType.FUNCTION -> node.setPresentation(icon, ObjectValuePresentation(trimFunctionDescription(value)), true)
ValueType.ARRAY -> context.viewSupport.computeArrayPresentation(value, variable, context, node, icon)
ValueType.BOOLEAN, ValueType.NULL, ValueType.UNDEFINED -> node.setPresentation(icon, XKeywordValuePresentation(value.valueString!!), false)
ValueType.NUMBER -> node.setPresentation(icon, createNumberPresentation(value.valueString!!), false)
ValueType.STRING -> {
node.setPresentation(icon, XStringValuePresentation(value.valueString!!), false)
// isTruncated in terms of debugger backend, not in our terms (i.e. sometimes we cannot control truncation),
// so, even in case of StringValue, we check value string length
if ((value is StringValue && value.isTruncated) || value.valueString!!.length > XValueNode.MAX_VALUE_LENGTH) {
node.setFullValueEvaluator(MyFullValueEvaluator(value))
}
}
else -> node.setPresentation(icon, null, value.valueString!!, true)
}
}
override fun computeChildren(node: XCompositeNode) {
node.setAlreadySorted(true)
if (value !is ObjectValue) {
node.addChildren(XValueChildrenList.EMPTY, true)
return
}
val list = remainingChildren
if (list != null) {
val to = Math.min(remainingChildrenOffset + XCompositeNode.MAX_CHILDREN_TO_SHOW, list.size)
val isLast = to == list.size
node.addChildren(createVariablesList(list, remainingChildrenOffset, to, this, _memberFilter), isLast)
if (!isLast) {
node.tooManyChildren(list.size - to)
remainingChildrenOffset += XCompositeNode.MAX_CHILDREN_TO_SHOW
}
return
}
val objectValue = value as ObjectValue
val hasNamedProperties = objectValue.hasProperties() != ThreeState.NO
val hasIndexedProperties = objectValue.hasIndexedProperties() != ThreeState.NO
val promises = SmartList<Promise<*>>()
val additionalProperties = viewSupport.computeAdditionalObjectProperties(objectValue, variable, this, node)
if (additionalProperties != null) {
promises.add(additionalProperties)
}
// we don't support indexed properties if additional properties added - behavior is undefined if object has indexed properties and additional properties also specified
if (hasIndexedProperties) {
promises.add(computeIndexedProperties(objectValue as ArrayValue, node, !hasNamedProperties && additionalProperties == null))
}
if (hasNamedProperties) {
// named properties should be added after additional properties
if (additionalProperties == null || additionalProperties.state != Promise.State.PENDING) {
promises.add(computeNamedProperties(objectValue, node, !hasIndexedProperties && additionalProperties == null))
}
else {
promises.add(additionalProperties.thenAsync(node) { computeNamedProperties(objectValue, node, true) })
}
}
if (hasIndexedProperties == hasNamedProperties || additionalProperties != null) {
promises.all().processed(node) { node.addChildren(XValueChildrenList.EMPTY, true) }
}
}
abstract class ObsolescentIndexedVariablesConsumer(protected val node: XCompositeNode) : IndexedVariablesConsumer() {
override val isObsolete: Boolean
get() = node.isObsolete
}
private fun computeIndexedProperties(value: ArrayValue, node: XCompositeNode, isLastChildren: Boolean): Promise<*> {
return value.getIndexedProperties(0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, object : ObsolescentIndexedVariablesConsumer(node) {
override fun consumeRanges(ranges: IntArray?) {
if (ranges == null) {
val groupList = XValueChildrenList()
addGroups(value, ::lazyVariablesGroup, groupList, 0, value.length, XCompositeNode.MAX_CHILDREN_TO_SHOW, this@VariableView)
node.addChildren(groupList, isLastChildren)
}
else {
addRanges(value, ranges, node, this@VariableView, isLastChildren)
}
}
override fun consumeVariables(variables: List<Variable>) {
node.addChildren(createVariablesList(variables, this@VariableView, null), isLastChildren)
}
})
}
private fun computeNamedProperties(value: ObjectValue, node: XCompositeNode, isLastChildren: Boolean) = processVariables(this, value.properties, node) { memberFilter, variables ->
_memberFilter = memberFilter
if (value.type == ValueType.ARRAY && value !is ArrayValue) {
computeArrayRanges(variables, node)
return@processVariables
}
var functionValue = value as? FunctionValue
if (functionValue != null && (functionValue.hasScopes() == ThreeState.NO)) {
functionValue = null
}
remainingChildren = processNamedObjectProperties(variables, node, this@VariableView, memberFilter, XCompositeNode.MAX_CHILDREN_TO_SHOW, isLastChildren && functionValue == null)
if (remainingChildren != null) {
remainingChildrenOffset = XCompositeNode.MAX_CHILDREN_TO_SHOW
}
if (functionValue != null) {
// we pass context as variable context instead of this variable value - we cannot watch function scopes variables, so, this variable name doesn't matter
node.addChildren(XValueChildrenList.bottomGroup(FunctionScopesValueGroup(functionValue, context)), isLastChildren && remainingChildren == null)
}
}
private fun computeArrayRanges(properties: List<Variable>, node: XCompositeNode) {
val variables = filterAndSort(properties, _memberFilter!!)
var count = variables.size
val bucketSize = XCompositeNode.MAX_CHILDREN_TO_SHOW
if (count <= bucketSize) {
node.addChildren(createVariablesList(variables, this, null), true)
return
}
while (count > 0) {
if (Character.isDigit(variables.get(count - 1).name[0])) {
break
}
count--
}
val groupList = XValueChildrenList()
if (count > 0) {
addGroups(variables, ::createArrayRangeGroup, groupList, 0, count, bucketSize, this)
}
var notGroupedVariablesOffset: Int
if ((variables.size - count) > bucketSize) {
notGroupedVariablesOffset = variables.size
while (notGroupedVariablesOffset > 0) {
if (!variables.get(notGroupedVariablesOffset - 1).name.startsWith("__")) {
break
}
notGroupedVariablesOffset--
}
if (notGroupedVariablesOffset > 0) {
addGroups(variables, ::createArrayRangeGroup, groupList, count, notGroupedVariablesOffset, bucketSize, this)
}
}
else {
notGroupedVariablesOffset = count
}
for (i in notGroupedVariablesOffset..variables.size - 1) {
val variable = variables.get(i)
groupList.add(VariableView(_memberFilter!!.rawNameToSource(variable), variable, this))
}
node.addChildren(groupList, true)
}
private val icon: Icon
get() = getIcon(value!!)
override fun getModifier(): XValueModifier? {
if (!variable.isMutable) {
return null
}
return object : XValueModifier() {
override fun getInitialValueEditorText(): String? {
if (value!!.type == ValueType.STRING) {
val string = value!!.valueString!!
val builder = StringBuilder(string.length)
builder.append('"')
StringUtil.escapeStringCharacters(string.length, string, builder)
builder.append('"')
return builder.toString()
}
else {
return if (value!!.type.isObjectType) null else value!!.valueString
}
}
override fun setValue(expression: XExpression, callback: XValueModifier.XModificationCallback) {
variable.valueModifier!!.setValue(variable, expression.expression, evaluateContext)
.doneRun {
value = null
callback.valueModified()
}
.onError { callback.errorOccurred(it.message!!) }
}
}
}
fun getValue(): Value? = variable.value
override fun canNavigateToSource(): Boolean = value is FunctionValue && value?.valueString?.contains("[native code]") != true
|| viewSupport.canNavigateToSource(variable, context)
override fun computeSourcePosition(navigatable: XNavigatable) {
if (value is FunctionValue) {
(value as FunctionValue).resolve()
.onSuccess { function ->
vm!!.scriptManager.getScript(function)
.onSuccess {
navigatable.setSourcePosition(it?.let { viewSupport.getSourceInfo(null, it, function.openParenLine, function.openParenColumn) }?.let {
object : XSourcePositionWrapper(it) {
override fun createNavigatable(project: Project): Navigatable {
return PsiVisitors.visit(myPosition, project) { position, element, positionOffset, document ->
// element will be "open paren", but we should navigate to function name,
// we cannot use specific PSI type here (like JSFunction), so, we try to find reference expression (i.e. name expression)
var referenceCandidate: PsiElement? = element
var psiReference: PsiElement? = null
while (true) {
referenceCandidate = referenceCandidate?.prevSibling ?: break
if (referenceCandidate is PsiReference) {
psiReference = referenceCandidate
break
}
}
if (psiReference == null) {
referenceCandidate = element.parent
while (true) {
referenceCandidate = referenceCandidate?.prevSibling ?: break
if (referenceCandidate is PsiReference) {
psiReference = referenceCandidate
break
}
}
}
(if (psiReference == null) element.navigationElement else psiReference.navigationElement) as? Navigatable
} ?: super.createNavigatable(project)
}
}
})
}
}
}
else {
viewSupport.computeSourcePosition(variableName, value!!, variable, context, navigatable)
}
}
override fun computeInlineDebuggerData(callback: XInlineDebuggerDataCallback): ThreeState = viewSupport.computeInlineDebuggerData(variableName, variable, context, callback)
override fun getEvaluationExpression(): String? {
if (!watchableAsEvaluationExpression()) {
return null
}
if (context.variableName == null) return variable.name // top level watch expression, may be call etc.
val list = SmartList<String>()
addVarName(list, parent, variable.name)
var parent: VariableContext? = context
while (parent != null && parent.variableName != null) {
addVarName(list, parent.parent, parent.variableName!!)
parent = parent.parent
}
return context.viewSupport.propertyNamesToString(list, false)
}
private fun addVarName(list: SmartList<String>, parent: VariableContext?, name: String) {
if (parent == null || parent.variableName != null) list.add(name)
else list.addAll(name.split(".").reversed())
}
private class MyFullValueEvaluator(private val value: Value) : XFullValueEvaluator(if (value is StringValue) value.length else value.valueString!!.length) {
override fun startEvaluation(callback: XFullValueEvaluator.XFullValueEvaluationCallback) {
if (value !is StringValue || !value.isTruncated) {
callback.evaluated(value.valueString!!)
return
}
val evaluated = AtomicBoolean()
value.fullString
.onSuccess {
if (!callback.isObsolete && evaluated.compareAndSet(false, true)) {
callback.evaluated(value.valueString!!)
}
}
.onError { callback.errorOccurred(it.message!!) }
}
}
companion object {
fun setObjectPresentation(value: ObjectValue, icon: Icon, node: XValueNode) {
node.setPresentation(icon, ObjectValuePresentation(getObjectValueDescription(value)), value.hasProperties() != ThreeState.NO)
}
fun setArrayPresentation(value: Value, context: VariableContext, icon: Icon, node: XValueNode) {
assert(value.type == ValueType.ARRAY)
if (value is ArrayValue) {
val length = value.length
node.setPresentation(icon, ArrayPresentation(length, value.className), length > 0)
return
}
val valueString = value.valueString
// only WIP reports normal description
if (valueString != null && (valueString.endsWith(")") || valueString.endsWith(']')) &&
ARRAY_DESCRIPTION_PATTERN.matcher(valueString).find()) {
node.setPresentation(icon, null, valueString, true)
}
else {
context.evaluateContext.evaluate("a.length", Collections.singletonMap<String, Any>("a", value), false)
.onSuccess(node) { node.setPresentation(icon, null, "Array[${it.value.valueString}]", true) }
.onError(node) {
logger<VariableView>().error("Failed to evaluate array length: $it")
node.setPresentation(icon, null, valueString ?: "Array", true)
}
}
}
fun getIcon(value: Value): Icon {
val type = value.type
return when (type) {
ValueType.FUNCTION -> AllIcons.Nodes.Function
ValueType.ARRAY -> AllIcons.Debugger.Db_array
else -> if (type.isObjectType) AllIcons.Debugger.Value else AllIcons.Debugger.Db_primitive
}
}
}
}
fun getClassName(value: ObjectValue): String {
val className = value.className
return if (className.isNullOrEmpty()) "Object" else className!!
}
fun getObjectValueDescription(value: ObjectValue): String {
val description = value.valueString
return if (description.isNullOrEmpty()) getClassName(value) else description!!
}
internal fun trimFunctionDescription(value: Value): String {
return trimFunctionDescription(value.valueString ?: return "")
}
fun trimFunctionDescription(value: String): String {
var endIndex = 0
while (endIndex < value.length && !StringUtil.isLineBreak(value[endIndex])) {
endIndex++
}
while (endIndex > 0 && Character.isWhitespace(value[endIndex - 1])) {
endIndex--
}
return value.substring(0, endIndex)
}
private fun createNumberPresentation(value: String): XValuePresentation {
return if (value == PrimitiveValue.NA_N_VALUE || value == PrimitiveValue.INFINITY_VALUE) XKeywordValuePresentation(value) else XNumericValuePresentation(value)
}
private val ARRAY_DESCRIPTION_PATTERN = Pattern.compile("^[a-zA-Z\\d]+[\\[(]\\d+[\\])]$")
private class ArrayPresentation(length: Int, className: String?) : XValuePresentation() {
private val length = Integer.toString(length)
private val className = if (className.isNullOrEmpty()) "Array" else className!!
override fun renderValue(renderer: XValuePresentation.XValueTextRenderer) {
renderer.renderSpecialSymbol(className)
renderer.renderSpecialSymbol("[")
renderer.renderSpecialSymbol(length)
renderer.renderSpecialSymbol("]")
}
}
private val PROTOTYPE_PROP = "__proto__"
|
apache-2.0
|
2bb8a4ba3c75399035402942a73549ef
| 39.458248 | 181 | 0.6838 | 5.154126 | false | false | false | false |
ktorio/ktor
|
ktor-server/ktor-server-netty/jvm/src/io/ktor/server/netty/http2/Http2LocalConnectionPoint.kt
|
1
|
2377
|
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.server.netty.http2
import io.ktor.http.*
import io.netty.handler.codec.http2.*
import java.net.*
internal class Http2LocalConnectionPoint(
private val nettyHeaders: Http2Headers,
private val localNetworkAddress: InetSocketAddress?,
private val remoteNetworkAddress: InetSocketAddress?,
) : RequestConnectionPoint {
override val method: HttpMethod = nettyHeaders.method()?.let { HttpMethod.parse(it.toString()) } ?: HttpMethod.Get
override val scheme: String
get() = nettyHeaders.scheme()?.toString() ?: "http"
override val version: String
get() = "HTTP/2"
override val uri: String
get() = nettyHeaders.path()?.toString() ?: "/"
@Deprecated("Use localHost or serverHost instead")
override val host: String
get() = nettyHeaders.authority()?.toString()?.substringBefore(":") ?: "localhost"
@Deprecated("Use localPort or serverPort instead")
override val port: Int
get() = nettyHeaders.authority()?.toString()
?.substringAfter(":", "")?.takeIf { it.isNotEmpty() }?.toInt()
?: localNetworkAddress?.port
?: 80
override val localHost: String
get() = localNetworkAddress?.let { it.hostName ?: it.hostString } ?: "localhost"
override val serverHost: String
get() = nettyHeaders.authority()
?.toString()
?.substringBefore(":")
?: localHost
override val localAddress: String
get() = localNetworkAddress?.hostString ?: "localhost"
private val defaultPort
get() = URLProtocol.createOrDefault(scheme).defaultPort
override val localPort: Int
get() = localNetworkAddress?.port ?: defaultPort
override val serverPort: Int
get() = nettyHeaders.authority()
?.toString()
?.substringAfter(":", defaultPort.toString())?.toInt()
?: localPort
override val remoteHost: String
get() = remoteNetworkAddress
?.let { it.hostName ?: it.address.hostAddress }
?: "unknown"
override val remotePort: Int
get() = remoteNetworkAddress?.port ?: 0
override val remoteAddress: String
get() = remoteNetworkAddress?.hostString ?: "unknown"
}
|
apache-2.0
|
096b78c219861846d11fef001bba49bd
| 35.015152 | 118 | 0.646613 | 4.679134 | false | false | false | false |
inorichi/mangafeed
|
app/src/main/java/eu/kanade/tachiyomi/util/lang/DateExtensions.kt
|
2
|
3808
|
package eu.kanade.tachiyomi.util.lang
import android.content.Context
import eu.kanade.tachiyomi.R
import java.text.DateFormat
import java.util.Calendar
import java.util.Date
import java.util.TimeZone
fun Date.toDateTimestampString(dateFormatter: DateFormat): String {
val date = dateFormatter.format(this)
val time = DateFormat.getTimeInstance(DateFormat.SHORT).format(this)
return "$date $time"
}
fun Date.toTimestampString(): String {
return DateFormat.getTimeInstance(DateFormat.SHORT).format(this)
}
/**
* Get date as time key
*
* @param date desired date
* @return date as time key
*/
fun Long.toDateKey(): Date {
val cal = Calendar.getInstance()
cal.time = Date(this)
cal[Calendar.HOUR_OF_DAY] = 0
cal[Calendar.MINUTE] = 0
cal[Calendar.SECOND] = 0
cal[Calendar.MILLISECOND] = 0
return cal.time
}
/**
* Convert epoch long to Calendar instance
*
* @return Calendar instance at supplied epoch time. Null if epoch was 0.
*/
fun Long.toCalendar(): Calendar? {
if (this == 0L) {
return null
}
val cal = Calendar.getInstance()
cal.timeInMillis = this
return cal
}
/**
* Convert local time millisecond value to Calendar instance in UTC
*
* @return UTC Calendar instance at supplied time. Null if time is 0.
*/
fun Long.toUtcCalendar(): Calendar? {
if (this == 0L) {
return null
}
val rawCalendar = Calendar.getInstance().apply {
timeInMillis = this@toUtcCalendar
}
return Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
clear()
set(
rawCalendar.get(Calendar.YEAR),
rawCalendar.get(Calendar.MONTH),
rawCalendar.get(Calendar.DAY_OF_MONTH),
rawCalendar.get(Calendar.HOUR_OF_DAY),
rawCalendar.get(Calendar.MINUTE),
rawCalendar.get(Calendar.SECOND)
)
}
}
/**
* Convert UTC time millisecond to Calendar instance in local time zone
*
* @return local Calendar instance at supplied UTC time. Null if time is 0.
*/
fun Long.toLocalCalendar(): Calendar? {
if (this == 0L) {
return null
}
val rawCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC")).apply {
timeInMillis = this@toLocalCalendar
}
return Calendar.getInstance().apply {
clear()
set(
rawCalendar.get(Calendar.YEAR),
rawCalendar.get(Calendar.MONTH),
rawCalendar.get(Calendar.DAY_OF_MONTH),
rawCalendar.get(Calendar.HOUR_OF_DAY),
rawCalendar.get(Calendar.MINUTE),
rawCalendar.get(Calendar.SECOND)
)
}
}
private const val MILLISECONDS_IN_DAY = 86_400_000L
fun Date.toRelativeString(
context: Context,
range: Int = 7,
dateFormat: DateFormat = DateFormat.getDateInstance(DateFormat.SHORT)
): String {
if (range == 0) {
return dateFormat.format(this)
}
val now = Date()
val difference = now.timeWithOffset.floorNearest(MILLISECONDS_IN_DAY) - this.timeWithOffset.floorNearest(MILLISECONDS_IN_DAY)
val days = difference.floorDiv(MILLISECONDS_IN_DAY).toInt()
return when {
difference < 0 -> context.getString(R.string.recently)
difference < MILLISECONDS_IN_DAY -> context.getString(R.string.relative_time_today)
difference < MILLISECONDS_IN_DAY.times(range) -> context.resources.getQuantityString(
R.plurals.relative_time,
days,
days
)
else -> dateFormat.format(this)
}
}
private val Date.timeWithOffset: Long
get() {
return Calendar.getInstance().run {
time = this@timeWithOffset
[email protected] + timeZone.rawOffset
}
}
fun Long.floorNearest(to: Long): Long {
return this.floorDiv(to) * to
}
|
apache-2.0
|
8cf546d136a4d4e60f39fe774a45c336
| 27.207407 | 129 | 0.653624 | 3.995803 | false | false | false | false |
BlueHuskyStudios/BHToolbox
|
BHToolbox/src/org/bh/tools/crossplatform/Comparable64.kt
|
1
|
2873
|
package org.bh.tools.crossplatform
/**
* Comparable64, made for BHToolbox, is made by and copyrighted to Blue Husky Programming, ©2012 BH-1-PS <hr/>
*
* The general behavior of any object that implements {@code Comparable64} should be equal to that of one that implements
* {@link Comparable}, but using 64-bit integers instead of 32-bit ones
*
* @author Supuhstar and Ben Leggiero of Blue Husky Studios
* @param <T> The type of object to compare
* @since Mar 10, 2012
* @version 2.0.0
* ! 2016-10-09 - Ben Leggiero converted this to Kotlin
* @see Comparable
*/
@Suppress("unused")
interface Comparable64<in T> : Comparable<T> //NOTE: Must be compiled in UTF-8
{
/**
* Compares this object with the specified object for order. Returns a
* negative integer, zero, or a positive integer as this object is less
* than, equal to, or greater than the specified object.
*
* <p>The implementor must ensure <tt>sgn(x.compareTo(y)) ==
* -sgn(y.compareTo(x))</tt> for all <tt>x</tt> and <tt>y</tt>. (This
* implies that <tt>x.compareTo(y)</tt> must throw an exception iff
* <tt>y.compareTo(x)</tt> throws an exception.)</p>
*
* <p>The implementor must also ensure that the relation is transitive:
* <tt>(x.compareTo(y)>0 && y.compareTo(z)>0)</tt> implies
* <tt>x.compareTo(z)>0</tt>.</p>
*
* <p>Finally, the implementor must ensure that <tt>x.compareTo(y)==0</tt>
* implies that <tt>sgn(x.compareTo(z)) == sgn(y.compareTo(z))</tt>, for
* all <tt>z</tt>.</p>
*
* <p>It is strongly recommended, but <i>not</i> strictly required that
* <tt>(x.compareTo(y)==0) == (x.equals(y))</tt>. Generally speaking, any
* class that implements the <tt>Comparable</tt> interface and violates
* this condition should clearly indicate this fact. The recommended
* language is "Note: this class has a natural ordering that is
* inconsistent with equals."</p>
*
* <p>In the foregoing description, the notation
* <tt>sgn(</tt><i>expression</i><tt>)</tt> designates the mathematical
* <i>signum</i> function, which is defined to return one of <tt>-1</tt>,
* <tt>0</tt>, or <tt>1</tt> according to whether the value of
* <i>expression</i> is negative, zero or positive.</p>
*
* @param otherComparable the object to be compared.
* @return a negative integer, zero, or a positive integer as this object
* is less than, equal to, or greater than the specified object.
*
* @throws NullPointerException if the specified object is null
* @throws ClassCastException if the specified object's type prevents it
* from being compared to this object.
*/
fun compareTo64(otherComparable: T): Long
}
|
gpl-3.0
|
9e049bf1d6ff31f6f707bbe887eedcd5
| 46.711864 | 121 | 0.640669 | 3.598997 | false | false | false | false |
meik99/CoffeeList
|
app/src/main/java/rynkbit/tk/coffeelist/db/entity/DatabaseInvoice.kt
|
1
|
1365
|
package rynkbit.tk.coffeelist.db.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.ForeignKey.SET_NULL
import androidx.room.PrimaryKey
import rynkbit.tk.coffeelist.contract.entity.Invoice
import rynkbit.tk.coffeelist.contract.entity.InvoiceState
import java.util.*
@Entity(
tableName = "invoice",
foreignKeys = [
ForeignKey(
onDelete = SET_NULL,
entity = DatabaseCustomer::class,
childColumns = ["customer_id"],
parentColumns = ["id"]
),
ForeignKey(
onDelete = SET_NULL,
entity = DatabaseItem::class,
childColumns = ["item_id"],
parentColumns = ["id"]
)
]
)
class DatabaseInvoice(
@PrimaryKey(autoGenerate = true)
override val id: Int,
@ColumnInfo(name = "customer_id")
override val customerId: Int?,
override val customerName: String,
@ColumnInfo(name = "item_id")
override val itemId: Int?,
override val itemName: String,
override val itemPrice: Double,
override val date: Date,
override val state: InvoiceState
) : Invoice
|
mit
|
6a0565b660f6301cbe8173f1267b541c
| 32.317073 | 57 | 0.567766 | 5.131579 | false | false | false | false |
spotify/heroic
|
consumer/collectd/src/main/java/com/spotify/heroic/consumer/collectd/CollectdValue.kt
|
1
|
1806
|
/*
* Copyright (c) 2019 Spotify AB.
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package com.spotify.heroic.consumer.collectd
import com.spotify.heroic.consumer.collectd.CollectdTypes.Field
interface CollectdValue {
fun convert(field: Field): Double
fun toDouble(): Double
}
data class Gauge(val value: Double): CollectdValue {
override fun convert(field: Field): Double = field.convertGauge(value)
override fun toDouble(): Double = value
}
data class Absolute(val value: Long): CollectdValue {
override fun convert(field: Field): Double = field.convertAbsolute(value)
override fun toDouble(): Double = value.toDouble()
}
data class Derive(val derivate: Long): CollectdValue {
override fun convert(field: Field): Double = field.convertAbsolute(derivate)
override fun toDouble(): Double = derivate.toDouble()
}
data class Counter(val counter: Long): CollectdValue {
override fun convert(field: Field): Double = field.convertAbsolute(counter)
override fun toDouble(): Double = counter.toDouble()
}
|
apache-2.0
|
7685906c8d710095a453519163dc0f3f
| 35.877551 | 80 | 0.745293 | 4.104545 | false | false | false | false |
dkandalov/katas
|
kotlin/src/katas/kotlin/generics/1.kt
|
1
|
2740
|
@file:Suppress(
"unused", "MemberVisibilityCanBePrivate", "UNUSED_VARIABLE",
"RemoveExplicitTypeArguments", "RedundantExplicitType"
)
package katas.kotlin.generics
open class A
open class B: A() {
fun foo() {}
}
object Foo_ {
init {
A()
B().foo()
}
}
// A B
// A a<=a a<=b
// B b!!a b<=b
// ()->A ()->B
// ()->A getA<=getA getA<=getB
// ()->B getB!!getA getB<=getB
// A->() B->()
// A->() setA<=setA setA!!setB
// B->() setB<=setA setB<=setB
object Foo0 {
init {
val x1: A = A()
val x2: B = B()
}
// replace rhs with all A's and B's
init {
val x1: A = A()
// val x2: B = A() // ()->A
val x3: A = B() // ()->B
val x4: B = B()
}
// replace lhs with all A's and B's
init {
val x1: A = A()
val x2: A = B() // setB<=setA
// val x3: B = A() // setA!!setB
val x4: B = B()
}
}
object Foo1 {
val a: A = A()
//val b: B = A() // 👈 Type mismatch
val a2: A = B()
val b2: B = B()
}
object Foo2 {
fun readA(): A = A()
fun readB(): B = B()
val a: A = readA()
// val b: B = readA() // 👈 Type mismatch
val a2: A = readB()
val b2: B = readB()
val x1: () -> A = ::readA
val x2: () -> B = ::readB
}
object `Foo2'` {
fun readReadA(): () -> A = { A() }
fun readReadB(): () -> B = { B() }
val x1: () -> () -> A = ::readReadA
val x2: () -> () -> A = ::readReadB
// val x3: () -> () -> B = ::readReadA // 👈 Type mismatch
val x4: () -> () -> B = ::readReadB
}
object Foo3 {
fun writeA(a: A) { val tmp: A = a }
fun writeB(b: B) { val tmp: B = b }
init {
writeA(A())
// writeB(A()) // 👈 Type mismatch
writeA(B())
writeB(B())
// val writeA: (A) -> Unit = ::writeB
val writeB: (B) -> Unit = ::writeA
}
}
object `Foo3'` {
fun writeWriteA(f: (A) -> Unit) {}
fun writeWriteB(f: (B) -> Unit) {}
val x1: ((A) -> Unit) -> Unit = ::writeWriteA
val x2: ((A) -> Unit) -> Unit = ::writeWriteB
// val x3: ((B) -> Unit) -> Unit = ::writeWriteA
val x4: ((B) -> Unit) -> Unit = ::writeWriteB
}
object Foo4 {
fun <T> read(): T = error("")
val a: A = read<A>()
val b: B = read<B>()
val a2: A = read<B>()
// val b2: B = read<A>() // 👈 Type mismatch
fun <T> write(value: T) {}
init {
write<A>(A())
write<B>(B())
// write<B>(A()) // 👈 Type mismatch
write<A>(B())
}
}
object Foo5 {
class Reader<T> {
fun read(): T = error("👻")
}
class Writer<T> {
fun write(value: T): Unit = error("")
}
}
|
unlicense
|
7970d63f211d208bee213eab1c53c871
| 18.846715 | 64 | 0.431776 | 2.77449 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structuralsearch/KotlinStructuralSearchUtil.kt
|
4
|
2582
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.structuralsearch
import com.google.common.collect.ImmutableBiMap
import com.intellij.psi.PsiComment
import com.intellij.psi.tree.IElementType
import com.intellij.structuralsearch.impl.matcher.handlers.MatchingHandler
import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.lexer.KtSingleValueToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.KotlinTypeFactory
import org.jetbrains.kotlin.types.TypeAttributes
import org.jetbrains.kotlin.types.expressions.OperatorConventions
fun getCommentText(comment: PsiComment): String {
return when (comment.tokenType) {
KtTokens.EOL_COMMENT -> comment.text.drop(2).trim()
KtTokens.BLOCK_COMMENT -> comment.text.drop(2).dropLast(2).trim()
else -> ""
}
}
private val BINARY_EXPR_OP_NAMES = ImmutableBiMap.builder<KtSingleValueToken, Name>()
.putAll(OperatorConventions.ASSIGNMENT_OPERATIONS)
.putAll(OperatorConventions.BINARY_OPERATION_NAMES)
.build()
fun IElementType.binaryExprOpName(): Name? = BINARY_EXPR_OP_NAMES[this]
fun KotlinType.renderNames(): Array<String> = arrayOf(
DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(this),
DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(this),
"$this"
)
fun String.removeTypeParameters(): String {
if (!this.contains('<') || !this.contains('>')) return this
return this.removeRange(
this.indexOfFirst { c -> c == '<' },
this.indexOfLast { c -> c == '>' } + 1
)
}
val MatchingHandler.withinHierarchyTextFilterSet: Boolean
get() = this is SubstitutionHandler && (this.isSubtype || this.isStrictSubtype)
fun KtDeclaration.resolveKotlinType(): KotlinType? =
(resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType
fun ClassDescriptor.toSimpleType(nullable: Boolean = false) =
KotlinTypeFactory.simpleType(TypeAttributes.Empty, this.typeConstructor, emptyList(), nullable)
|
apache-2.0
|
6429a9c028ae12245a1f573e170e8b7f
| 42.033333 | 158 | 0.782727 | 4.296173 | false | false | false | false |
elpassion/el-space-android
|
el-debate/src/main/java/pl/elpassion/elspace/debate/details/DebateDetailsController.kt
|
1
|
2186
|
package pl.elpassion.elspace.debate.details
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import pl.elpassion.elspace.common.SchedulersSupplier
import retrofit2.HttpException
class DebateDetailsController(
private val api: DebateDetails.Api,
private val view: DebateDetails.View,
private val schedulers: SchedulersSupplier) {
private val compositeDisposable = CompositeDisposable()
fun onCreate(token: String) {
getDebateDetails(token)
}
fun onDebateDetailsRefresh(token: String) {
getDebateDetails(token)
}
private fun getDebateDetails(token: String) {
api.getDebateDetails(token)
.subscribeOn(schedulers.backgroundScheduler)
.observeOn(schedulers.uiScheduler)
.doOnSubscribe { view.showLoader() }
.doFinally(view::hideLoader)
.subscribe(view::showDebateDetails,
{ error -> onGetDebateDetailsError(error) })
.addTo(compositeDisposable)
}
private fun onGetDebateDetailsError(error: Throwable) {
when {
error is HttpException && error.code() == 403 -> view.showDebateClosedError()
else -> view.showDebateDetailsError(error)
}
}
fun onVote(token: String, answer: Answer) {
api.vote(token, answer)
.subscribeOn(schedulers.backgroundScheduler)
.observeOn(schedulers.uiScheduler)
.doOnSubscribe { view.showVoteLoader(answer) }
.doFinally(view::hideVoteLoader)
.subscribe({ view.showVoteSuccess(answer) }, this::onVoteError)
.addTo(compositeDisposable)
}
private fun onVoteError(error: Throwable) {
when {
error is HttpException && error.code() == 403 -> view.showDebateClosedError()
error is HttpException && error.code() == 429 -> view.showSlowDownInformation()
else -> view.showVoteError(error)
}
}
fun onChat() {
view.openChatScreen()
}
fun onDestroy() {
compositeDisposable.dispose()
}
}
|
gpl-3.0
|
4b17537045b6bdf20a8c6f9b0cc1f0eb
| 32.136364 | 91 | 0.630833 | 4.825607 | false | false | false | false |
tateisu/SubwayTooter
|
app/src/main/java/jp/juggler/subwaytooter/table/PostDraft.kt
|
1
|
5312
|
package jp.juggler.subwaytooter.table
import android.annotation.SuppressLint
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.provider.BaseColumns
import jp.juggler.subwaytooter.global.appDatabase
import jp.juggler.util.*
class PostDraft {
var id: Long = 0
var time_save: Long = 0
var json: JsonObject? = null
var hash: String? = null
fun delete() {
try {
appDatabase.delete(table, "$COL_ID=?", arrayOf(id.toString()))
} catch (ex: Throwable) {
log.e(ex, "delete failed.")
}
}
class ColIdx(cursor: Cursor) {
val idx_id = cursor.getColumnIndex(COL_ID)
val idx_time_save = cursor.getColumnIndex(COL_TIME_SAVE)
val idx_json = cursor.getColumnIndex(COL_JSON)
val idx_hash = cursor.getColumnIndex(COL_HASH)
}
companion object : TableCompanion {
private val log = LogCategory("PostDraft")
override val table = "post_draft"
private const val COL_ID = BaseColumns._ID
private const val COL_TIME_SAVE = "time_save"
private const val COL_JSON = "json"
private const val COL_HASH = "hash"
override fun onDBCreate(db: SQLiteDatabase) {
log.d("onDBCreate!")
db.execSQL(
"""create table if not exists $table
($COL_ID INTEGER PRIMARY KEY
,$COL_TIME_SAVE integer not null
,$COL_JSON text not null
,$COL_HASH text not null
)""".trimIndent()
)
db.execSQL("create unique index if not exists ${table}_hash on $table($COL_HASH)")
db.execSQL("create index if not exists ${table}_time on $table($COL_TIME_SAVE)")
}
override fun onDBUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
if (oldVersion < 12 && newVersion >= 12) {
onDBCreate(db)
}
}
private fun deleteOld(now: Long) {
try {
// 古いデータを掃除する
val expire = now - 86400000L * 30
appDatabase.delete(table, "$COL_TIME_SAVE<?", arrayOf(expire.toString()))
} catch (ex: Throwable) {
log.e(ex, "deleteOld failed.")
}
}
fun save(now: Long, json: JsonObject) {
deleteOld(now)
try {
// make hash
val hash = StringBuilder().also { sb ->
json.keys.sorted().forEach { k ->
val v = json[k]?.toString() ?: "(null)"
sb.append("&")
sb.append(k)
sb.append("=")
sb.append(v)
}
}.toString().digestSHA256Hex()
// save to db
appDatabase.replace(table, null, ContentValues().apply {
put(COL_TIME_SAVE, now)
put(COL_JSON, json.toString())
put(COL_HASH, hash)
})
} catch (ex: Throwable) {
log.e(ex, "save failed.")
}
}
fun hasDraft(): Boolean {
try {
appDatabase.query(table, arrayOf("count(*)"), null, null, null, null, null)
.use { cursor ->
if (cursor.moveToNext()) {
val count = cursor.getInt(0)
return count > 0
}
}
} catch (ex: Throwable) {
log.trace(ex, "hasDraft failed.")
}
return false
}
// caller must close the cursor
@SuppressLint("Recycle")
fun createCursor(): Cursor? =
try {
appDatabase.query(
table,
null,
null,
null,
null,
null,
"$COL_TIME_SAVE desc"
)
} catch (ex: Throwable) {
log.trace(ex, "createCursor failed.")
null
}
fun loadFromCursor(cursor: Cursor, colIdxArg: ColIdx?, position: Int): PostDraft? {
return if (!cursor.moveToPosition(position)) {
log.d("loadFromCursor: move failed. position=$position")
null
} else {
PostDraft().also { dst ->
val colIdx = colIdxArg ?: ColIdx(cursor)
dst.id = cursor.getLong(colIdx.idx_id)
dst.time_save = cursor.getLong(colIdx.idx_time_save)
dst.hash = cursor.getString(colIdx.idx_hash)
dst.json = try {
cursor.getString(colIdx.idx_json).decodeJsonObject()
} catch (ex: Throwable) {
log.trace(ex)
JsonObject()
}
}
}
}
}
}
|
apache-2.0
|
538f322202a2583cf71407ab8ee08345
| 33.046358 | 94 | 0.459184 | 4.863971 | false | false | false | false |
georocket/georocket
|
src/main/kotlin/io/georocket/index/generic/DefaultMetaIndexerFactory.kt
|
1
|
2105
|
package io.georocket.index.generic
import io.georocket.index.DatabaseIndex
import io.georocket.index.MetaIndexerFactory
import io.georocket.query.*
import io.georocket.query.QueryCompiler.MatchPriority
import io.georocket.query.QueryPart.ComparisonOperator.EQ
/**
* Factory for [DefaultMetaIndexer] instances
* @author Michel Kraemer
*/
class DefaultMetaIndexerFactory : MetaIndexerFactory {
override fun createIndexer() = DefaultMetaIndexer()
override fun getQueryPriority(queryPart: QueryPart): MatchPriority {
return when (queryPart) {
is StringQueryPart, is LongQueryPart, is DoubleQueryPart -> MatchPriority.SHOULD
}
}
override fun compileQuery(queryPart: QueryPart): IndexQuery {
return when (queryPart) {
is StringQueryPart, is LongQueryPart, is DoubleQueryPart -> {
val key = queryPart.key
if (key == null) {
// match values of all fields regardless of their name
val search = queryPart.value
Or(
Contains("tags", search),
ElemMatchExists("props", "value" to search)
)
} else {
val r = ElemMatchCompare(
"props",
listOf("key" to key),
Compare("value", queryPart.value, queryPart.comparisonOperator ?: EQ),
)
if (queryPart.comparisonOperator == EQ && queryPart.key == "correlationId") {
Or(r, Compare("correlationId", queryPart.value, EQ))
} else {
r
}
}
}
}
}
override fun getDatabaseIndexes(indexedFields: List<String>): List<DatabaseIndex> = listOf(
DatabaseIndex.Array("tags", "tags_array"),
DatabaseIndex.ElemMatchExists("props", listOf("value", "key"), "props_elem_match_exists"),
*indexedFields.map { fieldName ->
DatabaseIndex.ElemMatchCompare(
"props",
"key",
"value",
fieldName,
"props_${fieldName}_elem_match_cmp"
)
}.toTypedArray(),
DatabaseIndex.Eq("correlationId", "correlation_id_eq"),
DatabaseIndex.StartsWith("layer", "layer_starts_with")
)
}
|
apache-2.0
|
1f6cd3f783f8ee38d1e6d0cbdd8dfe0c
| 31.890625 | 94 | 0.642755 | 4.459746 | false | false | false | false |
RuneSuite/client
|
plugins/src/main/java/org/runestar/client/plugins/markdestination/MarkDestination.kt
|
1
|
1216
|
package org.runestar.client.plugins.markdestination
import org.runestar.client.api.forms.BasicStrokeForm
import org.runestar.client.api.forms.RgbaForm
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.game.live.Game
import org.runestar.client.api.game.live.Canvas
import org.runestar.client.api.plugins.PluginSettings
import java.awt.Color
import java.awt.RenderingHints
class MarkDestination : DisposablePlugin<MarkDestination.Settings>() {
override val defaultSettings = Settings()
override val name = "Mark Destination"
override fun onStart() {
add(Canvas.repaints.subscribe { g ->
val destination = Game.destination ?: return@subscribe
if (!destination.isLoaded) return@subscribe
val outline = destination.outline()
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.color = settings.color.value
g.stroke = settings.stroke.value
g.draw(outline)
})
}
class Settings(
val stroke: BasicStrokeForm = BasicStrokeForm(2f),
val color: RgbaForm = RgbaForm(Color.WHITE)
) : PluginSettings()
}
|
mit
|
25a4fec7c4bc436ec6ac3b15603c92d1
| 34.794118 | 98 | 0.712171 | 4.421818 | false | false | false | false |
jeantuffier/reminder
|
app/src/main/java/fr/jeantuffier/reminder/free/home/presentation/HomeActivity.kt
|
1
|
2708
|
package fr.jeantuffier.reminder.free.home.presentation
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.DividerItemDecoration
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import android.widget.LinearLayout
import dagger.android.AndroidInjection
import fr.jeantuffier.reminder.R
import fr.jeantuffier.reminder.free.common.model.Task
import fr.jeantuffier.reminder.free.create.presentation.CreateTaskActivity
import kotlinx.android.synthetic.main.home_activity.*
import javax.inject.Inject
class HomeActivity : AppCompatActivity(), HomeContract.View {
companion object {
const val REQUEST_CREATE_TASK = 1
const val SUCCESS_CREATE_TASK = 10
}
@Inject
lateinit var presenter: HomeContract.Presenter
private val adapter = HomeAdapter(mutableListOf<Task>())
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.home_activity)
setToolbar()
setRecyclerView()
}
private fun setToolbar() {
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar?.title = getString(R.string.app_name)
}
private fun setRecyclerView() {
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
val divider = DividerItemDecoration(this, LinearLayout.VERTICAL)
recyclerView.addItemDecoration(divider)
presenter.loadData()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (requestCode == REQUEST_CREATE_TASK && resultCode == SUCCESS_CREATE_TASK) {
presenter.loadData()
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.display, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.menu_create_task) {
createTask()
}
return true
}
override fun setTasks(tasks: List<Task>) {
adapter.setItems(tasks)
recyclerView.adapter.notifyDataSetChanged()
}
private fun createTask() {
val intent = Intent(this, CreateTaskActivity::class.java)
startActivityForResult(intent, REQUEST_CREATE_TASK)
}
override fun deleteTask(position: Int) {
adapter.removeItem(position)
recyclerView.adapter.notifyItemRemoved(position)
}
}
|
mit
|
2d3115d4a47dec3685c2dedc0d3f7f0a
| 29.772727 | 86 | 0.710487 | 4.767606 | false | false | false | false |
google/intellij-community
|
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesListPanel.kt
|
1
|
35021
|
/*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* 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.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.ide.BrowserUtil
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.ui.DocumentAdapter
import com.intellij.ui.SearchTextField
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.components.JBPanelWithEmptyText
import com.intellij.ui.components.JBScrollPane
import com.intellij.util.ui.JBUI
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.data.PackageUpgradeCandidates
import com.jetbrains.packagesearch.intellij.plugin.fus.FUSGroupIds
import com.jetbrains.packagesearch.intellij.plugin.fus.PackageSearchEventsLogger
import com.jetbrains.packagesearch.intellij.plugin.ui.ComponentActionWrapper
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.FilterOptions
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.InstalledDependency
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageIdentifier
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageScope
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackagesToUpgrade
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ProjectDataProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.SearchResultUiState
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.matchesCoordinates
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperationFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.toUiPackageModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.versions.NormalizedPackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder
import com.jetbrains.packagesearch.intellij.plugin.ui.util.onOpacityChanged
import com.jetbrains.packagesearch.intellij.plugin.ui.util.onVisibilityChanged
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.CoroutineLRUCache
import com.jetbrains.packagesearch.intellij.plugin.util.FeatureFlags
import com.jetbrains.packagesearch.intellij.plugin.util.KotlinPluginStatus
import com.jetbrains.packagesearch.intellij.plugin.util.PowerSaveModeState
import com.jetbrains.packagesearch.intellij.plugin.util.hasKotlinModules
import com.jetbrains.packagesearch.intellij.plugin.util.kotlinPluginStatusFlow
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import com.jetbrains.packagesearch.intellij.plugin.util.logTrace
import com.jetbrains.packagesearch.intellij.plugin.util.logWarn
import com.jetbrains.packagesearch.intellij.plugin.util.lookAndFeelFlow
import com.jetbrains.packagesearch.intellij.plugin.util.moduleChangesSignalFlow
import com.jetbrains.packagesearch.intellij.plugin.util.onEach
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectCachesService
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService
import com.jetbrains.packagesearch.intellij.plugin.util.packageVersionNormalizer
import com.jetbrains.packagesearch.intellij.plugin.util.parallelFilterNot
import com.jetbrains.packagesearch.intellij.plugin.util.parallelFlatMap
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMap
import com.jetbrains.packagesearch.intellij.plugin.util.parallelMapNotNull
import com.jetbrains.packagesearch.intellij.plugin.util.timer
import com.jetbrains.packagesearch.intellij.plugin.util.uiStateSource
import com.jetbrains.packagesearch.intellij.plugin.util.whileLoading
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.combineTransform
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.debounce
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filterNot
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import net.miginfocom.swing.MigLayout
import org.jetbrains.packagesearch.api.v2.ApiPackagesResponse
import org.jetbrains.packagesearch.api.v2.ApiStandardPackage
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.event.ItemEvent
import javax.swing.BorderFactory
import javax.swing.Box
import javax.swing.BoxLayout
import javax.swing.JCheckBox
import javax.swing.JPanel
import javax.swing.JScrollPane
import javax.swing.JViewport
import javax.swing.event.DocumentEvent
import kotlin.time.Duration
import kotlin.time.Duration.Companion.milliseconds
import kotlin.time.Duration.Companion.minutes
import kotlin.time.measureTime
import kotlin.time.measureTimedValue
internal class PackagesListPanel(
private val project: Project,
private val headerOperationsCache: CoroutineLRUCache<PackagesToUpgrade.PackageUpgradeInfo, List<PackageSearchOperation<*>>> =
project.packageSearchProjectCachesService.headerOperationsCache,
private val searchCache: CoroutineLRUCache<SearchCommandModel, ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>> =
project.packageSearchProjectCachesService.searchCache,
private val searchPackageModelCache: CoroutineLRUCache<UiPackageModelCacheKey, UiPackageModel.SearchResult> =
project.packageSearchProjectCachesService.searchPackageModelCache,
operationFactory: PackageSearchOperationFactory,
operationExecutor: OperationExecutor,
viewModelFlow: Flow<ViewModel>,
private val dataProvider: ProjectDataProvider
) : PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.title")) {
private val searchFieldFocus = Channel<Unit>()
private val packagesTable = PackagesTable(project, operationExecutor, ::onSearchResultStateChanged)
private val onlyStableMutableStateFlow = MutableStateFlow(true)
val onlyStableStateFlow: StateFlow<Boolean> = onlyStableMutableStateFlow
val selectedPackageStateFlow: StateFlow<UiPackageModel<*>?> = packagesTable.selectedPackageStateFlow
private val onlyMultiplatformStateFlow = MutableStateFlow(false)
private val searchQueryStateFlow = MutableStateFlow("")
private val isSearchingStateFlow = MutableStateFlow(false)
private val isLoadingStateFlow = MutableStateFlow(false)
private val searchResultsUiStateOverridesState: MutableStateFlow<Map<PackageIdentifier, SearchResultUiState>> =
MutableStateFlow(emptyMap())
private val searchTextField = PackagesSmartSearchField(searchFieldFocus.consumeAsFlow(), project)
.apply {
goToTable = {
if (packagesTable.hasInstalledItems) {
packagesTable.selectedIndex = packagesTable.firstPackageIndex
IdeFocusManager.getInstance(project).requestFocus(packagesTable, false)
true
} else {
false
}
}
fieldClearedListener = {
PackageSearchEventsLogger.logSearchQueryClear()
}
}
private val packagesPanel = PackageSearchUI.borderPanel {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
}
private val onlyStableCheckBox = PackageSearchUI.checkBox(PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.filter.onlyStable"))
.apply {
isOpaque = false
border = emptyBorder(left = 6)
isSelected = true
}
private val onlyMultiplatformCheckBox =
PackageSearchUI.checkBox(PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.filter.onlyMpp")) {
isOpaque = false
border = emptyBorder(left = 6)
isSelected = false
}
private val searchFiltersToolbar = ActionManager.getInstance()
.createActionToolbar("Packages.Manage", createActionGroup(), true)
.apply {
component.background = if (PackageSearchUI.isNewUI) {
PackageSearchUI.Colors.panelBackground
} else {
PackageSearchUI.Colors.headerBackground
}
component.border = JBUI.Borders.customLineLeft(PackageSearchUI.Colors.panelBackground)
}
private fun createActionGroup() = DefaultActionGroup().apply {
add(ComponentActionWrapper { onlyStableCheckBox })
add(ComponentActionWrapper { onlyMultiplatformCheckBox })
}
private val searchPanel = PackageSearchUI.headerPanel {
PackageSearchUI.setHeightPreScaled(this, PackageSearchUI.mediumHeaderHeight.get())
border = BorderFactory.createEmptyBorder()
addToCenter(object : JPanel() {
init {
layout = MigLayout("ins 0, fill", "[left, fill, grow][right]", "fill")
add(searchTextField)
add(searchFiltersToolbar.component)
searchFiltersToolbar.targetComponent = this
if (PackageSearchUI.isNewUI) {
project.coroutineScope.launch {
// This is a hack — the ActionToolbar will reset its own background colour,
// so we need to wait for the next frame to set it
delay(16.milliseconds)
withContext(Dispatchers.EDT) {
searchFiltersToolbar.component.background = PackageSearchUI.Colors.panelBackground
}
}
}
border = JBUI.Borders.customLineBottom(PackageSearchUI.Colors.separator)
}
override fun getBackground() = PackageSearchUI.Colors.panelBackground
})
}
private val headerPanel = HeaderPanel {
logDebug("PackagesListPanel.headerPanel#onUpdateAllLinkClicked()") {
"The user has clicked the update all link. This will cause many operation(s) to be executed."
}
operationExecutor.executeOperations(it)
}.apply {
border = JBUI.Borders.customLineTop(PackageSearchUI.Colors.separator)
}
private val tableScrollPane = JBScrollPane(
packagesPanel.apply {
add(packagesTable)
add(Box.createVerticalGlue())
},
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER
).apply {
border = emptyBorder()
viewportBorder = emptyBorder()
viewport.scrollMode = JViewport.SIMPLE_SCROLL_MODE
verticalScrollBar.apply {
headerPanel.adjustForScrollbar(isVisible, isOpaque)
// Here, we should make sure we set IGNORE_SCROLLBAR_IN_INSETS, but alas, it doesn't work with JTables
// as of IJ 2022.3 (see JBViewport#updateBorder()). If it did, we could just set:
// UIUtil.putClientProperty(this, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, false)
// Instead, we have to work around the issue, inferring if the scrollbar is "floating" by looking at
// its isOpaque property — since Swing maps the opacity of scrollbars to whether they're "floating"
// (e.g., on macOS, System Preferences > General > Show scroll bars: "When scrolling")
onOpacityChanged { newIsOpaque ->
headerPanel.adjustForScrollbar(isVisible, newIsOpaque)
}
onVisibilityChanged { newIsVisible ->
headerPanel.adjustForScrollbar(newIsVisible, isOpaque)
}
}
}
private val listPanel = JBPanelWithEmptyText().apply {
emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.base")
layout = BorderLayout()
add(tableScrollPane, BorderLayout.CENTER)
background = PackageSearchUI.Colors.panelBackground
border = JBUI.Borders.customLineTop(PackageSearchUI.Colors.separator)
}
internal data class SearchCommandModel(
val onlyStable: Boolean,
val onlyMultiplatform: Boolean,
val searchQuery: String,
)
internal data class SearchResultsModel(
val onlyStable: Boolean,
val onlyMultiplatform: Boolean,
val searchQuery: String,
val apiSearchResults: ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>?
)
private data class ViewModels(
val targetModules: TargetModules,
val headerData: PackagesHeaderData,
val viewModel: PackagesTable.ViewModel
)
init {
registerForUiEvents()
val searchResultsFlow =
combine(onlyStableStateFlow, onlyMultiplatformStateFlow, searchQueryStateFlow) { onlyStable, onlyMultiplatform, searchQuery ->
SearchCommandModel(onlyStable, onlyMultiplatform, searchQuery)
}
.debounce(150)
.mapLatest { searchCommand ->
val (result, time) = isSearchingStateFlow.whileLoading {
val results = searchCache.getOrTryPutDefault(searchCommand) {
dataProvider.doSearch(
searchCommand.searchQuery,
FilterOptions(searchCommand.onlyStable, searchCommand.onlyMultiplatform)
)
}
SearchResultsModel(
searchCommand.onlyStable,
searchCommand.onlyMultiplatform,
searchCommand.searchQuery,
results
)
}
logTrace("PackagesListPanel main flow") { "Search took $time" }
result
}
.shareIn(project.lifecycleScope, SharingStarted.Eagerly, 1)
combine(
viewModelFlow,
searchResultsFlow,
searchResultsUiStateOverridesState
) { viewModel, searchResults, overrides ->
Triple(viewModel, searchResults, overrides)
}.mapLatest { (viewModel, searchResults, searchResultsUiStateOverrides) ->
val (
targetModules, installedPackages, packagesUpdateCandidates,
knownRepositoriesInTargetModules
) = viewModel
val (onlyStable, onlyMultiplatform, searchQuery, apiSearchResults) = searchResults
isLoadingStateFlow.emit(true)
val (result, time) = measureTimedValue {
val (result, time) = measureTimedValue {
val packagesToUpgrade = packagesUpdateCandidates.getPackagesToUpgrade(onlyStable)
val filteredPackageUpgrades = when (targetModules) {
is TargetModules.All -> packagesToUpgrade.allUpdates
is TargetModules.One -> packagesToUpgrade.getUpdatesForModule(targetModules.module)
TargetModules.None -> emptyList()
}
val filteredInstalledPackages = installedPackages.filterByTargetModules(targetModules)
filteredPackageUpgrades to filteredInstalledPackages
}
logTrace("PackagesListPanel main flow") { "Initial computation took $time" }
val (filteredPackageUpgrades, filteredInstalledPackages) = result
fun onComplete(computationName: String): (Duration) -> Unit =
{ time -> logTrace("PackagesListPanel main flow") { "Took $time for \"$computationName\"" } }
val filteredInstalledPackagesUiModels = computeFilteredInstalledPackagesUiModels(
packages = filteredInstalledPackages,
onlyMultiplatform = onlyMultiplatform,
targetModules = targetModules,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules,
onlyStable = onlyStable,
searchQuery = searchQuery,
project = project,
onComplete = onComplete("filteredInstalledPackagesUiModelsTime"),
)
val searchResultModels = computeSearchResultModels(
searchResults = apiSearchResults,
installedPackages = filteredInstalledPackagesUiModels,
onlyStable = onlyStable,
targetModules = targetModules,
searchResultsUiStateOverrides = searchResultsUiStateOverrides,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules,
project = project,
cache = searchPackageModelCache,
onComplete = onComplete("searchResultModels")
)
val tableItems = computePackagesTableItems(
packages = filteredInstalledPackagesUiModels + searchResultModels,
targetModules = targetModules,
onComplete = onComplete("tableItemsTime")
)
val headerData = project.lifecycleScope.computeHeaderData(
project = project,
totalItemsCount = tableItems.size,
packageUpdateInfos = filteredPackageUpgrades,
hasSearchResults = apiSearchResults?.packages?.isNotEmpty() ?: false,
targetModules = targetModules,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules,
operationFactory = operationFactory,
cache = headerOperationsCache,
onComplete = onComplete("headerDataTime")
)
ViewModels(
targetModules = targetModules,
headerData = headerData,
viewModel = PackagesTable.ViewModel(
items = tableItems,
onlyStable = onlyStable,
targetModules = targetModules,
knownRepositoriesInTargetModules = knownRepositoriesInTargetModules
)
)
}
logTrace("PackagesListPanel main flow") { "Total elaboration took $time" }
result
}
.flowOn(project.lifecycleScope.coroutineDispatcher)
.onEach { (targetModules, headerData, packagesTableViewModel) ->
val renderingTime = measureTime {
updateListEmptyState(targetModules, project.packageSearchProjectService.isLoadingFlow.value)
headerPanel.display(headerData)
packagesTable.display(packagesTableViewModel)
tableScrollPane.isVisible = packagesTableViewModel.items.isNotEmpty()
listPanel.updateAndRepaint()
packagesTable.updateAndRepaint()
packagesPanel.updateAndRepaint()
}
logTrace("PackagesListPanel main flow") {
"Rendering took $renderingTime for ${packagesTableViewModel.items.size} items"
}
isLoadingStateFlow.emit(false)
}
.flowOn(Dispatchers.EDT)
.catch { logWarn("Error in PackagesListPanel main flow", it) }
.launchIn(project.lifecycleScope)
combineTransform(
isLoadingStateFlow,
isSearchingStateFlow,
project.packageSearchProjectService.isLoadingFlow
) { booleans -> emit(booleans.any { it }) }
.debounce(150)
.onEach { headerPanel.showBusyIndicator(it) }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
project.lookAndFeelFlow.onEach { updateUiOnLafChange() }
.launchIn(project.lifecycleScope)
// The results may have changed server-side. Better clear caches...
timer(10.minutes)
.onEach {
searchPackageModelCache.clear()
searchCache.clear()
headerOperationsCache.clear()
}
.launchIn(project.lifecycleScope)
searchResultsFlow.map { it.searchQuery }
.debounce(500)
.distinctUntilChanged()
.filterNot { it.isBlank() }
.onEach { PackageSearchEventsLogger.logSearchRequest(it) }
.launchIn(project.lifecycleScope)
combine(
ApplicationManager.getApplication().kotlinPluginStatusFlow,
FeatureFlags.smartKotlinMultiplatformCheckboxEnabledFlow,
project.moduleChangesSignalFlow,
) { kotlinPluginStatus, useSmartCheckbox, _ ->
val isKotlinPluginAvailable = kotlinPluginStatus == KotlinPluginStatus.AVAILABLE
isKotlinPluginAvailable && (!useSmartCheckbox || project.hasKotlinModules())
}
.onEach(Dispatchers.EDT) { onlyMultiplatformCheckBox.isVisible = it }
.launchIn(project.lifecycleScope)
}
private fun updateListEmptyState(targetModules: TargetModules, loading: Boolean) {
listPanel.emptyText.clear()
when {
PowerSaveModeState.getCurrentState() == PowerSaveModeState.ENABLED -> {
listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.powerSaveMode")
)
}
isSearching() -> {
listPanel.emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.searching")
}
project.packageSearchProjectService.isComputationAllowed -> when {
targetModules is TargetModules.None -> {
listPanel.emptyText.text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.noModule")
}
!loading -> {
val targetModuleNames = when (targetModules) {
is TargetModules.All -> PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.allModules")
is TargetModules.One -> targetModules.module.projectModule.name
is TargetModules.None -> error("No module selected empty state should be handled separately")
}
listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.packagesOnly", targetModuleNames)
)
listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.learnMore"),
SimpleTextAttributes.LINK_ATTRIBUTES
) {
BrowserUtil.browse("https://www.jetbrains.com/help/idea/package-search-build-system-support-limitations.html")
}
}
else -> listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.loading")
)
}
else -> {
listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.interrupted")
)
listPanel.emptyText.appendLine(
PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.empty.interrupted.restart"),
SimpleTextAttributes.LINK_ATTRIBUTES
) {
project.packageSearchProjectService.resumeComputation()
}
}
}
}
private fun isSearching() = !searchTextField.text.isNullOrBlank()
internal data class ViewModel(
val targetModules: TargetModules,
val installedPackages: List<PackageModel.Installed>,
val packagesUpdateCandidates: PackageUpgradeCandidates,
val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules
)
private fun registerForUiEvents() {
packagesTable.transferFocusUp = {
IdeFocusManager.getInstance(project).requestFocus(searchTextField, false)
}
searchTextField.addOnTextChangedListener { text ->
searchQueryStateFlow.tryEmit(text)
}
onlyStableCheckBox.addSelectionChangedListener { selected ->
onlyStableMutableStateFlow.tryEmit(selected)
PackageSearchEventsLogger.logToggle(FUSGroupIds.ToggleTypes.OnlyStable, selected)
}
onlyMultiplatformCheckBox.addSelectionChangedListener { selected ->
onlyMultiplatformStateFlow.tryEmit(selected)
PackageSearchEventsLogger.logToggle(FUSGroupIds.ToggleTypes.OnlyKotlinMp, selected)
}
project.uiStateSource.searchQueryFlow.onEach { searchTextField.text = it }
.flowOn(Dispatchers.EDT)
.launchIn(project.lifecycleScope)
}
private suspend fun updateUiOnLafChange() = withContext(Dispatchers.EDT) {
@Suppress("MagicNumber") // Dimension constants
with(searchTextField) {
textEditor.putClientProperty("JTextField.Search.Gap", 6.scaled())
textEditor.putClientProperty("JTextField.Search.GapEmptyText", (-1).scaled())
textEditor.border = emptyBorder(left = 6)
textEditor.isOpaque = true
textEditor.background = PackageSearchUI.Colors.headerBackground
}
}
override fun build() = PackageSearchUI.boxPanel {
add(searchPanel)
add(headerPanel)
add(listPanel)
@Suppress("MagicNumber") // Dimension constants
minimumSize = Dimension(200.scaled(), minimumSize.height)
}
override fun getData(dataId: String) = null
private fun onSearchResultStateChanged(
searchResult: PackageModel.SearchResult,
overrideVersion: NormalizedPackageVersion<*>?,
overrideScope: PackageScope?
) {
project.lifecycleScope.launch {
val uiStates = searchResultsUiStateOverridesState.value.toMutableMap()
uiStates[searchResult.identifier] = SearchResultUiState(overrideVersion, overrideScope)
searchResultsUiStateOverridesState.emit(uiStates)
}
}
}
@Suppress("FunctionName")
private fun SearchTextFieldTextChangedListener(action: (DocumentEvent) -> Unit) =
object : DocumentAdapter() {
override fun textChanged(e: DocumentEvent) = action(e)
}
private fun SearchTextField.addOnTextChangedListener(action: (String) -> Unit) =
SearchTextFieldTextChangedListener { action(text) }.also { addDocumentListener(it) }
internal fun JCheckBox.addSelectionChangedListener(action: (Boolean) -> Unit) =
addItemListener { e -> action(e.stateChange == ItemEvent.SELECTED) }
private fun CoroutineScope.computeHeaderData(
project: Project,
totalItemsCount: Int,
packageUpdateInfos: List<PackagesToUpgrade.PackageUpgradeInfo>,
hasSearchResults: Boolean,
targetModules: TargetModules,
knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
operationFactory: PackageSearchOperationFactory,
cache: CoroutineLRUCache<PackagesToUpgrade.PackageUpgradeInfo, List<PackageSearchOperation<*>>>,
onComplete: (Duration) -> Unit = {}
): PackagesHeaderData {
val (result, time) = measureTimedValue {
val moduleNames = if (targetModules is TargetModules.One) {
targetModules.module.projectModule.name
} else {
PackageSearchBundle.message("packagesearch.ui.toolwindow.allModules").lowercase()
}
val title = if (hasSearchResults) {
PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.searchResults")
} else {
PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.installedPackages.addedIn", moduleNames)
}
val operations = async {
packageUpdateInfos.parallelFlatMap { packageUpdateInfo ->
cache.getOrPut(packageUpdateInfo) {
val repoToInstall = knownRepositoriesInTargetModules.repositoryToAddWhenInstallingOrUpgrading(
project = project,
packageModel = packageUpdateInfo.packageModel,
selectedVersion = packageUpdateInfo.targetVersion.originalVersion
)
operationFactory.createChangePackageVersionOperations(
packageModel = packageUpdateInfo.packageModel,
newVersion = packageUpdateInfo.targetVersion.originalVersion,
targetModules = targetModules,
repoToInstall = repoToInstall
)
}
}
}
PackagesHeaderData(
labelText = title,
count = totalItemsCount.coerceAtLeast(0),
availableUpdatesCount = packageUpdateInfos.distinctBy { it.packageModel.identifier }.size,
updateOperations = operations
)
}
onComplete(time)
return result
}
private fun List<PackageModel.Installed>.filterByTargetModules(
targetModules: TargetModules
) = when (targetModules) {
is TargetModules.All -> this
is TargetModules.One -> mapNotNull { installedPackage ->
val filteredUsages = installedPackage.usageInfo.filter {
it.projectModule == targetModules.module.projectModule
}
if (filteredUsages.isEmpty()) return@mapNotNull null
installedPackage.copyWithUsages(filteredUsages)
}
TargetModules.None -> emptyList()
}
private suspend fun computeSearchResultModels(
searchResults: ApiPackagesResponse<ApiStandardPackage, ApiStandardPackage.ApiStandardVersion>?,
installedPackages: List<UiPackageModel.Installed>,
onlyStable: Boolean,
targetModules: TargetModules,
searchResultsUiStateOverrides: Map<PackageIdentifier, SearchResultUiState>,
knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
project: Project,
onComplete: (Duration) -> Unit = {},
cache: CoroutineLRUCache<UiPackageModelCacheKey, UiPackageModel.SearchResult>
): List<UiPackageModel.SearchResult> {
val (result, time) = measureTimedValue {
if (searchResults == null || searchResults.packages.isEmpty()) return@measureTimedValue emptyList()
val installedDependencies = installedPackages
.map { InstalledDependency(it.packageModel.groupId, it.packageModel.artifactId) }
val index = searchResults.packages.parallelMap { "${it.groupId}:${it.artifactId}" }
searchResults.packages
.parallelFilterNot { installedDependencies.any { installed -> installed.matchesCoordinates(it) } }
.parallelMapNotNull { PackageModel.fromSearchResult(it, packageVersionNormalizer) }
.parallelMap {
val uiState = searchResultsUiStateOverrides[it.identifier]
cache.getOrPut(UiPackageModelCacheKey(targetModules, uiState, onlyStable, it)) {
it.toUiPackageModel(targetModules, project, uiState, knownRepositoriesInTargetModules, onlyStable)
}
}
.sortedBy { index.indexOf(it.identifier.rawValue) }
}
onComplete(time)
return result
}
private suspend fun computeFilteredInstalledPackagesUiModels(
packages: List<PackageModel.Installed>,
onlyMultiplatform: Boolean,
targetModules: TargetModules,
knownRepositoriesInTargetModules: KnownRepositories.InTargetModules,
onlyStable: Boolean,
searchQuery: String,
project: Project,
onComplete: (Duration) -> Unit = {}
): List<UiPackageModel.Installed> {
val (result, time) = measureTimedValue {
packages.let { list -> if (onlyMultiplatform) list.filter { it.isKotlinMultiplatform } else list }
.parallelMap { it.toUiPackageModel(targetModules, project, knownRepositoriesInTargetModules, onlyStable) }
.filter { it.sortedVersions.isNotEmpty() && it.packageModel.searchableInfo.contains(searchQuery) }
}
onComplete(time)
return result
}
internal data class UiPackageModelCacheKey(
val targetModules: TargetModules,
val uiState: SearchResultUiState?,
val onlyStable: Boolean,
val searchResult: PackageModel.SearchResult
)
|
apache-2.0
|
783ac39ce7cf45d2955009037f18da3e
| 46.384303 | 148 | 0.684525 | 5.878294 | false | false | false | false |
google/intellij-community
|
plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GrRecursiveCallLineMarkerProvider.kt
|
6
|
2320
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.plugins.groovy.codeInsight
import com.intellij.codeInsight.daemon.LineMarkerInfo
import com.intellij.codeInsight.daemon.LineMarkerProvider
import com.intellij.icons.AllIcons
import com.intellij.java.JavaBundle
import com.intellij.openapi.editor.markup.GutterIconRenderer
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import com.intellij.refactoring.suggested.endOffset
import com.intellij.util.FunctionUtil
import com.intellij.util.castSafelyTo
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
class GrRecursiveCallLineMarkerProvider : LineMarkerProvider {
override fun getLineMarkerInfo(element: PsiElement): LineMarkerInfo<*>? {
return null
}
override fun collectSlowLineMarkers(elements: MutableList<out PsiElement>, result: MutableCollection<in LineMarkerInfo<*>>) {
val lines = mutableSetOf<Int>()
for (element in elements) {
ProgressManager.checkCanceled()
if (element !is GrMethodCall) continue
val calledMethod = element.resolveMethod()?.castSafelyTo<GrMethod>() ?: continue
val parentMethod = element.parentOfType<GrMethod>() ?: continue
if (calledMethod == parentMethod) {
val invoked = element.invokedExpression
val leaf = invoked.castSafelyTo<GrReferenceExpression>()?.referenceNameElement ?: continue
val lineNumber = PsiDocumentManager.getInstance(element.project)?.getDocument(element.containingFile)?.getLineNumber(invoked.endOffset) ?: continue
if (lines.add(lineNumber)) {
result.add(LineMarkerInfo(leaf, leaf.textRange, AllIcons.Gutter.RecursiveMethod,
FunctionUtil.constant(JavaBundle.message("line.marker.recursive.call")), null,
GutterIconRenderer.Alignment.RIGHT) { JavaBundle.message("line.marker.recursive.call") })
}
}
}
}
}
|
apache-2.0
|
4033433868ec829c5b6824fc2aa4f3c9
| 51.75 | 155 | 0.764224 | 4.946695 | false | false | false | false |
Atsky/haskell-idea-plugin
|
plugin/src/org/jetbrains/haskell/util/ProcessRunner.kt
|
1
|
2569
|
package org.jetbrains.haskell.util
import java.io.*
import java.util.ArrayList
class ProcessRunner(workingDirectory: String? = null) {
private val myWorkingDirectory: String? = workingDirectory
fun executeNoFail(vararg cmd: String): String {
return executeNoFail(cmd.toList(), null)
}
fun executeNoFail(cmd: List<String>, input: String?): String {
try {
return executeOrFail(cmd, input)
} catch (e: IOException) {
return ""
}
}
fun executeOrFail(vararg cmd: String): String {
return executeOrFail(cmd.toList(), null)
}
fun executeOrFail(cmd: List<String>, input: String?): String {
val process = getProcess(cmd.toList())
if (input != null) {
val streamWriter = OutputStreamWriter(process.outputStream!!)
streamWriter.write(input)
streamWriter.close()
}
var myInput: InputStream = process.inputStream!!
val data = readData(myInput)
process.waitFor()
return data
}
fun getProcess(cmd: List<String>, path: String? = null): Process {
val processBuilder: ProcessBuilder = ProcessBuilder(cmd)
if (path != null) {
val environment = processBuilder.environment()!!
environment.put("PATH", environment.get("PATH") + ":" + path)
}
if (OSUtil.isMac) {
// It's hack to make homebrew based HaskellPlatform work
val environment = processBuilder.environment()!!
environment.put("PATH", environment.get("PATH") + ":/usr/local/bin")
}
if (myWorkingDirectory != null) {
processBuilder.directory(File(myWorkingDirectory))
}
processBuilder.redirectErrorStream(true)
return processBuilder.start()
}
fun readData(input: InputStream, callback: Callback): Unit {
val reader = BufferedReader(InputStreamReader(input))
while (true) {
var line = reader.readLine()
if (line == null) {
return
}
callback.call(line)
}
}
private fun readData(input: InputStream): String {
val builder = StringBuilder()
readData(input, object : Callback {
override fun call(command: String?): Boolean {
builder.append(command).append("\n")
return true
}
})
return builder.toString()
}
interface Callback {
fun call(command: String?): Boolean
}
}
|
apache-2.0
|
4c7df02991b58313a9bde40122b2bd92
| 26.923913 | 80 | 0.583106 | 4.828947 | false | false | false | false |
apollographql/apollo-android
|
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/codegen/kotlin/file/ObjectBuilder.kt
|
1
|
1649
|
package com.apollographql.apollo3.compiler.codegen.kotlin.file
import com.apollographql.apollo3.compiler.codegen.kotlin.CgFile
import com.apollographql.apollo3.compiler.codegen.kotlin.CgFileBuilder
import com.apollographql.apollo3.compiler.codegen.kotlin.CgOutputFileBuilder
import com.apollographql.apollo3.compiler.codegen.kotlin.KotlinContext
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.maybeAddDeprecation
import com.apollographql.apollo3.compiler.codegen.kotlin.helpers.maybeAddDescription
import com.apollographql.apollo3.compiler.ir.IrObject
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.TypeSpec
class ObjectBuilder(
private val context: KotlinContext,
private val obj: IrObject
): CgOutputFileBuilder {
private val layout = context.layout
private val packageName = layout.typePackageName()
private val simpleName = layout.compiledTypeName(name = obj.name)
override fun prepare() {
context.resolver.registerSchemaType(obj.name, ClassName(packageName, simpleName))
}
override fun build(): CgFile {
return CgFile(
packageName = packageName,
fileName = simpleName,
typeSpecs = listOf(obj.typeSpec())
)
}
private fun IrObject.typeSpec(): TypeSpec {
return TypeSpec
.classBuilder(simpleName)
.maybeAddDescription(description)
.maybeAddDeprecation(deprecationReason)
.addType(companionTypeSpec())
.build()
}
private fun IrObject.companionTypeSpec(): TypeSpec {
return TypeSpec.companionObjectBuilder()
.addProperty(typePropertySpec(context.resolver))
.build()
}
}
|
mit
|
eb16ed4513f6028ad044530700be7c12
| 34.085106 | 85 | 0.768344 | 4.480978 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/branchedTransformations/intentions/FlattenWhenIntention.kt
|
1
|
2803
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions.branchedTransformations.intentions
import com.intellij.openapi.editor.Editor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.core.moveCaret
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.util.psi.patternMatching.matches
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
class FlattenWhenIntention : SelfTargetingIntention<KtWhenExpression>(
KtWhenExpression::class.java,
KotlinBundle.lazyMessage("flatten.when.expression")
) {
override fun isApplicableTo(element: KtWhenExpression, caretOffset: Int): Boolean {
val subject = element.subjectExpression
if (subject != null && subject !is KtNameReferenceExpression) return false
if (!KtPsiUtil.checkWhenExpressionHasSingleElse(element)) return false
val elseEntry = element.entries.singleOrNull { it.isElse } ?: return false
val innerWhen = elseEntry.expression as? KtWhenExpression ?: return false
if (!subject.matches(innerWhen.subjectExpression)) return false
if (!KtPsiUtil.checkWhenExpressionHasSingleElse(innerWhen)) return false
return elseEntry.startOffset <= caretOffset && caretOffset <= innerWhen.whenKeyword.endOffset
}
override fun applyTo(element: KtWhenExpression, editor: Editor?) {
val subjectExpression = element.subjectExpression
val nestedWhen = element.elseExpression as KtWhenExpression
val outerEntries = element.entries
val innerEntries = nestedWhen.entries
val whenExpression = KtPsiFactory(element.project).buildExpression {
appendFixedText("when")
if (subjectExpression != null) {
appendFixedText("(").appendExpression(subjectExpression).appendFixedText(")")
}
appendFixedText("{\n")
for (entry in outerEntries) {
if (entry.isElse) continue
appendNonFormattedText(entry.text)
appendFixedText("\n")
}
for (entry in innerEntries) {
appendNonFormattedText(entry.text)
appendFixedText("\n")
}
appendFixedText("}")
} as KtWhenExpression
val newWhen = element.replaced(whenExpression)
val firstNewEntry = newWhen.entries[outerEntries.size - 1]
editor?.moveCaret(firstNewEntry.textOffset)
}
}
|
apache-2.0
|
8452d84a264b0c4a0b03c227b31c80a4
| 40.835821 | 158 | 0.709954 | 5.143119 | false | false | false | false |
matrix-org/matrix-android-sdk
|
matrix-sdk/src/androidTest/java/org/matrix/androidsdk/common/MockOkHttpInterceptor.kt
|
1
|
2588
|
/*
* 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 org.matrix.androidsdk.common
import okhttp3.*
import javax.net.ssl.HttpsURLConnection
/**
* Allows to intercept network requests for test purpose by
* - re-writing the response
* - changing the response code (200/404/etc..).
* - Test delays..
*
* Basic usage:
* <code>
* val mockInterceptor = MockOkHttpInterceptor()
* mockInterceptor.addRule(MockOkHttpInterceptor.SimpleRule(".well-known/matrix/client", 200, "{}"))
*
* RestHttpClientFactoryProvider.defaultProvider = RestClientHttpClientFactory(mockInterceptor)
* AutoDiscovery().findClientConfig("matrix.org", <callback>)
* </code>
*/
class MockOkHttpInterceptor : Interceptor {
private var rules: ArrayList<Rule> = ArrayList()
fun addRule(rule: Rule) {
rules.add(rule)
}
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
rules.forEach { rule ->
if (originalRequest.url().toString().contains(rule.match)) {
rule.process(originalRequest )?.let {
return it
}
}
}
return chain.proceed(originalRequest)
}
abstract class Rule(val match: String) {
abstract fun process(originalRequest: Request): Response?
}
/**
* Simple rule that reply with the given body for any request that matches the match param
*/
class SimpleRule(match: String,
private val code: Int = HttpsURLConnection.HTTP_OK,
private val body: String = "{}") : Rule(match) {
override fun process(originalRequest: Request): Response? {
return Response.Builder()
.protocol(Protocol.HTTP_1_1)
.request(originalRequest)
.message("mocked answer")
.body(ResponseBody.create(null, body))
.code(code)
.build()
}
}
}
|
apache-2.0
|
4ee9d30dbd60d7bf8b4a0e2386290285
| 30.573171 | 105 | 0.630989 | 4.580531 | false | false | false | false |
neo4j-graphql/neo4j-graphql
|
src/main/kotlin/org/neo4j/graphql/ExtensionFunctions.kt
|
1
|
587
|
package org.neo4j.graphql
import java.io.PrintWriter
import java.io.StringWriter
fun Throwable.stackTraceAsString(): String {
val sw = StringWriter()
this.printStackTrace(PrintWriter(sw))
return sw.toString()
}
fun <T> Iterable<T>.joinNonEmpty(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): String {
return if (iterator().hasNext()) joinTo(StringBuilder(), separator, prefix, postfix, limit, truncated, transform).toString() else ""
}
|
apache-2.0
|
b2cb74e78aaf8aef5461969ab51b6afb
| 40.928571 | 221 | 0.705281 | 4.104895 | false | false | false | false |
neo4j-graphql/neo4j-graphql
|
src/main/kotlin/org/neo4j/graphql/GraphSchema.kt
|
1
|
1654
|
package org.neo4j.graphql
import graphql.GraphQL
import org.neo4j.graphdb.GraphDatabaseService
import java.util.concurrent.atomic.AtomicLong
/**
* @author mh
* *
* @since 29.10.16
*/
object GraphSchema {
private var graphql: GraphQL? = null
private var lastSchemaElements = 0
private val lastUpdated : AtomicLong = AtomicLong()
private val lastCheck : AtomicLong = AtomicLong()
private val UPDATE_FREQ = 10_000
@JvmStatic fun getGraphQL(db: GraphDatabaseService): GraphQL {
val schemaElements = countSchemaElements(db)
if (graphql == null || lastSchemaElements != schemaElements || needUpdate(db)) {
lastSchemaElements = schemaElements
val graphQLSchema = GraphQLSchemaBuilder.buildSchema(db)
graphql = GraphQL.newGraphQL(graphQLSchema).build()
lastUpdated.set(System.currentTimeMillis())
}
return graphql!!
}
private fun needUpdate(db: GraphDatabaseService): Boolean {
val now = System.currentTimeMillis()
if (now - lastCheck.getAndSet(now) < UPDATE_FREQ) return false
return (GraphSchemaScanner.readIdlUpdate(db) > lastUpdated.get())
}
fun countSchemaElements(db: GraphDatabaseService): Int {
val tx = db.beginTx()
try {
val count = db.allLabels.count() + db.allRelationshipTypes.count() + db.allPropertyKeys.count() +
db.schema().constraints.count() + db.schema().indexes.count()
tx.success()
return count
} finally {
tx.close()
}
}
@JvmStatic fun reset() {
graphql = null
}
}
|
apache-2.0
|
1d9620043d7024107cd91b34ed321624
| 31.431373 | 109 | 0.641475 | 4.47027 | false | false | false | false |
zdary/intellij-community
|
platform/configuration-store-impl/src/statistic/eventLog/FeatureUsageSettingsEventScheduler.kt
|
4
|
4395
|
// Copyright 2000-2021 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.configurationStore.statistic.eventLog
import com.intellij.configurationStore.ComponentInfo
import com.intellij.configurationStore.ComponentStoreImpl
import com.intellij.internal.statistic.eventLog.fus.FeatureUsageLogger
import com.intellij.internal.statistic.eventLog.fus.FeatureUsageStateEventTracker
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ComponentManager
import com.intellij.openapi.components.PersistentStateComponent
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.util.concurrency.AppExecutorUtil
import java.util.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.Executor
import java.util.concurrent.TimeUnit
private const val PERIOD_DELAY = 24 * 60L
private const val INITIAL_DELAY = PERIOD_DELAY
private val EDT_EXECUTOR = Executor(ApplicationManager.getApplication()::invokeLater)
internal class FeatureUsageSettingsEventScheduler : FeatureUsageStateEventTracker {
override fun initialize() {
if (!FeatureUsageLogger.isEnabled()) {
return
}
AppExecutorUtil.getAppScheduledExecutorService()
.scheduleWithFixedDelay({ logConfigStateEvents() }, INITIAL_DELAY, PERIOD_DELAY, TimeUnit.MINUTES)
}
override fun reportNow(): CompletableFuture<Void> {
return logConfigStateEvents()
}
}
private fun logConfigStateEvents(): CompletableFuture<Void> {
if (!FeatureUsageLogger.isEnabled()) {
return CompletableFuture.completedFuture(null)
}
val applicationCompletableFuture = logInitializedProjectComponents(ApplicationManager.getApplication())
val projectManager = ProjectManagerEx.getInstanceEx()
val projects = ArrayDeque(projectManager.openProjects.toList())
if (projectManager.isDefaultProjectInitialized) {
projects.addFirst(projectManager.defaultProject)
}
val projectCompletableFuture = logProjectInitializedComponentsAndContinue(projects)
return CompletableFuture.allOf(applicationCompletableFuture, projectCompletableFuture);
}
private fun logProjectInitializedComponentsAndContinue(projects: ArrayDeque<Project>): CompletableFuture<Void?> {
val project = projects.pollFirst()
if (project == null || !project.isInitialized || project.isDisposed) {
return CompletableFuture.completedFuture(null)
}
else {
return logInitializedProjectComponents(project)
.thenCompose {
logProjectInitializedComponentsAndContinue(projects)
}
}
}
private fun logInitializedProjectComponents(componentManager: ComponentManager): CompletableFuture<Void?> {
val stateStore = (componentManager.stateStore as? ComponentStoreImpl) ?: return CompletableFuture.completedFuture(null)
val components = stateStore.getComponents()
return logInitializedComponentsAndContinue(componentManager as? Project, components, ArrayDeque(components.keys))
}
private fun logInitializedComponentsAndContinue(project: Project?,
components: Map<String, ComponentInfo>,
names: ArrayDeque<String>): CompletableFuture<Void?> {
while (true) {
val nextComponentName = names.pollFirst() ?: return CompletableFuture.completedFuture(null)
val future = logInitializedComponent(project, components.get(nextComponentName) ?: continue, nextComponentName) ?: continue
return future
.thenCompose {
logInitializedComponentsAndContinue(project, components, names)
}
}
}
private fun logInitializedComponent(project: Project?, info: ComponentInfo, name: String): CompletableFuture<Void?>? {
val stateSpec = info.stateSpec
if (stateSpec == null || !stateSpec.reportStatistic) {
return null
}
val component = info.component as? PersistentStateComponent<*> ?: return null
return CompletableFuture.runAsync({
try {
component.state?.let { FeatureUsageSettingsEvents.logConfigurationState(name, it, project) }
}
catch (e: Exception) {
logger<FeatureUsageSettingsEventScheduler>().warn("Error during configuration recording", e)
}
}, EDT_EXECUTOR)
}
|
apache-2.0
|
62d6d7a053a5d51236f4ac3fc3803fe4
| 40.857143 | 140 | 0.77884 | 5.282452 | false | true | false | false |
anthonycr/Lightning-Browser
|
app/src/main/java/acr/browser/lightning/search/engine/AskSearch.kt
|
1
|
287
|
package acr.browser.lightning.search.engine
import acr.browser.lightning.R
/**
* The Ask search engine.
*/
class AskSearch : BaseSearchEngine(
"file:///android_asset/ask.png",
"http://www.ask.com/web?qsrc=0&o=0&l=dir&qo=LightningBrowser&q=",
R.string.search_engine_ask
)
|
mpl-2.0
|
ec000ca8ee79b314a6738e1d4b839caf
| 22.916667 | 69 | 0.703833 | 2.958763 | false | false | false | false |
code-helix/slatekit
|
src/lib/kotlin/slatekit-data/src/main/kotlin/slatekit/data/core/Id.kt
|
1
|
1509
|
package slatekit.data.core
/**
* Used to operate on the Id ( primary key ) of a model ( class )
* This allows us to not put any constraints on the model T.
*/
interface Id<TId, T> where TId : Comparable<TId>, T: Any {
/**
* Name of the field representing the primary key
*/
fun name(): String
/**
* Determines if the model is persisted
*/
fun isPersisted(model:T):Boolean
/**
* Determines if the model is persisted
*/
fun isPersisted(id:TId):Boolean
/**
* Determines the identity of the model
*/
fun identity(model:T):TId
/**
* Converts the generated id ( from a database ) to the proper type of TId
*/
fun convertToId(id: String): TId
}
/**
* Long based id support for a model
*/
class LongId<T>(val idName:String = "id", val op:(T) -> Long) : Id<Long, T> where T: Any {
/**
* Name of the field representing the primary key
*/
override fun name(): String { return idName }
/**
* Determines if the model is persisted
*/
override fun isPersisted(model:T):Boolean = op(model) > 0L
/**
* Determines if the model is persisted
*/
override fun isPersisted(id:Long):Boolean = id > 0L
/**
* Determines the identity of the model
*/
override fun identity(model:T):Long = op(model)
/**
* Converts the generated id ( from a database ) to the proper type of TId
*/
override fun convertToId(id: String): Long = id.toLong()
}
|
apache-2.0
|
81f455ba1d111ad259ee57eb4c77ee38
| 22.215385 | 90 | 0.604374 | 3.96063 | false | false | false | false |
Pozo/threejs-kotlin
|
examples/src/main/kotlin/examples/HelloWorldShadow.kt
|
1
|
2324
|
package examples
import three.Shading
import three.ShadowMap
import three.cameras.PerspectiveCamera
import three.geometries.BoxGeometry
import three.lights.PointLight
import three.materials.phong.MeshPhongMaterial
import three.materials.phong.MeshPhongMaterialParam
import three.objects.Mesh
import three.renderers.webglrenderer.WebGLRenderer
import three.renderers.webglrenderer.WebGLRendererParams
import three.scenes.Scene
import kotlin.browser.document
import kotlin.browser.window
class HelloWorldShadow {
val renderer: WebGLRenderer
val scene: Scene
val camera: PerspectiveCamera
val cube: Mesh
init {
scene = Scene()
camera = PerspectiveCamera(75, (window.innerWidth / window.innerHeight).toDouble(), 0.1, 1000)
camera.position.z = 5.0
camera.position.y = 2.0
// renderer = WebGLRenderer()
renderer = WebGLRenderer(WebGLRendererParams())
renderer.setSize(window.innerWidth, window.innerHeight)
renderer.shadowMap.enabled = true
renderer.shadowMap.type = ShadowMap.PCFSoftShadowMap.value
document.body?.appendChild(renderer.domElement)
val light = createLight()
scene.add(light)
cube = createCube()
scene.add(cube)
}
private fun createCube(): Mesh {
val geometry = BoxGeometry(1, 1, 1)
val param = createPhongMaterialParam()
val material = MeshPhongMaterial(param)
val mesh = Mesh(geometry, material)
mesh.castShadow = true
return mesh
}
private fun createLight(): PointLight {
val light = PointLight(0xffffff, 1.0, 100)
light.position.set(0f, 12f, 0f)
light.castShadow = true
light.shadow.mapSize.width = 1024f
light.shadow.mapSize.height = 1024f
return light
}
private fun createPhongMaterialParam(): MeshPhongMaterialParam {
val param = MeshPhongMaterialParam()
param.color = 0xdddddd
param.specular = 0x999999
param.shininess = 15
param.shading = Shading.FlatShading.value
return param
}
fun render() {
window.requestAnimationFrame {
cube.rotation.x += 0.01
cube.rotation.y += 0.01
render()
}
renderer.render(scene, camera)
}
}
|
mit
|
bc8f025deb37ce5c7dc72cf72dfb5f37
| 27 | 102 | 0.670826 | 4.469231 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/functions/invoke/implicitInvokeInCompanionObjectWithFunctionalArgument.kt
|
2
|
280
|
class TestClass {
companion object {
inline operator fun <T> invoke(task: () -> T) = task()
}
}
fun box(): String {
val test1 = TestClass { "K" }
if (test1 != "K") return "fail1, 'test1' == $test1"
val ok = "OK"
val x = TestClass { return ok }
}
|
apache-2.0
|
24943b2ca643dd20fe0f07bba08aff47
| 19.071429 | 62 | 0.532143 | 3.181818 | false | true | false | false |
smmribeiro/intellij-community
|
platform/service-container/src/com/intellij/serviceContainer/BaseComponentAdapter.kt
|
4
|
7740
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment")
package com.intellij.serviceContainer
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.LoadingState
import com.intellij.diagnostic.PluginException
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.openapi.Disposable
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressIndicatorProvider
import com.intellij.openapi.util.Disposer
import org.picocontainer.ComponentAdapter
import org.picocontainer.PicoContainer
internal abstract class BaseComponentAdapter(internal val componentManager: ComponentManagerImpl,
val pluginDescriptor: PluginDescriptor,
@field:Volatile private var initializedInstance: Any?,
private var implementationClass: Class<*>?) : ComponentAdapter {
@Volatile
private var initializing = false
val pluginId: PluginId
get() = pluginDescriptor.pluginId
val isInitializing: Boolean
get() = initializing
protected abstract val implementationClassName: String
protected abstract fun isImplementationEqualsToInterface(): Boolean
final override fun getComponentImplementation() = getImplementationClass()
@Synchronized
fun getImplementationClass(): Class<*> {
var result = implementationClass
if (result == null) {
try {
result = componentManager.loadClass<Any>(implementationClassName, pluginDescriptor)
}
catch (e: ClassNotFoundException) {
throw PluginException("Failed to load class: $implementationClassName", e, pluginDescriptor.pluginId)
}
implementationClass = result
}
return result
}
fun getInitializedInstance() = initializedInstance
@Suppress("DeprecatedCallableAddReplaceWith")
@Deprecated("Do not use")
final override fun getComponentInstance(container: PicoContainer): Any? {
//LOG.error("Use getInstance() instead")
return getInstance(componentManager, null)
}
fun <T : Any> getInstance(componentManager: ComponentManagerImpl,
keyClass: Class<T>?,
createIfNeeded: Boolean = true,
indicator: ProgressIndicator? = null): T? {
// could be called during some component.dispose() call, in this case we don't attempt to instantiate
@Suppress("UNCHECKED_CAST")
val instance = initializedInstance as T?
if (instance != null || !createIfNeeded) {
return instance
}
return getInstanceUncached(componentManager, keyClass, indicator ?: ProgressIndicatorProvider.getGlobalProgressIndicator())
}
private fun <T : Any> getInstanceUncached(componentManager: ComponentManagerImpl, keyClass: Class<T>?, indicator: ProgressIndicator?): T {
LoadingState.COMPONENTS_REGISTERED.checkOccurred()
checkContainerIsActive(componentManager, indicator)
val activityCategory = if (StartUpMeasurer.isEnabled()) getActivityCategory(componentManager) else null
val beforeLockTime = if (activityCategory == null) -1 else StartUpMeasurer.getCurrentTime()
synchronized(this) {
@Suppress("UNCHECKED_CAST")
var instance = initializedInstance as T?
if (instance != null) {
if (activityCategory != null) {
val end = StartUpMeasurer.getCurrentTime()
if ((end - beforeLockTime) > 100) {
// do not report plugin id - not clear who calls us and how we should interpret this delay - total duration vs own duration is enough for plugin cost measurement
StartUpMeasurer.addCompletedActivity(beforeLockTime, end, implementationClassName, ActivityCategory.SERVICE_WAITING, /* pluginId = */ null)
}
}
return instance
}
if (initializing) {
LOG.error(PluginException("Cyclic service initialization: ${toString()}", pluginId))
}
try {
initializing = true
val startTime = StartUpMeasurer.getCurrentTime()
val implementationClass: Class<T>
when {
keyClass != null && isImplementationEqualsToInterface() -> {
implementationClass = keyClass
this.implementationClass = keyClass
}
else -> {
@Suppress("UNCHECKED_CAST")
implementationClass = getImplementationClass() as Class<T>
// check after loading class once again
checkContainerIsActive(componentManager, indicator)
}
}
instance = doCreateInstance(componentManager, implementationClass, indicator)
activityCategory?.let { category ->
val end = StartUpMeasurer.getCurrentTime()
if (activityCategory != ActivityCategory.MODULE_SERVICE || (end - startTime) > StartUpMeasurer.MEASURE_THRESHOLD) {
StartUpMeasurer.addCompletedActivity(startTime, end, implementationClassName, category, pluginId.idString)
}
}
initializedInstance = instance
return instance
}
finally {
initializing = false
}
}
}
/**
* Indicator must be always passed - if under progress, then ProcessCanceledException will be thrown instead of AlreadyDisposedException.
*/
private fun checkContainerIsActive(componentManager: ComponentManagerImpl, indicator: ProgressIndicator?) {
if (indicator != null) {
checkCanceledIfNotInClassInit()
}
if (componentManager.isDisposed) {
throwAlreadyDisposedError(toString(), componentManager, indicator)
}
if (!isGettingServiceAllowedDuringPluginUnloading(pluginDescriptor)) {
componentManager.componentContainerIsReadonly?.let {
val error = AlreadyDisposedException("Cannot create ${toString()} because container in read-only mode (reason=$it, container=${componentManager})")
throw if (indicator == null) error else ProcessCanceledException(error)
}
}
}
internal fun throwAlreadyDisposedError(componentManager: ComponentManagerImpl, indicator: ProgressIndicator?) {
throwAlreadyDisposedError(toString(), componentManager, indicator)
}
protected abstract fun getActivityCategory(componentManager: ComponentManagerImpl): ActivityCategory?
protected abstract fun <T : Any> doCreateInstance(componentManager: ComponentManagerImpl, implementationClass: Class<T>, indicator: ProgressIndicator?): T
@Synchronized
fun <T : Any> replaceInstance(keyAsClass: Class<*>,
instance: T,
parentDisposable: Disposable?,
hotCache: MutableMap<Class<*>, Any?>?): T? {
val old = initializedInstance
initializedInstance = instance
hotCache?.put(keyAsClass, instance)
if (parentDisposable != null) {
Disposer.register(parentDisposable, Disposable {
synchronized(this) {
@Suppress("DEPRECATION")
if (initializedInstance === instance && instance is Disposable && !Disposer.isDisposed(instance)) {
Disposer.dispose(instance)
}
initializedInstance = old
if (hotCache != null) {
if (old == null) {
hotCache.remove(keyAsClass)
}
else {
hotCache.put(keyAsClass, old)
}
}
}
})
}
@Suppress("UNCHECKED_CAST")
return old as T?
}
}
|
apache-2.0
|
33fdb05101f9cdc8bc7cb2b05b8035b1
| 38.697436 | 173 | 0.683075 | 5.819549 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedReceiverParameterInspection.kt
|
1
|
10669
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptorWithAccessors
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.isOverridable
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.isMainFunction
import org.jetbrains.kotlin.idea.quickfix.RemoveUnusedFunctionParameterFix
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeSignatureConfiguration
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinMethodDescriptor
import org.jetbrains.kotlin.idea.refactoring.changeSignature.modify
import org.jetbrains.kotlin.idea.refactoring.changeSignature.runChangeSignature
import org.jetbrains.kotlin.idea.refactoring.explicateAsTextForReceiver
import org.jetbrains.kotlin.idea.refactoring.getThisLabelName
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.idea.util.getThisReceiverOwner
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.anyDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class UnusedReceiverParameterInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return object : KtVisitorVoid() {
private fun check(callableDeclaration: KtCallableDeclaration) {
val receiverTypeReference = callableDeclaration.receiverTypeReference
if (receiverTypeReference == null || receiverTypeReference.textRange.isEmpty) return
if (callableDeclaration is KtProperty && callableDeclaration.accessors.isEmpty()) return
if (callableDeclaration is KtNamedFunction) {
if (!callableDeclaration.hasBody()) return
if (callableDeclaration.name == null) {
val parentQualified = callableDeclaration.getStrictParentOfType<KtQualifiedExpression>()
if (KtPsiUtil.deparenthesize(parentQualified?.callExpression?.calleeExpression) == callableDeclaration) return
}
}
if (callableDeclaration.hasModifier(KtTokens.OVERRIDE_KEYWORD) ||
callableDeclaration.hasModifier(KtTokens.OPERATOR_KEYWORD) ||
callableDeclaration.hasModifier(KtTokens.INFIX_KEYWORD) ||
callableDeclaration.hasActualModifier() ||
callableDeclaration.isOverridable()
) return
val context = callableDeclaration.analyzeWithContent()
val receiverType = context[BindingContext.TYPE, receiverTypeReference] ?: return
val receiverTypeDeclaration = receiverType.constructor.declarationDescriptor
if (DescriptorUtils.isCompanionObject(receiverTypeDeclaration)) return
val callable = context[BindingContext.DECLARATION_TO_DESCRIPTOR, callableDeclaration] ?: return
if (callableDeclaration.isMainFunction(callable)) return
val containingDeclaration = callable.containingDeclaration
if (containingDeclaration != null && containingDeclaration == receiverTypeDeclaration) {
val thisLabelName = containingDeclaration.getThisLabelName()
if (!callableDeclaration.anyDescendantOfType<KtThisExpression> { it.getLabelName() == thisLabelName }) {
registerProblem(receiverTypeReference, true)
}
return
}
var used = false
callableDeclaration.acceptChildren(object : KtVisitorVoid() {
override fun visitKtElement(element: KtElement) {
if (used) return
element.acceptChildren(this)
if (isUsageOfDescriptor(callable, element, context)) {
used = true
}
}
})
if (!used) registerProblem(receiverTypeReference)
}
override fun visitNamedFunction(function: KtNamedFunction) {
check(function)
}
override fun visitProperty(property: KtProperty) {
check(property)
}
private fun registerProblem(receiverTypeReference: KtTypeReference, inSameClass: Boolean = false) {
holder.registerProblem(
receiverTypeReference,
KotlinBundle.message("inspection.unused.receiver.parameter"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
RemoveReceiverFix(inSameClass)
)
}
}
}
class RemoveReceiverFix(private val inSameClass: Boolean) : LocalQuickFix {
override fun getName(): String = actionName
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as? KtTypeReference ?: return
if (!FileModificationService.getInstance().preparePsiElementForWrite(element)) return
apply(element, project, inSameClass)
}
override fun getFamilyName(): String = actionName
override fun startInWriteAction() = false
companion object {
@Nls
private val actionName = KotlinBundle.message("fix.unused.receiver.parameter.remove")
private fun configureChangeSignature() = object : KotlinChangeSignatureConfiguration {
override fun performSilently(affectedFunctions: Collection<PsiElement>) = true
override fun configure(originalDescriptor: KotlinMethodDescriptor) = originalDescriptor.modify { it.removeParameter(0) }
}
fun apply(element: KtTypeReference, project: Project, inSameClass: Boolean = false) {
val function = element.parent as? KtCallableDeclaration ?: return
val callableDescriptor = function.resolveToDescriptorIfAny(BodyResolveMode.FULL) as? CallableDescriptor ?: return
val typeParameters = RemoveUnusedFunctionParameterFix.typeParameters(element)
if (inSameClass) {
runWriteAction {
val explicateAsTextForReceiver = callableDescriptor.explicateAsTextForReceiver()
function.forEachDescendantOfType<KtThisExpression> {
if (it.text == explicateAsTextForReceiver) it.labelQualifier?.delete()
}
function.setReceiverTypeReference(null)
}
} else {
runChangeSignature(project, function.findExistingEditor(), callableDescriptor, configureChangeSignature(), element, actionName)
}
RemoveUnusedFunctionParameterFix.runRemoveUnusedTypeParameters(typeParameters)
}
}
}
}
fun isUsageOfDescriptor(descriptor: DeclarationDescriptor, element: KtElement, context: BindingContext): Boolean {
fun isUsageOfDescriptorInResolvedCall(resolvedCall: ResolvedCall<*>): Boolean {
// As receiver of call
if (resolvedCall.dispatchReceiver.getThisReceiverOwner(context) == descriptor ||
resolvedCall.extensionReceiver.getThisReceiverOwner(context) == descriptor
) {
return true
}
// As explicit "this"
if ((resolvedCall.candidateDescriptor as? ReceiverParameterDescriptor)?.containingDeclaration == descriptor) {
return true
}
if (resolvedCall is VariableAsFunctionResolvedCall) {
return isUsageOfDescriptorInResolvedCall(resolvedCall.variableCall)
}
return false
}
if (element !is KtExpression) return false
return when (element) {
is KtDestructuringDeclarationEntry -> {
listOf { context[BindingContext.COMPONENT_RESOLVED_CALL, element] }
}
is KtProperty -> {
val elementDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, element] as? VariableDescriptorWithAccessors
if (elementDescriptor != null) {
listOf(
{ context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, elementDescriptor.getter] },
{ context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, elementDescriptor.setter] },
{ context[BindingContext.PROVIDE_DELEGATE_RESOLVED_CALL, elementDescriptor] },
)
} else {
emptyList()
}
}
else -> {
listOf(
{ element.getResolvedCall(context) },
{ context[BindingContext.LOOP_RANGE_ITERATOR_RESOLVED_CALL, element] },
{ context[BindingContext.LOOP_RANGE_HAS_NEXT_RESOLVED_CALL, element] },
{ context[BindingContext.LOOP_RANGE_NEXT_RESOLVED_CALL, element] }
)
}
}.any { getResolveCall ->
val resolvedCall = getResolveCall() ?: return@any false
isUsageOfDescriptorInResolvedCall(resolvedCall)
}
}
|
apache-2.0
|
caff73c90fccb4572d305c3e32848c8c
| 49.089202 | 158 | 0.678976 | 6.199303 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MakeVisibleFactory.kt
|
6
|
2692
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities.*
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory3
import org.jetbrains.kotlin.idea.caches.resolve.findModuleDescriptor
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtModifierListOwner
import org.jetbrains.kotlin.psi.psiUtil.containingClass
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.getAllSuperclassesWithoutAny
object MakeVisibleFactory : KotlinIntentionActionsFactory() {
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val element = diagnostic.psiElement as? KtElement ?: return emptyList()
val usageModule = element.findModuleDescriptor()
@Suppress("UNCHECKED_CAST")
val factory = diagnostic.factory as DiagnosticFactory3<*, DeclarationDescriptor, *, DeclarationDescriptor>
val descriptor = factory.cast(diagnostic).c as? DeclarationDescriptorWithVisibility ?: return emptyList()
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(descriptor) as? KtModifierListOwner ?: return emptyList()
if (declaration.hasModifier(KtTokens.SEALED_KEYWORD) && descriptor is ClassConstructorDescriptor) return emptyList()
val module = DescriptorUtils.getContainingModule(descriptor)
val targetVisibilities = when (descriptor.visibility) {
PRIVATE, INVISIBLE_FAKE -> mutableListOf(PUBLIC).apply {
if (module == usageModule) add(INTERNAL)
val superClasses = (element.containingClass()?.descriptor as? ClassDescriptor)?.getAllSuperclassesWithoutAny()
if (superClasses?.contains(declaration.containingClass()?.descriptor) == true) add(PROTECTED)
}
else -> listOf(PUBLIC)
}
return targetVisibilities.mapNotNull { ChangeVisibilityFix.create(declaration, descriptor, it) }
}
}
|
apache-2.0
|
c5c3ba07b2d015ae3781a76ac592d9e3
| 56.276596 | 158 | 0.78529 | 5.299213 | false | false | false | false |
android/compose-samples
|
Jetsurvey/app/src/main/java/com/example/compose/jetsurvey/survey/SurveyFragment.kt
|
1
|
5798
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.compose.jetsurvey.survey
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts.TakePicture
import androidx.compose.animation.AnimatedContent
import androidx.compose.animation.AnimatedContentScope
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.with
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.platform.ComposeView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.example.compose.jetsurvey.R
import com.example.compose.jetsurvey.theme.JetsurveyTheme
import com.google.android.material.datepicker.MaterialDatePicker
class SurveyFragment : Fragment() {
private val viewModel: SurveyViewModel by viewModels {
SurveyViewModelFactory(PhotoUriManager(requireContext().applicationContext))
}
private val takePicture = registerForActivityResult(TakePicture()) { photoSaved ->
if (photoSaved) {
viewModel.onImageSaved()
}
}
@OptIn(ExperimentalAnimationApi::class)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
// In order for savedState to work, the same ID needs to be used for all instances.
id = R.id.sign_in_fragment
layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
setContent {
JetsurveyTheme {
val state = viewModel.uiState.observeAsState().value ?: return@JetsurveyTheme
AnimatedContent(
targetState = state,
transitionSpec = {
fadeIn() + slideIntoContainer(
towards = AnimatedContentScope
.SlideDirection.Up,
animationSpec = tween(ANIMATION_SLIDE_IN_DURATION)
) with
fadeOut(animationSpec = tween(ANIMATION_FADE_OUT_DURATION))
}
) { targetState ->
// It's important to use targetState and not state, as its critical to ensure
// a successful lookup of all the incoming and outgoing content during
// content transform.
when (targetState) {
is SurveyState.Questions -> SurveyQuestionsScreen(
questions = targetState,
shouldAskPermissions = viewModel.askForPermissions,
onAction = { id, action -> handleSurveyAction(id, action) },
onDoNotAskForPermissions = { viewModel.doNotAskForPermissions() },
onDonePressed = { viewModel.computeResult(targetState) },
onBackPressed = {
activity?.onBackPressedDispatcher?.onBackPressed()
}
)
is SurveyState.Result -> SurveyResultScreen(
result = targetState,
onDonePressed = {
activity?.onBackPressedDispatcher?.onBackPressed()
}
)
}
}
}
}
}
}
private fun handleSurveyAction(questionId: Int, actionType: SurveyActionType) {
when (actionType) {
SurveyActionType.PICK_DATE -> showDatePicker(questionId)
SurveyActionType.TAKE_PHOTO -> takeAPhoto()
SurveyActionType.SELECT_CONTACT -> selectContact(questionId)
}
}
private fun showDatePicker(questionId: Int) {
val date = viewModel.getCurrentDate(questionId = questionId)
val picker = MaterialDatePicker.Builder.datePicker()
.setSelection(date)
.build()
picker.show(requireActivity().supportFragmentManager, picker.toString())
picker.addOnPositiveButtonClickListener {
picker.selection?.let { selectedDate ->
viewModel.onDatePicked(questionId, selectedDate)
}
}
}
private fun takeAPhoto() {
takePicture.launch(viewModel.getUriToSaveImage())
}
@Suppress("UNUSED_PARAMETER")
private fun selectContact(questionId: Int) {
// TODO: unsupported for now
}
companion object {
private const val ANIMATION_SLIDE_IN_DURATION = 600
private const val ANIMATION_FADE_OUT_DURATION = 200
}
}
|
apache-2.0
|
f2c66c467856562fdf9dcb214d250b1a
| 40.414286 | 101 | 0.603484 | 5.780658 | false | false | false | false |
serssp/reakt
|
reakt/src/main/kotlin/com/github/andrewoma/react/Log.kt
|
3
|
1796
|
package com.github.andrewoma.react
// Enum doesn't seem to be supported
//public enum class LogLevel { debug info warn error none }
class LogLevel(val ordinal: Int) {
companion object {
val debug = LogLevel(1)
val info = LogLevel(2)
val warn = LogLevel(3)
val error = LogLevel(4)
val none = LogLevel(5)
fun parse(value: String): LogLevel {
return when (value) {
"debug" -> debug
"info" -> info
"warn" -> warn
"error" -> error
"none" -> none
else -> throw Exception("Unknown log level: '$value'")
}
}
}
}
public class Log(val logLevel: LogLevel) {
public fun debug(vararg objects: Any?): Unit = logIfEnabled(LogLevel.debug) { console.info(*objects) }
public fun info(vararg objects: Any?): Unit = logIfEnabled(LogLevel.info) { console.info(*objects) }
public fun warn(vararg objects: Any?): Unit = logIfEnabled(LogLevel.warn) { console.warn(*objects) }
public fun error(vararg objects: Any?): Unit = logIfEnabled(LogLevel.error) { console.error(*objects) }
inline private fun logIfEnabled(level: LogLevel, f: () -> Unit) {
if (level.ordinal >= logLevel.ordinal) f()
}
}
@native("document.location.search")
private val urlParameters: String = noImpl
private fun logLevelFromLocation(location: String): LogLevel {
// Doesn't seem to be regex support for capturing groups, so hack away
val prefix = "log-level="
for (token in location.split("[?&]".toRegex()).toTypedArray()) {
if (token.startsWith(prefix)) return LogLevel.parse(token.substring(prefix.length))
}
return LogLevel.none
}
public val log: Log = Log(logLevelFromLocation(urlParameters))
|
mit
|
0420d6147b713873d0ecacc04572fdfc
| 34.94 | 107 | 0.628062 | 4.176744 | false | false | false | false |
jotomo/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionSendSMS.kt
|
1
|
2196
|
package info.nightscout.androidaps.plugins.general.automation.actions
import android.widget.LinearLayout
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.PumpEnactResult
import info.nightscout.androidaps.plugins.general.automation.elements.InputString
import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.plugins.general.smsCommunicator.SmsCommunicatorPlugin
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.resources.ResourceHelper
import org.json.JSONObject
import javax.inject.Inject
class ActionSendSMS(injector: HasAndroidInjector) : Action(injector) {
@Inject lateinit var resourceHelper: ResourceHelper
@Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin
var text = InputString(injector)
override fun friendlyName(): Int = R.string.sendsmsactiondescription
override fun shortDescription(): String = resourceHelper.gs(R.string.sendsmsactionlabel, text.value)
override fun icon(): Int = R.drawable.ic_notifications
override fun doAction(callback: Callback) {
val result = smsCommunicatorPlugin.sendNotificationToAllNumbers(text.value)
callback.result(PumpEnactResult(injector).success(result).comment(if (result) R.string.ok else R.string.error))?.run()
}
override fun toJSON(): String {
val data = JSONObject().put("text", text.value)
return JSONObject()
.put("type", this.javaClass.name)
.put("data", data)
.toString()
}
override fun fromJSON(data: String): Action {
val o = JSONObject(data)
text.value = JsonHelper.safeGetString(o, "text", "")
return this
}
override fun hasDialog(): Boolean = true
override fun generateDialog(root: LinearLayout) {
LayoutBuilder()
.add(LabelWithElement(injector, resourceHelper.gs(R.string.sendsmsactiontext), "", text))
.build(root)
}
}
|
agpl-3.0
|
c617ed1d54ae9a9f5f18038dce558826
| 40.45283 | 126 | 0.752732 | 4.67234 | false | false | false | false |
cout970/Modeler
|
src/main/kotlin/com/cout970/modeler/gui/canvas/tool/Cursor3DTransformHelper.kt
|
1
|
6459
|
package com.cout970.modeler.gui.canvas.tool
import com.cout970.modeler.api.animation.AnimationTarget
import com.cout970.modeler.api.animation.AnimationTargetGroup
import com.cout970.modeler.api.animation.AnimationTargetObject
import com.cout970.modeler.api.model.IModel
import com.cout970.modeler.api.model.`object`.IGroupRef
import com.cout970.modeler.api.model.selection.ISelection
import com.cout970.modeler.api.model.selection.SelectionTarget
import com.cout970.modeler.api.model.selection.SelectionType
import com.cout970.modeler.core.helpers.TransformationHelper
import com.cout970.modeler.core.model.TRSTransformation
import com.cout970.modeler.core.model.objects
import com.cout970.modeler.gui.Gui
import com.cout970.modeler.gui.canvas.Canvas
import com.cout970.modeler.gui.canvas.helpers.CanvasHelper
import com.cout970.modeler.gui.canvas.helpers.RotationHelper
import com.cout970.modeler.gui.canvas.helpers.ScaleHelper
import com.cout970.modeler.gui.canvas.helpers.TranslationHelper
import com.cout970.modeler.util.toAxisRotations
import com.cout970.modeler.util.toIQuaternion
import com.cout970.modeler.util.toRads
import com.cout970.modeler.util.transform
import com.cout970.vector.api.IQuaternion
import com.cout970.vector.api.IVector2
import com.cout970.vector.api.IVector3
import com.cout970.vector.extensions.Vector3
import com.cout970.vector.extensions.plus
import com.cout970.vector.extensions.times
import com.cout970.vector.extensions.unaryMinus
import org.joml.Quaterniond
class Cursor3DTransformHelper {
var cache: IModel? = null
var offset: Float = 0f
fun applyTransformation(gui: Gui, selection: ISelection, cursor: Cursor3D, hovered: CursorPart,
mouse: Pair<IVector2, IVector2>, canvas: Canvas): IModel {
val oldModel = gui.programState.model
val modelCache = this.cache ?: oldModel
val vector = cursor.rotation.transform(hovered.vector)
val newOffset = when (hovered.mode) {
CursorMode.TRANSLATION -> {
val context = CanvasHelper.getContext(canvas, mouse)
TranslationHelper.getOffset(-vector, canvas, gui.input, context.first, context.second)
}
CursorMode.ROTATION -> {
RotationHelper.getOffsetGlobal(cursor.position, vector, canvas, mouse, gui.input)
}
CursorMode.SCALE -> {
val context = CanvasHelper.getContext(canvas, mouse)
ScaleHelper.getOffset(-vector, canvas, gui.input, context.first, context.second)
}
}
if (newOffset != offset) {
this.offset = newOffset
val animator = gui.animator
// val model = if (animator.selectedAnimation != AnimationRefNone &&
// animator.selectedChannel != null &&
// animator.selectedKeyframe != null &&
// matchesSelection(selection, gui.state.selectedGroup,
// animator.animation.channelMapping[animator.selectedChannel!!])) {
//
// when (hovered.mode) {
// CursorMode.TRANSLATION -> {
// val transform = TRSTransformation(translation = vector * offset)
// AnimationHelper.transformKeyframe(transform, oldModel, animator)
// }
// CursorMode.ROTATION -> {
// val transform = TRSTransformation.fromRotationPivot(cursor.position, quatOfAxisAngled(vector, offset).toAxisRotations())
// AnimationHelper.transformKeyframe(transform, oldModel, animator)
// }
// CursorMode.SCALE -> {
// if (cursor.useLinearScale) {
// AnimationHelper.scaleKeyframe(oldModel, animator, vector, offset)
// } else {
// val transform = TRSTransformation.fromScalePivot(cursor.position, Vector3.ONE + vector * offset)
// AnimationHelper.transformKeyframe(transform, oldModel, animator)
// }
// }
// }
// } else {
val model = when (hovered.mode) {
CursorMode.TRANSLATION -> {
val transform = TRSTransformation(translation = vector * offset)
TransformationHelper.transformLocal(oldModel, selection, animator, transform)
}
CursorMode.ROTATION -> {
val transform = TRSTransformation.fromRotationPivot(cursor.position, quatOfAxisAngled(vector, offset).toAxisRotations())
TransformationHelper.transformLocal(oldModel, selection, animator, transform)
}
CursorMode.SCALE -> {
if (cursor.useLinearScale) {
TransformationHelper.scaleLocal(oldModel, selection, animator, vector, offset)
} else {
val transform = TRSTransformation.fromScalePivot(cursor.position, Vector3.ONE + vector * offset)
TransformationHelper.transformLocal(oldModel, selection, animator, transform)
}
}
}
// }
this.cache = model
return model
} else {
this.cache = modelCache
this.offset = newOffset
return this.cache!!
}
}
fun matchesSelection(selection: ISelection, group: IGroupRef, target: AnimationTarget?): Boolean {
target ?: return false
when (target) {
is AnimationTargetObject -> {
if (selection.selectionTarget != SelectionTarget.MODEL) return false
if (selection.selectionType != SelectionType.OBJECT) return false
if (selection.size != 1) return false
if (target.refs.first() != selection.objects.first()) return false
return true
}
is AnimationTargetGroup -> {
return target.ref == group
}
}
}
// degrees
fun quatOfAxisAngled(angles: IVector3, angle: Number): IQuaternion {
return Quaterniond().rotateAxis(
angle.toDouble(),
angles.x.toRads(),
angles.y.toRads(),
angles.z.toRads()
).toIQuaternion()
}
}
|
gpl-3.0
|
f163c12e980cb86d370eda2e339a91c2
| 43.544828 | 146 | 0.617123 | 4.616869 | false | false | false | false |
cout970/Modeler
|
src/main/kotlin/com/cout970/modeler/gui/leguicomp/LeguiDSL.kt
|
1
|
4309
|
package com.cout970.modeler.gui.leguicomp
import com.cout970.glutilities.structure.Timer
import com.cout970.modeler.controller.Dispatch
import com.cout970.modeler.gui.CSSTheme
import com.cout970.modeler.gui.EventGuiCommand
import com.cout970.modeler.util.forEachComponent
import com.cout970.modeler.util.toColor
import com.cout970.reactive.core.Listener
import com.cout970.reactive.core.RBuilder
import com.cout970.reactive.dsl.*
import org.joml.Vector4f
import org.liquidengine.legui.component.Component
import org.liquidengine.legui.component.TextArea
import org.liquidengine.legui.component.TextComponent
import org.liquidengine.legui.event.Event
import org.liquidengine.legui.event.MouseClickEvent
import org.liquidengine.legui.listener.ListenerMap
import org.liquidengine.legui.theme.Themes
/**
* Created by cout970 on 2017/09/07.
*/
fun panel(func: Panel.() -> Unit): Panel {
val panel = Panel()
func(panel)
return panel
}
val Component.key: String get() = metadata["key"].toString()
fun Component.printPaths(prefix: String = "") {
println("$prefix/$key")
forEachComponent {
printPaths("$prefix/$key/${it.key}")
}
}
fun spaces(amount: Int): String = buildString {
repeat((0 until amount).count()) { append(' ') }
}
fun Component.alignAsColumn(padding: Float, margin: Float = 0f) {
var y = margin
childComponents.forEach {
it.posY = y
y += it.sizeY + padding
}
}
fun Component.alignAsRowFromFixedSize(margin: Float = 0f) {
if (childComponents.isEmpty()) return
val spaceLeft = sizeX - childComponents.sumBy { it.sizeX.toInt() }
val separation = if (childComponents.size == 1) 0f else spaceLeft / (childComponents.size - 1)
var x = margin
childComponents.forEach {
it.posX = x
x += it.sizeY + separation
}
}
fun Component.alignAsRowFromFlexibleSize(padding: Float = 5f, margin: Float = 0f) {
if (childComponents.isEmpty()) return
val space = sizeX - margin * 2
val emptySpace = if (childComponents.size == 1) space else space - padding * (childComponents.size - 1)
val itemSize = emptySpace / childComponents.size
var x = margin
childComponents.forEach {
it.posX = x
it.sizeX = itemSize
x += itemSize + padding
}
}
fun Component.classes(vararg classes: String) {
metadata["classes"] = if (metadata["classes"] is String) {
(metadata["classes"] as String) + "," + classes.joinToString(",")
} else {
classes.joinToString(",")
}
Themes.getDefaultTheme().applyAll(this)
}
fun Component.onMouse(func: (MouseClickEvent<*>) -> Unit) {
listenerMap.addListener(MouseClickEvent::class.java) {
func(it)
}
}
fun Component.onClick(func: (MouseClickEvent<*>) -> Unit) {
listenerMap.addListener(MouseClickEvent::class.java) {
if (it.action == MouseClickEvent.MouseClickAction.CLICK) {
func(it)
}
}
}
fun RBuilder.onDoubleClick(time: Int = 500, func: (MouseClickEvent<*>) -> Unit) {
var timer = Timer.miliTime
onClick {
if (Timer.miliTime - timer < time) {
func(it)
}
timer = Timer.miliTime
}
}
fun TextComponent.defaultTextColor() {
(this as Component).style.textColor = CSSTheme.getColor("text").toColor()
}
fun TextComponent.fontSize(size: Float = 16f) {
(this as Component).style.fontSize = size
}
fun TextArea.defaultTextColor() {
(this as Component).style.textColor = CSSTheme.getColor("text").toColor()
}
fun Component.debugPixelBorder() {
style.border = PixelBorder().apply {
enableBottom = true
enableTop = true
enableLeft = true
enableRight = true
color = Vector4f(1f, 0f, 0f, 1f)
}
}
fun Component.forEachRecursive(func: (Component) -> Unit) {
func(this)
childComponents.forEach { it.forEachRecursive(func) }
}
fun RBuilder.onCmd(cmd: String, func: (args: Map<String, Any>) -> Unit) {
listeners.add(Listener(EventGuiCommand::class.java) { command ->
if (command.command == cmd) {
func(command.args)
}
})
}
fun <T : Event<*>> ListenerMap.clear(clazz: Class<T>) {
getListeners(clazz).forEach { removeListener(clazz, it) }
}
fun Component.dispatch(str: String) {
Dispatch.run(str, this)
}
|
gpl-3.0
|
7d39906877c66868975c0fa1feb445d5
| 27.169935 | 107 | 0.67417 | 3.679761 | false | false | false | false |
charlesng/SampleAppArch
|
app/src/main/java/com/cn29/aac/binding/TextInputEditTextBindingUtil.kt
|
1
|
2642
|
package com.cn29.aac.binding
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import androidx.databinding.BindingAdapter
import com.google.android.material.textfield.TextInputLayout
/**
* Created by Charles Ng on 7/9/2017.
*/
object TextInputEditTextBindingUtil {
@JvmStatic
@BindingAdapter("validation", "errorMsg")
fun setErrorEnable(textInputLayout: TextInputLayout,
stringRule: StringRule,
errorMsg: String?) {
textInputLayout.editText
?.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence,
i: Int,
i1: Int,
i2: Int) {
}
override fun onTextChanged(charSequence: CharSequence,
i: Int,
i1: Int,
i2: Int) {
}
override fun afterTextChanged(editable: Editable) {
textInputLayout.isErrorEnabled = stringRule.validate(
textInputLayout.editText
?.text)
if (stringRule.validate(textInputLayout.editText
?.text)) {
textInputLayout.error = errorMsg
} else {
textInputLayout.error = null
}
}
})
textInputLayout.isErrorEnabled = stringRule.validate(textInputLayout.editText
?.text)
if (stringRule.validate(textInputLayout.editText!!.text)) {
textInputLayout.error = errorMsg
} else {
textInputLayout.error = null
}
}
interface StringRule {
fun validate(s: Editable?): Boolean
}
object Rule {
@JvmField
var NOT_EMPTY_RULE: StringRule = object : StringRule {
override fun validate(s: Editable?): Boolean {
return TextUtils.isEmpty(s.toString())
}
}
var EMAIL_RULE: StringRule = object : StringRule {
override fun validate(s: Editable?): Boolean {
return s.toString().length > 18
}
}
}
}
|
apache-2.0
|
d4483273eb1ce9827da64f3daabfc1f2
| 36.757143 | 85 | 0.466313 | 6.555831 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/TrailingCommaIntention.kt
|
1
|
1779
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.model.SideEffectGuard
import com.intellij.openapi.editor.Editor
import com.intellij.psi.codeStyle.CodeStyleSettingsManager
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingIntention
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.formatter.trailingComma.canAddTrailingCommaWithRegistryCheck
import org.jetbrains.kotlin.psi.KtElement
class TrailingCommaIntention : SelfTargetingIntention<KtElement>(
KtElement::class.java,
KotlinBundle.lazyMessage("intention.trailing.comma.text")
), LowPriorityAction {
override fun applyTo(element: KtElement, editor: Editor?) {
SideEffectGuard.checkSideEffectAllowed(SideEffectGuard.EffectType.SETTINGS)
val kotlinCustomSettings = element.containingKtFile.kotlinCustomSettings
kotlinCustomSettings.ALLOW_TRAILING_COMMA = !kotlinCustomSettings.ALLOW_TRAILING_COMMA
CodeStyleSettingsManager.getInstance(element.project).notifyCodeStyleSettingsChanged()
}
override fun isApplicableTo(element: KtElement, caretOffset: Int): Boolean = element.canAddTrailingCommaWithRegistryCheck().also {
val actionNumber = 1.takeIf { element.containingKtFile.kotlinCustomSettings.ALLOW_TRAILING_COMMA } ?: 0
setTextGetter(KotlinBundle.lazyMessage("intention.trailing.comma.custom.text", actionNumber))
}
override fun startInWriteAction(): Boolean = false
}
|
apache-2.0
|
a1c3c4304329806cebd7b30511f5ebe0
| 54.59375 | 158 | 0.81394 | 5.025424 | false | false | false | false |
idea4bsd/idea4bsd
|
platform/platform-api/src/com/intellij/credentialStore/CredentialAttributes.kt
|
1
|
6007
|
/*
* 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.credentialStore
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.ArrayUtil
import com.intellij.util.ExceptionUtil
import com.intellij.util.io.toByteArray
import com.intellij.util.text.CharArrayCharSequence
import com.intellij.util.text.nullize
import java.nio.ByteBuffer
import java.nio.CharBuffer
import java.nio.charset.CodingErrorAction
import java.util.concurrent.atomic.AtomicReference
/**
* requestor is deprecated. Never use it in new code.
*/
data class CredentialAttributes @JvmOverloads constructor(val serviceName: String, val userName: String? = null, val requestor: Class<*>? = null, val isPasswordMemoryOnly: Boolean = false) {
}
fun CredentialAttributes.toPasswordStoreable() = if (isPasswordMemoryOnly) CredentialAttributes(serviceName, userName, requestor) else this
// user cannot be empty, but password can be
class Credentials(user: String?, val password: OneTimeString? = null) {
constructor(user: String?, password: String?) : this(user, password?.let(::OneTimeString))
constructor(user: String?, password: CharArray?) : this(user, password?.let { OneTimeString(it) })
constructor(user: String?, password: ByteArray?) : this(user, password?.let { OneTimeString(password) })
val userName = user.nullize()
fun getPasswordAsString() = password?.toString()
override fun equals(other: Any?): Boolean {
if (other !is Credentials) return false
return userName == other.userName && password == other.password
}
override fun hashCode() = (userName?.hashCode() ?: 0) * 37 + (password?.hashCode() ?: 0)
}
/**
* DEPRECATED. Never use it in a new code.
*/
fun CredentialAttributes(requestor: Class<*>, userName: String?) = CredentialAttributes(requestor.name, userName, requestor)
fun Credentials?.isFulfilled() = this != null && userName != null && !password.isNullOrEmpty()
fun Credentials?.hasOnlyUserName() = this != null && userName != null && password.isNullOrEmpty()
fun Credentials?.isEmpty() = this == null || (userName == null && password == null)
// input will be cleared
@JvmOverloads
fun OneTimeString(value: ByteArray, offset: Int = 0, length: Int = value.size - offset, clearable: Boolean = false): OneTimeString {
if (length == 0) {
return OneTimeString(ArrayUtil.EMPTY_CHAR_ARRAY)
}
// jdk decodes to heap array, but since this code is very critical, we cannot rely on it, so, we don't use Charsets.UTF_8.decode()
val charsetDecoder = Charsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPLACE).onUnmappableCharacter(CodingErrorAction.REPLACE)
val charArray = CharArray((value.size * charsetDecoder.maxCharsPerByte().toDouble()).toInt())
charsetDecoder.reset()
val charBuffer = CharBuffer.wrap(charArray)
var cr = charsetDecoder.decode(ByteBuffer.wrap(value, offset, length), charBuffer, true)
if (!cr.isUnderflow) {
cr.throwException()
}
cr = charsetDecoder.flush(charBuffer)
if (!cr.isUnderflow) {
cr.throwException()
}
value.fill(0, offset, offset + length)
return OneTimeString(charArray, 0, charBuffer.position(), clearable = clearable)
}
/**
* clearable only if specified explicitly.
*
* Case —
* 1) you create OneTimeString manually on user input.
* 2) you store it in CredentialStore
* 3) you consume it... BUT native credentials store do not store credentials immediately — write is postponed, so, will be an critical error.
*
* so, currently — only credentials store implementations should set this flag on get.
*/
@Suppress("EqualsOrHashCode")
class OneTimeString @JvmOverloads constructor(value: CharArray, offset: Int = 0, length: Int = value.size, private var clearable: Boolean = false) : CharArrayCharSequence(value, offset, offset + length) {
private val consumed = AtomicReference<String?>()
constructor(value: String): this(value.toCharArray()) {
}
private fun consume(willBeCleared: Boolean) {
if (!clearable) {
return
}
if (!willBeCleared) {
consumed.get()?.let { throw IllegalStateException("Already consumed: $it\n---\n") }
}
else if (!consumed.compareAndSet(null, ExceptionUtil.currentStackTrace())) {
throw IllegalStateException("Already consumed at ${consumed.get()}")
}
}
fun toString(clear: Boolean = false): String {
consume(clear)
val result = super.toString()
clear()
return result
}
// string will be cleared and not valid after
@JvmOverloads
fun toByteArray(clear: Boolean = true): ByteArray {
consume(clear)
val result = Charsets.UTF_8.encode(CharBuffer.wrap(myChars, myStart, length))
if (clear) {
clear()
}
return result.toByteArray()
}
private fun clear() {
if (clearable) {
myChars.fill('\u0000', myStart, myEnd)
}
}
@JvmOverloads
fun toCharArray(clear: Boolean = true): CharArray {
consume(clear)
if (clear) {
val result = CharArray(length)
getChars(result, 0)
clear()
return result
}
else {
return chars
}
}
fun clone(clear: Boolean, clearable: Boolean) = OneTimeString(toCharArray(clear), clearable = clearable)
override fun equals(other: Any?): Boolean {
if (other is CharSequence) {
return StringUtil.equals(this, other)
}
return super.equals(other)
}
fun appendTo(builder: StringBuilder) {
consume(false)
builder.append(myChars, myStart, length)
}
}
|
apache-2.0
|
8c14b5d9541fcf45b5fffa59f4013cf0
| 33.494253 | 204 | 0.715714 | 4.124399 | false | false | false | false |
siosio/intellij-community
|
uast/uast-common/src/org/jetbrains/uast/UastUtils.kt
|
2
|
9542
|
// Copyright 2000-2021 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:JvmMultifileClass
@file:JvmName("UastUtils")
package org.jetbrains.uast
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ArrayUtil
import org.jetbrains.annotations.ApiStatus
import java.io.File
inline fun <reified T : UElement> UElement.getParentOfType(strict: Boolean = true): T? = getParentOfType(T::class.java, strict)
@JvmOverloads
fun <T : UElement> UElement.getParentOfType(parentClass: Class<out T>, strict: Boolean = true): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (parentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
element = element.uastParent ?: return null
}
}
fun UElement.skipParentOfType(strict: Boolean, vararg parentClasses: Class<out UElement>): UElement? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (!parentClasses.any { it.isInstance(element) }) {
return element
}
element = element.uastParent ?: return null
}
}
@SafeVarargs
fun <T : UElement> UElement.getParentOfType(
parentClass: Class<out T>,
strict: Boolean = true,
vararg terminators: Class<out UElement>
): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (parentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
if (terminators.any { it.isInstance(element) }) {
return null
}
element = element.uastParent ?: return null
}
}
fun <T : UElement> UElement.getParentOfType(
strict: Boolean = true,
firstParentClass: Class<out T>,
vararg parentClasses: Class<out T>
): T? {
var element = (if (strict) uastParent else this) ?: return null
while (true) {
if (firstParentClass.isInstance(element)) {
@Suppress("UNCHECKED_CAST")
return element as T
}
if (parentClasses.any { it.isInstance(element) }) {
@Suppress("UNCHECKED_CAST")
return element as T
}
element = element.uastParent ?: return null
}
}
@JvmOverloads
fun UElement?.getUCallExpression(searchLimit: Int = Int.MAX_VALUE): UCallExpression? =
this?.withContainingElements?.take(searchLimit)?.mapNotNull {
when (it) {
is UCallExpression -> it
is UQualifiedReferenceExpression -> it.selector as? UCallExpression
else -> null
}
}?.firstOrNull()
fun UElement.getContainingUFile(): UFile? = getParentOfType(UFile::class.java, false)
fun UElement.getContainingUClass(): UClass? = getParentOfType(UClass::class.java)
fun UElement.getContainingUMethod(): UMethod? = getParentOfType(UMethod::class.java)
fun UElement.getContainingUVariable(): UVariable? = getParentOfType(UVariable::class.java)
fun <T : UElement> PsiElement?.findContaining(clazz: Class<T>): T? {
var element = this
while (element != null && element !is PsiFileSystemItem) {
element.toUElement(clazz)?.let { return it }
element = element.parent
}
return null
}
fun <T : UElement> PsiElement?.findAnyContaining(vararg types: Class<out T>): T? = findAnyContaining(Int.Companion.MAX_VALUE, *types)
fun <T : UElement> PsiElement?.findAnyContaining(depthLimit: Int, vararg types: Class<out T>): T? {
var element = this
var i = 0
while (i < depthLimit && element != null && element !is PsiFileSystemItem) {
element.toUElementOfExpectedTypes(*types)?.let { return it }
element = element.parent
i++
}
return null
}
fun isPsiAncestor(ancestor: UElement, child: UElement): Boolean {
val ancestorPsi = ancestor.sourcePsi ?: return false
val childPsi = child.sourcePsi ?: return false
return PsiTreeUtil.isAncestor(ancestorPsi, childPsi, false)
}
fun UElement.isUastChildOf(probablyParent: UElement?, strict: Boolean = false): Boolean {
tailrec fun isChildOf(current: UElement?, probablyParent: UElement): Boolean {
return when (current) {
null -> false
probablyParent -> true
else -> isChildOf(current.uastParent, probablyParent)
}
}
if (probablyParent == null) return false
return isChildOf(if (strict) uastParent else this, probablyParent)
}
/**
* Resolves the receiver element if it implements [UResolvable].
*
* @return the resolved element, or null if the element was not resolved, or if the receiver element is not an [UResolvable].
*/
fun UElement.tryResolve(): PsiElement? = (this as? UResolvable)?.resolve()
fun UElement.tryResolveNamed(): PsiNamedElement? = (this as? UResolvable)?.resolve() as? PsiNamedElement
fun UReferenceExpression?.getQualifiedName(): String? = (this?.resolve() as? PsiClass)?.qualifiedName
/**
* Returns the String expression value, or null if the value can't be calculated or if the calculated value is not a String.
*/
fun UExpression.evaluateString(): String? = evaluate() as? String
fun UExpression.skipParenthesizedExprDown(): UExpression? {
var expression = this
while (expression is UParenthesizedExpression) {
expression = expression.expression
}
return expression
}
fun skipParenthesizedExprUp(elem: UElement?): UElement? {
var parent = elem
while (parent is UParenthesizedExpression) {
parent = parent.uastParent
}
return parent
}
/**
* Get a physical [File] for this file, or null if there is no such file on disk.
*/
fun UFile.getIoFile(): File? = sourcePsi.virtualFile?.let { VfsUtilCore.virtualToIoFile(it) }
@Deprecated("use UastFacade", ReplaceWith("UastFacade"))
@ApiStatus.ScheduledForRemoval(inVersion = "2021.3")
@Suppress("Deprecation")
tailrec fun UElement.getUastContext(): UastContext {
val psi = this.sourcePsi
if (psi != null) {
return psi.project.getService(UastContext::class.java) ?: error("UastContext not found")
}
return (uastParent ?: error("PsiElement should exist at least for UFile")).getUastContext()
}
@Deprecated("could unexpectedly throw exception", ReplaceWith("UastFacade.findPlugin"))
tailrec fun UElement.getLanguagePlugin(): UastLanguagePlugin {
val psi = this.sourcePsi
if (psi != null) {
return UastFacade.findPlugin(psi) ?: error("Language plugin was not found for $this (${this.javaClass.name})")
}
return (uastParent ?: error("PsiElement should exist at least for UFile")).getLanguagePlugin()
}
fun Collection<UElement?>.toPsiElements(): List<PsiElement> = mapNotNull { it?.sourcePsi }
/**
* A helper function for getting parents for given [PsiElement] that could be considered as identifier.
* Useful for working with gutter according to recommendations in [com.intellij.codeInsight.daemon.LineMarkerProvider].
*
* @see [getUParentForAnnotationIdentifier] for working with annotations
*/
fun getUParentForIdentifier(identifier: PsiElement): UElement? {
val uIdentifier = identifier.toUElementOfType<UIdentifier>() ?: return null
return uIdentifier.uastParent
}
/**
* @param arg expression in call arguments list of [this]
* @return parameter that corresponds to the [arg] in declaration to which [this] resolves
*/
fun UCallExpression.getParameterForArgument(arg: UExpression): PsiParameter? {
val psiMethod = resolve() ?: return null
val parameters = psiMethod.parameterList.parameters
return parameters.withIndex().find { (i, p) ->
val argumentForParameter = getArgumentForParameter(i) ?: return@find false
if (wrapULiteral(argumentForParameter) == wrapULiteral(arg)) return@find true
if (arg is ULambdaExpression && arg.sourcePsi?.parent == argumentForParameter.sourcePsi) return@find true // workaround for KT-25297
if (p.isVarArgs && argumentForParameter is UExpressionList) return@find argumentForParameter.expressions.contains(arg)
return@find false
}?.value
}
@ApiStatus.Experimental
tailrec fun UElement.isLastElementInControlFlow(scopeElement: UElement? = null): Boolean =
when (val parent = this.uastParent) {
scopeElement -> if (scopeElement is UBlockExpression) scopeElement.expressions.lastOrNull() == this else true
is UBlockExpression -> if (parent.expressions.lastOrNull() == this) parent.isLastElementInControlFlow(scopeElement) else false
is UElement -> parent.isLastElementInControlFlow(scopeElement)
else -> false
}
fun UNamedExpression.getAnnotationMethod(): PsiMethod? {
val annotation : UAnnotation? = getParentOfType(UAnnotation::class.java, true)
val fqn = annotation?.qualifiedName ?: return null
val annotationSrc = annotation.sourcePsi
if (annotationSrc == null) return null
val psiClass = JavaPsiFacade.getInstance(annotationSrc.project).findClass(fqn, annotationSrc.resolveScope)
if (psiClass != null && psiClass.isAnnotationType) {
return ArrayUtil.getFirstElement(psiClass.findMethodsByName(this.name ?: "value", false))
}
return null
}
val UElement.textRange: TextRange?
get() = sourcePsi?.textRange
/**
* A helper function for getting [UMethod] for element for LineMarker.
* It handles cases, when [getUParentForIdentifier] returns same `parent` for more than one `identifier`.
* Such situations cause multiple LineMarkers for same declaration.
*/
inline fun <reified T : UDeclaration> getUParentForDeclarationLineMarkerElement(lineMarkerElement: PsiElement): T? {
val parent = getUParentForIdentifier(lineMarkerElement) as? T ?: return null
if (parent.uastAnchor.sourcePsiElement != lineMarkerElement) return null
return parent
}
|
apache-2.0
|
b9f503c93efb2f8b20856d1b4ff0728a
| 36.132296 | 140 | 0.735904 | 4.313743 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/createClass/CreateClassFromConstructorCallActionFactory.kt
|
2
|
5765
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass
import org.jetbrains.kotlin.descriptors.ClassConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAndGetResult
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.ParameterInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.TypeInfo
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.getTypeInfoForTypeArguments
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.calls.callUtil.getCall
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.utils.ifEmpty
import java.util.*
object CreateClassFromConstructorCallActionFactory : CreateClassFromUsageFactory<KtCallExpression>() {
override fun getElementOfInterest(diagnostic: Diagnostic): KtCallExpression? {
val diagElement = diagnostic.psiElement
if (diagElement.getNonStrictParentOfType<KtTypeReference>() != null) return null
val callExpr = diagElement.parent as? KtCallExpression ?: return null
return if (callExpr.calleeExpression == diagElement) callExpr else null
}
override fun getPossibleClassKinds(element: KtCallExpression, diagnostic: Diagnostic): List<ClassKind> {
val inAnnotationEntry = diagnostic.psiElement.getNonStrictParentOfType<KtAnnotationEntry>() != null
val (context, moduleDescriptor) = element.analyzeAndGetResult()
val call = element.getCall(context) ?: return emptyList()
val targetParents = getTargetParentsByCall(call, context).ifEmpty { return emptyList() }
val classKind = if (inAnnotationEntry) ClassKind.ANNOTATION_CLASS else ClassKind.PLAIN_CLASS
val fullCallExpr = element.getQualifiedExpressionForSelectorOrThis()
val expectedType = fullCallExpr.guessTypeForClass(context, moduleDescriptor)
if (expectedType != null && !targetParents.any { getClassKindFilter(expectedType, it)(classKind) }) return emptyList()
return listOf(classKind)
}
override fun extractFixData(element: KtCallExpression, diagnostic: Diagnostic): ClassInfo? {
val diagElement = diagnostic.psiElement
if (diagElement.getNonStrictParentOfType<KtTypeReference>() != null) return null
val inAnnotationEntry = diagElement.getNonStrictParentOfType<KtAnnotationEntry>() != null
val callExpr = diagElement.parent as? KtCallExpression ?: return null
if (callExpr.calleeExpression != diagElement) return null
val calleeExpr = callExpr.calleeExpression as? KtSimpleNameExpression ?: return null
val name = calleeExpr.getReferencedName()
if (!inAnnotationEntry && !name.checkClassName()) return null
val callParent = callExpr.parent
val fullCallExpr = if (callParent is KtQualifiedExpression && callParent.selectorExpression == callExpr) callParent else callExpr
val (context, moduleDescriptor) = callExpr.analyzeAndGetResult()
val call = callExpr.getCall(context) ?: return null
val targetParents = getTargetParentsByCall(call, context).ifEmpty { return null }
val inner = isInnerClassExpected(call)
val valueArguments = callExpr.valueArguments
val defaultParamName = if (inAnnotationEntry && valueArguments.size == 1) "value" else null
val anyType = moduleDescriptor.builtIns.nullableAnyType
val parameterInfos = valueArguments.map {
ParameterInfo(
it.getArgumentExpression()?.let { expression -> TypeInfo(expression, Variance.IN_VARIANCE) } ?: TypeInfo(
anyType,
Variance.IN_VARIANCE
),
it.getArgumentName()?.referenceExpression?.getReferencedName() ?: defaultParamName
)
}
val classKind = if (inAnnotationEntry) ClassKind.ANNOTATION_CLASS else ClassKind.PLAIN_CLASS
val expectedType = fullCallExpr.guessTypeForClass(context, moduleDescriptor)
val expectedTypeInfo = expectedType?.toClassTypeInfo() ?: TypeInfo.Empty
val filteredParents = if (expectedType != null) {
targetParents.filter { getClassKindFilter(expectedType, it)(classKind) }.ifEmpty { return null }
} else targetParents
val typeArgumentInfos = if (inAnnotationEntry) Collections.emptyList() else callExpr.getTypeInfoForTypeArguments()
val argumentClassVisibilities = valueArguments.mapNotNull {
(it.getArgumentExpression()?.getCallableDescriptor() as? ClassConstructorDescriptor)?.containingDeclaration?.visibility
}
val primaryConstructorVisibility = when {
DescriptorVisibilities.PRIVATE in argumentClassVisibilities -> DescriptorVisibilities.PRIVATE
DescriptorVisibilities.INTERNAL in argumentClassVisibilities -> DescriptorVisibilities.INTERNAL
else -> null
}
return ClassInfo(
name = name,
targetParents = filteredParents,
expectedTypeInfo = expectedTypeInfo,
inner = inner,
typeArguments = typeArgumentInfos,
parameterInfos = parameterInfos,
primaryConstructorVisibility = primaryConstructorVisibility
)
}
}
|
apache-2.0
|
2c2172ef8e7215f0f5a03c27a54bcc4a
| 51.409091 | 158 | 0.739115 | 5.888662 | false | false | false | false |
google/iosched
|
mobile/src/main/java/com/google/samples/apps/iosched/ui/sessiondetail/SessionDetailFragment.kt
|
1
|
18080
|
/*
* 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.google.samples.apps.iosched.ui.sessiondetail
import android.content.Intent
import android.os.Bundle
import android.provider.CalendarContract
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.content.res.AppCompatResources
import androidx.core.app.ShareCompat
import androidx.core.net.toUri
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.doOnLayout
import androidx.core.view.doOnNextLayout
import androidx.core.view.forEach
import androidx.core.view.updatePadding
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.FragmentNavigatorExtras
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView.RecycledViewPool
import androidx.transition.TransitionInflater
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.R.style
import com.google.samples.apps.iosched.databinding.FragmentSessionDetailBinding
import com.google.samples.apps.iosched.model.Session
import com.google.samples.apps.iosched.model.SpeakerId
import com.google.samples.apps.iosched.shared.analytics.AnalyticsActions
import com.google.samples.apps.iosched.shared.analytics.AnalyticsHelper
import com.google.samples.apps.iosched.shared.di.MapFeatureEnabledFlag
import com.google.samples.apps.iosched.shared.domain.users.SwapRequestParameters
import com.google.samples.apps.iosched.shared.notifications.AlarmBroadcastReceiver
import com.google.samples.apps.iosched.shared.result.successOr
import com.google.samples.apps.iosched.shared.util.toEpochMilli
import com.google.samples.apps.iosched.ui.messages.SnackbarMessageManager
import com.google.samples.apps.iosched.ui.reservation.RemoveReservationDialogFragment
import com.google.samples.apps.iosched.ui.reservation.RemoveReservationDialogFragment.Companion.DIALOG_REMOVE_RESERVATION
import com.google.samples.apps.iosched.ui.reservation.RemoveReservationDialogParameters
import com.google.samples.apps.iosched.ui.reservation.SwapReservationDialogFragment
import com.google.samples.apps.iosched.ui.reservation.SwapReservationDialogFragment.Companion.DIALOG_SWAP_RESERVATION
import com.google.samples.apps.iosched.ui.schedule.ScheduleTwoPaneViewModel
import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailNavigationAction.NavigateToSessionFeedback
import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailNavigationAction.NavigateToSignInDialogAction
import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailNavigationAction.NavigateToSpeakerDetail
import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailNavigationAction.NavigateToSwapReservationDialogAction
import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailNavigationAction.NavigateToYoutube
import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailNavigationAction.RemoveReservationDialogAction
import com.google.samples.apps.iosched.ui.sessiondetail.SessionDetailNavigationAction.ShowNotificationsPrefAction
import com.google.samples.apps.iosched.ui.signin.NotificationsPreferenceDialogFragment
import com.google.samples.apps.iosched.ui.signin.NotificationsPreferenceDialogFragment.Companion.DIALOG_NOTIFICATIONS_PREFERENCE
import com.google.samples.apps.iosched.ui.signin.SignInDialogFragment
import com.google.samples.apps.iosched.ui.signin.SignInDialogFragment.Companion.DIALOG_SIGN_IN
import com.google.samples.apps.iosched.util.doOnApplyWindowInsets
import com.google.samples.apps.iosched.util.launchAndRepeatWithViewLifecycle
import com.google.samples.apps.iosched.util.openWebsiteUrl
import com.google.samples.apps.iosched.util.setContentMaxWidth
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import timber.log.Timber
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Named
@AndroidEntryPoint
class SessionDetailFragment : Fragment(), SessionFeedbackFragment.Listener {
private var shareString = ""
@Inject
lateinit var snackbarMessageManager: SnackbarMessageManager
private val sessionDetailViewModel: SessionDetailViewModel by viewModels()
private val scheduleTwoPaneViewModel: ScheduleTwoPaneViewModel by activityViewModels()
@Inject
lateinit var analyticsHelper: AnalyticsHelper
@Inject
@Named("tagViewPool")
lateinit var tagRecycledViewPool: RecycledViewPool
@Inject
@JvmField
@MapFeatureEnabledFlag
var isMapEnabled: Boolean = false
private var session: Session? = null
private lateinit var sessionTitle: String
private lateinit var binding: FragmentSessionDetailBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
sharedElementReturnTransition = TransitionInflater.from(requireContext())
.inflateTransition(R.transition.speaker_shared_enter)
// Delay the enter transition until speaker image has loaded.
postponeEnterTransition(500L, TimeUnit.MILLISECONDS)
val themedInflater =
inflater.cloneInContext(ContextThemeWrapper(requireActivity(), style.AppTheme_Detail))
binding = FragmentSessionDetailBinding.inflate(themedInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.viewModel = sessionDetailViewModel
binding.lifecycleOwner = viewLifecycleOwner
binding.sessionDetailBottomAppBar.run {
inflateMenu(R.menu.session_detail_menu)
menu.findItem(R.id.menu_item_map)?.isVisible = isMapEnabled
setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.menu_item_share -> {
ShareCompat.IntentBuilder.from(requireActivity())
.setType("text/plain")
.setText(shareString)
.setChooserTitle(R.string.intent_chooser_session_detail)
.startChooser()
}
R.id.menu_item_star -> {
sessionDetailViewModel.userSession.value?.let(
scheduleTwoPaneViewModel::onStarClicked
)
}
R.id.menu_item_map -> {
// TODO support opening Map
}
R.id.menu_item_ask_question -> {
sessionDetailViewModel.session.value?.let { session ->
openWebsiteUrl(requireContext(), session.doryLink)
}
}
R.id.menu_item_calendar -> {
sessionDetailViewModel.session.value?.let(::addToCalendar)
}
}
true
}
}
val detailsAdapter = SessionDetailAdapter(
viewLifecycleOwner,
sessionDetailViewModel,
scheduleTwoPaneViewModel,
tagRecycledViewPool
)
binding.sessionDetailRecyclerView.run {
adapter = detailsAdapter
itemAnimator?.run {
addDuration = 120L
moveDuration = 120L
changeDuration = 120L
removeDuration = 100L
}
doOnApplyWindowInsets { view, insets, padding ->
val systemInsets = insets.getInsets(
WindowInsetsCompat.Type.systemBars() or WindowInsetsCompat.Type.ime()
)
view.updatePadding(bottom = padding.bottom + systemInsets.bottom)
// CollapsingToolbarLayout's default scrim visible trigger height is a bit large.
// Choose something smaller so that the content stays visible longer.
binding.collapsingToolbar.scrimVisibleHeightTrigger = systemInsets.top * 2
}
doOnNextLayout {
setContentMaxWidth(this)
}
}
launchAndRepeatWithViewLifecycle {
observeViewModel()
}
}
private fun CoroutineScope.observeViewModel() {
val menu = binding.sessionDetailBottomAppBar.menu
val starMenu = menu.findItem(R.id.menu_item_star)
launch {
sessionDetailViewModel.shouldShowStarInBottomNav.collect { showStar ->
starMenu.isVisible = showStar
}
}
launch {
sessionDetailViewModel.userEvent.collect { userEvent ->
userEvent?.let {
if (it.isStarred) {
starMenu.setIcon(R.drawable.ic_star)
} else {
starMenu.setIcon(R.drawable.ic_star_border)
}
}
}
}
launch {
sessionDetailViewModel.session.collect {
if (it != null) {
sessionTitle = it.title
activity?.let { activity ->
analyticsHelper.sendScreenView(
"Session Details: $sessionTitle", activity
)
}
}
}
}
// Navigation
launch {
sessionDetailViewModel.navigationActions.collect { action ->
when (action) {
is NavigateToSessionFeedback -> openFeedbackDialog(action.sessionId)
NavigateToSignInDialogAction -> openSignInDialog(requireActivity())
is NavigateToSpeakerDetail -> {
val sharedElement = findSpeakerHeadshot(
binding.sessionDetailRecyclerView,
action.speakerId
)
findNavController().navigate(
SessionDetailFragmentDirections.toSpeakerDetail(action.speakerId),
FragmentNavigatorExtras(
sharedElement to sharedElement.transitionName
)
)
}
is NavigateToSwapReservationDialogAction ->
openSwapReservationDialog(requireActivity(), action.params)
is NavigateToYoutube -> openYoutubeUrl(action.videoId)
is RemoveReservationDialogAction -> openRemoveReservationDialog(
requireActivity(), action.params
)
ShowNotificationsPrefAction -> openNotificationsPreferenceDialog()
}
}
}
launch {
sessionDetailViewModel.session.collect { session ->
shareString = if (session == null) {
""
} else {
getString(
R.string.share_text_session_detail, session.title, session.sessionUrl
)
}
(binding.sessionDetailRecyclerView.adapter as SessionDetailAdapter)
.speakers = session?.speakers?.toList() ?: emptyList()
// ViewBinding is binding the session so we should wait until after the session
// has been laid out to report fully drawn. Note that we are *not* waiting for the
// speaker images to be downloaded and displayed because we are showing a
// placeholder image. Thus the screen appears fully drawn to the user. In terms of
// performance, this allows us to obtain a stable start up times by not including
// the network call to download images, which can vary greatly based on
// uncontrollable factors, mainly network speed.
binding.sessionDetailRecyclerView.doOnLayout {
// If this activity was launched from a deeplink, then the logcat statement is
// printed. Otherwise, SessionDetailFragment is started from the MainActivity
// which would have already reported fully drawn to the framework.
activity?.reportFullyDrawn()
}
}
}
launch {
sessionDetailViewModel.relatedUserSessions.collect {
(binding.sessionDetailRecyclerView.adapter as SessionDetailAdapter)
.related = it.successOr(emptyList())
}
}
launch {
sessionDetailViewModel.showFeedbackButton.collect { showFeedbackButton ->
// When opened from the post session notification, open the feedback dialog
arguments?.let {
val sessionId = SessionDetailFragmentArgs.fromBundle(it).sessionId
val openRateSession =
arguments?.getBoolean(AlarmBroadcastReceiver.EXTRA_SHOW_RATE_SESSION_FLAG)
?: false
if (showFeedbackButton && openRateSession) {
openFeedbackDialog(sessionId)
}
}
}
}
launch {
// Only show the back/up arrow in the toolbar in single-pane configurations.
scheduleTwoPaneViewModel.isTwoPane.collect { isTwoPane ->
if (isTwoPane) {
binding.toolbar.navigationIcon = null
binding.toolbar.setNavigationOnClickListener(null)
} else {
binding.toolbar.navigationIcon =
AppCompatResources.getDrawable(requireContext(), R.drawable.ic_arrow_back)
binding.toolbar.setNavigationOnClickListener {
scheduleTwoPaneViewModel.returnToListPane()
}
}
}
}
launch {
sessionDetailViewModel.session.collect { session ->
menu.findItem(R.id.menu_item_ask_question).isVisible =
session?.doryLink?.isNotBlank() == true
}
}
}
override fun onFeedbackSubmitted() {
binding.snackbar.show(R.string.feedback_thank_you)
}
private fun openYoutubeUrl(youtubeUrl: String) {
analyticsHelper.logUiEvent(sessionTitle, AnalyticsActions.YOUTUBE_LINK)
startActivity(Intent(Intent.ACTION_VIEW, youtubeUrl.toUri()))
}
private fun openSignInDialog(activity: FragmentActivity) {
SignInDialogFragment().show(activity.supportFragmentManager, DIALOG_SIGN_IN)
}
private fun openNotificationsPreferenceDialog() {
NotificationsPreferenceDialogFragment()
.show(requireActivity().supportFragmentManager, DIALOG_NOTIFICATIONS_PREFERENCE)
}
private fun openRemoveReservationDialog(
activity: FragmentActivity,
parameters: RemoveReservationDialogParameters
) {
RemoveReservationDialogFragment.newInstance(parameters)
.show(activity.supportFragmentManager, DIALOG_REMOVE_RESERVATION)
}
private fun openSwapReservationDialog(
activity: FragmentActivity,
parameters: SwapRequestParameters
) {
SwapReservationDialogFragment.newInstance(parameters)
.show(activity.supportFragmentManager, DIALOG_SWAP_RESERVATION)
}
private fun findSpeakerHeadshot(speakers: ViewGroup, speakerId: SpeakerId): View {
speakers.forEach {
if (it.getTag(R.id.tag_speaker_id) == speakerId) {
return it.findViewById(R.id.speaker_item_headshot)
}
}
Timber.e("Could not find view for speaker id $speakerId")
return speakers
}
private fun addToCalendar(session: Session) {
val intent = Intent(Intent.ACTION_INSERT)
.setData(CalendarContract.Events.CONTENT_URI)
.putExtra(CalendarContract.Events.TITLE, session.title)
.putExtra(CalendarContract.Events.EVENT_LOCATION, session.room?.name)
.putExtra(
CalendarContract.Events.DESCRIPTION,
session.getCalendarDescription(
getString(R.string.paragraph_delimiter),
getString(R.string.speaker_delimiter)
)
)
.putExtra(
CalendarContract.EXTRA_EVENT_BEGIN_TIME,
session.startTime.toEpochMilli()
)
.putExtra(
CalendarContract.EXTRA_EVENT_END_TIME,
session.endTime.toEpochMilli()
)
if (intent.resolveActivity(requireContext().packageManager) != null) {
startActivity(intent)
}
}
private fun openFeedbackDialog(sessionId: String) {
SessionFeedbackFragment.createInstance(sessionId)
.show(childFragmentManager, FRAGMENT_SESSION_FEEDBACK)
}
companion object {
private const val FRAGMENT_SESSION_FEEDBACK = "feedback"
}
}
|
apache-2.0
|
ac9c7df7353d864ea42dac462e2f6e4c
| 42.461538 | 128 | 0.648119 | 5.488767 | false | false | false | false |
youdonghai/intellij-community
|
platform/projectModel-impl/src/com/intellij/configurationStore/SchemeManagerIprProvider.kt
|
1
|
2896
|
/*
* 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.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.util.ArrayUtil
import com.intellij.util.PathUtilRt
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.loadElement
import com.intellij.util.toByteArray
import org.jdom.Element
import java.io.InputStream
class SchemeManagerIprProvider(private val subStateTagName: String) : StreamProvider {
private val nameToData = ContainerUtil.newConcurrentMap<String, ByteArray>()
override fun read(fileSpec: String, roamingType: RoamingType, consumer: (InputStream?) -> Unit): Boolean {
nameToData.get(PathUtilRt.getFileName(fileSpec))?.let(ByteArray::inputStream).let { consumer(it) }
return true
}
override fun delete(fileSpec: String, roamingType: RoamingType): Boolean {
nameToData.remove(PathUtilRt.getFileName(fileSpec))
return true
}
override fun processChildren(path: String,
roamingType: RoamingType,
filter: (String) -> Boolean,
processor: (String, InputStream, Boolean) -> Boolean): Boolean {
for ((name, data) in nameToData) {
if (filter(name) && !data.inputStream().use { processor(name, it, false) }) {
break
}
}
return true
}
override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
val name = PathUtilRt.getFileName(fileSpec)
nameToData.put(name, ArrayUtil.realloc(content, size))
}
fun load(state: Element?) {
nameToData.clear()
if (state == null) {
return
}
for (profileElement in state.getChildren(subStateTagName)) {
var name: String? = null
for (optionElement in profileElement.getChildren("option")) {
if (optionElement.getAttributeValue("name") == "myName") {
name = optionElement.getAttributeValue("value")
}
}
if (name.isNullOrEmpty()) {
continue
}
nameToData.put("$name.xml", profileElement.toByteArray())
}
}
fun writeState(state: Element) {
val names = nameToData.keys.toTypedArray()
names.sort()
for (name in names) {
nameToData.get(name)?.let { state.addContent(loadElement(it.inputStream())) }
}
}
}
|
apache-2.0
|
227d18deebbc056ec841ee151e5772f5
| 32.298851 | 108 | 0.686464 | 4.441718 | false | false | false | false |
androidx/androidx
|
camera/camera-core/src/test/java/androidx/camera/core/processing/SurfaceOutputImplTest.kt
|
3
|
4755
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.core.processing
import android.graphics.PixelFormat
import android.graphics.SurfaceTexture
import android.os.Build
import android.os.Looper
import android.util.Size
import android.view.Surface
import androidx.camera.core.CameraEffect
import androidx.camera.core.impl.utils.TransformUtils.sizeToRect
import androidx.camera.core.impl.utils.executor.CameraXExecutors.mainThreadExecutor
import com.google.common.truth.Truth.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.Shadows.shadowOf
import org.robolectric.annotation.Config
import org.robolectric.annotation.internal.DoNotInstrument
/**
* Unit tests for [SurfaceOutputImpl].
*/
@RunWith(RobolectricTestRunner::class)
@DoNotInstrument
@Config(minSdk = Build.VERSION_CODES.LOLLIPOP)
class SurfaceOutputImplTest {
companion object {
private const val TARGET = CameraEffect.PREVIEW
private const val FORMAT = PixelFormat.RGBA_8888
private val OUTPUT_SIZE = Size(640, 480)
private val INPUT_SIZE = Size(640, 480)
}
private lateinit var fakeSurface: Surface
private lateinit var fakeSurfaceTexture: SurfaceTexture
private val surfacesToCleanup = mutableListOf<SettableSurface>()
private val surfaceOutputsToCleanup = mutableListOf<SurfaceOutputImpl>()
@Before
fun setUp() {
fakeSurfaceTexture = SurfaceTexture(0)
fakeSurface = Surface(fakeSurfaceTexture)
}
@After
fun tearDown() {
fakeSurfaceTexture.release()
fakeSurface.release()
surfacesToCleanup.forEach {
it.close()
}
surfaceOutputsToCleanup.forEach {
it.close()
}
}
@Test
fun closeSurface_closeFutureIsDone() {
// Arrange.
val surfaceOutImpl = createFakeSurfaceOutputImpl()
// Act: close the SurfaceOutput.
surfaceOutImpl.close()
shadowOf(Looper.getMainLooper()).idle()
// Assert:
assertThat(surfaceOutImpl.closeFuture.isDone).isTrue()
}
@Test
fun requestClose_receivesOnCloseRequested() {
// Arrange.
val surfaceOutImpl = createFakeSurfaceOutputImpl()
var hasRequestedClose = false
surfaceOutImpl.getSurface(mainThreadExecutor()) {
hasRequestedClose = true
}
// Act.
surfaceOutImpl.requestClose()
shadowOf(Looper.getMainLooper()).idle()
// Assert.
assertThat(hasRequestedClose).isTrue()
}
@Test
fun updateMatrix_containsOpenGlFlipping() {
// Arrange.
val surfaceOut = createFakeSurfaceOutputImpl()
val input = FloatArray(16).also {
android.opengl.Matrix.setIdentityM(it, 0)
}
// Act.
val result = FloatArray(16)
surfaceOut.updateTransformMatrix(result, input)
// Assert: the result contains the flipping for OpenGL.
val expected = FloatArray(16).also {
android.opengl.Matrix.setIdentityM(it, 0)
android.opengl.Matrix.translateM(it, 0, 0f, 1f, 0f)
android.opengl.Matrix.scaleM(it, 0, 1f, -1f, 1f)
}
assertThat(result).usingTolerance(1E-4).containsExactly(expected)
}
@Test
fun closedSurface_noLongerReceivesCloseRequest() {
// Arrange.
val surfaceOutImpl = createFakeSurfaceOutputImpl()
var hasRequestedClose = false
surfaceOutImpl.getSurface(mainThreadExecutor()) {
hasRequestedClose = true
}
// Act.
surfaceOutImpl.close()
surfaceOutImpl.requestClose()
shadowOf(Looper.getMainLooper()).idle()
// Assert.
assertThat(hasRequestedClose).isFalse()
}
private fun createFakeSurfaceOutputImpl() = SurfaceOutputImpl(
fakeSurface,
TARGET,
FORMAT,
OUTPUT_SIZE,
INPUT_SIZE,
sizeToRect(INPUT_SIZE),
/*rotationDegrees=*/0,
/*mirroring=*/false
).apply {
surfaceOutputsToCleanup.add(this)
}
}
|
apache-2.0
|
7e8aedd0267baf0c6e00bc53d51c2656
| 30.084967 | 83 | 0.680336 | 4.507109 | false | true | false | false |
androidx/androidx
|
lifecycle/lifecycle-livedata-core-ktx-lint/src/main/java/androidx/lifecycle/lint/NonNullableMutableLiveDataDetector.kt
|
3
|
11622
|
/*
* Copyright 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.lifecycle.lint
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Detector.UastScanner
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.LintFix
import com.android.tools.lint.detector.api.Scope
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.UastLintUtils
import com.android.tools.lint.detector.api.isKotlin
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiVariable
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.impl.source.PsiImmediateClassType
import org.jetbrains.kotlin.asJava.elements.KtLightTypeParameter
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtNullableType
import org.jetbrains.kotlin.psi.KtTypeReference
import org.jetbrains.uast.UAnnotated
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UReferenceExpression
import org.jetbrains.uast.getUastParentOfType
import org.jetbrains.uast.isNullLiteral
import org.jetbrains.uast.kotlin.KotlinUField
import org.jetbrains.uast.kotlin.KotlinUSimpleReferenceExpression
import org.jetbrains.uast.resolveToUElement
/**
* Lint check for ensuring that [androidx.lifecycle.MutableLiveData] values are never null when
* the type is defined as non-nullable in Kotlin.
*/
class NonNullableMutableLiveDataDetector : Detector(), UastScanner {
companion object {
val ISSUE = Issue.Companion.create(
id = "NullSafeMutableLiveData",
briefDescription = "LiveData value assignment nullability mismatch",
explanation = """This check ensures that LiveData values are not null when explicitly \
declared as non-nullable.
Kotlin interoperability does not support enforcing explicit null-safety when using \
generic Java type parameters. Since LiveData is a Java class its value can always \
be null even when its type is explicitly declared as non-nullable. This can lead \
to runtime exceptions from reading a null LiveData value that is assumed to be \
non-nullable.""",
category = Category.INTEROPERABILITY_KOTLIN,
severity = Severity.FATAL,
implementation = Implementation(
NonNullableMutableLiveDataDetector::class.java,
Scope.JAVA_FILE_SCOPE
),
androidSpecific = true
)
}
val typesMap = HashMap<String, KtTypeReference>()
val methods = listOf("setValue", "postValue")
override fun getApplicableUastTypes(): List<Class<out UElement>>? {
return listOf(UCallExpression::class.java, UClass::class.java)
}
override fun createUastHandler(context: JavaContext): UElementHandler? {
return object : UElementHandler() {
override fun visitClass(node: UClass) {
for (element in node.uastDeclarations) {
if (element is KotlinUField) {
getFieldTypeReference(element)?.let {
// map the variable name to the type reference of its expression.
typesMap.put(element.name, it)
}
}
}
}
private fun getFieldTypeReference(element: KotlinUField): KtTypeReference? {
// If field has type reference, we need to use type reference
// Given the field `val liveDataField: MutableLiveData<Boolean> = MutableLiveData()`
// reference: `MutableLiveData<Boolean>`
// argument: `Boolean`
val typeReference = element.sourcePsi
?.children
?.firstOrNull { it is KtTypeReference } as? KtTypeReference
val typeArgument = typeReference?.typeElement?.typeArgumentsAsTypes?.singleOrNull()
if (typeArgument != null) {
return typeArgument
}
// We need to extract type from the call expression
// Given the field `val liveDataField = MutableLiveData<Boolean>()`
// expression: `MutableLiveData<Boolean>()`
// argument: `Boolean`
val expression = element.sourcePsi
?.children
?.firstOrNull { it is KtCallExpression } as? KtCallExpression
return expression?.typeArguments?.singleOrNull()?.typeReference
}
override fun visitCallExpression(node: UCallExpression) {
if (!isKotlin(node.sourcePsi) || !methods.contains(node.methodName) ||
!context.evaluator.isMemberInSubClassOf(
node.resolve()!!, "androidx.lifecycle.LiveData", false
)
) return
val receiverType = node.receiverType as? PsiClassType
var liveDataType =
if (receiverType != null && receiverType.hasParameters()) {
val receiver =
(node.receiver as? KotlinUSimpleReferenceExpression)?.resolve()
val variable = (receiver as? PsiVariable)
val assignment = variable?.let {
UastLintUtils.findLastAssignment(it, node)
}
val constructorExpression = assignment?.sourcePsi as? KtCallExpression
constructorExpression?.typeArguments?.singleOrNull()?.typeReference
} else {
getTypeArg(receiverType)
}
if (liveDataType == null) {
liveDataType = typesMap[getVariableName(node)] ?: return
}
checkNullability(liveDataType, context, node)
}
private fun getVariableName(node: UCallExpression): String? {
// We need to get the variable this expression is being assigned to
// Given the assignment `liveDataField.value = null`
// node.sourcePsi : `value`
// dot: `.`
// variable: `liveDataField`
val dot = generateSequence(node.sourcePsi?.prevSibling) {
it.prevSibling
}.firstOrNull { it !is PsiWhiteSpace }
val variable = generateSequence(generateSequence(dot?.prevSibling) {
it.prevSibling
}.firstOrNull { it !is PsiWhiteSpace }) {
it.firstChild
}.firstOrNull { it !is PsiWhiteSpace }
return variable?.text
}
}
}
/**
* Iterates [classType]'s hierarchy to find its [androidx.lifecycle.LiveData] value type.
*
* @param classType The [PsiClassType] to search
* @return The LiveData type argument.
*/
fun getTypeArg(classType: PsiClassType?): KtTypeReference? {
if (classType == null) {
return null
}
val cls = classType.resolve().getUastParentOfType<UClass>()
val parentPsiType = cls?.superClassType as PsiClassType
if (parentPsiType.hasParameters()) {
val parentTypeReference = cls.uastSuperTypes[0]
val superType = (parentTypeReference.sourcePsi as KtTypeReference).typeElement
return superType!!.typeArgumentsAsTypes[0]
}
return getTypeArg(parentPsiType)
}
fun checkNullability(
liveDataType: KtTypeReference,
context: JavaContext,
node: UCallExpression
) {
// ignore generic types
if (node.isGenericTypeDefinition()) return
if (liveDataType.typeElement !is KtNullableType) {
val fixes = mutableListOf<LintFix>()
if (context.getLocation(liveDataType).file == context.file) {
// Quick Fixes can only be applied to current file
fixes.add(
fix().name("Change `LiveData` type to nullable")
.replace().with("?").range(context.getLocation(liveDataType)).end().build()
)
}
val argument = node.valueArguments[0]
if (argument.isNullLiteral()) {
// Don't report null!! quick fix.
checkNullability(
context,
argument,
"Cannot set non-nullable LiveData value to `null`",
fixes
)
} else if (argument.isNullable()) {
fixes.add(
fix().name("Add non-null asserted (!!) call")
.replace().with("!!").range(context.getLocation(argument)).end().build()
)
checkNullability(context, argument, "Expected non-nullable value", fixes)
}
}
}
private fun UCallExpression.isGenericTypeDefinition(): Boolean {
val classType = typeArguments.singleOrNull() as? PsiImmediateClassType
val resolveGenerics = classType?.resolveGenerics()
return resolveGenerics?.element is KtLightTypeParameter
}
/**
* Reports a lint error at [element]'s location with message and quick fixes.
*
* @param context The lint detector context.
* @param element The [UElement] to report this error at.
* @param message The error message to report.
* @param fixes The Lint Fixes to report.
*/
private fun checkNullability(
context: JavaContext,
element: UElement,
message: String,
fixes: List<LintFix>
) {
if (fixes.isEmpty()) {
context.report(ISSUE, context.getLocation(element), message)
} else {
context.report(
ISSUE, context.getLocation(element), message,
fix().alternatives(*fixes.toTypedArray())
)
}
}
}
/**
* Checks if the [UElement] is nullable. Always returns `false` if the [UElement] is not a
* [UReferenceExpression] or [UCallExpression].
*
* @return `true` if instance is nullable, `false` otherwise.
*/
internal fun UElement.isNullable(): Boolean {
if (this is UCallExpression) {
val psiMethod = resolve() ?: return false
return psiMethod.hasAnnotation(NULLABLE_ANNOTATION)
} else if (this is UReferenceExpression) {
return (resolveToUElement() as? UAnnotated)?.findAnnotation(NULLABLE_ANNOTATION) != null
}
return false
}
const val NULLABLE_ANNOTATION = "org.jetbrains.annotations.Nullable"
|
apache-2.0
|
2253fd8e94794f199c5de61c5b888a14
| 41.885609 | 100 | 0.616933 | 5.321429 | false | false | false | false |
googlecodelabs/android-dagger-to-hilt
|
app/src/main/java/com/example/android/dagger/user/UserManager.kt
|
1
|
3011
|
/*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.dagger.user
import com.example.android.dagger.storage.Storage
import javax.inject.Inject
import javax.inject.Singleton
private const val REGISTERED_USER = "registered_user"
private const val PASSWORD_SUFFIX = "password"
/**
* Handles User lifecycle. Manages registrations, logs in and logs out.
* Knows when the user is logged in.
*
* Marked with @Singleton since we only one an instance of UserManager in the application graph.
*/
@Singleton
class UserManager @Inject constructor(
private val storage: Storage,
// Since UserManager will be in charge of managing the UserComponent lifecycle,
// it needs to know how to create instances of it
private val userComponentFactory: UserComponent.Factory
) {
/**
* UserComponent is specific to a logged in user. Holds an instance of UserComponent.
* This determines if the user is logged in or not, when the user logs in,
* a new Component will be created. When the user logs out, this will be null.
*/
var userComponent: UserComponent? = null
private set
val username: String
get() = storage.getString(REGISTERED_USER)
fun isUserLoggedIn() = userComponent != null
fun isUserRegistered() = storage.getString(REGISTERED_USER).isNotEmpty()
fun registerUser(username: String, password: String) {
storage.setString(REGISTERED_USER, username)
storage.setString("$username$PASSWORD_SUFFIX", password)
userJustLoggedIn()
}
fun loginUser(username: String, password: String): Boolean {
val registeredUser = this.username
if (registeredUser != username) return false
val registeredPassword = storage.getString("$username$PASSWORD_SUFFIX")
if (registeredPassword != password) return false
userJustLoggedIn()
return true
}
fun logout() {
// When the user logs out, we remove the instance of UserComponent from memory
userComponent = null
}
fun unregister() {
val username = storage.getString(REGISTERED_USER)
storage.setString(REGISTERED_USER, "")
storage.setString("$username$PASSWORD_SUFFIX", "")
logout()
}
private fun userJustLoggedIn() {
// When the user logs in, we create a new instance of UserComponent
userComponent = userComponentFactory.create()
}
}
|
apache-2.0
|
e7e0f71629de37bdbafbc97331d796f0
| 33.215909 | 96 | 0.703421 | 4.589939 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/decompiler/common/KotlinMetadataDecompiler.kt
|
1
|
5839
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.decompiler.common
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiManager
import com.intellij.psi.compiled.ClassFileDecompilers
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.decompiler.KotlinDecompiledFileViewProvider
import org.jetbrains.kotlin.idea.decompiler.KtDecompiledFile
import org.jetbrains.kotlin.idea.decompiler.textBuilder.DecompiledText
import org.jetbrains.kotlin.idea.decompiler.textBuilder.buildDecompiledText
import org.jetbrains.kotlin.idea.decompiler.textBuilder.defaultDecompilerRendererOptions
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.metadata.deserialization.NameResolverImpl
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol
import org.jetbrains.kotlin.serialization.deserialization.ClassDeserializer
import org.jetbrains.kotlin.serialization.deserialization.FlexibleTypeDeserializer
import org.jetbrains.kotlin.serialization.deserialization.getClassId
import org.jetbrains.kotlin.utils.addIfNotNull
import java.io.IOException
abstract class KotlinMetadataDecompiler<out V : BinaryVersion>(
private val fileType: FileType,
private val serializerProtocol: () -> SerializerExtensionProtocol,
private val flexibleTypeDeserializer: FlexibleTypeDeserializer,
private val expectedBinaryVersion: () -> V,
private val invalidBinaryVersion: () -> V,
stubVersion: Int
) : ClassFileDecompilers.Full() {
private val metadataStubBuilder: KotlinMetadataStubBuilder =
KotlinMetadataStubBuilder(stubVersion, fileType, serializerProtocol, ::readFileSafely)
private val renderer: DescriptorRenderer by lazy {
DescriptorRenderer.withOptions { defaultDecompilerRendererOptions() }
}
abstract fun readFile(bytes: ByteArray, file: VirtualFile): FileWithMetadata?
override fun accepts(file: VirtualFile) = file.fileType == fileType
override fun getStubBuilder() = metadataStubBuilder
override fun createFileViewProvider(file: VirtualFile, manager: PsiManager, physical: Boolean): FileViewProvider {
return KotlinDecompiledFileViewProvider(manager, file, physical) { provider ->
val virtualFile = provider.virtualFile
readFileSafely(virtualFile)?.let { fileWithMetadata ->
KtDecompiledFile(provider) {
check(it == virtualFile) {
"Unexpected file $it, expected ${virtualFile.fileType}"
}
buildDecompiledText(fileWithMetadata)
}
}
}
}
@TestOnly
fun readFile(file: VirtualFile) = readFileSafely(file)
private fun readFileSafely(file: VirtualFile, content: ByteArray? = null): FileWithMetadata? {
if (!file.isValid) return null
return try {
readFile(content ?: file.contentsToByteArray(false), file)
} catch (e: IOException) {
// This is needed because sometimes we're given VirtualFile instances that point to non-existent .jar entries.
// Such files are valid (isValid() returns true), but an attempt to read their contents results in a FileNotFoundException.
// Note that although calling "refresh()" instead of catching an exception would seem more correct here,
// it's not always allowed and also is likely to degrade performance
null
}
}
private fun buildDecompiledText(file: FileWithMetadata): DecompiledText {
return when (file) {
is FileWithMetadata.Incompatible -> {
createIncompatibleAbiVersionDecompiledText(expectedBinaryVersion(), file.version)
}
is FileWithMetadata.Compatible -> {
val packageFqName = file.packageFqName
val resolver = KotlinMetadataDeserializerForDecompiler(
packageFqName, file.proto, file.nameResolver, file.version,
serializerProtocol(), flexibleTypeDeserializer
)
val declarations = arrayListOf<DeclarationDescriptor>()
declarations.addAll(resolver.resolveDeclarationsInFacade(packageFqName))
for (classProto in file.classesToDecompile) {
val classId = file.nameResolver.getClassId(classProto.fqName)
declarations.addIfNotNull(resolver.resolveTopLevelClass(classId))
}
buildDecompiledText(packageFqName, declarations, renderer)
}
}
}
}
sealed class FileWithMetadata {
class Incompatible(val version: BinaryVersion) : FileWithMetadata()
open class Compatible(
val proto: ProtoBuf.PackageFragment,
val version: BinaryVersion,
serializerProtocol: SerializerExtensionProtocol
) : FileWithMetadata() {
val nameResolver = NameResolverImpl(proto.strings, proto.qualifiedNames)
val packageFqName = FqName(nameResolver.getPackageFqName(proto.`package`.getExtension(serializerProtocol.packageFqName)))
open val classesToDecompile: List<ProtoBuf.Class> =
proto.class_List.filter { proto ->
val classId = nameResolver.getClassId(proto.fqName)
!classId.isNestedClass && classId !in ClassDeserializer.BLACK_LIST
}
}
}
|
apache-2.0
|
da37eb4564e87b28c0a3a2e6e17c8a2a
| 47.256198 | 158 | 0.721356 | 5.603647 | false | false | false | false |
xgouchet/ArachneMergeTool
|
tests/data/kotlin_imports/no_imports.kt
|
2
|
14661
|
/*
* Copyright 2010-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.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("CollectionsKt")
package kotlin.collections
// import kotlin.comparisons.compareValues
internal object EmptyIterator : ListIterator<Nothing> {
override fun hasNext(): Boolean = false
override fun hasPrevious(): Boolean = false
override fun nextIndex(): Int = 0
override fun previousIndex(): Int = -1
override fun next(): Nothing = throw NoSuchElementException()
override fun previous(): Nothing = throw NoSuchElementException()
}
internal object EmptyList : List<Nothing>, Serializable, RandomAccess {
private const val serialVersionUID: Long = -7390468764508069838L
override fun equals(other: Any?): Boolean = other is List<*> && other.isEmpty()
override fun hashCode(): Int = 1
override fun toString(): String = "[]"
override val size: Int get() = 0
override fun isEmpty(): Boolean = true
override fun contains(element: Nothing): Boolean = false
override fun containsAll(elements: Collection<Nothing>): Boolean = elements.isEmpty()
override fun get(index: Int): Nothing = throw IndexOutOfBoundsException("Empty list doesn't contain element at index $index.")
override fun indexOf(element: Nothing): Int = -1
override fun lastIndexOf(element: Nothing): Int = -1
override fun iterator(): Iterator<Nothing> = EmptyIterator
override fun listIterator(): ListIterator<Nothing> = EmptyIterator
override fun listIterator(index: Int): ListIterator<Nothing> {
if (index != 0) throw IndexOutOfBoundsException("Index: $index")
return EmptyIterator
}
override fun subList(fromIndex: Int, toIndex: Int): List<Nothing> {
if (fromIndex == 0 && toIndex == 0) return this
throw IndexOutOfBoundsException("fromIndex: $fromIndex, toIndex: $toIndex")
}
private fun readResolve(): Any = EmptyList
}
internal fun <T> Array<out T>.asCollection(): Collection<T> = ArrayAsCollection(this, isVarargs = false)
private class ArrayAsCollection<T>(val values: Array<out T>, val isVarargs: Boolean): Collection<T> {
override val size: Int get() = values.size
override fun isEmpty(): Boolean = values.isEmpty()
override fun contains(element: T): Boolean = values.contains(element)
override fun containsAll(elements: Collection<T>): Boolean = elements.all { contains(it) }
override fun iterator(): Iterator<T> = values.iterator()
// override hidden toArray implementation to prevent copying of values array
public fun toArray(): Array<out Any?> = values.copyToArrayOfAny(isVarargs)
}
/** Returns an empty read-only list. The returned list is serializable (JVM). */
public fun <T> emptyList(): List<T> = EmptyList
/** Returns a new read-only list of given elements. The returned list is serializable (JVM). */
public fun <T> listOf(vararg elements: T): List<T> = if (elements.size > 0) elements.asList() else emptyList()
/** Returns an empty read-only list. The returned list is serializable (JVM). */
@kotlin.internal.InlineOnly
public inline fun <T> listOf(): List<T> = emptyList()
/**
* Returns an immutable list containing only the specified object [element].
* The returned list is serializable.
*/
@JvmVersion
public fun <T> listOf(element: T): List<T> = java.util.Collections.singletonList(element)
/** Returns an empty new [MutableList]. */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> mutableListOf(): MutableList<T> = ArrayList()
/** Returns an empty new [ArrayList]. */
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> arrayListOf(): ArrayList<T> = ArrayList()
/** Returns a new [MutableList] with the given elements. */
public fun <T> mutableListOf(vararg elements: T): MutableList<T>
= if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
/** Returns a new [ArrayList] with the given elements. */
public fun <T> arrayListOf(vararg elements: T): ArrayList<T>
= if (elements.size == 0) ArrayList() else ArrayList(ArrayAsCollection(elements, isVarargs = true))
/** Returns a new read-only list either of single given element, if it is not null, or empty list it the element is null. The returned list is serializable (JVM). */
public fun <T : Any> listOfNotNull(element: T?): List<T> = if (element != null) listOf(element) else emptyList()
/** Returns a new read-only list only of those given elements, that are not null. The returned list is serializable (JVM). */
public fun <T : Any> listOfNotNull(vararg elements: T?): List<T> = elements.filterNotNull()
/**
* Creates a new read-only list with the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns a list element given its index.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> List(size: Int, init: (index: Int) -> T): List<T> = MutableList(size, init)
/**
* Creates a new mutable list with the specified [size], where each element is calculated by calling the specified
* [init] function. The [init] function returns a list element given its index.
*/
@SinceKotlin("1.1")
@kotlin.internal.InlineOnly
public inline fun <T> MutableList(size: Int, init: (index: Int) -> T): MutableList<T> {
val list = ArrayList<T>(size)
repeat(size) { index -> list.add(init(index)) }
return list
}
/**
* Returns an [IntRange] of the valid indices for this collection.
*/
public val Collection<*>.indices: IntRange
get() = 0..size - 1
/**
* Returns the index of the last item in the list or -1 if the list is empty.
*
* @sample samples.collections.Collections.Lists.lastIndexOfList
*/
public val <T> List<T>.lastIndex: Int
get() = this.size - 1
/** Returns `true` if the collection is not empty. */
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>.isNotEmpty(): Boolean = !isEmpty()
/** Returns this Collection if it's not `null` and the empty list otherwise. */
@kotlin.internal.InlineOnly
public inline fun <T> Collection<T>?.orEmpty(): Collection<T> = this ?: emptyList()
/** Returns this List if it's not `null` and the empty list otherwise. */
@kotlin.internal.InlineOnly
public inline fun <T> List<T>?.orEmpty(): List<T> = this ?: emptyList()
/**
* Returns a list containing the elements returned by this enumeration
* in the order they are returned by the enumeration.
*/
@JvmVersion
@kotlin.internal.InlineOnly
public inline fun <T> java.util.Enumeration<T>.toList(): List<T> = java.util.Collections.list(this)
/**
* Checks if all elements in the specified collection are contained in this collection.
*
* Allows to overcome type-safety restriction of `containsAll` that requires to pass a collection of type `Collection<E>`.
*/
@kotlin.internal.InlineOnly
public inline fun <@kotlin.internal.OnlyInputTypes T> Collection<T>.containsAll(elements: Collection<T>): Boolean = this.containsAll(elements)
internal fun <T> List<T>.optimizeReadOnlyList() = when (size) {
0 -> emptyList()
1 -> listOf(this[0])
else -> this
}
@JvmVersion
@kotlin.internal.InlineOnly
internal inline fun copyToArrayImpl(collection: Collection<*>): Array<Any?> =
kotlin.jvm.internal.CollectionToArray.toArray(collection)
@JvmVersion
@kotlin.internal.InlineOnly
internal inline fun <T> copyToArrayImpl(collection: Collection<*>, array: Array<T>): Array<T> =
kotlin.jvm.internal.CollectionToArray.toArray(collection, array)
// copies typed varargs array to array of objects
@JvmVersion
private fun <T> Array<out T>.copyToArrayOfAny(isVarargs: Boolean): Array<Any?> =
if (isVarargs && this.javaClass == Array<Any?>::class.java)
// if the array came from varargs and already is array of Any, copying isn't required
@Suppress("UNCHECKED_CAST") (this as Array<Any?>)
else
java.util.Arrays.copyOf(this, this.size, Array<Any?>::class.java)
/**
* Searches this list or its range for the provided [element] using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the Comparable natural ordering of its elements,
* otherwise the result is undefined.
*
* If the list contains multiple elements equal to the specified [element], there is no guarantee which one will be found.
*
* `null` value is considered to be less than any non-null value.
*
* @return the index of the element, if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted.
*/
public fun <T: Comparable<T>> List<T?>.binarySearch(element: T?, fromIndex: Int = 0, toIndex: Int = size): Int {
rangeCheck(size, fromIndex, toIndex)
var low = fromIndex
var high = toIndex - 1
while (low <= high) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = get(mid)
val cmp = compareValues(midVal, element)
if (cmp < 0)
low = mid + 1
else if (cmp > 0)
high = mid - 1
else
return mid // key found
}
return -(low + 1) // key not found
}
/**
* Searches this list or its range for the provided [element] using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the specified [comparator],
* otherwise the result is undefined.
*
* If the list contains multiple elements equal to the specified [element], there is no guarantee which one will be found.
*
* `null` value is considered to be less than any non-null value.
*
* @return the index of the element, if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted according to the specified [comparator].
*/
public fun <T> List<T>.binarySearch(element: T, comparator: Comparator<in T>, fromIndex: Int = 0, toIndex: Int = size): Int {
rangeCheck(size, fromIndex, toIndex)
var low = fromIndex
var high = toIndex - 1
while (low <= high) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = get(mid)
val cmp = comparator.compare(midVal, element)
if (cmp < 0)
low = mid + 1
else if (cmp > 0)
high = mid - 1
else
return mid // key found
}
return -(low + 1) // key not found
}
/**
* Searches this list or its range for an element having the key returned by the specified [selector] function
* equal to the provided [key] value using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the Comparable natural ordering of keys of its elements.
* otherwise the result is undefined.
*
* If the list contains multiple elements with the specified [key], there is no guarantee which one will be found.
*
* `null` value is considered to be less than any non-null value.
*
* @return the index of the element with the specified [key], if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted.
*/
public inline fun <T, K : Comparable<K>> List<T>.binarySearchBy(key: K?, fromIndex: Int = 0, toIndex: Int = size, crossinline selector: (T) -> K?): Int =
binarySearch(fromIndex, toIndex) { compareValues(selector(it), key) }
// do not introduce this overload --- too rare
//public fun <T, K> List<T>.binarySearchBy(key: K, comparator: Comparator<K>, fromIndex: Int = 0, toIndex: Int = size(), selector: (T) -> K): Int =
// binarySearch(fromIndex, toIndex) { comparator.compare(selector(it), key) }
/**
* Searches this list or its range for an element for which [comparison] function returns zero using the binary search algorithm.
* The list is expected to be sorted into ascending order according to the provided [comparison],
* otherwise the result is undefined.
*
* If the list contains multiple elements for which [comparison] returns zero, there is no guarantee which one will be found.
*
* @param comparison function that compares an element of the list with the element being searched.
*
* @return the index of the found element, if it is contained in the list within the specified range;
* otherwise, the inverted insertion point `(-insertion point - 1)`.
* The insertion point is defined as the index at which the element should be inserted,
* so that the list (or the specified subrange of list) still remains sorted.
*/
public fun <T> List<T>.binarySearch(fromIndex: Int = 0, toIndex: Int = size, comparison: (T) -> Int): Int {
rangeCheck(size, fromIndex, toIndex)
var low = fromIndex
var high = toIndex - 1
while (low <= high) {
val mid = (low + high).ushr(1) // safe from overflows
val midVal = get(mid)
val cmp = comparison(midVal)
if (cmp < 0)
low = mid + 1
else if (cmp > 0)
high = mid - 1
else
return mid // key found
}
return -(low + 1) // key not found
}
/**
* Checks that `from` and `to` are in
* the range of [0..size] and throws an appropriate exception, if they aren't.
*/
private fun rangeCheck(size: Int, fromIndex: Int, toIndex: Int) {
when {
fromIndex > toIndex -> throw IllegalArgumentException("fromIndex ($fromIndex) is greater than toIndex ($toIndex).")
fromIndex < 0 -> throw IndexOutOfBoundsException("fromIndex ($fromIndex) is less than zero.")
toIndex > size -> throw IndexOutOfBoundsException("toIndex ($toIndex) is greater than size ($size).")
}
}
|
apache-2.0
|
e27c5254cae81dca62bad9ab470c9f44
| 41.619186 | 165 | 0.70002 | 4.096396 | false | false | false | false |
JetBrains/kotlin-native
|
backend.native/tests/codegen/coroutines/controlFlow_tryCatch3.kt
|
4
|
1240
|
/*
* 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 file.
*/
package codegen.coroutines.controlFlow_tryCatch3
import kotlin.test.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resumeWith(result: Result<Any?>) { result.getOrThrow() }
}
suspend fun s1(): Int = suspendCoroutineUninterceptedOrReturn { x ->
println("s1")
x.resume(42)
COROUTINE_SUSPENDED
}
suspend fun s2(): Int = suspendCoroutineUninterceptedOrReturn { x ->
println("s2")
x.resumeWithException(Error())
COROUTINE_SUSPENDED
}
fun f1(): Int {
println("f1")
return 117
}
fun f2(): Int {
println("f2")
return 1
}
fun f3(x: Int, y: Int): Int {
println("f3")
return x + y
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
@Test fun runTest() {
var result = 0
builder {
result = try {
s2()
} catch (t: Throwable) {
f2()
}
}
println(result)
}
|
apache-2.0
|
0f75a4079e07866cdbb07314ba9e2489
| 19.344262 | 115 | 0.649194 | 3.862928 | false | false | false | false |
GunoH/intellij-community
|
platform/platform-impl/src/com/intellij/ide/actions/HideAllToolWindowsAction.kt
|
2
|
2492
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ide.actions
import com.intellij.ide.IdeBundle
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.openapi.wm.ex.ToolWindowManagerEx
import com.intellij.openapi.wm.impl.ToolWindowManagerImpl
import com.intellij.toolWindow.ToolWindowEventSource
internal class HideAllToolWindowsAction : DumbAwareAction() {
override fun actionPerformed(event: AnActionEvent) {
val toolWindowManager = ToolWindowManager.getInstance(event.project ?: return) as? ToolWindowManagerImpl ?: return
val idsToHide = getIdsToHide(toolWindowManager)
if (idsToHide.none()) {
toolWindowManager.layoutToRestoreLater?.let {
toolWindowManager.layoutToRestoreLater = null
toolWindowManager.setLayout(it)
}
}
else {
val layout = toolWindowManager.getLayout().copy()
toolWindowManager.clearSideStack()
for (id in idsToHide) {
toolWindowManager.hideToolWindow(id = id, source = ToolWindowEventSource.HideAllWindowsAction)
}
toolWindowManager.layoutToRestoreLater = layout
toolWindowManager.activateEditorComponent()
}
}
override fun update(event: AnActionEvent) {
val presentation = event.presentation
presentation.isEnabled = false
val toolWindowManager = ToolWindowManager.getInstance(event.project ?: return) as ToolWindowManagerEx
if (getIdsToHide(toolWindowManager).any()) {
presentation.isEnabled = true
presentation.putClientProperty(MaximizeEditorInSplitAction.CURRENT_STATE_IS_MAXIMIZED_KEY, false)
presentation.text = IdeBundle.message("action.hide.all.windows")
}
else if (toolWindowManager.layoutToRestoreLater != null) {
presentation.isEnabled = true
presentation.text = IdeBundle.message("action.restore.windows")
presentation.putClientProperty(MaximizeEditorInSplitAction.CURRENT_STATE_IS_MAXIMIZED_KEY, true)
return
}
}
override fun getActionUpdateThread() = ActionUpdateThread.EDT
}
private fun getIdsToHide(toolWindowManager: ToolWindowManagerEx): Sequence<String> {
return toolWindowManager.toolWindows.asSequence()
.filter { HideToolWindowAction.shouldBeHiddenByShortCut(it) }
.map { it.id }
}
|
apache-2.0
|
419a0b169da148944117d1d0752c28e5
| 41.982759 | 120 | 0.770867 | 4.974052 | false | false | false | false |
smmribeiro/intellij-community
|
platform/platform-api/src/com/intellij/util/animation/Animations.kt
|
1
|
6254
|
// Copyright 2000-2021 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:JvmName("Animations")
package com.intellij.util.animation
import com.intellij.ui.ColorUtil
import java.awt.Color
import java.awt.Dimension
import java.awt.Point
import java.awt.Rectangle
import java.util.function.Consumer
import java.util.function.DoubleConsumer
import java.util.function.DoubleFunction
import java.util.function.IntConsumer
import java.util.function.LongConsumer
import kotlin.math.roundToInt
import kotlin.math.roundToLong
/**
* Update [animations] delay time in such a way that
* animations will be run one by one.
*/
fun makeSequent(vararg animations: Animation): Collection<Animation> {
for (i in 1 until animations.size) {
val prev = animations[i - 1]
val curr = animations[i]
curr.delay += prev.delay + prev.duration
}
return animations.toList()
}
/**
* Empty animation (do nothing).
*
* May be used as an anchor frame for any of [Animation.runWhenScheduled], [Animation.runWhenUpdated] or [Animation.runWhenExpired] methods.
*/
fun animation(): Animation = animation {}
/**
* Very common animation.
*/
fun animation(consumer: DoubleConsumer) = Animation(consumer)
fun animation(from: Int, to: Int, consumer: IntConsumer): Animation {
return Animation(DoubleConsumer { value ->
consumer.accept((from + value * (to - from)).roundToInt())
})
}
fun <T> animation(context: AnimationContext<T>, function: DoubleFunction<T>): Animation {
return Animation.withContext(context, function)
}
fun animation(from: Long, to: Long, consumer: LongConsumer): Animation {
return Animation(DoubleConsumer { value ->
consumer.accept((from + value * (to - from)).roundToLong())
})
}
fun animation(from: Float, to: Float, consumer: FloatConsumer): Animation {
return Animation(DoubleConsumer { value ->
consumer.accept(from + (value * (to - from)).toFloat())
})
}
fun animation(from: Double, to: Double, consumer: DoubleConsumer): Animation {
return Animation(DoubleConsumer { value ->
consumer.accept(from + value * (to - from))
})
}
fun animation(from: Point, to: Point, consumer: Consumer<Point>): Animation {
return Animation(DoublePointFunction(from, to), consumer)
}
fun animation(from: Rectangle, to: Rectangle, consumer: Consumer<Rectangle>): Animation {
return Animation(DoubleRectangleFunction(from, to), consumer)
}
fun <T> animation(values: Array<T>, consumer: Consumer<T>): Animation {
return Animation(DoubleArrayFunction(values), consumer)
}
fun animation(from: Dimension, to: Dimension, consumer: Consumer<Dimension>): Animation {
return Animation(DoubleDimensionFunction(from, to), consumer)
}
fun animation(from: Color, to: Color, consumer: Consumer<Color>): Animation {
return Animation(DoubleColorFunction(from, to), consumer)
}
fun transparent(color: Color, consumer: Consumer<Color>) = animation(color, ColorUtil.withAlpha(color, 0.0), consumer)
fun <T> consumer(function: DoubleFunction<T>, consumer: Consumer<T>): DoubleConsumer {
return DoubleConsumer { consumer.accept(function.apply(it)) }
}
private fun text(from: String, to: String): DoubleFunction<String> {
val shorter = if (from.length < to.length) from else to
val longer = if (from === shorter) to else from
if (shorter.length == longer.length || !longer.startsWith(shorter)) {
val fraction = from.length.toDouble() / (from.length + to.length)
return DoubleFunction { timeline: Double ->
if (timeline < fraction) {
from.substring(0, (from.length * ((fraction - timeline) / fraction)).roundToInt())
}
else {
to.substring(0, (to.length * (timeline - fraction) / (1 - fraction)).roundToInt())
}
}
}
return if (from === shorter) {
DoubleFunction { timeline: Double ->
longer.substring(0, (shorter.length + (longer.length - shorter.length) * timeline).roundToInt())
}
}
else {
DoubleFunction { timeline: Double ->
longer.substring(0, (longer.length - (longer.length - shorter.length) * timeline).roundToInt())
}
}
}
fun animation(from: String, to: String, consumer: Consumer<String>): Animation {
return Animation(text(from, to), consumer)
}
private fun range(from: Int, to: Int): DoubleIntFunction {
return DoubleIntFunction { value -> (from + value * (to - from)).toInt() }
}
private fun interface DoubleIntFunction {
fun apply(value: Double): Int
}
class DoubleColorFunction(
val from: Color,
val to: Color
) : DoubleFunction<Color> {
private val red = range(from.red, to.red)
private val green = range(from.green, to.green)
private val blue = range(from.blue, to.blue)
private val alpha = range(from.alpha, to.alpha)
override fun apply(value: Double) = Color(
red.apply(value),
green.apply(value),
blue.apply(value),
alpha.apply(value)
)
}
class DoublePointFunction(
val from: Point,
val to: Point
) : DoubleFunction<Point> {
private val x = range(from.x, to.x)
private val y = range(from.y, to.y)
override fun apply(value: Double): Point {
return Point(x.apply(value), y.apply(value))
}
}
class DoubleDimensionFunction(
val from: Dimension,
val to: Dimension
) : DoubleFunction<Dimension> {
private val width = range(from.width, to.width)
private val height = range(from.height, to.height)
override fun apply(value: Double) = Dimension(
width.apply(value),
height.apply(value)
)
}
class DoubleRectangleFunction(
val from: Rectangle,
val to: Rectangle
) : DoubleFunction<Rectangle> {
private val x = range(from.x, to.x)
private val y = range(from.y, to.y)
private val width = range(from.width, to.width)
private val height = range(from.height, to.height)
override fun apply(value: Double) = Rectangle(
x.apply(value),
y.apply(value),
width.apply(value),
height.apply(value)
)
}
/**
* For any value in [0.0, 1.0] chooses value from an array.
*/
class DoubleArrayFunction<T>(
val array: Array<T>
) : DoubleFunction<T> {
override fun apply(value: Double): T {
return array[(array.size * value).roundToInt().coerceIn(0, (array.size - 1))]
}
}
fun interface FloatConsumer {
fun accept(value: Float)
}
|
apache-2.0
|
77581e9beee942ca453796a8619fe1a9
| 28.504717 | 140 | 0.70371 | 3.653037 | false | false | false | false |
myunusov/maxur-mserv
|
maxur-mserv-core/src/main/kotlin/org/maxur/mserv/frame/service/hk2/LocatorHK2Impl.kt
|
1
|
7448
|
package org.maxur.mserv.frame.service.hk2
import gov.va.oia.HK2Utilities.HK2RuntimeInitializer
import org.glassfish.hk2.api.Factory
import org.glassfish.hk2.api.MultiException
import org.glassfish.hk2.api.ServiceLocator
import org.glassfish.hk2.api.ServiceLocatorState
import org.glassfish.hk2.api.TypeLiteral
import org.glassfish.hk2.utilities.ServiceLocatorUtilities
import org.glassfish.hk2.utilities.binding.AbstractBinder
import org.glassfish.hk2.utilities.binding.ScopedBindingBuilder
import org.glassfish.hk2.utilities.binding.ServiceBindingBuilder
import org.maxur.mserv.core.Either
import org.maxur.mserv.core.ErrorResult
import org.maxur.mserv.core.Result
import org.maxur.mserv.core.Value
import org.maxur.mserv.core.fold
import org.maxur.mserv.core.left
import org.maxur.mserv.core.right
import org.maxur.mserv.core.tryTo
import org.maxur.mserv.frame.LocatorConfig
import org.maxur.mserv.frame.LocatorImpl
import org.maxur.mserv.frame.kotlin.Locator
import org.maxur.mserv.frame.service.properties.Properties
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.reflect.KClass
import kotlin.reflect.full.isSubclassOf
/**
* Locator is the registry for services. The HK2 ServiceLocator adapter.
* <p>
* @property name The locator name
* @param packages The set of package names to scan recursively.
*/
class LocatorHK2Impl @Inject constructor(override val name: String, packages: Set<String> = emptySet()) : LocatorImpl {
private val locator: ServiceLocator by lazy {
if (packages.isNotEmpty()) {
HK2RuntimeInitializer.init(name, true, *packages.toTypedArray())
} else {
ServiceLocatorUtilities.createAndPopulateServiceLocator(name)
}.also {
ServiceLocatorUtilities.enableImmediateScope(it)
}
}
/** {@inheritDoc} */
override fun inject(injectMe: Any) {
locator.inject(injectMe)
}
/** {@inheritDoc} */
@Suppress("UNCHECKED_CAST")
override fun <T> implementation(): T = locator as T
/** {@inheritDoc} */
override fun names(contractOrImpl: Class<*>): List<String> =
locator.getAllServiceHandles(contractOrImpl).map { it.activeDescriptor.name }
/** {@inheritDoc} */
override fun <T> property(key: String, clazz: Class<T>): T? =
locator.getService(Properties::class.java).read(key, clazz)
/** {@inheritDoc} */
override fun <T> service(contractOrImpl: Class<T>, name: String?): T? = tryTo {
when (name) {
null -> locator.getService<T>(contractOrImpl)
else -> locator.getService(contractOrImpl, name)
}
}.result()
/**
* Return result or throws IllegalStateException
* @return result
*/
fun <E : Throwable, V> Result<E, V>.result(): V = when (this) {
is Value -> value
is ErrorResult -> throw convertError(error)
}
private tailrec fun convertError(error: Throwable): IllegalStateException = when (error) {
is MultiException ->
if (error.errors.size == 1)
convertError(error.errors[0])
else
IllegalStateException(error)
is IllegalStateException -> error
else -> IllegalStateException(error)
}
/** {@inheritDoc} */
override fun <T> services(contractOrImpl: Class<T>): List<T> =
locator.getAllServices(contractOrImpl).map { it as T }
/** {@inheritDoc} */
override fun configurationError() = service(ErrorHandler::class.java)?.latestError
/** {@inheritDoc} */
override fun close() {
if (locator.state == ServiceLocatorState.RUNNING)
locator.shutdown()
}
override fun config(): org.maxur.mserv.frame.LocatorConfig = Config(this)
class Config(locatorImpl: LocatorImpl) : LocatorConfig(locatorImpl) {
override fun <T : Any> makeDescriptor(bean: Bean<T>, contract: Contract<T>?): Descriptor<T> =
object : Descriptor<T>(bean, contract?.let { mutableSetOf(contract) } ?: mutableSetOf()) {
@Suppress("UNCHECKED_CAST")
override fun toSpecificContract(contract: Any) {
if (contract is TypeLiteral<*>)
contracts.add(ContractTypeLiteral(contract as TypeLiteral<in T>))
}
}
override fun apply() {
val binder = object : AbstractBinder() {
override fun configure() {
descriptors.forEach { makeBinders(it) }
}
}
ServiceLocatorUtilities.bind(locator.implementation<ServiceLocator>(), binder)
}
@Suppress("UNCHECKED_CAST")
private fun AbstractBinder.makeBinders(descriptor: Descriptor<out Any>) {
if (descriptor.contracts.isEmpty()) {
throw IllegalStateException("Contract must be")
}
val binder = builder(descriptor)
descriptor.contracts.forEach {
when (it) {
is ContractClass -> binder.bind(it.contract.java as Class<Any>)
is ContractTypeLiteral -> binder.bind(it.literal as TypeLiteral<Any>)
}
}
descriptor.name?.let { binder.named(it) }
binder.initScope()
}
private fun AbstractBinder.builder(descriptor: Descriptor<out Any>): Binder<Any> {
val bean = descriptor.bean
return Binder(
when (bean) {
is BeanFunction -> left(bindFactory(ServiceProvider(locator, bean.func)))
is BeanObject -> {
right(bind(bean.impl))
}
is BeanSingleton<out Any> -> {
if (bean.impl.isSubclassOf(Factory::class)) {
@Suppress("UNCHECKED_CAST")
val factoryClass: KClass<Factory<Any>> = bean.impl as KClass<Factory<Any>>
left(bindFactory(factoryClass.java))
} else
left(bind(bean.impl.java))
}
else -> throw IllegalStateException("Unknown description")
} as Either<ServiceBindingBuilder<out Any>, ScopedBindingBuilder<out Any>>
)
}
@Suppress("UNCHECKED_CAST")
private class Binder<out T>(val binder: Either<ServiceBindingBuilder<out T>, ScopedBindingBuilder<out T>>) {
fun bind(clazz: Class<Any>) {
val arg = clazz as Class<in T>
return binder.fold({ it.to(arg) }, { it.to(arg) })
}
fun bind(literal: TypeLiteral<Any>) =
binder.fold({ it.to(literal) }, { it.to(literal) })
fun named(name: String) =
binder.fold({ it.named(name) }, { it.named(name) })
fun initScope() =
binder.fold({ it.`in`(Singleton::class.java) }, { it })
}
private class ServiceProvider<T>(val locator: LocatorImpl, val func: (Locator) -> T) : Factory<T> {
val result: T by lazy { func.invoke(Locator(locator)) }
/** {@inheritDoc} */
override fun dispose(instance: T) = Unit
/** {@inheritDoc} */
override fun provide(): T = result
}
class ContractTypeLiteral<T : Any>(val literal: TypeLiteral<in T>) : Contract<T>()
}
}
|
apache-2.0
|
f51cdb6a03156c4f8faafc957d471bc4
| 37.994764 | 119 | 0.608083 | 4.524909 | false | false | false | false |
Waboodoo/HTTP-Shortcuts
|
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/http/HttpHeaders.kt
|
1
|
889
|
package ch.rmy.android.http_shortcuts.http
import ch.rmy.android.framework.extensions.getCaseInsensitive
import okhttp3.Headers
class HttpHeaders private constructor(private val headers: Map<String, List<String>>) {
fun getLast(name: String): String? =
headers.getCaseInsensitive(name)
?.lastOrNull()
fun toMultiMap(): Map<String, List<String>> = headers
companion object {
fun parse(headers: Headers) =
HttpHeaders(
headers.names()
.associateWith { name -> headers.values(name) }
)
const val AUTHORIZATION = "Authorization"
const val CONNECTION = "Connection"
const val CONTENT_ENCODING = "Content-Encoding"
const val CONTENT_TYPE = "Content-Type"
const val SET_COOKIE = "Set-Cookie"
const val USER_AGENT = "User-Agent"
}
}
|
mit
|
80e1bf5984d58be365caf2a67a05fc3e
| 25.147059 | 87 | 0.631046 | 4.535714 | false | false | false | false |
mapzen/eraser-map
|
app/src/main/kotlin/com/mapzen/erasermap/view/RoutePreviewView.kt
|
1
|
9926
|
package com.mapzen.erasermap.view
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Point
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.view.animation.AccelerateDecelerateInterpolator
import android.widget.Button
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import com.mapzen.erasermap.EraserMapApplication
import com.mapzen.erasermap.R
import com.mapzen.erasermap.controller.MainActivity
import com.mapzen.erasermap.model.MultiModalHelper
import com.mapzen.erasermap.model.RouteManager
import com.mapzen.erasermap.util.FeatureDisplayHelper
import com.mapzen.pelias.SimpleFeature
import com.mapzen.valhalla.Instruction
import com.mapzen.valhalla.Route
import com.mapzen.valhalla.Router
import java.util.ArrayList
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class RoutePreviewView : RelativeLayout {
@Inject lateinit var displayHelper: FeatureDisplayHelper
val startView: TextView by lazy { findViewById(R.id.starting_point) as TextView }
val destinationView: TextView by lazy { findViewById(R.id.destination) as TextView }
val distancePreview: DistanceView by lazy { findViewById(R.id.distance_preview) as DistanceView }
val timePreview: TimeView by lazy { findViewById(R.id.time_preview) as TimeView }
val viewListButton: Button by lazy { findViewById(R.id.view_list) as Button }
val startNavigationButton: Button by lazy { findViewById(R.id.start_navigation) as Button }
val noRouteFound: TextView by lazy { findViewById(R.id.no_route_found) as TextView }
val tryAnotherMode: TextView? by lazy { findViewById(R.id.try_another_mode) as TextView? }
val routeTopContainer: RelativeLayout by lazy { findViewById(R.id.main_content) as RelativeLayout }
val routeBtmContainer: LinearLayout by lazy { findViewById(R.id.bottom_content) as LinearLayout }
val previewDirectionListView: DirectionListView by lazy { findViewById(R.id.list_view) as DirectionListView }
val previewToggleBtn: View by lazy { findViewById(R.id.map_list_toggle) }
val balancerView: View by lazy { findViewById(R.id.balancer) }
val distanceView: DistanceView by lazy { findViewById(R.id.destination_distance) as DistanceView }
val destinationNameTextView: TextView by lazy { findViewById(R.id.destination_name) as TextView }
var divider: Drawable? = null
var dividerHeight: Int? = null
var reverse : Boolean = false
set (value) {
field = value
if (value) {
if (destination != null) {
startView.text = displayHelper.getDisplayName(
destination as SimpleFeature)
}
destinationView.setText(R.string.current_location)
} else {
startView.setText(R.string.current_location)
if (destination != null) {
destinationView.text = displayHelper.getDisplayName(
destination as SimpleFeature)
}
}
}
var destination: SimpleFeature? = null
set (value) {
field = value
startView.setText(R.string.current_location)
if (value != null) {
destinationView.text = displayHelper.getDisplayName(value)
}
}
var route: Route? = null
set (value) {
field = value
val distance = value?.getTotalDistance() ?: 0
distancePreview.distanceInMeters = distance
val time = value?.getTotalTime() ?: 0
timePreview.timeInMinutes = TimeUnit.SECONDS.toMinutes(time.toLong()).toInt()
}
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int)
: super(context, attrs, defStyleAttr) {
init()
}
private fun init() {
(context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater)
.inflate(R.layout.view_route_preview, this, true)
(context.applicationContext as EraserMapApplication).component().inject(this)
}
fun disableStartNavigation() {
startNavigationButton.visibility = View.GONE
viewListButton.visibility = View.GONE
noRouteFound.visibility = View.VISIBLE
tryAnotherMode?.visibility = View.VISIBLE
}
fun enableStartNavigation(type: Router.Type, reverse: Boolean) {
if (type != Router.Type.MULTIMODAL && !reverse) {
startNavigationButton.visibility = View.VISIBLE
} else {
startNavigationButton.visibility = View.GONE
}
viewListButton.visibility = View.VISIBLE
noRouteFound.visibility = View.GONE
tryAnotherMode?.visibility = View.GONE
}
fun showDirectionsListView(routeManager: RouteManager, windowManager: WindowManager, compass: View) {
val instructions = routeManager.route?.getRouteInstructions()
val simpleFeature = SimpleFeature.fromFeature(routeManager.destination)
val display = windowManager.defaultDisplay
val size = Point()
display.getSize(size);
val height = size.y.toFloat();
previewToggleBtn.visibility = View.GONE
balancerView.visibility = View.GONE
routeBtmContainer.translationY = height
routeBtmContainer.visibility = View.VISIBLE
distanceView.distanceInMeters = routeManager.route?.getTotalDistance() as Int
destinationNameTextView.text = simpleFeature.name()
if (routeManager.type == Router.Type.MULTIMODAL) {
val instructionGrouper = InstructionGrouper(instructions as ArrayList<Instruction>)
previewDirectionListView.adapter = MultiModalDirectionListAdapter(this.context, instructionGrouper,
routeManager.reverse, MultiModalHelper())
if (divider == null) {
divider = previewDirectionListView.divider
dividerHeight = previewDirectionListView.dividerHeight
}
previewDirectionListView.divider = null;
previewDirectionListView.dividerHeight = 0;
} else {
val instructionStrings = ArrayList<String>()
val instructionTypes = ArrayList<Int>()
val instructionDistances = ArrayList<Int>()
if (instructions != null) {
for(instruction in instructions) {
val humanInstruction = instruction.getHumanTurnInstruction()
if (humanInstruction is String) {
instructionStrings.add(humanInstruction)
}
instructionTypes.add(instruction.turnInstruction)
instructionDistances.add(instruction.distance)
}
}
previewDirectionListView.adapter = DirectionListAdapter(this.context, instructionStrings,
instructionTypes, instructionDistances, routeManager.reverse)
if (divider != null) {
previewDirectionListView.divider = divider
previewDirectionListView.dividerHeight = dividerHeight as Int
}
}
val topContainerAnimator = ObjectAnimator.ofFloat(routeTopContainer, View.TRANSLATION_Y,-height)
val btmContainerAnimator = ObjectAnimator.ofFloat(routeBtmContainer, View.TRANSLATION_Y, 0f)
val animations = AnimatorSet()
animations.playTogether(topContainerAnimator, btmContainerAnimator)
animations.duration = MainActivity.DIRECTION_LIST_ANIMATION_DURATION
animations.interpolator = AccelerateDecelerateInterpolator()
animations.addListener(object: Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {
compass.visibility = View.GONE
}
override fun onAnimationEnd(animation: Animator) {}
override fun onAnimationRepeat(animation: Animator) {}
override fun onAnimationCancel(animation: Animator) {}
})
animations.start()
}
fun hideDirectionsListView(windowManager: WindowManager, compass: View) {
val display = windowManager.defaultDisplay
val size = Point()
display.getSize(size);
val height = size.y.toFloat();
val topContainerAnimator = ObjectAnimator.ofFloat(routeTopContainer, View.TRANSLATION_Y, 0f)
val btmContainerAnimator = ObjectAnimator.ofFloat(routeBtmContainer, View.TRANSLATION_Y, height)
val animations = AnimatorSet()
animations.playTogether(topContainerAnimator, btmContainerAnimator)
animations.duration = MainActivity.DIRECTION_LIST_ANIMATION_DURATION
animations.interpolator = AccelerateDecelerateInterpolator()
animations.addListener(object: Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator) {
compass.visibility = View.VISIBLE
}
override fun onAnimationEnd(animation: Animator) {
routeBtmContainer.visibility = View.GONE
}
override fun onAnimationRepeat(animation: Animator) {}
override fun onAnimationCancel(animation: Animator) {}
})
animations.start()
}
fun restore(routeManager: RouteManager) {
if (routeManager.type == Router.Type.MULTIMODAL || routeManager.reverse) {
startNavigationButton.visibility = View.GONE
}
reverse = routeManager.reverse
}
}
|
gpl-3.0
|
37161317089dcaa0ca8a09b721406e97
| 43.711712 | 113 | 0.680435 | 5.003024 | false | false | false | false |
koma-im/koma
|
src/main/kotlin/link/continuum/desktop/util/http/download.kt
|
1
|
1071
|
package link.continuum.desktop.util.http
import koma.Failure
import koma.Server
import koma.network.media.MHUrl
import koma.util.*
import koma.util.coroutine.adapter.okhttp.await
import link.continuum.desktop.util.*
import mu.KotlinLogging
import okhttp3.*
import java.util.*
import java.util.concurrent.TimeUnit
private val logger = KotlinLogging.logger {}
private typealias Option<T> = Optional<T>
typealias MediaServer = Server
suspend fun downloadHttp(
url: HttpUrl, client: OkHttpClient, maxStale: Int? = null
): KResult<ByteArray, Failure> {
val req = Request.Builder().url(url).given(maxStale) {
cacheControl(CacheControl
.Builder()
.maxStale(it, TimeUnit.SECONDS)
.build())
}.build()
val r = client.newCall(req).await()
if (r.isFailure) return Err(r.failureOrThrow())
val res = r.getOrThrow()
val b = res.body
if (!res.isSuccessful || b == null) {
return fmtErr { "failed to get response body for $url" }
}
return Ok(b.use { it.bytes() })
}
|
gpl-3.0
|
3b666a5cec5c31b9be340f25be465d7c
| 29.628571 | 65 | 0.669468 | 3.95203 | false | false | false | false |
justin-hayes/kotlin-boot-react
|
backend/src/main/kotlin/me/justinhayes/bookclub/client/BookClient.kt
|
1
|
907
|
package me.justinhayes.bookclub.client
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import me.justinhayes.bookclub.domain.Book
import org.apache.http.HttpStatus
import org.apache.http.client.methods.HttpGet
import org.apache.http.impl.client.CloseableHttpClient
import org.apache.http.impl.client.HttpClients
interface BookClient {
val client: CloseableHttpClient
get() = HttpClients.createDefault()
val mapper: ObjectMapper
get() = ObjectMapper().registerModule(KotlinModule())
fun getBookByIsbn(isbn: String): Book
fun findCoverForBook(isbn: String): String? {
val coverUrl = "http://covers.openlibrary.org/b/isbn/${isbn}-L.jpg"
val response = client.execute(HttpGet(coverUrl))
if (response.statusLine.statusCode == HttpStatus.SC_OK) return coverUrl else return null
}
}
|
mit
|
399782bd34f065d5340f5e51e0fcda5b
| 35.32 | 96 | 0.750827 | 4.013274 | false | false | false | false |
zak0/CalendarCountdown
|
app/src/main/java/zak0/github/calendarcountdown/widget/CountdownAppWidgetRemoteViewsFactory.kt
|
1
|
2373
|
package zak0.github.calendarcountdown.widget
import android.content.Context
import android.content.Intent
import android.util.Log
import android.widget.RemoteViews
import android.widget.RemoteViewsService
import zak0.github.calendarcountdown.R
import zak0.github.calendarcountdown.data.CountdownSettings
import zak0.github.calendarcountdown.storage.DatabaseHelper
class CountdownAppWidgetRemoteViewsFactory(private val context: Context)
: RemoteViewsService.RemoteViewsFactory {
private lateinit var countdowns: ArrayList<CountdownSettings>
override fun onCreate() {
Log.d(TAG, "onCreate()")
loadCountdownsFromDb()
}
override fun getLoadingView(): RemoteViews {
// TODO Consider adding a separate view for "Loading..." state
return RemoteViews(context.packageName, R.layout.widget_layout_empty)
}
override fun getItemId(position: Int): Long = countdowns[position].dbId.toLong()
override fun onDataSetChanged() {
Log.d(TAG, "onDataSetChanged()")
loadCountdownsFromDb()
}
override fun hasStableIds(): Boolean = true
override fun getViewAt(position: Int): RemoteViews {
Log.d(TAG, "getViewAt($position)")
val countdown = countdowns[position]
val views = RemoteViews(context.packageName, R.layout.widget_listitem_countdown)
views.setTextViewText(R.id.days, "${countdown.daysToEndDate}")
views.setTextViewText(R.id.title, countdown.label)
views.setTextViewText(R.id.daysUntilLabel, context.getString(R.string.countdowns_list_days_until))
val fillInIntent = Intent()
fillInIntent.putExtra(CountdownSettings.extraName, countdown) // TODO Currently not used, but added because I can...
views.setOnClickFillInIntent(R.id.container, fillInIntent)
return views
}
override fun getCount(): Int = countdowns.size
override fun getViewTypeCount(): Int = 1
override fun onDestroy() = Unit
private fun loadCountdownsFromDb() {
DatabaseHelper(context, DatabaseHelper.DB_NAME, DatabaseHelper.DB_VERSION).apply {
openDb()
countdowns = ArrayList(loadSettingsForWidget())
countdowns.sort()
closeDb()
}
}
companion object {
private val TAG = CountdownAppWidgetRemoteViewsFactory::class.java.simpleName
}
}
|
mit
|
5634c23adb69fefaf139fb144278fe38
| 33.405797 | 124 | 0.713443 | 4.862705 | false | false | false | false |
badoualy/kotlogram
|
mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/MTFutureSalts.kt
|
1
|
1424
|
package com.github.badoualy.telegram.mtproto.tl
import com.github.badoualy.telegram.tl.StreamUtils.*
import com.github.badoualy.telegram.tl.TLContext
import com.github.badoualy.telegram.tl.core.TLObject
import com.github.badoualy.telegram.tl.core.TLVector
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
class MTFutureSalts @JvmOverloads constructor(var requestId: Long = 0, var now: Int = 0, var salts: TLVector<MTFutureSalt> = TLVector()) : TLObject() {
override fun getConstructorId(): Int {
return CONSTRUCTOR_ID
}
@Throws(IOException::class)
override fun serializeBody(stream: OutputStream) {
writeLong(requestId, stream)
writeInt(now, stream)
writeInt(salts.size, stream)
for (salt in salts) {
salt.serializeBody(stream)
}
}
@Throws(IOException::class)
override fun deserializeBody(stream: InputStream, context: TLContext) {
requestId = readLong(stream)
now = readInt(stream)
val count = readInt(stream)
salts.clear()
for (i in 0..count - 1) {
val salt = MTFutureSalt()
salt.deserializeBody(stream, context)
salts.add(salt)
}
}
override fun toString(): String {
return "future_salts#ae500895"
}
companion object {
@JvmField
val CONSTRUCTOR_ID = -1370486635
}
}
|
mit
|
bbe621a3880cd4ef87889b83e1cb9df9
| 28.666667 | 151 | 0.65941 | 4 | false | false | false | false |
EMResearch/EvoMaster
|
core/src/test/kotlin/org/evomaster/core/search/gene/TimeGeneTest.kt
|
1
|
3351
|
package org.evomaster.core.search.gene
import org.evomaster.core.search.gene.datetime.TimeGene
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
class TimeGeneTest {
@Test
fun testDefaultTimeGeneFormat() {
val gene = TimeGene("time")
gene.apply {
hour.value = 3
minute.value = 4
second.value = 5
}
assertEquals(
"03:04:05.000Z",
gene.getValueAsRawString()
)
}
@Test
fun testTimeWithMillisFormat() {
val gene = TimeGene("time",
timeGeneFormat = TimeGene.TimeGeneFormat.TIME_WITH_MILLISECONDS
)
gene.apply {
hour.value = 3
minute.value = 4
second.value = 5
}
assertEquals(
"03:04:05.000Z",
gene.getValueAsRawString()
)
}
@Test
fun testDefaultDateTimeFormat() {
val gene = TimeGene("time",
timeGeneFormat = TimeGene.TimeGeneFormat.ISO_LOCAL_DATE_FORMAT
)
gene.apply {
hour.value = 3
minute.value = 4
second.value = 5
}
assertEquals(
"03:04:05",
gene.getValueAsRawString()
)
}
@Test
fun testCopyOfISOLocalTimeFormat() {
val gene = TimeGene("time",
timeGeneFormat = TimeGene.TimeGeneFormat.ISO_LOCAL_DATE_FORMAT
)
gene.apply {
hour.value = 3
minute.value = 4
second.value = 5
}
val copy = gene.copy()
assertTrue(copy is TimeGene)
copy as TimeGene
copy.apply {
assertEquals(3, hour.value)
assertEquals(4, minute.value)
assertEquals(5, second.value)
assertEquals(TimeGene.TimeGeneFormat.ISO_LOCAL_DATE_FORMAT, timeGeneFormat)
}
}
@Test
fun testCopyOfTimeWithMillisFormat() {
val gene = TimeGene("time",
timeGeneFormat = TimeGene.TimeGeneFormat.TIME_WITH_MILLISECONDS
)
gene.apply {
hour.value = 3
minute.value = 4
second.value = 5
}
val copy = gene.copy()
assertTrue(copy is TimeGene)
copy as TimeGene
copy.apply {
assertEquals(3, hour.value)
assertEquals(4, minute.value)
assertEquals(5, second.value)
assertEquals(TimeGene.TimeGeneFormat.TIME_WITH_MILLISECONDS, timeGeneFormat)
}
}
@Test
fun testCopyValueFrom() {
val gene0 = TimeGene("time",
timeGeneFormat = TimeGene.TimeGeneFormat.TIME_WITH_MILLISECONDS
)
gene0.apply {
hour.value = 3
minute.value = 4
second.value = 5
}
val gene1 = TimeGene("time",
timeGeneFormat = TimeGene.TimeGeneFormat.ISO_LOCAL_DATE_FORMAT
)
gene1.copyValueFrom(gene0)
gene1.apply {
assertEquals(3, hour.value)
assertEquals(4, minute.value)
assertEquals(5, second.value)
assertEquals(TimeGene.TimeGeneFormat.ISO_LOCAL_DATE_FORMAT, timeGeneFormat)
}
}
}
|
lgpl-3.0
|
2733df977400fee9cc5295f4c3d164cb
| 25.816 | 88 | 0.545807 | 4.380392 | false | true | false | false |
artem-zinnatullin/RxUi
|
rxui-sample-kotlin/src/test/kotlin/com/artemzin/rxui/sample/kotlin/TestMainView.kt
|
1
|
1306
|
package com.artemzin.rxui.sample.kotlin
import com.artemzin.rxui.sample.kotlin.AuthService.Response.Failure
import com.artemzin.rxui.sample.kotlin.AuthService.Response.Success
import com.artemzin.rxui.test.TestRxUi.testUi
import io.reactivex.functions.Consumer
import io.reactivex.subjects.PublishSubject
import org.mockito.Mockito
class TestMainView : MainView {
val signInEnableAction = Mockito.mock(Consumer::class.java) as Consumer<Unit>
val signInDisableAction = Mockito.mock(Consumer::class.java) as Consumer<Unit>
val signInSuccessAction = Mockito.mock(Consumer::class.java) as Consumer<Success>
val signInFailureAction = Mockito.mock(Consumer::class.java) as Consumer<Failure>
// Produces.
override val login = PublishSubject.create<String>()
override val password = PublishSubject.create<String>()
override val signInClicks = PublishSubject.create<Unit>()
// Consumes.
override val signInEnable = testUi { enable: Unit -> signInEnableAction.accept(Unit) }
override val signInDisable = testUi { disable: Unit -> signInDisableAction.accept(Unit) }
override val signInSuccess = testUi { success: Success -> signInSuccessAction.accept(success) }
override val signInFailure = testUi { failure: Failure -> signInFailureAction.accept(failure) }
}
|
mit
|
0bc4781d01d3b2b457cba18fc41a02c8
| 47.37037 | 99 | 0.774885 | 4.08125 | false | true | false | false |
mchernyavsky/kotlincheck
|
src/main/kotlin/io/kotlincheck/gen/TuplesGen.kt
|
1
|
6370
|
package io.kotlincheck.gen
import io.kotlincheck.*
class PairGen<A, B>(
val gen1: Gen<A>, val gen2: Gen<B>
) : Gen<Pair<A, B>> {
override fun generate(): Pair<A, B> = Pair(gen1.generate(), gen2.generate())
override fun isAcceptable(value: Pair<A, B>): Boolean =
gen1.isAcceptable(value.first) && gen2.isAcceptable(value.second)
}
class TripleGen<A, B, C>(
val gen1: Gen<A>, val gen2: Gen<B>, val gen3: Gen<C>
) : Gen<Triple<A, B, C>> {
override fun generate(): Triple<A, B, C> = Triple(gen1.generate(), gen2.generate(), gen3.generate())
override fun isAcceptable(value: Triple<A, B, C>): Boolean =
gen1.isAcceptable(value.first) && gen2.isAcceptable(value.second) && gen3.isAcceptable(value.third)
}
internal class Tuple2Gen<T1, T2>(
val gen1: Gen<T1>,
val gen2: Gen<T2>
) : Gen<Tuple2<T1, T2>> {
override fun generate(): Tuple2<T1, T2> = Tuple2(gen1.generate(), gen2.generate())
override fun isAcceptable(value: Tuple2<T1, T2>): Boolean =
gen1.isAcceptable(value.elem1) && gen2.isAcceptable(value.elem2)
}
internal class Tuple3Gen<T1, T2, T3>(
val gen1: Gen<T1>,
val gen2: Gen<T2>,
val gen3: Gen<T3>
) : Gen<Tuple3<T1, T2, T3>> {
override fun generate(): Tuple3<T1, T2, T3> = Tuple3(gen1.generate(), gen2.generate(), gen3.generate())
override fun isAcceptable(value: Tuple3<T1, T2, T3>): Boolean =
gen1.isAcceptable(value.elem1) && gen2.isAcceptable(value.elem2) && gen3.isAcceptable(value.elem3)
}
internal class Tuple4Gen<T1, T2, T3, T4>(
val gen1: Gen<T1>,
val gen2: Gen<T2>,
val gen3: Gen<T3>,
val gen4: Gen<T4>
) : Gen<Tuple4<T1, T2, T3, T4>> {
override fun generate(): Tuple4<T1, T2, T3, T4> =
Tuple4(
gen1.generate(), gen2.generate(), gen3.generate(),
gen4.generate()
)
override fun isAcceptable(value: Tuple4<T1, T2, T3, T4>): Boolean =
gen1.isAcceptable(value.elem1) && gen2.isAcceptable(value.elem2) && gen3.isAcceptable(value.elem3) &&
gen4.isAcceptable(value.elem4)
}
internal class Tuple5Gen<T1, T2, T3, T4, T5>(
val gen1: Gen<T1>,
val gen2: Gen<T2>,
val gen3: Gen<T3>,
val gen4: Gen<T4>,
val gen5: Gen<T5>
) : Gen<Tuple5<T1, T2, T3, T4, T5>> {
override fun generate(): Tuple5<T1, T2, T3, T4, T5> =
Tuple5(
gen1.generate(), gen2.generate(), gen3.generate(),
gen4.generate(), gen5.generate()
)
override fun isAcceptable(value: Tuple5<T1, T2, T3, T4, T5>): Boolean =
gen1.isAcceptable(value.elem1) && gen2.isAcceptable(value.elem2) && gen3.isAcceptable(value.elem3) &&
gen4.isAcceptable(value.elem4) && gen5.isAcceptable(value.elem5)
}
internal class Tuple6Gen<T1, T2, T3, T4, T5, T6>(
val gen1: Gen<T1>,
val gen2: Gen<T2>,
val gen3: Gen<T3>,
val gen4: Gen<T4>,
val gen5: Gen<T5>,
val gen6: Gen<T6>
) : Gen<Tuple6<T1, T2, T3, T4, T5, T6>> {
override fun generate(): Tuple6<T1, T2, T3, T4, T5, T6> =
Tuple6(
gen1.generate(), gen2.generate(), gen3.generate(),
gen4.generate(), gen5.generate(), gen6.generate()
)
override fun isAcceptable(value: Tuple6<T1, T2, T3, T4, T5, T6>): Boolean =
gen1.isAcceptable(value.elem1) && gen2.isAcceptable(value.elem2) && gen3.isAcceptable(value.elem3) &&
gen4.isAcceptable(value.elem4) && gen5.isAcceptable(value.elem5) && gen6.isAcceptable(value.elem6)
}
internal class Tuple7Gen<T1, T2, T3, T4, T5, T6, T7>(
val gen1: Gen<T1>,
val gen2: Gen<T2>,
val gen3: Gen<T3>,
val gen4: Gen<T4>,
val gen5: Gen<T5>,
val gen6: Gen<T6>,
val gen7: Gen<T7>
) : Gen<Tuple7<T1, T2, T3, T4, T5, T6, T7>> {
override fun generate(): Tuple7<T1, T2, T3, T4, T5, T6, T7> =
Tuple7(
gen1.generate(), gen2.generate(), gen3.generate(),
gen4.generate(), gen5.generate(), gen6.generate(),
gen7.generate()
)
override fun isAcceptable(value: Tuple7<T1, T2, T3, T4, T5, T6, T7>): Boolean =
gen1.isAcceptable(value.elem1) && gen2.isAcceptable(value.elem2) && gen3.isAcceptable(value.elem3)
&& gen4.isAcceptable(value.elem4) && gen5.isAcceptable(value.elem5) && gen6.isAcceptable(value.elem6)
&& gen7.isAcceptable(value.elem7)
}
internal class Tuple8Gen<T1, T2, T3, T4, T5, T6, T7, T8>(
val gen1: Gen<T1>,
val gen2: Gen<T2>,
val gen3: Gen<T3>,
val gen4: Gen<T4>,
val gen5: Gen<T5>,
val gen6: Gen<T6>,
val gen7: Gen<T7>,
val gen8: Gen<T8>
) : Gen<Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>> {
override fun generate(): Tuple8<T1, T2, T3, T4, T5, T6, T7, T8> =
Tuple8(
gen1.generate(), gen2.generate(), gen3.generate(),
gen4.generate(), gen5.generate(), gen6.generate(),
gen7.generate(), gen8.generate()
)
override fun isAcceptable(value: Tuple8<T1, T2, T3, T4, T5, T6, T7, T8>): Boolean =
gen1.isAcceptable(value.elem1) && gen2.isAcceptable(value.elem2) && gen3.isAcceptable(value.elem3)
&& gen4.isAcceptable(value.elem4) && gen5.isAcceptable(value.elem5) && gen6.isAcceptable(value.elem6)
&& gen7.isAcceptable(value.elem7) && gen8.isAcceptable(value.elem8)
}
internal class Tuple9Gen<T1, T2, T3, T4, T5, T6, T7, T8, T9>(
val gen1: Gen<T1>,
val gen2: Gen<T2>,
val gen3: Gen<T3>,
val gen4: Gen<T4>,
val gen5: Gen<T5>,
val gen6: Gen<T6>,
val gen7: Gen<T7>,
val gen8: Gen<T8>,
val gen9: Gen<T9>
) : Gen<Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9>> {
override fun generate(): Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9> =
Tuple9(
gen1.generate(), gen2.generate(), gen3.generate(),
gen4.generate(), gen5.generate(), gen6.generate(),
gen7.generate(), gen8.generate(), gen9.generate()
)
override fun isAcceptable(value: Tuple9<T1, T2, T3, T4, T5, T6, T7, T8, T9>): Boolean =
gen1.isAcceptable(value.elem1) && gen2.isAcceptable(value.elem2) && gen3.isAcceptable(value.elem3)
&& gen4.isAcceptable(value.elem4) && gen5.isAcceptable(value.elem5) && gen6.isAcceptable(value.elem6)
&& gen7.isAcceptable(value.elem7) && gen8.isAcceptable(value.elem8) && gen9.isAcceptable(value.elem9)
}
|
mit
|
a4b6f8fcebd9aff7ae2fdec32ce07254
| 35.609195 | 117 | 0.60675 | 2.696867 | false | false | false | false |
sonnytron/FitTrainerBasic
|
mobile/src/main/java/com/sonnyrodriguez/fittrainer/fittrainerbasic/library/GymAdapter.kt
|
1
|
2810
|
package com.sonnyrodriguez.fittrainer.fittrainerbasic.library
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
abstract class GymAdapter<E> : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
val internalItemList = ArrayList<E>()
internal var clickListener: OnItemClickedListener? = null
val isEmpty: Boolean
get() = internalItemList.isEmpty()
val isNotEmpty: Boolean
get() = !isEmpty
override fun onAttachedToRecyclerView(recyclerView: RecyclerView?) {
super.onAttachedToRecyclerView(recyclerView)
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
clickListener?.let { listener ->
holder.setOnItemClickedListener(listener)
}
onBindInternalItemView(holder, position)
}
fun setOnItemClickedListener(listener: (Int) -> Unit) {
this.clickListener = object : OnItemClickedListener {
override fun onItemClicked(position: Int) {
listener(position)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return onCreateInternalItemViewHolder(parent, viewType)
}
override fun getItemCount() = internalItemList.size
fun add(index: Int, item: E) {
internalItemList.add(index, item)
notifyItemInserted(index)
}
fun add(item: E, notifyItem: Boolean = true) {
internalItemList.add(item)
if (notifyItem) {
notifyItemInserted(itemCount)
}
}
fun set(item: E, index: Int) {
internalItemList[index] = item
notifyItemChanged(index)
}
fun addAll(itemList: List<E>) {
internalItemList.addAll(itemList)
if (isEmpty) {
notifyDataSetChanged()
} else {
notifyItemInserted(itemCount - itemList.size)
}
}
fun clearAll() {
internalItemList.clear()
notifyDataSetChanged()
}
fun getInternalItem(position: Int) = internalItemList[position]
fun clearItem(item: E, notifyRemoved: Boolean = true) {
val clearPosition = indexOf(item)
internalItemList.remove(item)
if (notifyRemoved) {
notifyItemRemoved(clearPosition)
}
}
fun changeAll(itemList: List<E>) {
internalItemList.clear()
internalItemList.addAll(itemList)
notifyDataSetChanged()
}
fun indexOf(item: E) = internalItemList.indexOf(item)
protected abstract fun onBindInternalItemView(viewHolder: RecyclerView.ViewHolder, position: Int)
protected abstract fun onCreateInternalItemViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder
}
|
apache-2.0
|
491be950355a110924123aadd9c97cb7
| 28.893617 | 116 | 0.668683 | 4.938489 | false | false | false | false |
artem-zinnatullin/RxUi
|
rxui-sample-kotlin/src/main/kotlin/com/artemzin/rxui/sample/kotlin/MainPresenter.kt
|
1
|
2067
|
package com.artemzin.rxui.sample.kotlin
import com.artemzin.rxui.kotlin.bind
import com.artemzin.rxui.sample.kotlin.AuthService.Response.Failure
import com.artemzin.rxui.sample.kotlin.AuthService.Response.Success
import io.reactivex.Scheduler
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
class MainPresenter(private val authService: AuthService, private val ioScheduler: Scheduler) {
fun bind(view: MainView): Disposable {
val disposable = CompositeDisposable()
val login = view.login.share()
val password = view.password.share()
// Boolean is valid/invalid flag.
fun Pair<String, String>.valid(): Boolean {
val (login, password) = this
return login.isNotEmpty() && password.isNotEmpty()
}
val credentials = Observables
.combineLatest(login, password)
.publish()
disposable += credentials
.filter { it.valid() }
.map { Unit }
.bind(view.signInEnable) // YES, that short, that simple and that readable!
disposable += credentials
.filter { !it.valid() }
.map { Unit }
.startWith(Unit) // Sign In should be disabled by default.
.bind(view.signInDisable)
val signInResult = view
.signInClicks
.withLatestFrom(credentials, { click, credentials -> credentials.first to credentials.second })
.switchMap { authService.signIn(login = it.first, password = it.second).subscribeOn(ioScheduler) }
.share()
disposable += credentials.connect()
disposable += signInResult
.filter { it is Success }
.map { it as Success }
.bind(view.signInSuccess)
disposable += signInResult
.filter { it is Failure }
.map { it as Failure }
.bind(view.signInFailure)
return disposable
}
}
|
mit
|
500f6c9196e4189f0981a4ebdece4a1a
| 33.45 | 114 | 0.600871 | 4.909739 | false | false | false | false |
bubelov/coins-android
|
app/src/main/java/com/bubelov/coins/util/CircleTransformation.kt
|
1
|
1014
|
package com.bubelov.coins.util
import android.graphics.*
import com.squareup.picasso.Transformation
import kotlin.math.min
class CircleTransformation : Transformation {
override fun transform(source: Bitmap): Bitmap {
val size = min(source.width, source.height)
val x = (source.width - size) / 2
val y = (source.height - size) / 2
val squaredBitmap = Bitmap.createBitmap(source, x, y, size, size)
if (squaredBitmap != source) {
source.recycle()
}
val paint = Paint().apply {
shader = BitmapShader(squaredBitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP)
isAntiAlias = true
}
val roundBitmap = Bitmap.createBitmap(size, size, source.config)
val canvas = Canvas(roundBitmap)
val radius = size / 2f
canvas.drawCircle(radius, radius, radius, paint)
squaredBitmap.recycle()
return roundBitmap
}
override fun key(): String = javaClass.simpleName
}
|
unlicense
|
8cd25fc19222b0646aacb6d1d6e2ef55
| 28 | 94 | 0.640039 | 4.408696 | false | false | false | false |
lovejjfg/PowerRecyclerView
|
app/src/main/java/com/lovejjfg/swiperefreshrecycleview/activity/CatsActivity.kt
|
1
|
4957
|
package com.lovejjfg.swiperefreshrecycleview.activity
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView.LayoutManager
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.lovejjfg.powerrecycle.PowerAdapter
import com.lovejjfg.powerrecycle.SelectPowerAdapter
import com.lovejjfg.powerrecycle.holder.PowerHolder
import com.lovejjfg.powerrecycle.model.ISelect
import com.lovejjfg.swiperefreshrecycleview.R
import com.lovejjfg.swiperefreshrecycleview.model.Cat
import kotlinx.android.synthetic.main.activity_list.recycleView
import kotlinx.android.synthetic.main.activity_list.refresh
import kotlinx.android.synthetic.main.holder_cat.view.catCheckState
import kotlinx.android.synthetic.main.holder_cat.view.catImage
/**
* Created by joe on 2018/11/20.
* Email: [email protected]
*/
class CatsActivity : BaseSelectActivity<Cat>() {
override fun startRefresh() {
recycleView.postDelayed(
{
adapter.clearList()
initData()
refresh.isRefreshing = false
}, 1000
)
}
override fun initManager(): LayoutManager {
return GridLayoutManager(this, 2)
}
override fun initAdapter(): PowerAdapter<Cat> {
return CatsAdapter()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initToolbar("猫猫图", R.menu.menu_select) {
when (it.itemId) {
R.id.select_single -> {
selectAdapter.setSelectedMode(ISelect.SINGLE_MODE)
selectAdapter.setCurrentPositions(0, 1, 2, 3)
}
R.id.select_mul -> {
selectAdapter.setSelectedMode(ISelect.MULTIPLE_MODE)
val list = selectAdapter.list
val cat0 = list[0]
cat0.isSelected = true
val cat2 = list[2]
cat2.isSelected = true
val cat5 = list[5]
cat5.isSelected = true
adapter.updateItem(cat0)
adapter.updateItem(cat2, "textxxx2")
adapter.updateItem(cat5)
}
R.id.delete_select -> selectAdapter.deleteSelectedItems()
R.id.revert_select -> selectAdapter.revertAllSelected()
R.id.selet_all -> selectAdapter.selectAll()
R.id.unselect_all -> selectAdapter.resetAll()
R.id.default_select -> selectAdapter.isCancelAble = !selectAdapter.isCancelAble
}
return@initToolbar true
}
initData()
}
private fun initData() {
val cats = arrayOf(R.mipmap.cat1, R.mipmap.cat2, R.mipmap.cat3, R.mipmap.cat4, R.mipmap.cat5, R.mipmap.cat6)
val list = ArrayList<Cat>(30)
for (i in 0..29) {
list.add(Cat(cats[i % cats.size], "黑猫$i"))
}
selectAdapter.setList(list)
selectAdapter.setOnItemClickListener { holder, position, item ->
selectAdapter.removeItem(position)
}
}
class CatsAdapter : SelectPowerAdapter<Cat>(ISelect.MULTIPLE_MODE, true) {
override fun onViewHolderCreate(parent: ViewGroup, viewType: Int): PowerHolder<Cat> {
return CatHolder(LayoutInflater.from(parent.context).inflate(R.layout.holder_cat, parent, false))
}
override fun onViewHolderBind(holder: PowerHolder<Cat>, position: Int) {
println("onViewHolderBind:")
holder.onBind(list[position], isSelectMode)
}
override fun onViewHolderBind(holder: PowerHolder<Cat>, position: Int, payloads: MutableList<Any>) {
println("onViewHolderBind:$payloads")
holder.onPartBind(list[position], isSelectMode, payloads)
}
override fun getMaxSelectCount(): Int {
return 3
}
override fun onReceivedMaxSelectCount(count: Int) {
Log.e("CatsAdapter", "onReceivedMaxSelectCount:$count")
}
}
class CatHolder(view: View) : PowerHolder<Cat>(view) {
private val catSrc = view.catImage
private val catState = view.catCheckState
override fun onBind(t: Cat, isSelectMode: Boolean) {
println("onBind:${t.name}")
catSrc.setImageResource(t.src)
catState.isChecked = t.isSelected
catState.isVisible = isSelectMode
catState.text = t.name
}
override fun onPartBind(t: Cat, isSelectMode: Boolean, payloads: MutableList<Any>) {
println("onBindPart:::${t.name},,$payloads")
catState.isVisible = isSelectMode
catState.isChecked = t.isSelected
catState.text = t.name
}
}
}
|
apache-2.0
|
f7fffb6be8ab1e8770c88a5a2a1e52ad
| 36.477273 | 116 | 0.624621 | 4.381754 | false | false | false | false |
gradle/gradle
|
subprojects/configuration-cache/src/main/kotlin/org/gradle/configurationcache/serialization/Contexts.kt
|
2
|
11984
|
/*
* Copyright 2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.configurationcache.serialization
import it.unimi.dsi.fastutil.objects.ReferenceArrayList
import org.gradle.api.internal.initialization.ClassLoaderScope
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.logging.LogLevel
import org.gradle.api.logging.Logger
import org.gradle.configurationcache.ClassLoaderScopeSpec
import org.gradle.configurationcache.problems.ProblemsListener
import org.gradle.configurationcache.problems.PropertyProblem
import org.gradle.configurationcache.problems.PropertyTrace
import org.gradle.configurationcache.problems.StructuredMessageBuilder
import org.gradle.configurationcache.serialization.beans.BeanStateReader
import org.gradle.configurationcache.serialization.beans.BeanStateReaderLookup
import org.gradle.configurationcache.serialization.beans.BeanStateWriter
import org.gradle.configurationcache.serialization.beans.BeanStateWriterLookup
import org.gradle.initialization.ClassLoaderScopeOrigin
import org.gradle.initialization.ClassLoaderScopeRegistry
import org.gradle.internal.hash.HashCode
import org.gradle.internal.serialize.Decoder
import org.gradle.internal.serialize.Encoder
internal
class DefaultWriteContext(
codec: Codec<Any?>,
private
val encoder: Encoder,
private
val scopeLookup: ScopeLookup,
private
val beanStateWriterLookup: BeanStateWriterLookup,
override val logger: Logger,
override val tracer: Tracer?,
problemsListener: ProblemsListener
) : AbstractIsolateContext<WriteIsolate>(codec, problemsListener), WriteContext, Encoder by encoder, AutoCloseable {
override val sharedIdentities = WriteIdentities()
override val circularReferences = CircularReferences()
private
val classes = WriteIdentities()
private
val scopes = WriteIdentities()
/**
* Closes the given [encoder] if it is [AutoCloseable].
*/
override fun close() {
(encoder as? AutoCloseable)?.close()
}
override fun beanStateWriterFor(beanType: Class<*>): BeanStateWriter =
beanStateWriterLookup.beanStateWriterFor(beanType)
override val isolate: WriteIsolate
get() = getIsolate()
override suspend fun write(value: Any?) {
getCodec().run {
encode(value)
}
}
override fun writeClass(type: Class<*>) {
val id = classes.getId(type)
if (id != null) {
writeSmallInt(id)
} else {
val scope = scopeLookup.scopeFor(type.classLoader)
val newId = classes.putInstance(type)
writeSmallInt(newId)
writeString(type.name)
if (scope == null) {
writeBoolean(false)
} else {
writeBoolean(true)
writeScope(scope.first)
writeBoolean(scope.second.local)
}
}
}
private
fun writeScope(scope: ClassLoaderScopeSpec) {
val id = scopes.getId(scope)
if (id != null) {
writeSmallInt(id)
} else {
val newId = scopes.putInstance(scope)
writeSmallInt(newId)
if (scope.parent == null) {
writeBoolean(false)
} else {
writeBoolean(true)
writeScope(scope.parent)
}
writeString(scope.name)
if (scope.origin is ClassLoaderScopeOrigin.Script) {
writeBoolean(true)
writeString(scope.origin.fileName)
writeString(scope.origin.displayName)
} else {
writeBoolean(false)
}
writeClassPath(scope.localClassPath)
writeHashCode(scope.localImplementationHash)
writeClassPath(scope.exportClassPath)
}
}
private
fun writeHashCode(hashCode: HashCode?) {
if (hashCode == null) {
writeBoolean(false)
} else {
writeBoolean(true)
writeBinary(hashCode.toByteArray())
}
}
// TODO: consider interning strings
override fun writeString(string: CharSequence) =
encoder.writeString(string)
override fun newIsolate(owner: IsolateOwner): WriteIsolate =
DefaultWriteIsolate(owner)
}
internal
class LoggingTracer(
private val profile: String,
private val writePosition: () -> Long,
private val logger: Logger,
private val level: LogLevel
) : Tracer {
// Include a sequence number in the events so the order of events can be preserved in face of log output reordering
private
var nextSequenceNumber = 0L
override fun open(frame: String) {
log(frame, 'O')
}
override fun close(frame: String) {
log(frame, 'C')
}
private
fun log(frame: String, openOrClose: Char) {
logger.log(
level,
"""{"profile":"$profile","type":"$openOrClose","frame":"$frame","at":${writePosition()},"sn":${nextSequenceNumber()}}"""
)
}
private
fun nextSequenceNumber() = nextSequenceNumber.also {
nextSequenceNumber += 1
}
}
interface EncodingProvider<T> {
suspend fun WriteContext.encode(value: T)
}
@JvmInline
value class ClassLoaderRole(val local: Boolean)
internal
interface ScopeLookup {
fun scopeFor(classLoader: ClassLoader?): Pair<ClassLoaderScopeSpec, ClassLoaderRole>?
}
internal
class DefaultReadContext(
codec: Codec<Any?>,
private
val decoder: Decoder,
private
val beanStateReaderLookup: BeanStateReaderLookup,
override val logger: Logger,
problemsListener: ProblemsListener
) : AbstractIsolateContext<ReadIsolate>(codec, problemsListener), ReadContext, Decoder by decoder, AutoCloseable {
override val sharedIdentities = ReadIdentities()
private
val classes = ReadIdentities()
private
val scopes = ReadIdentities()
private
lateinit var projectProvider: ProjectProvider
override lateinit var classLoader: ClassLoader
override fun onFinish(action: () -> Unit) {
pendingOperations.add(action)
}
internal
fun finish() {
for (op in pendingOperations) {
op()
}
pendingOperations.clear()
}
private
var pendingOperations = ReferenceArrayList<() -> Unit>()
internal
fun initClassLoader(classLoader: ClassLoader) {
this.classLoader = classLoader
}
internal
fun initProjectProvider(projectProvider: ProjectProvider) {
this.projectProvider = projectProvider
}
override var immediateMode: Boolean = false
override fun close() {
(decoder as? AutoCloseable)?.close()
}
override suspend fun read(): Any? = getCodec().run {
decode()
}
override val isolate: ReadIsolate
get() = getIsolate()
override fun beanStateReaderFor(beanType: Class<*>): BeanStateReader =
beanStateReaderLookup.beanStateReaderFor(beanType)
override fun readClass(): Class<*> {
val id = readSmallInt()
val type = classes.getInstance(id)
if (type != null) {
return type as Class<*>
}
val name = readString()
val classLoader = if (readBoolean()) {
val scope = readScope()
if (readBoolean()) {
scope.localClassLoader
} else {
scope.exportClassLoader
}
} else {
this.classLoader
}
val newType = Class.forName(name, false, classLoader)
classes.putInstance(id, newType)
return newType
}
private
fun readScope(): ClassLoaderScope {
val id = readSmallInt()
val scope = scopes.getInstance(id)
if (scope != null) {
return scope as ClassLoaderScope
}
val parent = if (readBoolean()) {
readScope()
} else {
ownerService<ClassLoaderScopeRegistry>().coreAndPluginsScope
}
val name = readString()
val origin = if (readBoolean()) {
ClassLoaderScopeOrigin.Script(readString(), readString())
} else {
null
}
val localClassPath = readClassPath()
val localImplementationHash = readHashCode()
val exportClassPath = readClassPath()
val newScope = if (localImplementationHash != null && exportClassPath.isEmpty) {
parent.createLockedChild(name, origin, localClassPath, localImplementationHash, null)
} else {
parent.createChild(name, origin).local(localClassPath).export(exportClassPath).lock()
}
scopes.putInstance(id, newScope)
return newScope
}
private
fun readHashCode() = if (readBoolean()) {
HashCode.fromBytes(readBinary())
} else {
null
}
override fun getProject(path: String): ProjectInternal =
projectProvider(path)
override fun newIsolate(owner: IsolateOwner): ReadIsolate =
DefaultReadIsolate(owner)
}
interface DecodingProvider<T> {
suspend fun ReadContext.decode(): T?
}
internal
typealias ProjectProvider = (String) -> ProjectInternal
internal
abstract class AbstractIsolateContext<T>(
codec: Codec<Any?>,
problemsListener: ProblemsListener
) : MutableIsolateContext {
private
var currentProblemsListener: ProblemsListener = problemsListener
private
var currentIsolate: T? = null
private
var currentCodec = codec
override var trace: PropertyTrace = PropertyTrace.Gradle
protected
abstract fun newIsolate(owner: IsolateOwner): T
protected
fun getIsolate(): T = currentIsolate.let { isolate ->
require(isolate != null) {
"`isolate` is only available during Task serialization."
}
isolate
}
protected
fun getCodec() = currentCodec
private
val contexts = ArrayList<Pair<T?, Codec<Any?>>>()
override fun push(codec: Codec<Any?>) {
contexts.add(0, Pair(currentIsolate, currentCodec))
currentCodec = codec
}
override fun push(owner: IsolateOwner, codec: Codec<Any?>) {
contexts.add(0, Pair(currentIsolate, currentCodec))
currentIsolate = newIsolate(owner)
currentCodec = codec
}
override fun pop() {
val previousValues = contexts.removeAt(0)
currentIsolate = previousValues.first
currentCodec = previousValues.second
}
override fun onProblem(problem: PropertyProblem) {
currentProblemsListener.onProblem(problem)
}
override fun onError(error: Exception, message: StructuredMessageBuilder) {
currentProblemsListener.onError(trace, error, message)
}
override suspend fun forIncompatibleType(action: suspend () -> Unit) {
val previousListener = currentProblemsListener
currentProblemsListener = previousListener.forIncompatibleType()
try {
action()
} finally {
currentProblemsListener = previousListener
}
}
}
internal
class DefaultWriteIsolate(override val owner: IsolateOwner) : WriteIsolate {
override val identities: WriteIdentities = WriteIdentities()
}
internal
class DefaultReadIsolate(override val owner: IsolateOwner) : ReadIsolate {
override val identities: ReadIdentities = ReadIdentities()
}
|
apache-2.0
|
4952e7f2bee525e22ef8af77cd2a3434
| 26.360731 | 132 | 0.65771 | 4.824477 | false | false | false | false |
UweTrottmann/SeriesGuide
|
app/src/main/java/com/battlelancer/seriesguide/shows/overview/SeasonsViewModel.kt
|
1
|
1457
|
package com.battlelancer.seriesguide.shows.overview
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.battlelancer.seriesguide.provider.SgRoomDatabase
class SeasonsViewModel(
application: Application,
private val showId: Long
): AndroidViewModel(application) {
private val order = MutableLiveData<SeasonsSettings.SeasonSorting>()
val seasons = Transformations.switchMap(order) {
val helper = SgRoomDatabase.getInstance(application).sgSeason2Helper()
if (it == SeasonsSettings.SeasonSorting.LATEST_FIRST) {
helper.getSeasonsOfShowLatestFirst(showId)
} else {
helper.getSeasonsOfShowOldestFirst(showId)
}
}
val remainingCountData = RemainingCountLiveData(application, viewModelScope)
init {
updateOrder()
}
fun updateOrder() {
order.value = SeasonsSettings.getSeasonSortOrder(getApplication())
}
}
class SeasonsViewModelFactory(
private val application: Application,
private val showId: Long
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
@Suppress("UNCHECKED_CAST")
return SeasonsViewModel(application, showId) as T
}
}
|
apache-2.0
|
3ef898e8ddb1e8ba118dcbf02c31a3cd
| 30.695652 | 80 | 0.74674 | 4.922297 | false | false | false | false |
joseph-roque/BowlingCompanion
|
app/src/main/java/ca/josephroque/bowlingcompanion/utils/Preferences.kt
|
1
|
955
|
package ca.josephroque.bowlingcompanion.utils
/**
* Copyright (C) 2018 Joseph Roque
*
* Keys for user preferences.
*/
object Preferences {
/** Identifier for if user has opened the facebook page in the past. */
const val FACEBOOK_PAGE_OPENED = "fb_page_opened"
/** Identifier for if user has closed the facebook promotional content since opening the app. */
const val FACEBOOK_CLOSED = "fb_closed"
/**
* Identifier for preference indicating sort order which user prefers for bowlers.
*/
const val BOWLER_SORT_ORDER = "pref_bowler_sort_order"
/**
* Identifier for preference indicating sort order which user prefers for teams.
* Identical sort order to [BOWLER_SORT_ORDER].
*/
const val TEAM_SORT_ORDER = BOWLER_SORT_ORDER
/**
* Identifier for preference indicating sort order which user prefers for leagues.
*/
const val LEAGUE_SORT_ORDER = "pref_league_sort_order"
}
|
mit
|
a600126c851e2541d3a98dd7b8696076
| 29.806452 | 101 | 0.687958 | 4.081197 | false | false | false | false |
redpen-cc/redpen-intellij-plugin
|
test/cc/redpen/intellij/SettingsManagerTest.kt
|
1
|
2467
|
package cc.redpen.intellij
import cc.redpen.config.ValidatorConfiguration
import com.intellij.openapi.project.ProjectManager
import com.nhaarman.mockito_kotlin.mock
import com.nhaarman.mockito_kotlin.spy
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.Mockito.RETURNS_DEEP_STUBS
import org.mockito.Mockito.doNothing
import java.util.*
class SettingsManagerTest : BaseTest() {
val config = config("en")
val manager: SettingsManager
init {
val projectManager = mock<ProjectManager>(RETURNS_DEEP_STUBS)
whenever(application.getComponent(ProjectManager::class.java)).thenReturn(projectManager)
manager = spy(SettingsManager(project))
}
@Before
fun setUp() {
doNothing().whenever(manager).restartInspections()
manager.provider = mock(RETURNS_DEEP_STUBS)
manager.settingsPane = mock()
whenever(manager.settingsPane.config).thenReturn(config);
}
@Test
fun applyConfigSwitch() {
manager.apply()
verify(manager.provider).activeConfig = config;
}
@Test
fun applyValidatorsAndSymbols() {
manager.apply()
verify(manager.settingsPane).save()
verify(manager).restartInspections()
}
@Test
fun reset() {
manager.reset()
verify(manager.settingsPane).resetChanges()
}
@Test
fun isNotModified() {
val configs = manager.provider.configs
whenever(manager.settingsPane.configs).thenReturn(configs)
assertFalse(manager.isModified)
verify(manager.settingsPane).applyChanges()
}
@Test
fun isModified() {
whenever(manager.settingsPane.configs).thenReturn(hashMapOf())
assertTrue(manager.isModified)
verify(manager.settingsPane).applyChanges()
}
@Test
fun isModified_validatorProperty() {
val config = configWithValidators(listOf(ValidatorConfiguration("blah")))
val configs = hashMapOf("en" to config.clone())
configs["en"]!!.validatorConfigs[0].properties["blah"] = "blah";
whenever(manager.settingsPane.configs).thenReturn(configs)
whenever(manager.provider.configs).thenReturn(hashMapOf("en" to config))
assertTrue(manager.isModified)
verify(manager.settingsPane).applyChanges()
}
}
|
apache-2.0
|
bf97e9cc8f351601ca0ac3f4473d907e
| 30.240506 | 97 | 0.699635 | 4.518315 | false | true | false | false |
RP-Kit/RPKit
|
bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/database/table/RPKPermanentStoreItemTable.kt
|
1
|
5239
|
/*
* Copyright 2022 Ren Binden
*
* 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.rpkit.store.bukkit.database.table
import com.rpkit.core.database.Database
import com.rpkit.core.database.Table
import com.rpkit.store.bukkit.RPKStoresBukkit
import com.rpkit.store.bukkit.database.create
import com.rpkit.store.bukkit.database.jooq.Tables.RPKIT_PERMANENT_STORE_ITEM
import com.rpkit.store.bukkit.database.jooq.Tables.RPKIT_STORE_ITEM
import com.rpkit.store.bukkit.storeitem.RPKPermanentStoreItem
import com.rpkit.store.bukkit.storeitem.RPKPermanentStoreItemImpl
import com.rpkit.store.bukkit.storeitem.RPKStoreItemId
import java.util.concurrent.CompletableFuture
import java.util.logging.Level
class RPKPermanentStoreItemTable(
private val database: Database,
private val plugin: RPKStoresBukkit
) : Table {
private val cache = if (plugin.config.getBoolean("caching.rpkit_permanent_store_item.id.enabled")) {
database.cacheManager.createCache(
"rpkit-stores-bukkit.rpkit_permanent_store_item.id",
Int::class.javaObjectType,
RPKPermanentStoreItem::class.java,
plugin.config.getLong("caching.rpkit_permanent_store_item.id.size")
)
} else {
null
}
fun insert(entity: RPKPermanentStoreItem): CompletableFuture<Void> {
return CompletableFuture.runAsync {
val id = database.getTable(RPKStoreItemTable::class.java).insert(entity).join()
database.create
.insertInto(
RPKIT_PERMANENT_STORE_ITEM,
RPKIT_PERMANENT_STORE_ITEM.STORE_ITEM_ID
)
.values(
id.value
)
.execute()
entity.id = id
cache?.set(id.value, entity)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to insert permanent store item", exception)
throw exception
}
}
fun update(entity: RPKPermanentStoreItem): CompletableFuture<Void> {
val id = entity.id ?: return CompletableFuture.completedFuture(null)
return CompletableFuture.runAsync {
database.getTable(RPKStoreItemTable::class.java).update(entity).join()
cache?.set(id.value, entity)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to update permanent store item", exception)
throw exception
}
}
operator fun get(id: RPKStoreItemId): CompletableFuture<out RPKPermanentStoreItem?> {
if (cache?.containsKey(id.value) == true) {
return CompletableFuture.completedFuture(cache[id.value])
} else {
return CompletableFuture.supplyAsync {
val result = database.create
.select(
RPKIT_STORE_ITEM.PLUGIN,
RPKIT_STORE_ITEM.IDENTIFIER,
RPKIT_STORE_ITEM.DESCRIPTION,
RPKIT_STORE_ITEM.COST
)
.from(
RPKIT_STORE_ITEM,
RPKIT_PERMANENT_STORE_ITEM
)
.where(RPKIT_STORE_ITEM.ID.eq(id.value))
.and(RPKIT_STORE_ITEM.ID.eq(RPKIT_PERMANENT_STORE_ITEM.STORE_ITEM_ID))
.fetchOne() ?: return@supplyAsync null
val storeItem = RPKPermanentStoreItemImpl(
id,
result[RPKIT_STORE_ITEM.PLUGIN],
result[RPKIT_STORE_ITEM.IDENTIFIER],
result[RPKIT_STORE_ITEM.DESCRIPTION],
result[RPKIT_STORE_ITEM.COST]
)
cache?.set(id.value, storeItem)
return@supplyAsync storeItem
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to get permanent store item", exception)
throw exception
}
}
}
fun delete(entity: RPKPermanentStoreItem): CompletableFuture<Void> {
val id = entity.id ?: return CompletableFuture.completedFuture(null)
return CompletableFuture.runAsync {
database.getTable(RPKStoreItemTable::class.java).delete(entity).join()
database.create
.deleteFrom(RPKIT_PERMANENT_STORE_ITEM)
.where(RPKIT_PERMANENT_STORE_ITEM.STORE_ITEM_ID.eq(id.value))
.execute()
cache?.remove(id.value)
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to delete permanent store item", exception)
throw exception
}
}
}
|
apache-2.0
|
8ccdd9f7475236231cf61ef53a87ad0c
| 39.620155 | 104 | 0.615766 | 4.762727 | false | false | false | false |
pchrysa/Memento-Calendar
|
android_mobile/src/main/java/com/alexstyl/specialdates/person/PersonCallProvider.kt
|
1
|
1441
|
package com.alexstyl.specialdates.person
import com.alexstyl.specialdates.contact.Contact
import com.alexstyl.specialdates.contact.ContactSource
import io.reactivex.Observable
class PersonCallProvider(
private val androidActionsProvider: ContactActionsProvider,
private val facebookContactActionsProvider: ContactActionsProvider) {
fun getCallsFor(contact: Contact): Observable<List<ContactActionViewModel>> {
return Observable.fromCallable {
if (contact.source == ContactSource.SOURCE_FACEBOOK) {
facebookContactActionsProvider.callActionsFor(contact)
} else if (contact.source == ContactSource.SOURCE_DEVICE) {
androidActionsProvider.callActionsFor(contact)
} else {
throw IllegalArgumentException("unknown contact type " + contact.source)
}
}
}
fun getMessagesFor(contact: Contact): Observable<List<ContactActionViewModel>> {
return Observable.fromCallable {
if (contact.source == ContactSource.SOURCE_FACEBOOK) {
facebookContactActionsProvider.messagingActionsFor(contact)
} else if (contact.source == ContactSource.SOURCE_DEVICE) {
androidActionsProvider.messagingActionsFor(contact)
} else {
throw IllegalArgumentException("unknown contact type " + contact.source)
}
}
}
}
|
mit
|
8aa6b95174f46717bb2b06868f677a73
| 39.027778 | 88 | 0.679389 | 5.356877 | false | false | false | false |
a642500/Ybook
|
app/src/main/kotlin/com/ybook/app/ui/main/MainActivity.kt
|
1
|
10957
|
/*
Copyright 2015 Carlos
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.ybook.app.ui.main
import android.os.Bundle
import android.support.v4.widget.DrawerLayout
import android.view.Menu
import android.view.MenuItem
import com.ybook.app.R
import android.app.ActionBar
import android.content.Intent
import android.support.v4.app.FragmentActivity
import com.umeng.analytics.MobclickAgent
import com.ybook.app.id
import com.balysv.materialmenu.MaterialMenuIcon
import android.graphics.Color
import com.balysv.materialmenu.MaterialMenuDrawable.Stroke
import android.os.PersistableBundle
import com.balysv.materialmenu.MaterialMenuDrawable.IconState
import com.ybook.app.ui.main.NavigationDrawerFragment.OnDrawerListener
import android.view.View
import com.balysv.materialmenu.MaterialMenuDrawable.AnimationState
import android.util.Log
import android.support.v7.widget.SearchView
import android.app.SearchManager
import android.content.Context
import com.ybook.app.ui.main.NavigationDrawerFragment.NavigationDrawerCallbacks
import android.view.ViewTreeObserver
import com.ybook.app.ui.home.HomeFragment
import android.support.v7.widget.Toolbar
import android.content.ComponentName
import com.ybook.app.ui.search.SearchActivity
import android.support.v7.widget.SearchView.OnQueryTextListener
import com.ybook.app.ui.others.FeedBackActivity
import com.ybook.app.ui.others.AboutFragment
import android.support.v7.app.ActionBarActivity
import com.ybook.app.ui.home.HomeTabFragment
import com.ybook.app.ui.home.HomeTabFragment
import android.net.Uri
import com.ybook.app.ui.home.IdentityFragment
import com.github.ksoichiro.android.observablescrollview.ObservableScrollViewCallbacks
import com.github.ksoichiro.android.observablescrollview.ScrollState
import com.github.ksoichiro.android.observablescrollview.Scrollable
import me.toxz.kotlin.makeTag
import me.toxz.kotlin.after
import android.view.animation.AccelerateInterpolator
val ARG_SECTION_NUMBER: String = "section_number"
public class MainActivity : ActionBarActivity(),
NavigationDrawerCallbacks,
ObservableScrollViewCallbacks,
HomeTabFragment.OnFragmentInteractionListener,
IdentityFragment.OnFragmentInteractionListener {
val TAG = makeTag()
override fun onFragmentInteraction(id: String) {
}
override fun onScrollChanged(p0: Int, p1: Boolean, p2: Boolean) {
}
override fun onDownMotionEvent() {
}
override fun onUpOrCancelMotionEvent(p0: ScrollState?) {
Log.i(TAG, "ScrollState: " + p0)
when (p0) {
ScrollState.UP -> showHeadView(false)
ScrollState.DOWN -> showHeadView(true)
}
}
override fun onFragmentInteraction(uri: Uri) {
//TODO
}
override fun onBackPressed() {
if (mNavDrawerFragment?.isDrawerOpen() ?: false) {
mNavDrawerFragment!!.close()
} else if (mColDrawerFragment?.isDrawerOpen() ?: false) {
mColDrawerFragment!!.close()
} else super<ActionBarActivity>.onBackPressed()
}
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private var mNavDrawerFragment: NavigationDrawerFragment? = null
private var mColDrawerFragment: CollectionDrawerFragment? = null
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private var mTitle: CharSequence? = null
override fun onResume() {
super<ActionBarActivity>.onResume()
MobclickAgent.onResume(this)
if (!(mSearchView?.isIconified() ?: true)) {
[email protected]()
}
}
override fun onPause() {
super<ActionBarActivity>.onPause()
MobclickAgent.onPause(this);
}
// var materialMenu: MaterialMenuIcon? = null
var mToolBar: Toolbar? = null
override fun onCreate(savedInstanceState: android.os.Bundle?) {
super<ActionBarActivity>.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar((id(R.id.toolBar) as Toolbar) after { mToolBar = it })
val fm = getSupportFragmentManager()
mNavDrawerFragment = (fm findFragmentById R.id.navigation_drawer ) as NavigationDrawerFragment
mNavDrawerFragment!!.setUp(R.id.navigation_drawer, id(R.id.drawer_layout) as DrawerLayout)
mTitle = getTitle()
mColDrawerFragment = (fm findFragmentById R.id.collection_drawer) as CollectionDrawerFragment
mColDrawerFragment!!.setUp(R.id.collection_drawer, id(R.id.drawer_layout) as DrawerLayout)
// materialMenu = MaterialMenuIcon(this, Color.WHITE, Stroke.THIN);
// mNavigationDrawerFragment?.setOnDrawerListener(object : OnDrawerListener {
// var isOpened = false
//
// override fun onDrawerSlide(p0: View?, p1: Float) {
// Log.d("onDrawerSlide", "float: " + p1)
// materialMenu?.setTransformationOffset(if (isOpened) AnimationState.ARROW_CHECK else AnimationState.BURGER_ARROW, p1)
// }
//
// override fun onDrawerOpened(p0: View?) {
// isOpened = true
// }
//
// override fun onDrawerClosed(p0: View?) {
// isOpened = false
// }
//
// override fun onDrawerStateChanged(p0: Int) {
// }
//
// })
onNavigationDrawerItemSelected(0)
}
override fun onPostCreate(savedInstanceState: android.os.Bundle?) {
super<ActionBarActivity>.onPostCreate(savedInstanceState)
// materialMenu?.syncState(savedInstanceState);
}
override fun onSaveInstanceState(outState: android.os.Bundle?) {
super<ActionBarActivity>.onSaveInstanceState(outState)
// materialMenu?.onSaveInstanceState(outState);
}
override fun onNavigationDrawerItemSelected(position: Int) {
when (position) {
0 -> getSupportFragmentManager().beginTransaction().replace(R.id.container, HomeTabFragment.newInstance()).commit()
1 -> getSupportFragmentManager().beginTransaction().replace(R.id.container, AboutFragment()).commit()
2 -> startActivity(Intent(this, javaClass<FeedBackActivity>()))
}
}
public fun onSectionAttached(number: Int) {
when (number) {
0 -> mTitle = getString(R.string.navigationHome)
1 -> mTitle = getString(R.string.navigationAbout)
}
}
public fun restoreActionBar() {
// val actionBar = getActionBar()
// actionBar setNavigationMode ActionBar.NAVIGATION_MODE_STANDARD
// actionBar setDisplayShowTitleEnabled true
// getActionBar() setDisplayUseLogoEnabled false
// getActionBar() setDisplayHomeAsUpEnabled true
// getActionBar() setDisplayOptions ActionBar.DISPLAY_SHOW_TITLE
// actionBar setTitle mTitle
}
var mSearchView: SearchView ? = null
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
if (!mNavDrawerFragment!!.isDrawerOpen() && !mColDrawerFragment!!.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.global, menu)
// Associate searchable configuration with the SearchView
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
mSearchView = menu!!.findItem(R.id.action_search)?.getActionView() as SearchView
mSearchView!!.setSearchableInfo(searchManager.getSearchableInfo(android.content.ComponentName(this, javaClass<SearchActivity>())))
// mSearchView.setOnQueryTextListener(object : OnQueryTextListener {
// override fun onQueryTextSubmit(p0: String?): Boolean {
// mSearchView.setQuery("", false)
// mSearchView.clearFocus()
// mSearchView.setIconified(true)
// [email protected]()
// return false
// }
//
// override fun onQueryTextChange(p0: String?): Boolean {
// return false
// }
//
// })
restoreActionBar()
return true
}
return super<ActionBarActivity>.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.getItemId()) {
R.id.action_search -> (item!!.getActionView() as SearchView).let { it.setQuery("", false);it.setIconified(true) }
// android.R.id.home -> if (!mNavigationDrawerFragment!!.isDrawerOpen() && !mCollectionDrawerFragment!!.isDrawerOpen())
//// materialMenu?.animatePressedState(IconState.ARROW) else materialMenu?.animatePressedState(IconState.BURGER)
// R.id.action_about -> startActivity(Intent(this, javaClass<AboutActivity>()))
}
return super<ActionBarActivity>.onOptionsItemSelected(item)
}
var toolBarBottom: Int ? = null
fun showHeadView(bool: Boolean) {
if (toolBarBottom == null) {
toolBarBottom = mToolBar!!.getBottom()
}
if (bool) {
//open the view
mToolBar?.animate()?.translationY(0F)?.setInterpolator(AccelerateInterpolator())?.start()
} else {
mToolBar?.animate()?.translationY(-toolBarBottom!!.toFloat())?.setInterpolator(AccelerateInterpolator())?.start();
}
mHeadViewHideOrShowListener?.onHideOrShow(bool, toolBarBottom!!)
}
var mHeadViewHideOrShowListener: OnHeadViewHideOrShowListener? = null
public fun setOnHeadViewHideOrShowListener(l: OnHeadViewHideOrShowListener) {
mHeadViewHideOrShowListener = l
}
}
public trait OnHeadViewHideOrShowListener {
public fun onHideOrShow(isShow: Boolean, parentBottom: Int)
}
|
apache-2.0
|
6a7003ab7cacba46245b155e922cd775
| 38.989051 | 142 | 0.661677 | 4.770135 | false | false | false | false |
Kotlin/anko
|
anko/idea-plugin/xml-converter/src/org/jetbrains/kotlin/android/xmlconverter/AttributeParser.kt
|
2
|
4439
|
/*
* Copyright 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 org.jetbrains.kotlin.android.xmlconverter
import org.jetbrains.kotlin.android.attrs.Attr
import org.jetbrains.kotlin.android.attrs.NoAttr
import java.util.regex.Pattern
internal fun renderLayoutAttributes(attributes: List<KeyValuePair>, parentName: String): String {
val map = attributes.map { it.key.replace("android:layout_", "") to it.value }.toMap()
fun renderLayoutDimension(s: String) = when {
s == "wrap_content" -> "wrapContent"
s == "match_parent" || s == "fill_parent" -> "matchParent"
s.isDimension() -> {
val dimension = s.parseDimension()
"${dimension.second}(${dimension.first})"
}
else -> s
}
val width = renderLayoutDimension(map["width"] ?: "wrap_content")
val height = renderLayoutDimension(map["height"] ?: "wrap_content")
val options = (layoutAttributeRenderers.findFirst { it(parentName, map) } ?: emptyList()).filterNotNull()
val optionsString = if (options.isNotEmpty()) {
options.map { it.toString().indent(1) }.joinToString("\n", " {\n", "\n}")
} else ""
return ".lparams(width = $width, height = $height)$optionsString"
}
internal fun transformAttribute(widgetName: String, name: String, value: String): KeyValuePair? {
return when {
name.startsWith("xmlns:") -> null
name.startsWith("tools:") -> null
name == "style" -> null
name.startsWith("android:") -> {
val shortName = name.substring("android:".length)
// Search for attribute in `widgetName` styleable, then in superclass styleables,
// then in `View` styleable, then in free attributes
val attr = attrs.free.firstOrNull { it.name == shortName } ?:
attrs.styleables[widgetName]?.attrs?.firstOrNull { it.name == shortName } ?:
viewHierarchy[widgetName]?.findFirst { attrs.styleables[it]?.attrs?.firstOrNull { it.name == shortName } }
attrs.styleables["View"]?.attrs?.firstOrNull { it.name == shortName }
return if (attr != null) {
renderAttribute(attr, shortName, value)
} else renderAttribute(NoAttr, shortName, value)
}
else -> name * value
}
}
internal fun renderAttribute(attr: Attr, p: KeyValuePair) = renderAttribute(attr, p.key, p.value)
private fun renderAttribute(attr: Attr, key: String, value: String): KeyValuePair? {
for (renderer in viewAttributeRenderers) {
val v = renderer(attr, key, value)
if (v != null) return v
}
return null
}
fun String.parseReference(): XmlReference? {
val matcher = Pattern.compile("@((([A-Za-z0-9._]+)\\:)?)([+A-Za-z0-9_]+)\\/([A-Za-z0-9_]+)").matcher(this)
if (!matcher.matches()) {
return null
}
return XmlReference(matcher.group(3) ?: "", matcher.group(4), matcher.group(5))
}
fun String.parseFlagValue(): Int {
return if (startsWith("0x")) Integer.parseInt(this.substring(2), 16) else this.toInt()
}
fun String.isReference(): Boolean {
return startsWith("@")
}
fun String.isSpecialReferenceAttribute() = when (this) {
"text" -> true
"background" -> true
else -> false
}
fun String.isDimension(): Boolean {
return endsWith("sp") || endsWith("dp") || endsWith("px") || endsWith("dip")
}
fun String.isColor(): Boolean {
return toLowerCase().matches("#[0-9a-f]+".toRegex())
}
fun String.parseDimension(): Pair<String, String> {
val matcher = Pattern.compile("([0-9\\.]+)(dip|dp|px|sp)").matcher(this)
if (!matcher.matches()) {
throw RuntimeException("Invalid dimension: $this")
}
val numericValue = matcher.group(1)
val dimensionUnit = matcher.group(2).let { if (it == "dp") "dip" else it }
return (if ("." in numericValue) "${numericValue}f" else numericValue) to dimensionUnit
}
|
apache-2.0
|
14f3609a11b1cde8d109dda73d8ae576
| 36.627119 | 122 | 0.644515 | 3.911013 | false | false | false | false |
quarck/CalendarNotification
|
app/src/main/java/com/github/quarck/calnotify/calendarmonitor/CalendarMonitor.kt
|
1
|
16620
|
//
// Calendar Notifications Plus
// Copyright (C) 2017 Sergey Parshin ([email protected])
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software Foundation,
// Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
//
package com.github.quarck.calnotify.calendarmonitor
import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.github.quarck.calnotify.Consts
import com.github.quarck.calnotify.Settings
import com.github.quarck.calnotify.app.ApplicationController
import com.github.quarck.calnotify.broadcastreceivers.ManualEventAlarmBroadcastReceiver
import com.github.quarck.calnotify.broadcastreceivers.ManualEventExactAlarmBroadcastReceiver
import com.github.quarck.calnotify.broadcastreceivers.ManualEventAlarmPeriodicRescanBroadcastReceiver
import com.github.quarck.calnotify.calendar.*
import com.github.quarck.calnotify.logs.DevLog
import com.github.quarck.calnotify.monitorstorage.MonitorStorage
import com.github.quarck.calnotify.permissions.PermissionsManager
import com.github.quarck.calnotify.ui.MainActivity
import com.github.quarck.calnotify.utils.alarmManager
import com.github.quarck.calnotify.utils.cancelExactAndAlarm
import com.github.quarck.calnotify.utils.detailed
import com.github.quarck.calnotify.utils.setExactAndAlarm
class CalendarMonitor(val calendarProvider: CalendarProviderInterface) :
CalendarMonitorInterface {
private val manualScanner: CalendarMonitorManual by lazy {
CalendarMonitorManual(calendarProvider, this)
}
private var lastScan = 0L
override fun onSystemTimeChange(context: Context) {
DevLog.info(LOG_TAG, "onSystemTimeChange");
launchRescanService(context)
}
override fun onPeriodicRescanBroadcast(context: Context, intent: Intent) {
DevLog.info(LOG_TAG, "onPeriodicRescanBroadcast");
val currentTime = System.currentTimeMillis()
if (currentTime - lastScan < Consts.ALARM_THRESHOLD / 4)
return
launchRescanService(context)
}
// should return true if we have fired at new requests, so UI should reload if it is open
override fun onAppResumed(context: Context, monitorSettingsChanged: Boolean) {
DevLog.info(LOG_TAG, "onAppResumed")
val currentTime = System.currentTimeMillis()
val doMonitorRescan = monitorSettingsChanged || (currentTime - lastScan >= Consts.ALARM_THRESHOLD / 4)
launchRescanService(
context,
reloadCalendar = true,
rescanMonitor = doMonitorRescan,
userActionUntil = System.currentTimeMillis() + Consts.MAX_USER_ACTION_DELAY
)
}
override fun onAlarmBroadcast(context: Context, intent: Intent) {
if (!Settings(context).enableCalendarRescan) {
DevLog.error(LOG_TAG, "onAlarmBroadcast - manual scan disabled")
setOrCancelAlarm(context, Long.MAX_VALUE)
return
}
if (!PermissionsManager.hasAllCalendarPermissionsNoCache(context)) {
DevLog.error(LOG_TAG, "onAlarmBroadcast - no calendar permission to proceed")
setOrCancelAlarm(context, Long.MAX_VALUE)
return
}
DevLog.info(LOG_TAG, "onAlarmBroadcast")
try {
val state = CalendarMonitorState(context)
val currentTime = System.currentTimeMillis()
val nextEventFireFromScan = state.nextEventFireFromScan
if (nextEventFireFromScan < currentTime + Consts.ALARM_THRESHOLD) {
DevLog.info(LOG_TAG, "onAlarmBroadcast: nextEventFireFromScan $nextEventFireFromScan is less than current" +
" time $currentTime + THRS, checking what to fire")
val firedManual = manualScanner.manualFireEventsAt_NoHousekeeping(
context, state.nextEventFireFromScan, state.prevEventFireFromScan)
if (firedManual) {
ApplicationController.afterCalendarEventFired(context)
}
}
launchRescanService(
context,
reloadCalendar = true,
rescanMonitor = true
)
}
catch (ex: Exception) {
DevLog.error(LOG_TAG, "Exception in onAlarmBroadcast: $ex, ${ex.detailed}")
}
}
// proper broadcast from the Calendar Provider. Normally this is a proper
// way of receiving information about ongoing requests. Apparently not always
// working, that's why the rest of the class is here
override fun onProviderReminderBroadcast(context: Context, intent: Intent) {
if (!PermissionsManager.hasAllCalendarPermissionsNoCache(context)) {
DevLog.error(LOG_TAG, "onProviderReminderBroadcast - no calendar permission to proceed")
setOrCancelAlarm(context, Long.MAX_VALUE)
return
}
DevLog.info(LOG_TAG, "onProviderReminderBroadcast");
val uri = intent.data;
val alertTime = uri?.lastPathSegment?.toLongOrNull()
if (alertTime == null) {
DevLog.error(LOG_TAG, "ERROR alertTime is null!")
launchRescanService(context)
return
}
val eventsToPost = mutableListOf<EventAlertRecord>()
val eventsToSilentlyDrop = mutableListOf<EventAlertRecord>()
try {
val settings = Settings(context)
val events = CalendarProvider.getAlertByTime(
context, alertTime,
skipDismissed = false,
skipExpiredEvents = settings.skipExpiredEvents
)
for (event in events) {
if (getAlertWasHandled(context, event)) {
DevLog.info(LOG_TAG, "Broadcast: Event ${event.eventId} / ${event.instanceStartTime} was handled already")
continue
}
DevLog.info(LOG_TAG, "Broadcast: Seen event ${event.eventId} / ${event.instanceStartTime}")
event.origin = EventOrigin.ProviderBroadcast
event.timeFirstSeen = System.currentTimeMillis()
if (ApplicationController.shouldMarkEventAsHandledAndSkip(context, event)) {
eventsToSilentlyDrop.add(event)
}
else if (ApplicationController.registerNewEvent(context, event)) {
eventsToPost.add(event)
}
}
}
catch (ex: Exception) {
DevLog.error(LOG_TAG, "Exception while trying to load fired event details, ${ex.detailed}")
}
try {
ApplicationController.postEventNotifications(context, eventsToPost)
for (event in eventsToSilentlyDrop) {
setAlertWasHandled(context, event, createdByUs = false)
CalendarProvider.dismissNativeEventAlert(context, event.eventId);
DevLog.info(LOG_TAG, "IGNORED Event ${event.eventId} / ${event.instanceStartTime} is marked as handled in the DB and in the provider")
}
for (event in eventsToPost) {
setAlertWasHandled(context, event, createdByUs = false)
CalendarProvider.dismissNativeEventAlert(context, event.eventId);
DevLog.info(LOG_TAG, "Event ${event.eventId} / ${event.instanceStartTime}: marked as handled in the DB and in the provider")
}
}
catch (ex: Exception) {
DevLog.error(LOG_TAG, "Exception while posting notifications: ${ex.detailed}")
}
ApplicationController.afterCalendarEventFired(context)
launchRescanService(
context,
reloadCalendar = true,
rescanMonitor = true
)
}
// should return true if we have fired at new requests, so UI should reload if it is open
override fun launchRescanService(
context: Context,
delayed: Int,
reloadCalendar: Boolean,
rescanMonitor: Boolean,
userActionUntil: Long
) {
lastScan = System.currentTimeMillis()
CalendarMonitorService.startRescanService(context, delayed, reloadCalendar, rescanMonitor, userActionUntil)
}
override fun onEventEditedByUs(context: Context, eventId: Long) {
DevLog.info(LOG_TAG, "onEventEditedByUs")
val settings = Settings(context)
if (!settings.enableCalendarRescan) {
DevLog.error(LOG_TAG, "onEventEditedByUs - manual scan disabled")
return
}
if (!settings.rescanCreatedEvent) {
DevLog.error(LOG_TAG, "onEventEditedByUs - manual scan disabled[2]")
return
}
if (!PermissionsManager.hasAllCalendarPermissionsNoCache(context)) {
DevLog.error(LOG_TAG, "onEventEditedByUs - no calendar permission to proceed")
setOrCancelAlarm(context, Long.MAX_VALUE)
return
}
val event: EventRecord? = calendarProvider.getEvent(context, eventId)
if (event == null) {
DevLog.error(LOG_TAG, "onEventEditedByUs - cannot find event $eventId")
return
}
var firedAnything = false
try {
val scanStart = System.currentTimeMillis()
firedAnything = manualScanner.scanForSingleEvent(context, event)
val scanEnd = System.currentTimeMillis()
DevLog.info(LOG_TAG, "scanForSingleEvent, perf: ${scanEnd - scanStart}")
}
catch (ex: java.lang.SecurityException) {
DevLog.error(LOG_TAG, "onEventEditedByUs: SecurityException, ${ex.detailed}")
}
catch (ex: Exception) {
DevLog.error(LOG_TAG, "onEventEditedByUs: exception, ${ex.detailed}")
}
if (firedAnything)
ApplicationController.afterCalendarEventFired(context)
}
override fun onRescanFromService(context: Context) {
if (!PermissionsManager.hasAllCalendarPermissionsNoCache(context)) {
DevLog.error(LOG_TAG, "onRescanFromService - no calendar permission to proceed")
setOrCancelAlarm(context, Long.MAX_VALUE)
return
}
// Always schedule it regardless of..
schedulePeriodicRescanAlarm(context)
if (!Settings(context).enableCalendarRescan) {
DevLog.error(LOG_TAG, "onRescanFromService - manual scan disabled")
setOrCancelAlarm(context, Long.MAX_VALUE)
return
}
DevLog.info(LOG_TAG, "onRescanFromService")
var firedAnything = false
try {
val t0 = System.currentTimeMillis()
val state = CalendarMonitorState(context)
val t1 = System.currentTimeMillis()
val (nextAlarmFromManual, firedEventsManual) = manualScanner.scanNextEvent(context, state)
val t2 = System.currentTimeMillis()
setOrCancelAlarm(context, nextAlarmFromManual)
val t3 = System.currentTimeMillis()
DevLog.info(LOG_TAG, "Manual scan, next alarm: $nextAlarmFromManual, " +
"timings: ${t3-t2},${t2-t1},${t1-t0}")
firedAnything = firedEventsManual
}
catch (ex: java.lang.SecurityException) {
DevLog.error(LOG_TAG, "onRescanFromService: SecurityException, ${ex.detailed}")
}
catch (ex: Exception) {
DevLog.error(LOG_TAG, "onRescanFromService: exception, ${ex.detailed}")
}
if (firedAnything)
ApplicationController.afterCalendarEventFired(context)
}
private fun setOrCancelAlarm(context: Context, time: Long) {
DevLog.debug(LOG_TAG, "setOrCancelAlarm");
val settings = Settings(context)
if (time != Long.MAX_VALUE && time != 0L) {
val now = System.currentTimeMillis()
DevLog.info(LOG_TAG, "Setting alarm at $time (T+${(time - now) / 1000L / 60L}min)")
val exactTime = time + Consts.ALARM_THRESHOLD / 2 // give calendar provider a little chance - schedule alarm to a bit after
context.alarmManager.setExactAndAlarm(
context,
settings.useSetAlarmClockForFailbackEventPaths,
exactTime,
ManualEventAlarmBroadcastReceiver::class.java, // ignored on KitKat and below
ManualEventExactAlarmBroadcastReceiver::class.java,
MainActivity::class.java // alarm info intent
)
}
else {
DevLog.info(LOG_TAG, "No next alerts, cancelling")
context.alarmManager.cancelExactAndAlarm(
context,
ManualEventAlarmBroadcastReceiver::class.java,
ManualEventExactAlarmBroadcastReceiver::class.java
)
}
}
private fun schedulePeriodicRescanAlarm(context: Context) {
val interval = Consts.CALENDAR_RESCAN_INTERVAL
val next = System.currentTimeMillis() + interval
DevLog.debug(LOG_TAG, "schedulePeriodicRescanAlarm, interval: $interval");
val intent = Intent(context, ManualEventAlarmPeriodicRescanBroadcastReceiver::class.java);
val pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
context.alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, next, interval, pendingIntent)
}
override fun getAlertsAt(context: android.content.Context, time: Long): List<MonitorEventAlertEntry> {
val ret = MonitorStorage(context).use {
db ->
db.getAlertsAt(time)
}
return ret
}
override fun getAlertsForAlertRange(context: Context, scanFrom: Long, scanTo: Long): List<MonitorEventAlertEntry> {
val ret = MonitorStorage(context).use {
db ->
db.getAlertsForAlertRange(scanFrom, scanTo)
}
return ret
}
override fun setAlertWasHandled(context: Context, ev: EventAlertRecord, createdByUs: Boolean) {
MonitorStorage(context).use {
db ->
var alert: MonitorEventAlertEntry? = db.getAlert(ev.eventId, ev.alertTime, ev.instanceStartTime)
if (alert != null) {
DevLog.debug(LOG_TAG, "setAlertWasHandled, ${ev.eventId}, ${ev.instanceStartTime}, ${ev.alertTime}: seen this alert already, updating status to wasHandled");
alert.wasHandled = true
db.updateAlert(alert)
}
else {
DevLog.debug(LOG_TAG, "setAlertWasHandled, ${ev.eventId}, ${ev.instanceStartTime}, ${ev.alertTime}: new alert, simply adding");
alert = MonitorEventAlertEntry(
eventId = ev.eventId,
alertTime = ev.alertTime,
isAllDay = ev.isAllDay,
instanceStartTime = ev.instanceStartTime,
instanceEndTime = ev.instanceEndTime,
wasHandled = true,
alertCreatedByUs = createdByUs
)
db.addAlert(alert)
}
}
}
override fun getAlertWasHandled(db: MonitorStorage, ev: EventAlertRecord): Boolean {
DevLog.debug(LOG_TAG, "getAlertWasHandled, ${ev.eventId}, ${ev.instanceStartTime}, ${ev.alertTime}");
return db.getAlert(ev.eventId, ev.alertTime, ev.instanceStartTime)?.wasHandled ?: false
}
override fun getAlertWasHandled(context: Context, ev: EventAlertRecord): Boolean {
return MonitorStorage(context).use {
db ->
getAlertWasHandled(db, ev)
}
}
companion object {
private const val LOG_TAG = "CalendarMonitor"
//val logger = com.github.quarck.calnotify.logs.Logger(LOG_TAG)
}
}
|
gpl-3.0
|
f83fbddd623fde3ba56f184197af0164
| 35.853659 | 173 | 0.634356 | 4.799307 | false | false | false | false |
droibit/quickly
|
app/src/main/kotlin/com/droibit/quickly/main/QuickActionDialogFragment.kt
|
1
|
6865
|
package com.droibit.quickly.main
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager.MATCH_DEFAULT_ONLY
import android.os.Bundle
import android.support.design.widget.BottomSheetBehavior
import android.support.design.widget.BottomSheetBehavior.BottomSheetCallback
import android.support.design.widget.BottomSheetDialogFragment
import android.support.design.widget.CoordinatorLayout
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemClickListener
import com.droibit.quickly.BuildConfig
import com.droibit.quickly.R
import com.droibit.quickly.data.provider.eventbus.RxBus
import com.droibit.quickly.data.provider.intent.IntentCreator
import com.droibit.quickly.data.repository.appinfo.AppInfo
import com.droibit.quickly.main.MainContract.QuickActionEvent
import com.droibit.quickly.main.MainContract.QuickActionItem
import com.droibit.quickly.main.MainContract.QuickActionItem.*
import com.github.droibit.chopstick.bindView
import com.github.droibit.chopstick.findView
import com.github.salomonbrys.kodein.Kodein
import com.github.salomonbrys.kodein.KodeinAware
import com.github.salomonbrys.kodein.KodeinInjector
import com.github.salomonbrys.kodein.instance
import java.util.*
class QuickActionDialogFragment : BottomSheetDialogFragment(),
OnItemClickListener {
companion object {
@JvmStatic
fun newInstance(app: AppInfo): QuickActionDialogFragment {
return QuickActionDialogFragment().apply {
arguments = Bundle(1).apply { putParcelable(ARG_APP, app) }
}
}
private val ARG_APP = "ARG_APP"
}
private val app: AppInfo by lazy { arguments.getParcelable<AppInfo>(ARG_APP) }
private val bottomSheetCallback: BottomSheetCallback = object : BottomSheetCallback() {
override fun onSlide(bottomSheet: View, slideOffset: Float) {
}
override fun onStateChanged(bottomSheet: View, newState: Int) {
if (newState == BottomSheetBehavior.STATE_HIDDEN) {
dismiss()
}
}
}
private val injector = KodeinInjector()
private val intentCreator: IntentCreator by injector.instance()
private val localEventBus: RxBus by injector.instance("localEventBus")
private lateinit var listAdapter: QuickActionAdapter
override fun onAttach(context: Context?) {
super.onAttach(context)
injector.inject(Kodein {
val parentKodein = context as? KodeinAware
?: throw IllegalStateException("KodeinAware is not implemented.")
extend(parentKodein.kodein)
})
}
override fun setupDialog(dialog: Dialog, style: Int) {
super.setupDialog(dialog, style)
listAdapter = QuickActionAdapter(context, items = createQuickActions())
val contentView = QuickActionLayout(context).apply {
appName = app.name
listAdapter = [email protected]
onItemClickListener = this@QuickActionDialogFragment
showLocked(visible = app.preInstalled)
dialog.setContentView(this)
}
val layoutParams = (contentView.parent as View).layoutParams as CoordinatorLayout.LayoutParams
val behavior = layoutParams.behavior
if (behavior != null && behavior is BottomSheetBehavior<*>) {
behavior.apply {
setBottomSheetCallback(bottomSheetCallback)
}
}
}
// OnItemClickListener
override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
val item = listAdapter.getItem(position)
localEventBus.call(item.toEvent(app))
dismiss()
}
// Private
private fun createQuickActions(): List<QuickActionItem> {
return ArrayList<QuickActionItem>().apply {
if (BuildConfig.APPLICATION_ID != app.packageName
&& resolveActivity(intentCreator.newUninstallIntent(app.packageName))) {
add(UNINSTALL)
}
add(SHARE_PACKAGE)
if (resolveActivity(intentCreator.newAppInfoIntent(app.packageName))) {
add(OPEN_APP_INFO)
}
}
}
private fun resolveActivity(intent: Intent): Boolean {
val resolveInfos = context.packageManager.queryIntentActivities(intent, MATCH_DEFAULT_ONLY)
return resolveInfos.isNotEmpty()
}
}
private fun QuickActionItem.toEvent(app: AppInfo): QuickActionEvent {
return when (this) {
UNINSTALL -> QuickActionEvent.Uninstall(app)
SHARE_PACKAGE -> QuickActionEvent.SharePackage(app)
OPEN_APP_INFO -> QuickActionEvent.OpenAppInfo(app)
}
}
private class QuickActionLayout @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0) : LinearLayout(context, attrs, defStyleAttr) {
var appName: String
get() = appNameView.text.toString()
set(value) {
appNameView.text = value
}
var listAdapter: ListAdapter
get() = listView.adapter
set(value) {
listView.adapter = value
}
var onItemClickListener: OnItemClickListener
get() = listView.onItemClickListener
set(value) {
listView.onItemClickListener = value
}
private val appNameView: TextView by bindView(R.id.app_name)
private val listView: ListView by bindView(R.id.list)
private val lockedView: View by bindView(R.id.lock_icon)
init {
View.inflate(context, R.layout.fragment_dialog_quick_action, this)
}
fun showLocked(visible: Boolean) {
lockedView.visibility = if (visible) View.VISIBLE else View.GONE
}
}
// TODO: Hide uninstall item if preinstall app
private class QuickActionAdapter(context: Context, items: List<QuickActionItem>)
: ArrayAdapter<QuickActionItem>(context, -1, items) {
private val inflater = LayoutInflater.from(context)
private class ViewHolder(itemView: View) {
val iconView: ImageView = itemView.findView(R.id.icon)
val labelView: TextView = itemView.findView(R.id.label)
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
val view = convertView ?: inflater.inflate(R.layout.list_item_quick_action, parent, false).apply {
tag = ViewHolder(itemView = this)
}
return view.apply {
val holder = tag as ViewHolder
val item = getItem(position)
holder.labelView.setText(item.labelRes)
holder.iconView.setImageResource(item.iconRes)
}
}
}
|
apache-2.0
|
9c36e290e0a2552de16ef53330a17f1d
| 32.325243 | 106 | 0.68842 | 4.777314 | false | false | false | false |
MoonCheesez/sstannouncer
|
sstannouncer/app/src/main/java/sst/com/anouncements/feed/model/Feed.kt
|
1
|
459
|
package sst.com.anouncements.feed.model
import java.util.Date
data class Feed(
val id: String,
val entries: List<Entry>,
val lastUpdated: Date,
val categories: List<String>,
val title: String,
val subtitle: String
) {
override fun equals(other: Any?): Boolean =
other is Feed &&
id == other.id &&
lastUpdated.compareTo(other.lastUpdated) == 0
override fun hashCode() = (id + lastUpdated).hashCode()
}
|
mit
|
ba00300dd342f170d205c88c06372832
| 23.210526 | 59 | 0.64488 | 3.956897 | false | false | false | false |
MichaelRocks/lightsaber
|
processor/src/main/java/io/michaelrocks/lightsaber/processor/analysis/ModuleProviderParser.kt
|
1
|
4950
|
/*
* Copyright 2020 Michael Rozumyanskiy
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.michaelrocks.lightsaber.processor.analysis
import io.michaelrocks.grip.Grip
import io.michaelrocks.grip.and
import io.michaelrocks.grip.annotatedWith
import io.michaelrocks.grip.fields
import io.michaelrocks.grip.from
import io.michaelrocks.grip.methodType
import io.michaelrocks.grip.methods
import io.michaelrocks.grip.mirrors.Annotated
import io.michaelrocks.grip.mirrors.ClassMirror
import io.michaelrocks.grip.mirrors.FieldMirror
import io.michaelrocks.grip.mirrors.MethodMirror
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.signature.GenericType
import io.michaelrocks.grip.not
import io.michaelrocks.grip.or
import io.michaelrocks.grip.returns
import io.michaelrocks.lightsaber.processor.ErrorReporter
import io.michaelrocks.lightsaber.processor.ProcessingException
import io.michaelrocks.lightsaber.processor.commons.Types
import io.michaelrocks.lightsaber.processor.logging.getLogger
import io.michaelrocks.lightsaber.processor.model.Module
import io.michaelrocks.lightsaber.processor.model.ModuleProvider
import io.michaelrocks.lightsaber.processor.model.ModuleProvisionPoint
interface ModuleProviderParser {
fun parseModuleProviders(
mirror: ClassMirror,
moduleRegistry: ModuleRegistry,
importeeModuleTypes: Collection<Type.Object>,
isComponentDefaultModule: Boolean
): Collection<ModuleProvider>
}
class ModuleProviderParserImpl(
private val grip: Grip,
private val errorReporter: ErrorReporter
) : ModuleProviderParser {
private val logger = getLogger()
override fun parseModuleProviders(
mirror: ClassMirror,
moduleRegistry: ModuleRegistry,
importeeModuleTypes: Collection<Type.Object>,
isComponentDefaultModule: Boolean
): Collection<ModuleProvider> {
val isImportable = createImportAnnotationMatcher(includeProvidesAnnotation = !isComponentDefaultModule)
val methodsQuery = grip select methods from mirror where (isImportable and methodType(not(returns(Type.Primitive.Void))))
val fieldsQuery = grip select fields from mirror where isImportable
val kind = if (isComponentDefaultModule) "Component" else "Module"
logger.debug("{}: {}", kind, mirror.type.className)
val methods = methodsQuery.execute()[mirror.type].orEmpty().mapNotNull { method ->
logger.debug(" Method: {}", method)
tryParseModuleProvider(method, moduleRegistry)
}
val fields = fieldsQuery.execute()[mirror.type].orEmpty().mapNotNull { field ->
logger.debug(" Field: {}", field)
tryParseModuleProvider(field, moduleRegistry)
}
val inverseImports = importeeModuleTypes.map { importeeType ->
logger.debug(" Inverse import: {}", importeeType.className)
val module = moduleRegistry.getModule(importeeType)
ModuleProvider(module, ModuleProvisionPoint.InverseImport(mirror.type, importeeType))
}
return methods + fields + inverseImports
}
private fun createImportAnnotationMatcher(includeProvidesAnnotation: Boolean): (Grip, Annotated) -> Boolean {
val annotatedWithImport = annotatedWith(Types.IMPORT_TYPE)
return if (includeProvidesAnnotation) annotatedWithImport or annotatedWith(Types.PROVIDES_TYPE) else annotatedWithImport
}
private fun tryParseModuleProvider(method: MethodMirror, moduleRegistry: ModuleRegistry): ModuleProvider? {
val module = tryParseModule(method.signature.returnType, moduleRegistry) ?: return null
return ModuleProvider(module, ModuleProvisionPoint.Method(method))
}
private fun tryParseModuleProvider(field: FieldMirror, moduleRegistry: ModuleRegistry): ModuleProvider? {
val module = tryParseModule(field.signature.type, moduleRegistry) ?: return null
return ModuleProvider(module, ModuleProvisionPoint.Field(field))
}
private fun tryParseModule(generic: GenericType, moduleRegistry: ModuleRegistry): Module? {
if (generic !is GenericType.Raw) {
errorReporter.reportError("Module provider cannot have a generic type: $generic")
return null
}
val type = generic.type
if (type !is Type.Object) {
errorReporter.reportError("Module provider cannot have an array type: $generic")
return null
}
return try {
moduleRegistry.getModule(type)
} catch (exception: ProcessingException) {
errorReporter.reportError(exception)
null
}
}
}
|
apache-2.0
|
31e7d7ac3588826dfb18516ef4425998
| 38.6 | 125 | 0.774343 | 4.600372 | false | false | false | false |
NoodleMage/tachiyomi
|
app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferencesHelper.kt
|
2
|
6704
|
package eu.kanade.tachiyomi.data.preference
import android.content.Context
import android.net.Uri
import android.os.Environment
import android.preference.PreferenceManager
import com.f2prateek.rx.preferences.Preference
import com.f2prateek.rx.preferences.RxSharedPreferences
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.data.track.TrackService
import eu.kanade.tachiyomi.source.Source
import java.io.File
import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys
fun <T> Preference<T>.getOrDefault(): T = get() ?: defaultValue()!!
fun Preference<Boolean>.invert(): Boolean = getOrDefault().let { set(!it); !it }
class PreferencesHelper(val context: Context) {
private val prefs = PreferenceManager.getDefaultSharedPreferences(context)
private val rxPrefs = RxSharedPreferences.create(prefs)
private val defaultDownloadsDir = Uri.fromFile(
File(Environment.getExternalStorageDirectory().absolutePath + File.separator +
context.getString(R.string.app_name), "downloads"))
private val defaultBackupDir = Uri.fromFile(
File(Environment.getExternalStorageDirectory().absolutePath + File.separator +
context.getString(R.string.app_name), "backup"))
fun startScreen() = prefs.getInt(Keys.startScreen, 1)
fun clear() = prefs.edit().clear().apply()
fun theme() = prefs.getInt(Keys.theme, 1)
fun rotation() = rxPrefs.getInteger(Keys.rotation, 1)
fun pageTransitions() = rxPrefs.getBoolean(Keys.enableTransitions, true)
fun doubleTapAnimSpeed() = rxPrefs.getInteger(Keys.doubleTapAnimationSpeed, 500)
fun showPageNumber() = rxPrefs.getBoolean(Keys.showPageNumber, true)
fun fullscreen() = rxPrefs.getBoolean(Keys.fullscreen, true)
fun keepScreenOn() = rxPrefs.getBoolean(Keys.keepScreenOn, true)
fun customBrightness() = rxPrefs.getBoolean(Keys.customBrightness, false)
fun customBrightnessValue() = rxPrefs.getInteger(Keys.customBrightnessValue, 0)
fun colorFilter() = rxPrefs.getBoolean(Keys.colorFilter, false)
fun colorFilterValue() = rxPrefs.getInteger(Keys.colorFilterValue, 0)
fun defaultViewer() = prefs.getInt(Keys.defaultViewer, 1)
fun imageScaleType() = rxPrefs.getInteger(Keys.imageScaleType, 1)
fun imageDecoder() = rxPrefs.getInteger(Keys.imageDecoder, 0)
fun zoomStart() = rxPrefs.getInteger(Keys.zoomStart, 1)
fun readerTheme() = rxPrefs.getInteger(Keys.readerTheme, 0)
fun cropBorders() = rxPrefs.getBoolean(Keys.cropBorders, false)
fun readWithTapping() = rxPrefs.getBoolean(Keys.readWithTapping, true)
fun readWithVolumeKeys() = rxPrefs.getBoolean(Keys.readWithVolumeKeys, false)
fun readWithVolumeKeysInverted() = rxPrefs.getBoolean(Keys.readWithVolumeKeysInverted, false)
fun portraitColumns() = rxPrefs.getInteger(Keys.portraitColumns, 0)
fun landscapeColumns() = rxPrefs.getInteger(Keys.landscapeColumns, 0)
fun updateOnlyNonCompleted() = prefs.getBoolean(Keys.updateOnlyNonCompleted, false)
fun autoUpdateTrack() = prefs.getBoolean(Keys.autoUpdateTrack, true)
fun askUpdateTrack() = prefs.getBoolean(Keys.askUpdateTrack, false)
fun lastUsedCatalogueSource() = rxPrefs.getLong(Keys.lastUsedCatalogueSource, -1)
fun lastUsedCategory() = rxPrefs.getInteger(Keys.lastUsedCategory, 0)
fun lastVersionCode() = rxPrefs.getInteger("last_version_code", 0)
fun catalogueAsList() = rxPrefs.getBoolean(Keys.catalogueAsList, false)
fun enabledLanguages() = rxPrefs.getStringSet(Keys.enabledLanguages, setOf("en"))
fun sourceUsername(source: Source) = prefs.getString(Keys.sourceUsername(source.id), "")
fun sourcePassword(source: Source) = prefs.getString(Keys.sourcePassword(source.id), "")
fun setSourceCredentials(source: Source, username: String, password: String) {
prefs.edit()
.putString(Keys.sourceUsername(source.id), username)
.putString(Keys.sourcePassword(source.id), password)
.apply()
}
fun trackUsername(sync: TrackService) = prefs.getString(Keys.trackUsername(sync.id), "")
fun trackPassword(sync: TrackService) = prefs.getString(Keys.trackPassword(sync.id), "")
fun setTrackCredentials(sync: TrackService, username: String, password: String) {
prefs.edit()
.putString(Keys.trackUsername(sync.id), username)
.putString(Keys.trackPassword(sync.id), password)
.apply()
}
fun trackToken(sync: TrackService) = rxPrefs.getString(Keys.trackToken(sync.id), "")
fun anilistScoreType() = rxPrefs.getInteger("anilist_score_type", 0)
fun backupsDirectory() = rxPrefs.getString(Keys.backupDirectory, defaultBackupDir.toString())
fun downloadsDirectory() = rxPrefs.getString(Keys.downloadsDirectory, defaultDownloadsDir.toString())
fun downloadOnlyOverWifi() = prefs.getBoolean(Keys.downloadOnlyOverWifi, true)
fun numberOfBackups() = rxPrefs.getInteger(Keys.numberOfBackups, 1)
fun backupInterval() = rxPrefs.getInteger(Keys.backupInterval, 0)
fun removeAfterReadSlots() = prefs.getInt(Keys.removeAfterReadSlots, -1)
fun removeAfterMarkedAsRead() = prefs.getBoolean(Keys.removeAfterMarkedAsRead, false)
fun libraryUpdateInterval() = rxPrefs.getInteger(Keys.libraryUpdateInterval, 0)
fun libraryUpdateRestriction() = prefs.getStringSet(Keys.libraryUpdateRestriction, emptySet())
fun libraryUpdateCategories() = rxPrefs.getStringSet(Keys.libraryUpdateCategories, emptySet())
fun libraryAsList() = rxPrefs.getBoolean(Keys.libraryAsList, false)
fun downloadBadge() = rxPrefs.getBoolean(Keys.downloadBadge, false)
fun filterDownloaded() = rxPrefs.getBoolean(Keys.filterDownloaded, false)
fun filterUnread() = rxPrefs.getBoolean(Keys.filterUnread, false)
fun filterCompleted() = rxPrefs.getBoolean(Keys.filterCompleted, false)
fun librarySortingMode() = rxPrefs.getInteger(Keys.librarySortingMode, 0)
fun librarySortingAscending() = rxPrefs.getBoolean("library_sorting_ascending", true)
fun automaticUpdates() = prefs.getBoolean(Keys.automaticUpdates, false)
fun hiddenCatalogues() = rxPrefs.getStringSet("hidden_catalogues", emptySet())
fun downloadNew() = rxPrefs.getBoolean(Keys.downloadNew, false)
fun downloadNewCategories() = rxPrefs.getStringSet(Keys.downloadNewCategories, emptySet())
fun lang() = prefs.getString(Keys.lang, "")
fun defaultCategory() = prefs.getInt(Keys.defaultCategory, -1)
fun migrateFlags() = rxPrefs.getInteger("migrate_flags", Int.MAX_VALUE)
fun trustedSignatures() = rxPrefs.getStringSet("trusted_signatures", emptySet())
}
|
apache-2.0
|
ff455a52a742f2c8fa921d29673590cc
| 38.204678 | 105 | 0.741348 | 4.270064 | false | false | false | false |
Lennoard/HEBF
|
app/src/main/java/com/androidvip/hebf/ui/account/AccountFragment.kt
|
1
|
2976
|
package com.androidvip.hebf.ui.account
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.androidvip.hebf.R
import com.androidvip.hebf.databinding.FragmentAccountBinding
import com.androidvip.hebf.helpers.HebfApp
import com.androidvip.hebf.ui.base.binding.BaseViewBindingFragment
import com.androidvip.hebf.ui.data.BackupActivity
import com.androidvip.hebf.ui.data.ImportDataActivity
import com.androidvip.hebf.utils.ContextBottomSheet
import com.androidvip.hebf.utils.K
import com.androidvip.hebf.utils.SheetOption
import com.androidvip.hebf.utils.Utils
import java.io.File
import java.util.*
class AccountFragment : BaseViewBindingFragment<FragmentAccountBinding>(
FragmentAccountBinding::inflate
) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val achievements = userPrefs.getStringSet(K.PREF.ACHIEVEMENT_SET, HashSet())
binding.achievements.text = when {
achievements.isEmpty() -> getString(R.string.none)
achievements.size == 7 -> "$achievements You got them all!"
else -> achievements.toString()
}
binding.restoreLayout.setOnClickListener { showRestoreSheet() }
binding.backupLayout.setOnClickListener {
startActivity(Intent(requireContext(), BackupActivity::class.java))
}
}
override fun onStart() {
super.onStart()
populate()
}
private fun populate() {
val backups = File(requireContext().filesDir, "backups").listFiles()
if (backups != null) {
binding.restoreBackup.text = resources.getQuantityString(
R.plurals.backups_count, backups.size, backups.size
)
}
}
private fun showRestoreSheet() {
val menuOptions = arrayListOf(
SheetOption(
getString(R.string.local_backup), "local", R.drawable.ic_backup_local
),
SheetOption(getString(R.string.cloud_backup), "cloud", R.drawable.ic_backup)
)
val contextSheet = ContextBottomSheet.newInstance(getString(R.string.restore), menuOptions)
contextSheet.onOptionClickListener = object : ContextBottomSheet.OnOptionClickListener {
override fun onOptionClick(tag: String) {
contextSheet.dismiss()
when (tag) {
"local" -> {
Intent(findContext(), ImportDataActivity::class.java).apply {
putExtra(K.EXTRA_RESTORE_ACTIVITY, true)
startActivity(this)
}
}
"cloud" -> throw UnsupportedOperationException()
}
}
}
contextSheet.show((requireActivity() as AppCompatActivity).supportFragmentManager, "sheet")
}
}
|
apache-2.0
|
8755d51c16dd62d2f5236c39e4fac718
| 35.304878 | 100 | 0.652554 | 4.831169 | false | false | false | false |
christophpickl/kpotpourri
|
release4k/src/test/kotlin/com/github/christophpickl/kpotpourri/release4k/non_test/usage.kt
|
1
|
3003
|
package com.github.christophpickl.kpotpourri.release4k.non_test
import com.github.christophpickl.kpotpourri.common.io.Keyboard
import com.github.christophpickl.kpotpourri.release4k.Version.VersionParts2.Companion.readVersion2FromStdin
import com.github.christophpickl.kpotpourri.release4k.release4k
import java.io.File
fun main(args: Array<String>) = release4k {
val versionTxtFilename = "version.txt"
val gitUrl = "https://github.com/christophpickl/kpotpourri.git"
// =================================================================================================================
val currentVersion = readVersionFromTxt(versionTxtFilename).toVersion2()
val nextVersion = readVersion2FromStdin(
prompt = "Enter next release version",
defaultVersion = currentVersion.incrementMinor()
)
val nextVersionString = nextVersion.niceString
val syspropNextVersion = "-Dkpotpourri.version=$nextVersionString"
// =================================================================================================================
printHeader("VERIFY NO CHANGES")
git(listOf("status"))
println()
if (!Keyboard.readConfirmation(prompt = "Are you sure there are no changes and everything was pushed?!")) {
return
}
// =================================================================================================================
printHeader("RELEASE NOTES")
println("Base release directory: ${release4kDirectory.canonicalPath}")
println("GitHub URL: $gitUrl")
println("Version file: ${File(versionTxtFilename).canonicalPath}")
println("Versions: ${currentVersion.niceString} => $nextVersionString")
println()
// =================================================================================================================
if (!Keyboard.readConfirmation(prompt = "Do you wanna release this?")) {
return
}
// =================================================================================================================
printHeader("GIT CHECKOUT")
checkoutGitProject(gitUrl)
// =================================================================================================================
printHeader("GRADLE BUILD")
gradlew(listOf("clean","check","checkTodo","test","build", syspropNextVersion))
// =================================================================================================================
printHeader("CHANGE VERSION")
File(gitCheckoutDirectory, versionTxtFilename).writeText(nextVersionString)
// =================================================================================================================
printHeader("GIT COMMIT")
git(listOf("status"))
git(listOf("add","."))
git(listOf("commit","-m", "[Auto-Release] Preparing release $nextVersionString"))
git(listOf("tag", nextVersionString))
git(listOf("push"))
git(listOf("push", "origin", "--tags"))
}
|
apache-2.0
|
813418de932d830c5fc6ea04f878f284
| 45.2 | 120 | 0.487512 | 5.842412 | false | false | false | false |
google/xplat
|
j2kt/jre/java/common/javaemul/lang/JavaMap.kt
|
1
|
8231
|
/*
* Copyright 2022 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package javaemul.lang
import java.util.function.BiConsumer
import java.util.function.BiFunction
import java.util.function.Function
interface JavaMap<K, V> : MutableMap<K, V> {
override fun containsKey(key: K): Boolean = java_containsKey(key)
override fun containsValue(value: V): Boolean = java_containsValue(value)
override operator fun get(key: K): V? = java_get(key)
override fun remove(key: K): V? = java_remove(key)
// TODO(b/243046587): Rewrite to handle case in which t is not mutable
override fun putAll(t: Map<out K, V>) = java_putAll(t as MutableMap<K, V>)
fun java_compute(key: K, remappingFunction: BiFunction<in K, in V?, out V>): V? =
default_compute(key, remappingFunction)
fun java_computeIfAbsent(key: K, mappingFunction: Function<in K, out V>): V =
default_computeIfAbsent(key, mappingFunction)
fun java_computeIfPresent(key: K, remappingFunction: BiFunction<in K, in V, out V>): V? =
default_computeIfPresent(key, remappingFunction)
fun java_containsKey(key: Any?): Boolean
fun java_containsValue(value: Any?): Boolean
fun java_get(key: Any?): V?
fun java_getOrDefault(key: Any?, defaultValue: V?): V? = default_getOrDefault(key, defaultValue)
fun java_forEach(action: BiConsumer<in K, in V>) = default_forEach(action)
// The Java `merge` function exists on Kotlin/JVM but is undocumented. So we rename our `merge` to
// avoid a collision.
fun java_merge(key: K, value: V, remap: BiFunction<in V, in V, out V?>): V? =
default_merge(key, value, remap)
fun java_putAll(t: MutableMap<out K, out V>)
fun java_putIfAbsent(key: K, value: V): V? = default_putIfAbsent(key, value)
fun java_remove(key: Any?): V?
fun java_remove(key: Any?, value: Any?): Boolean = default_remove(key, value)
fun java_replace(key: K, value: V): V? = default_replace(key, value)
fun java_replace(key: K, oldValue: V, newValue: V): Boolean =
default_replace(key, oldValue, newValue)
fun java_replaceAll(function: BiFunction<in K, in V, out V>) = default_replaceAll(function)
}
// Note: No need to check for the runtime type below. The bridge interface is
// only necessary to allow overriding with the Java signature. Calling with the
// Java signature does not require any trampolines, only manual type erasure.
@Suppress("UNCHECKED_CAST")
fun <K, V> MutableMap<K, V>.java_containsKey(key: Any?): Boolean = containsKey(key as K)
@Suppress("UNCHECKED_CAST")
fun <K, V> MutableMap<K, V>.java_containsValue(value: Any?): Boolean = containsValue(value as V)
@Suppress("UNCHECKED_CAST") fun <K, V> MutableMap<K, V>.java_get(key: Any?): V? = get(key as K)
@Suppress("UNCHECKED_CAST")
fun <K, V> MutableMap<K, V>.java_putAll(t: MutableMap<out K, out V>) = putAll(t as Map<out K, V>)
@Suppress("UNCHECKED_CAST")
fun <K, V> MutableMap<K, V>.java_remove(key: Any?): V? = remove(key as K)
fun <K, V> MutableMap<K, V>.java_compute(
key: K,
mappingFunction: BiFunction<in K, in V?, out V>
): V? =
if (this is JavaMap) java_compute(key, mappingFunction) else default_compute(key, mappingFunction)
fun <K, V> MutableMap<K, V>.java_computeIfAbsent(
key: K,
mappingFunction: Function<in K, out V>
): V =
if (this is JavaMap) java_computeIfAbsent(key, mappingFunction)
else default_computeIfAbsent(key, mappingFunction)
fun <K, V> MutableMap<K, V>.java_computeIfPresent(
key: K,
mappingFunction: BiFunction<in K, in V, out V>
): V? =
if (this is JavaMap) java_computeIfPresent(key, mappingFunction)
else default_computeIfPresent(key, mappingFunction)
fun <K, V> MutableMap<K, V>.java_forEach(action: BiConsumer<in K, in V>) =
if (this is JavaMap) java_forEach(action) else default_forEach(action)
fun <K, V> MutableMap<K, V>.java_getOrDefault(key: Any?, defaultValue: V?): V? =
if (this is JavaMap) java_getOrDefault(key, defaultValue)
else default_getOrDefault(key, defaultValue)
fun <K, V> MutableMap<K, V>.java_merge(
key: K,
value: V,
remap: BiFunction<in V, in V, out V?>
): V? = if (this is JavaMap) java_merge(key, value, remap) else default_merge(key, value, remap)
fun <K, V> MutableMap<K, V>.java_putIfAbsent(key: K, value: V): V? =
if (this is JavaMap) java_putIfAbsent(key, value) else default_putIfAbsent(key, value)
fun <K, V> MutableMap<K, V>.java_remove(key: Any?, value: Any?): Boolean =
if (this is JavaMap) java_remove(key, value) else default_remove(key, value)
fun <K, V> MutableMap<K, V>.java_replace(key: K, value: V): V? =
if (this is JavaMap) java_replace(key, value) else default_replace(key, value)
fun <K, V> MutableMap<K, V>.java_replace(key: K, oldValue: V, newValue: V): Boolean =
if (this is JavaMap) java_replace(key, oldValue, newValue)
else default_replace(key, oldValue, newValue)
fun <K, V> MutableMap<K, V>.java_replaceAll(function: BiFunction<in K, in V, out V>) =
if (this is JavaMap) java_replaceAll(function) else default_replaceAll(function)
private fun <K, V> MutableMap<K, V>.default_forEach(action: BiConsumer<in K, in V>) {
this.forEach { entry -> action.accept(entry.key, entry.value) }
}
private fun <K, V> MutableMap<K, V>.default_compute(
key: K,
remappingFunction: BiFunction<in K, in V?, out V>
): V? {
val oldValue = this[key]
val newValue = remappingFunction.apply(key, oldValue)
if (oldValue != null) {
if (newValue != null) {
this.put(key, newValue)
return newValue
} else {
this.remove(key)
return null
}
} else if (newValue != null) {
this.put(key, newValue)
return newValue
}
return null
}
private fun <K, V> MutableMap<K, V>.default_computeIfAbsent(
key: K,
mappingFunction: Function<in K, out V>
): V {
val oldValue = this[key]
if (oldValue == null) {
val newValue = mappingFunction.apply(key)
if (newValue != null) this.put(key, newValue)
return newValue
}
return oldValue
}
private fun <K, V> MutableMap<K, V>.default_computeIfPresent(
key: K,
remappingFunction: BiFunction<in K, in V, out V>
): V? {
val oldValue = this[key]
if (oldValue != null) {
val newValue = remappingFunction.apply(key, oldValue)
if (newValue != null) this.put(key, newValue) else this.remove(key)
return newValue
}
return null
}
@Suppress("UNCHECKED_CAST")
private fun <K, V> MutableMap<K, V>.default_getOrDefault(key: Any?, defaultValue: V?): V? {
if (this.containsKey(key as K)) {
return this[key as K]
}
return defaultValue
}
private fun <K, V> MutableMap<K, V>.default_merge(
key: K,
value: V,
remap: BiFunction<in V, in V, out V?>
): V? {
val oldValue = get(key)
val newValue: V? = if (oldValue == null) value else remap.apply(oldValue, value)
if (newValue == null) {
remove(key)
} else {
put(key, newValue)
}
return newValue
}
private fun <K, V> MutableMap<K, V>.default_putIfAbsent(key: K, value: V): V? {
return getOrPut(key) { value }
}
@Suppress("UNCHECKED_CAST")
private fun <K, V> MutableMap<K, V>.default_remove(key: Any?, value: Any?): Boolean {
if (this.containsKey(key as K) && this[key as K] == value as V) {
this.remove(key as K)
return true
} else return false
}
private fun <K, V> MutableMap<K, V>.default_replace(key: K, value: V): V? =
if (this.containsKey(key)) this.put(key, value) else null
private fun <K, V> MutableMap<K, V>.default_replace(key: K, oldValue: V, newValue: V): Boolean {
if (this.containsKey(key) && this[key] == oldValue) {
this[key] = newValue
return true
} else return false
}
private fun <K, V> MutableMap<K, V>.default_replaceAll(function: BiFunction<in K, in V, out V>) {
this.forEach { entry -> function.apply(entry.key, entry.value) }
}
|
apache-2.0
|
7020d3527b11e3c6e36dbbefaa8b3bab
| 33.295833 | 100 | 0.689102 | 3.284517 | false | false | false | false |
adamWeesner/Tax-Fetcher
|
tax-fetcher/src/main/kotlin/weesner/tax_fetcher/CheckModel.kt
|
1
|
6446
|
package weesner.tax_fetcher
class Check(
var payInfo: PayInfo,
var payrollInfo: PayrollInfo,
var retirement: List<Retirement>? = null,
var payrollDeductions: List<PayrollDeduction>? = null
) {
constructor(payInfo: PayInfo, payrollInfo: PayrollInfo, retirement: Retirement, payrollDeduction: PayrollDeduction)
: this(payInfo, payrollInfo, listOf(retirement), listOf(payrollDeduction))
constructor(payInfo: PayInfo, payrollInfo: PayrollInfo, retirement: List<Retirement>? = null, payrollDeduction: PayrollDeduction)
: this(payInfo, payrollInfo, retirement, listOf(payrollDeduction))
constructor(payInfo: PayInfo, payrollInfo: PayrollInfo, retirement: Retirement, payrollDeductions: List<PayrollDeduction>? = null)
: this(payInfo, payrollInfo, listOf(retirement), payrollDeductions)
/** Total of [healthCareDeductionsAmount] and [nonHealthCareDeductionsAmount] */
var deductionsAmount: Double = 0.0
/** Health-care deductions total amount of the [PayInfo.amount], used to get the [PayInfo.ficaTaxable] amount */
var healthCareDeductionsAmount: Double = 0.0
/** non-Health-care deductions total amount of the [PayInfo.amount], used to get the [PayInfo.ficaTaxable] amount */
var nonHealthCareDeductionsAmount: Double = 0.0
/** Year to date gross amount, used to determine Fica tax maximums. Default: [PayInfo.amount]*/
var yearToDateGross: Double = payInfo.amount
/** Total of [retirementAfterTaxesAmount] and [retirementBeforeTaxesAmount] */
var retirementAmount: Double = 0.0
/** Retirement amount to be taken out of the [PayInfo.amount] before federal taxes */
var retirementBeforeTaxesAmount: Double = 0.0
/** Retirement amount to be taken out of the [PayInfo.amount] after federal taxes */
var retirementAfterTaxesAmount: Double = 0.0
/** Amount of medicare tax to be taken out */
var medicareAmount: Double = 0.0
/** Amount of social security tax to be taken out */
var socialSecurityAmount: Double = 0.0
/** Amount of federal income tax to be taken out */
var federalIncomeTaxAmount: Double = 0.0
/** Amount of federal taxes to be taken out */
var federalTaxesAmount = 0.0
/** Amount of check after taxes, retirement and deductions, to be taken out */
var afterTax: Double = 0.0
init {
if (payrollDeductions != null) {
payrollDeductions!!.forEach { deduction ->
if (deduction.isHealthCare) healthCareDeductionsAmount += deduction.amountOfCheck(payInfo.amount)
else nonHealthCareDeductionsAmount += deduction.amountOfCheck(payInfo.amount)
}
}
if (retirement != null) {
retirement!!.forEach { retirement ->
if (retirement.isTakenBeforeTaxes) retirementBeforeTaxesAmount += retirement.amountOfCheck(payInfo.amount)
}
retirementAmount = retirementBeforeTaxesAmount
}
payInfo.ficaTaxable = payInfo.amount - healthCareDeductionsAmount
}
fun addRetirement(listOfRetirement: List<Retirement>) {
listOfRetirement.forEach {
if (it.isTakenBeforeTaxes) retirementBeforeTaxesAmount += it.amountOfCheck(payInfo.amount)
}
retirementAmount = retirementBeforeTaxesAmount
}
fun addRetirement(retirement: Retirement) {
addRetirement(listOf(retirement))
}
fun addPayrollDeductions(listOfDeductions: List<PayrollDeduction>) {
listOfDeductions.forEach {
val amount = it.amountOfCheck(payInfo.amount)
if (it.isHealthCare) healthCareDeductionsAmount += amount
else nonHealthCareDeductionsAmount += amount
}
payInfo.ficaTaxable = payInfo.amount - healthCareDeductionsAmount
deductionsAmount = healthCareDeductionsAmount + nonHealthCareDeductionsAmount
}
fun addPayrollDeduction(deduction: PayrollDeduction) {
addPayrollDeductions(listOf(deduction))
}
fun calculateTaxes(federalTaxes: FederalTaxes) {
federalTaxes.linkCheck(this)
medicareAmount = federalTaxes.medicare.amountOfFicaTaxable()
socialSecurityAmount = federalTaxes.socialSecurity.amountOfFicaTaxable()
val taxWithholding = federalTaxes.taxWithholding
federalIncomeTaxAmount = federalTaxes.federalIncomeTax.apply {
FederalIncomeTax.withholding = taxWithholding
}.amountOfFicaTaxable()
federalTaxesAmount = (federalIncomeTaxAmount + medicareAmount + socialSecurityAmount)
retirement?.filter { !it.isTakenBeforeTaxes }?.forEach { retirementAfterTaxesAmount += it.amountOfCheck(payInfo.amount - federalTaxesAmount) }
retirementAmount += retirementAfterTaxesAmount
afterTax = payInfo.amount - (federalTaxesAmount + deductionsAmount + retirementAmount)
}
}
class PayInfo(
var hourlyRate: Double = 0.0,
var hours: Double = 0.0,
var overtimeHours: Double = 0.0
) {
constructor(amount: Double) : this() {
this.amount = amount
}
var baseAmount = hourlyRate * hours
var overtimeRate = hourlyRate * 1.5
var overtimeAmount = overtimeRate * overtimeHours
var amount = baseAmount + overtimeAmount
var ficaTaxable = 0.0
}
class PayrollInfo(
var maritalStatus: String = SINGLE,
var payrollAllowances: Int = 0,
var payPeriod: String = WEEKLY
) {
init {
maritalStatus.validate("Marital Status", listOf(MARRIED, SINGLE))
payrollAllowances.toString().validate("Payroll Allowances", listOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"))
payPeriod.validate("Pay Period Type", listOf(WEEKLY, BIWEEKLY, SEMIMONTHLY, MONTHLY, QUARTERLY, SEMIANNUAL, ANNUAL, DAILY))
}
}
class Retirement(
val name: String = "retirementAccount",
var amount: Double,
val isPercentage: Boolean,
val isTakenBeforeTaxes: Boolean = false
) {
fun amountOfCheck(checkAmount: Double): Double {
return if (isPercentage) (amount * .01) * checkAmount
else amount
}
}
class PayrollDeduction(
val name: String = "deduction",
var amount: Double,
val isPercentage: Boolean,
val isHealthCare: Boolean
) {
fun amountOfCheck(checkAmount: Double): Double {
return if (isPercentage) (amount * .01) * checkAmount
else amount
}
}
|
mit
|
530a40f8c2b22182c488fa77ee254fba
| 38.552147 | 150 | 0.687403 | 3.654195 | false | false | false | false |
kotlintest/kotlintest
|
kotest-assertions/src/jvmMain/kotlin/io/kotest/matchers/concurrent/concurrent.kt
|
1
|
1032
|
package io.kotest.matchers.concurrent
import io.kotest.assertions.Failures
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import kotlin.concurrent.thread
fun <A> shouldCompleteWithin(timeout: Long, unit: TimeUnit, thunk: () -> A) {
val ref = AtomicReference<A>(null)
val latch = CountDownLatch(1)
val t = thread {
val a = thunk()
ref.set(a)
latch.countDown()
}
if (!latch.await(timeout, unit)) {
t.interrupt()
throw Failures.failure("Test should have completed within $timeout/$unit")
}
ref.get()
}
fun <A> shouldTimeout(timeout: Long, unit: TimeUnit, thunk: () -> A) {
val latch = CountDownLatch(1)
val t = thread {
thunk()
latch.countDown()
}
// if the latch didn't complete in the time period then we did timeout
val timedOut = !latch.await(timeout, unit)
if (timedOut) {
t.interrupt()
} else {
throw Failures.failure("Expected test to timeout for $timeout/$unit")
}
}
|
apache-2.0
|
c002f9e8e699201612580e6aaa07bd6a
| 22.454545 | 78 | 0.689922 | 3.608392 | false | true | false | false |
ruuvi/Android_RuuvitagScanner
|
app/src/main/java/com/ruuvi/station/app/preferences/Preferences.kt
|
1
|
10190
|
package com.ruuvi.station.app.preferences
import android.content.Context
import android.content.SharedPreferences
import androidx.preference.PreferenceManager
import com.ruuvi.station.units.model.HumidityUnit
import com.ruuvi.station.units.model.PressureUnit
import com.ruuvi.station.units.model.TemperatureUnit
import com.ruuvi.station.util.BackgroundScanModes
import com.ruuvi.station.util.extensions.isUpdateInstall
import java.util.*
import kotlin.math.max
import kotlin.math.round
class Preferences constructor(val context: Context) {
private val sharedPreferences: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(context) }
var backgroundScanInterval: Int
get() = sharedPreferences.getInt(PREF_BACKGROUND_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL)
set(interval) {
sharedPreferences.edit().putInt(PREF_BACKGROUND_SCAN_INTERVAL, interval).apply()
}
var backgroundScanMode: BackgroundScanModes
get() = BackgroundScanModes.fromInt(sharedPreferences.getInt(PREF_BACKGROUND_SCAN_MODE, BackgroundScanModes.DISABLED.value))
?: BackgroundScanModes.DISABLED
set(mode) {
sharedPreferences.edit().putInt(PREF_BACKGROUND_SCAN_MODE, mode.value).apply()
}
var isFirstStart: Boolean
get() = sharedPreferences.getBoolean(PREF_FIRST_START, true)
set(enabled) {
sharedPreferences.edit().putBoolean(PREF_FIRST_START, enabled).apply()
}
var isFirstGraphVisit: Boolean
get() = sharedPreferences.getBoolean(PREF_FIRST_GRAPH, true)
set(enabled) {
sharedPreferences.edit().putBoolean(PREF_FIRST_GRAPH, enabled).apply()
}
var temperatureUnit: TemperatureUnit
get() {
return when (sharedPreferences.getString(PREF_TEMPERATURE_UNIT, DEFAULT_TEMPERATURE_UNIT)) {
"C" -> TemperatureUnit.CELSIUS
"F" -> TemperatureUnit.FAHRENHEIT
"K" -> TemperatureUnit.KELVIN
else -> TemperatureUnit.CELSIUS
}
}
set(unit) {
sharedPreferences.edit().putString(PREF_TEMPERATURE_UNIT, unit.code).apply()
}
var humidityUnit: HumidityUnit
get() {
return when (sharedPreferences.getInt(PREF_HUMIDITY_UNIT, 0)) {
0 -> HumidityUnit.PERCENT
1 -> HumidityUnit.GM3
2 -> HumidityUnit.DEW
else -> HumidityUnit.PERCENT
}
}
set(value) {
sharedPreferences.edit().putInt(PREF_HUMIDITY_UNIT, value.code).apply()
}
var pressureUnit: PressureUnit
get() {
return when (sharedPreferences.getInt(PREF_PRESSURE_UNIT, 1)) {
0 -> PressureUnit.PA
1 -> PressureUnit.HPA
2 -> PressureUnit.MMHG
3 -> PressureUnit.INHG
else -> PressureUnit.HPA
}
}
set(value) {
sharedPreferences.edit().putInt(PREF_PRESSURE_UNIT, value.code).apply()
}
var gatewayUrl: String
get() = sharedPreferences.getString(PREF_BACKEND, DEFAULT_GATEWAY_URL)
?: DEFAULT_GATEWAY_URL
set(url) {
sharedPreferences.edit().putString(PREF_BACKEND, url).apply()
}
var deviceId: String
get() = sharedPreferences.getString(PREF_DEVICE_ID, DEFAULT_DEVICE_ID) ?: DEFAULT_DEVICE_ID
set(id) {
sharedPreferences.edit().putString(PREF_DEVICE_ID, id).apply()
}
var serviceWakelock: Boolean
get() = sharedPreferences.getBoolean(PREF_WAKELOCK, false)
set(enabled) {
sharedPreferences.edit().putBoolean(PREF_WAKELOCK, enabled).apply()
}
var dashboardEnabled: Boolean
get() = sharedPreferences.getBoolean(PREF_DASHBOARD_ENABLED, false)
set(enabled) {
sharedPreferences.edit().putBoolean(PREF_DASHBOARD_ENABLED, enabled).apply()
}
var batterySaverEnabled: Boolean
get() = sharedPreferences.getBoolean(PREF_BGSCAN_BATTERY_SAVING, false)
set(enabled) {
sharedPreferences.edit().putBoolean(PREF_BGSCAN_BATTERY_SAVING, enabled).apply()
}
// chart interval between data points (in minutes)
var graphPointInterval: Int
get() = sharedPreferences.getInt(PREF_GRAPH_POINT_INTERVAL, DEFAULT_GRAPH_POINT_INTERVAL)
set(interval) {
sharedPreferences.edit().putInt(PREF_GRAPH_POINT_INTERVAL, interval).apply()
}
// chart view period (in hours)
var graphViewPeriod: Int
get() = sharedPreferences.getInt(PREF_GRAPH_VIEW_PERIOD, DEFAULT_GRAPH_VIEW_PERIOD)
set(period) {
sharedPreferences.edit().putInt(PREF_GRAPH_VIEW_PERIOD, period).apply()
}
// chart view period (in days)
var graphViewPeriodDays: Int
get() = sharedPreferences.getInt(PREF_GRAPH_VIEW_PERIOD_DAYS, getDefaultGraphViewPeriodDays())
set(period) {
sharedPreferences.edit().putInt(PREF_GRAPH_VIEW_PERIOD_DAYS, period).apply()
}
var graphShowAllPoint: Boolean
get() = sharedPreferences.getBoolean(PREF_GRAPH_SHOW_ALL_POINTS, DEFAULT_GRAPH_SHOW_ALL_POINTS)
set(showAllPoints) {
sharedPreferences.edit().putBoolean(PREF_GRAPH_SHOW_ALL_POINTS, showAllPoints).apply()
}
var graphDrawDots: Boolean
get() = sharedPreferences.getBoolean(PREF_GRAPH_DRAW_DOTS, DEFAULT_GRAPH_DRAW_DOTS)
set(drawDots) {
sharedPreferences.edit().putBoolean(PREF_GRAPH_DRAW_DOTS, drawDots).apply()
}
var locale: String
get() {
var preferenceLocale = sharedPreferences.getString(PREF_LOCALE, null)
if (preferenceLocale == null) {
val defaultLanguage = Locale.getDefault().language
if (SUPPORTED_LOCALES.contains(defaultLanguage)) {
preferenceLocale = defaultLanguage
} else {
preferenceLocale = DEFAULT_LOCALE
}
preferenceLocale?.let{
locale = preferenceLocale
}
}
return preferenceLocale ?: DEFAULT_LOCALE
}
set(locale) {
sharedPreferences.edit().putString(PREF_LOCALE, locale).apply()
}
var networkEmail: String
get() = sharedPreferences.getString(PREF_NETWORK_EMAIL, "") ?: ""
set(email) {
sharedPreferences.edit().putString(PREF_NETWORK_EMAIL, email).apply()
}
var networkToken: String
get() = sharedPreferences.getString(PREF_NETWORK_TOKEN, "") ?: ""
set(token) {
sharedPreferences.edit().putString(PREF_NETWORK_TOKEN, token).apply()
}
var lastSyncDate: Long
get() = sharedPreferences.getLong(PREF_LAST_SYNC_DATE, Long.MIN_VALUE)
set(syncDate) {
sharedPreferences.edit().putLong(PREF_LAST_SYNC_DATE, syncDate).apply()
}
var experimentalFeatures: Boolean
get() = sharedPreferences.getBoolean(PREF_EXPERIMENTAL_FEATURES, false)
set(experimentalFeatures) {
sharedPreferences.edit().putBoolean(PREF_EXPERIMENTAL_FEATURES, experimentalFeatures).apply()
}
fun getUserEmailLiveData() = SharedPreferenceStringLiveData(sharedPreferences, PREF_NETWORK_EMAIL, "")
fun getLastSyncDateLiveData() = SharedPreferenceLongLiveData(sharedPreferences, PREF_LAST_SYNC_DATE, Long.MIN_VALUE)
fun getExperimentalFeaturesLiveData() = SharedPreferenceBooleanLiveData(sharedPreferences, PREF_EXPERIMENTAL_FEATURES, false)
private fun getDefaultGraphViewPeriodDays(): Int {
return if (context.isUpdateInstall()) {
return max(round(graphViewPeriod / 24f).toInt(), 1)
} else {
DEFAULT_GRAPH_VIEW_PERIOD_DAYS
}
}
companion object {
private const val DEFAULT_SCAN_INTERVAL = 15 * 60
private const val PREF_BACKGROUND_SCAN_INTERVAL = "pref_background_scan_interval"
private const val PREF_BACKGROUND_SCAN_MODE = "pref_background_scan_mode"
private const val PREF_FIRST_START = "FIRST_START_PREF"
private const val PREF_FIRST_GRAPH = "first_graph_visit"
private const val PREF_TEMPERATURE_UNIT = "pref_temperature_unit"
private const val PREF_HUMIDITY_UNIT = "pref_humidity_unit"
private const val PREF_PRESSURE_UNIT = "pref_pressure_unit"
private const val PREF_BACKEND = "pref_backend"
private const val PREF_DEVICE_ID = "pref_device_id"
private const val PREF_WAKELOCK = "pref_wakelock"
private const val PREF_DASHBOARD_ENABLED = "DASHBOARD_ENABLED_PREF"
private const val PREF_BGSCAN_BATTERY_SAVING = "pref_bgscan_battery_saving"
private const val PREF_GRAPH_POINT_INTERVAL = "pref_graph_point_interval"
private const val PREF_GRAPH_VIEW_PERIOD = "pref_graph_view_period"
private const val PREF_GRAPH_VIEW_PERIOD_DAYS = "pref_graph_view_period_days"
private const val PREF_GRAPH_SHOW_ALL_POINTS = "pref_graph_show_all_points"
private const val PREF_GRAPH_DRAW_DOTS = "pref_graph_draw_dots"
private const val PREF_LOCALE = "pref_locale"
private const val PREF_NETWORK_EMAIL = "pref_network_email"
private const val PREF_NETWORK_TOKEN = "pref_network_token"
private const val PREF_LAST_SYNC_DATE = "pref_last_sync_date"
private const val PREF_EXPERIMENTAL_FEATURES = "pref_experimental_features"
private const val DEFAULT_TEMPERATURE_UNIT = "C"
private const val DEFAULT_GATEWAY_URL = ""
private const val DEFAULT_DEVICE_ID = ""
private const val DEFAULT_GRAPH_POINT_INTERVAL = 1
private const val DEFAULT_GRAPH_VIEW_PERIOD = 24
private const val DEFAULT_GRAPH_VIEW_PERIOD_DAYS = 10
private const val DEFAULT_GRAPH_SHOW_ALL_POINTS = true
private const val DEFAULT_GRAPH_DRAW_DOTS = false
private const val DEFAULT_LOCALE = "en"
private val SUPPORTED_LOCALES = listOf("en", "fi", "sv", "ru")
}
}
|
mit
|
0161cd28f7ee9601b7f7ef1e0456b647
| 40.938272 | 132 | 0.649755 | 4.477153 | false | false | false | false |
world-federation-of-advertisers/common-jvm
|
src/main/kotlin/org/wfanet/measurement/gcloud/gcs/GcsFromFlags.kt
|
1
|
1624
|
// Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.gcloud.gcs
import com.google.cloud.storage.Storage
import com.google.cloud.storage.StorageOptions
import picocli.CommandLine
/** Client access provider for Google Cloud Storage (GCS) via command-line flags. */
class GcsFromFlags(private val flags: Flags) {
private val storageOptions: StorageOptions by lazy {
StorageOptions.newBuilder().setProjectId(flags.projectName).build()
}
val storage: Storage
get() = storageOptions.service
val bucket: String
get() = flags.bucket
class Flags {
@CommandLine.Option(
names = ["--google-cloud-storage-project"],
description = ["Name of the Google Cloud Storage project to use."],
required = true
)
lateinit var projectName: String
private set
@CommandLine.Option(
names = ["--google-cloud-storage-bucket"],
description = ["Name of the Google Cloud Storage project to use."],
required = true
)
lateinit var bucket: String
private set
}
}
|
apache-2.0
|
5bf719e9271e5a1b5e943a14c6eebc79
| 30.843137 | 84 | 0.716749 | 4.377358 | false | false | false | false |
Ph1b/MaterialAudiobookPlayer
|
data/src/test/kotlin/de/ph1b/audiobook/data/BookSubject.kt
|
1
|
1523
|
package de.ph1b.audiobook.data
import com.google.common.truth.FailureMetadata
import com.google.common.truth.Subject
import com.google.common.truth.Subject.Factory
import com.google.common.truth.Truth.assertAbout
class BookSubject private constructor(failureMetaData: FailureMetadata, private val actual: Book?) :
Subject(failureMetaData, actual) {
fun positionIs(position: Long) {
if (actual?.content?.position != position) {
failWithActual("position", position)
}
}
fun durationIs(duration: Long) {
if (actual?.content?.duration != duration) {
failWithActual("duration", duration)
}
}
fun currentChapterIs(currentChapter: Chapter) {
if (actual?.content?.currentChapter != currentChapter) {
failWithActual("currentChapter", currentChapter)
}
}
fun currentChapterIndexIs(currentChapterIndex: Int) {
if (actual?.content?.currentChapterIndex != currentChapterIndex) {
failWithActual("currentChapterIndex", currentChapterIndex)
}
}
fun nextChapterIs(nextChapter: Chapter?) {
if (actual?.content?.nextChapter != nextChapter) {
failWithActual("nextChapter", arrayOf(nextChapter))
}
}
fun previousChapterIs(previousChapter: Chapter?) {
if (actual?.content?.previousChapter != previousChapter) {
failWithActual("previousChapter", arrayOf(previousChapter))
}
}
companion object {
val factory = Factory(::BookSubject)
}
}
fun Book?.assertThat(): BookSubject = assertAbout(BookSubject.factory).that(this)
|
lgpl-3.0
|
fcb89520d2382b10ccf0350d8581b150
| 28.288462 | 100 | 0.723572 | 4.266106 | false | false | false | false |
robinverduijn/gradle
|
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/resolver/SourceDistributionProvider.kt
|
1
|
6342
|
/*
* Copyright 2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.resolver
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.repositories.ArtifactRepository
import org.gradle.api.artifacts.repositories.IvyArtifactRepository
import org.gradle.api.artifacts.transform.TransformAction
import org.gradle.api.artifacts.transform.TransformParameters
import org.gradle.api.artifacts.transform.TransformSpec
import org.gradle.api.attributes.Attribute
import org.gradle.kotlin.dsl.*
import org.gradle.util.GradleVersion
import java.io.File
interface SourceDistributionProvider {
fun sourceDirs(): Collection<File>
}
class SourceDistributionResolver(val project: Project) : SourceDistributionProvider {
companion object {
val artifactType = Attribute.of("artifactType", String::class.java)
val zipType = "zip"
val unzippedDistributionType = "unzipped-distribution"
val sourceDirectory = "src-directory"
}
override fun sourceDirs(): Collection<File> =
try {
collectSourceDirs()
} catch (ex: Exception) {
project.logger.warn("Unexpected exception while resolving Gradle distribution sources: ${ex.message}", ex)
emptyList()
}
private
fun collectSourceDirs() =
withSourceRepository {
registerTransforms()
transientConfigurationForSourcesDownload().files
}
private
fun <T> withSourceRepository(produce: () -> T): T =
createSourceRepository().let {
try {
produce()
} finally {
repositories.remove(it)
}
}
private
fun registerTransforms() {
registerTransform<UnzipDistribution> {
from.attribute(artifactType, zipType)
to.attribute(artifactType, unzippedDistributionType)
}
registerTransform<FindGradleSources> {
from.attribute(artifactType, unzippedDistributionType)
to.attribute(artifactType, sourceDirectory)
}
}
private
fun transientConfigurationForSourcesDownload() =
detachedConfigurationFor(gradleSourceDependency()).apply {
attributes.attribute(artifactType, sourceDirectory)
}
private
fun detachedConfigurationFor(dependency: Dependency) =
configurations.detachedConfiguration(dependency)
private
fun gradleSourceDependency() = dependencies.create(
group = "gradle",
name = "gradle",
version = dependencyVersion(gradleVersion),
configuration = null,
classifier = "src",
ext = "zip")
private
fun createSourceRepository() = ivy {
val repoName = repositoryNameFor(gradleVersion)
name = "Gradle $repoName"
setUrl("https://services.gradle.org/$repoName")
metadataSources { sources ->
sources.artifact()
}
patternLayout { layout ->
if (isSnapshot(gradleVersion)) {
layout.ivy("/dummy") // avoids a lookup that interferes with version listing
}
layout.artifact("[module]-[revision](-[classifier])(.[ext])")
}
}.also {
// push the repository first in the list, for performance
makeItFirstInTheList(it)
}
private
fun repositoryNameFor(gradleVersion: String) =
if (isSnapshot(gradleVersion)) "distributions-snapshots" else "distributions"
private
fun dependencyVersion(gradleVersion: String) =
if (isSnapshot(gradleVersion)) toVersionRange(gradleVersion) else gradleVersion
private
fun isSnapshot(gradleVersion: String) = gradleVersion.contains('+')
private
fun toVersionRange(gradleVersion: String) =
"(${minimumGradleVersion()}, $gradleVersion]"
private
fun makeItFirstInTheList(repository: ArtifactRepository) {
repositories.apply {
remove(repository)
addFirst(repository)
}
}
private
inline fun <reified T : TransformAction<TransformParameters.None>> registerTransform(crossinline configure: TransformSpec<TransformParameters.None>.() -> Unit) =
dependencies.registerTransform(T::class.java) { configure(it) }
private
fun ivy(configure: IvyArtifactRepository.() -> Unit) =
repositories.ivy { configure(it) }
private
fun minimumGradleVersion(): String? {
val baseVersionString = GradleVersion.version(gradleVersion).baseVersion.version
val (major, minor) = baseVersionString.split('.')
return when (minor) {
// TODO:kotlin-dsl consider commenting out this clause once the 1st 6.0 snapshot is out
"0" -> {
// When testing against a `major.0` snapshot we need to take into account
// that source distributions matching the major version might not have
// been published yet. In that case we adjust the constraint to include
// source distributions beginning from the previous major version.
"${previous(major)}.0"
}
else -> {
// Otherwise include source distributions beginning from the previous minor version only.
"$major.${previous(minor)}"
}
}
}
private
fun previous(versionDigit: String) =
Integer.valueOf(versionDigit) - 1
private
val repositories
get() = project.repositories
private
val configurations
get() = project.configurations
private
val dependencies
get() = project.dependencies
private
val gradleVersion
get() = project.gradle.gradleVersion
}
|
apache-2.0
|
ea66eea4dc32769753bfd6b4b1e701be
| 32.204188 | 165 | 0.659571 | 5.057416 | false | true | false | false |
Deletescape-Media/Lawnchair
|
lawnchair/src/app/lawnchair/ui/preferences/components/FontPreference.kt
|
1
|
935
|
package app.lawnchair.ui.preferences.components
import androidx.compose.foundation.clickable
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import app.lawnchair.preferences.BasePreferenceManager
import app.lawnchair.preferences.getAdapter
import app.lawnchair.ui.preferences.LocalNavController
@Composable
fun FontPreference(
fontPref: BasePreferenceManager.FontPref,
label: String,
) {
val navController = LocalNavController.current
PreferenceTemplate(
title = { Text(text = label) },
description = {
val font = fontPref.getAdapter().state.value
Text(
text = font.fullDisplayName,
fontFamily = font.composeFontFamily
)
},
modifier = Modifier
.clickable { navController.navigate(route = "/fontSelection/${fontPref.key}/") },
)
}
|
gpl-3.0
|
7d45dba14c7fe641276ac71649a76a3c
| 30.166667 | 93 | 0.699465 | 4.770408 | false | false | false | false |
dataloom/conductor-client
|
src/main/kotlin/com/openlattice/organizations/roles/HazelcastPrincipalService.kt
|
1
|
15294
|
/*
* Copyright (C) 2018. OpenLattice, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can contact the owner of the copyright at [email protected]
*
*/
package com.openlattice.organizations.roles
import com.auth0.json.mgmt.users.User
import com.google.common.base.Preconditions
import com.google.common.collect.ImmutableSet
import com.google.common.collect.Sets
import com.google.common.eventbus.EventBus
import com.hazelcast.core.HazelcastInstance
import com.hazelcast.query.Predicate
import com.hazelcast.query.Predicates
import com.openlattice.authorization.*
import com.openlattice.authorization.mapstores.PrincipalMapstore
import com.openlattice.datastore.util.Util
import com.openlattice.hazelcast.HazelcastMap
import com.openlattice.hazelcast.processors.GetPrincipalFromSecurablePrincipalsEntryProcessor
import com.openlattice.organization.roles.Role
import com.openlattice.organizations.processors.NestedPrincipalMerger
import com.openlattice.organizations.processors.NestedPrincipalRemover
import com.openlattice.organizations.roles.processors.PrincipalDescriptionUpdater
import com.openlattice.organizations.roles.processors.PrincipalTitleUpdater
import com.openlattice.principals.PrincipalExistsEntryProcessor
import com.openlattice.principals.RoleCreatedEvent
import com.openlattice.principals.UserCreatedEvent
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import java.util.*
@Service
class HazelcastPrincipalService(
hazelcastInstance: HazelcastInstance,
private val reservations: HazelcastAclKeyReservationService,
private val authorizations: AuthorizationManager,
private val eventBus: EventBus
) : SecurePrincipalsManager, AuthorizingComponent {
private val principals = HazelcastMap.PRINCIPALS.getMap(hazelcastInstance)
private val principalTrees = HazelcastMap.PRINCIPAL_TREES.getMap(hazelcastInstance)
private val users = HazelcastMap.USERS.getMap(hazelcastInstance)
companion object {
private val logger = LoggerFactory
.getLogger(HazelcastPrincipalService::class.java)
private fun findPrincipal(p: Principal): Predicate<AclKey, SecurablePrincipal> {
return Predicates.equal(PrincipalMapstore.PRINCIPAL_INDEX, p)
}
private fun findPrincipals(principals: Collection<Principal>): Predicate<AclKey, SecurablePrincipal> {
return Predicates.`in`(PrincipalMapstore.PRINCIPAL_INDEX, *principals.toTypedArray())
}
private fun hasPrincipalType(principalType: PrincipalType): Predicate<AclKey, SecurablePrincipal> {
return Predicates.equal<AclKey, SecurablePrincipal>(PrincipalMapstore.PRINCIPAL_TYPE_INDEX, principalType)
}
private fun hasSecurablePrincipal(principalAclKey: AclKey): Predicate<AclKey, AclKeySet> {
return Predicates.equal("this.index[any]", principalAclKey.index)
}
private fun hasAnySecurablePrincipal(aclKeys: Set<AclKey>): Predicate<AclKey, AclKeySet> {
return Predicates.`in`("this.index[any]", *aclKeys.map { it.index }.toTypedArray())
}
}
override fun createSecurablePrincipalIfNotExists(owner: Principal, principal: SecurablePrincipal): Boolean {
if (reservations.isReserved(principal.name)) {
logger.warn("Securable Principal {} already exists", principal)
return false
}
createSecurablePrincipal(owner, principal)
return true
}
override fun createSecurablePrincipal(owner: Principal, principal: SecurablePrincipal) {
val aclKey = principal.aclKey
try {
// Reserve securable object id
reservations.reserveIdAndValidateType(principal, { principal.name })
// Initialize entries in principals and principalTrees mapstores
principals[aclKey] = principal
principalTrees[aclKey] = AclKeySet()
// Initialize permissions
authorizations.setSecurableObjectType(aclKey, principal.category)
authorizations.addPermission(aclKey, owner, EnumSet.allOf(Permission::class.java))
// Post to EventBus if principal is a USER or ROLE
when (principal.principalType) {
PrincipalType.USER -> eventBus.post(UserCreatedEvent(principal))
PrincipalType.ROLE -> eventBus.post(RoleCreatedEvent(principal as Role))
else -> Unit
}
} catch (e: Exception) {
logger.error("Unable to create principal {}", principal, e)
Util.deleteSafely(principals, aclKey)
Util.deleteSafely(principalTrees, aclKey)
authorizations.deletePermissions(aclKey)
reservations.release(principal.id)
throw IllegalStateException("Unable to create principal: $principal")
}
}
override fun updateTitle(aclKey: AclKey, title: String) {
principals.executeOnKey(aclKey, PrincipalTitleUpdater(title))
}
override fun updateDescription(aclKey: AclKey, description: String) {
principals.executeOnKey(aclKey, PrincipalDescriptionUpdater(description))
}
override fun getSecurablePrincipal(aclKey: AclKey): SecurablePrincipal? {
return principals[aclKey]
}
override fun lookup(p: Principal): AclKey {
return getFirstSecurablePrincipal(findPrincipal(p)).aclKey
}
override fun lookup(p: MutableSet<Principal>): MutableMap<Principal, AclKey> {
return principals.entrySet(findPrincipals(p)).associate { it.value.principal to it.key }.toMutableMap()
}
override fun lookupRole(principal: Principal): Role {
require(principal.type == PrincipalType.ROLE) { "The provided principal is not a role" }
return getFirstSecurablePrincipal(findPrincipal(principal)) as Role
}
override fun getPrincipal(principalId: String): SecurablePrincipal {
val id = Preconditions.checkNotNull(reservations.getId(principalId),
"AclKey not found for Principal %s", principalId
)
return Util.getSafely(principals, AclKey(id))
}
override fun getAllRolesInOrganization(organizationId: UUID): Collection<SecurablePrincipal> {
val rolesInOrganization = Predicates.and<AclKey, SecurablePrincipal>(
hasPrincipalType(PrincipalType.ROLE),
Predicates.equal<AclKey, SecurablePrincipal>(PrincipalMapstore.ACL_KEY_ROOT_INDEX, organizationId)
)
return principals.values(rolesInOrganization)
}
override fun deletePrincipal(aclKey: AclKey) {
ensurePrincipalsExist(setOf(aclKey))
authorizations.deletePrincipalPermissions(principals[aclKey]!!.principal)
authorizations.deletePermissions(aclKey)
principalTrees.executeOnEntries(NestedPrincipalRemover(setOf(aclKey)), hasSecurablePrincipal(aclKey))
reservations.release(aclKey[aclKey.getSize() - 1])
Util.deleteSafely(principalTrees, aclKey)
Util.deleteSafely(principals, aclKey)
}
override fun deleteAllRolesInOrganization(organizationId: UUID) {
getAllRolesInOrganization(organizationId).forEach { deletePrincipal(it.aclKey) }
}
override fun addPrincipalToPrincipal(source: AclKey, target: AclKey) {
ensurePrincipalsExist(setOf(source, target))
principalTrees.executeOnKey(target, NestedPrincipalMerger(ImmutableSet.of(source)))
}
override fun removePrincipalFromPrincipal(source: AclKey, target: AclKey) {
removePrincipalsFromPrincipals(setOf(source), setOf(target))
}
override fun removePrincipalsFromPrincipals(source: Set<AclKey>, target: Set<AclKey>) {
ensurePrincipalsExist(target + source)
principalTrees.executeOnKeys(target, NestedPrincipalRemover(source))
}
override fun getAllPrincipalsWithPrincipal(aclKey: AclKey): Collection<SecurablePrincipal> {
//We start from the bottom layer and use predicates to sweep up the tree and enumerate all roles with this role.
var parentLayer = principalTrees.keySet(hasSecurablePrincipal(aclKey))
val principalsWithPrincipal = parentLayer.toMutableSet()
while (parentLayer.isNotEmpty()) {
parentLayer = principalTrees.keySet(hasAnySecurablePrincipal(parentLayer))
principalsWithPrincipal.addAll(parentLayer)
}
return principals.getAll(principalsWithPrincipal).values
}
override fun getSecurablePrincipals(p: Predicate<AclKey, SecurablePrincipal>): MutableCollection<SecurablePrincipal> {
return principals.values(p)
}
override fun getParentPrincipalsOfPrincipal(aclKey: AclKey): Collection<SecurablePrincipal> {
val parentLayer = principalTrees.keySet(hasSecurablePrincipal(aclKey))
return principals.getAll(parentLayer).values
}
override fun principalHasChildPrincipal(parent: AclKey, child: AclKey): Boolean {
return principalTrees[parent]?.contains(child) ?: false
}
override fun getAllUsersWithPrincipal(aclKey: AclKey): Collection<Principal> {
return getAllPrincipalsWithPrincipal(aclKey)
.filter { it.principalType == PrincipalType.USER }
.map { it.principal }
.toList()
}
override fun getAllUserProfilesWithPrincipal(principal: AclKey): Collection<User> {
return users.getAll(getAllUsersWithPrincipal(principal).map { it.id }.toSet()).values
}
override fun getSecurablePrincipals(simplePrincipals: Collection<Principal>): Collection<SecurablePrincipal> {
return principals.values(findPrincipals(simplePrincipals))
}
override fun principalExists(p: Principal): Boolean {
return principals.keySet(Predicates.equal(PrincipalMapstore.PRINCIPAL_INDEX, p)).isNotEmpty()
}
override fun getUser(userId: String): User {
return users.getValue(userId)
}
override fun getRole(organizationId: UUID, roleId: UUID): Role {
val aclKey = AclKey(organizationId, roleId)
return Util.getSafely(principals, aclKey) as Role
}
override fun getAllPrincipals(sp: SecurablePrincipal): Collection<SecurablePrincipal> {
val roles = principalTrees[sp.aclKey] ?: return listOf()
var nextLayer: Set<AclKey> = roles
while (nextLayer.isNotEmpty()) {
nextLayer = principalTrees.getAll(nextLayer)
.values
.flatten()
.filter { !roles.contains(it) }
.toSet()
roles.addAll(nextLayer)
}
return principals.getAll(roles).values
}
override fun bulkGetUnderlyingPrincipals(sps: Set<SecurablePrincipal>): Map<SecurablePrincipal, Set<Principal>> {
val aclKeyPrincipals = mutableMapOf<AclKey,AclKeySet>()
// Bulk load all relevant principal trees from hazelcast
var nextLayer = sps.mapTo(mutableSetOf()) { it.aclKey }
while (nextLayer.isNotEmpty()) {
//Don't load what's already been loaded.
val nextLayerMap = principalTrees.getAll(nextLayer - aclKeyPrincipals.keys)
nextLayer = nextLayerMap.values.flatMapTo(mutableSetOf()) { it.value }
aclKeyPrincipals.putAll(nextLayerMap)
}
// Map all loaded principals to SecurablePrincipals
val aclKeysToPrincipals = principals.getAll(aclKeyPrincipals.keys + aclKeyPrincipals.values.flatten())
// Map each SecurablePrincipal to all its aclKey children from the in-memory map, and from there a SortedPrincipalSet
return sps.associate { sp ->
val childAclKeys = mutableSetOf<AclKey>(sp.aclKey) //Need to include self.
aclKeyPrincipals.getOrDefault(sp.aclKey, AclKeySet()).forEach { childAclKeys.add(it) }
var nextAclKeyLayer : Set<AclKey> = childAclKeys
while (nextAclKeyLayer.isNotEmpty()) {
nextAclKeyLayer = (nextAclKeyLayer.flatMapTo(mutableSetOf<AclKey>()) {
aclKeyPrincipals[it] ?: setOf()
}) - childAclKeys
childAclKeys += nextAclKeyLayer
}
val principals = childAclKeys.mapNotNullTo( Sets.newLinkedHashSetWithExpectedSize(childAclKeys.size) ) { aclKey ->
aclKeysToPrincipals[aclKey]?.principal
}
if (childAclKeys.size != principals.size) {
logger.warn("Unable to retrieve principals for acl keys: ${childAclKeys - aclKeysToPrincipals.keys}")
}
sp to principals
}
}
override fun getAllUnderlyingPrincipals(sp: SecurablePrincipal): Collection<Principal> {
val roles = principalTrees[sp.aclKey] ?: return listOf()
var nextLayer: Set<AclKey> = roles
while (nextLayer.isNotEmpty()) {
nextLayer = principalTrees.getAll(nextLayer)
.values
.flatten()
.toSet()
roles.addAll(nextLayer)
}
return principals.executeOnKeys(roles, GetPrincipalFromSecurablePrincipalsEntryProcessor()).values
}
override fun getAuthorizedPrincipalsOnSecurableObject(key: AclKey, permissions: EnumSet<Permission>): Set<Principal> {
return authorizations.getAuthorizedPrincipalsOnSecurableObject(key, permissions)
}
override fun ensurePrincipalsExist(aclKeys: Set<AclKey>) {
val principalsMap = principals.executeOnKeys(aclKeys, PrincipalExistsEntryProcessor())
val nonexistentAclKeys = principalsMap.filterValues { !(it as Boolean) }.keys
Preconditions.checkState(
nonexistentAclKeys.isEmpty(),
"All principals must exist, but principals with aclKeys [$nonexistentAclKeys] do not exist."
)
}
private fun getFirstSecurablePrincipal(p: Predicate<AclKey, SecurablePrincipal>): SecurablePrincipal {
return principals.values(p).first()
}
override fun getAuthorizationManager(): AuthorizationManager {
return authorizations
}
override fun getSecurablePrincipalById(id: UUID): SecurablePrincipal {
return getFirstSecurablePrincipal(Predicates.equal(PrincipalMapstore.PRINCIPAL_ID_INDEX, id))
}
override fun getCurrentUserId(): UUID {
return getPrincipal(Principals.getCurrentUser().id).id
}
override fun getAllRoles(): Set<Role> {
return principals.values(hasPrincipalType(PrincipalType.ROLE)).map { it as Role }.toSet()
}
override fun getAllUsers(): Set<SecurablePrincipal> {
return principals.values(hasPrincipalType(PrincipalType.USER)).toSet()
}
}
|
gpl-3.0
|
56702abf52fae6805aef51dfff3743f3
| 42.084507 | 126 | 0.706552 | 4.771919 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.