repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/promo/SubscriptionBuyGemsPromoView.kt | 2 | 1043 | package com.habitrpg.android.habitica.ui.views.promo
import android.content.Context
import android.util.AttributeSet
import android.widget.Button
import android.widget.RelativeLayout
import androidx.core.content.ContextCompat
import androidx.core.os.bundleOf
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.helpers.MainNavigationController
class SubscriptionBuyGemsPromoView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : RelativeLayout(context, attrs, defStyleAttr) {
init {
inflate(R.layout.promo_subscription_buy_gems, true)
setBackgroundColor(ContextCompat.getColor(context, R.color.window_background))
clipToPadding = false
clipChildren = false
clipToOutline = false
findViewById<Button>(R.id.button).setOnClickListener { MainNavigationController.navigate(R.id.gemPurchaseActivity, bundleOf(Pair("openSubscription", true))) }
}
}
| gpl-3.0 | 5e7a024d36987ae3aa942b6bf69eb50d | 37.62963 | 166 | 0.779482 | 4.515152 | false | false | false | false |
HabitRPG/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/social/party/PartyFragment.kt | 1 | 8988 | package com.habitrpg.android.habitica.ui.fragments.social.party
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.databinding.FragmentViewpagerBinding
import com.habitrpg.android.habitica.models.social.Group
import com.habitrpg.android.habitica.ui.activities.GroupFormActivity
import com.habitrpg.android.habitica.ui.activities.GroupInviteActivity
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.fragments.social.ChatFragment
import com.habitrpg.android.habitica.ui.viewmodels.GroupViewType
import com.habitrpg.android.habitica.ui.viewmodels.PartyViewModel
class PartyFragment : BaseMainFragment<FragmentViewpagerBinding>() {
private var detailFragment: PartyDetailFragment? = null
private var chatFragment: ChatFragment? = null
private var viewPagerAdapter: FragmentStateAdapter? = null
internal val viewModel: PartyViewModel by viewModels()
override var binding: FragmentViewpagerBinding? = null
override fun createBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentViewpagerBinding {
return FragmentViewpagerBinding.inflate(inflater, container, false)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
this.usesTabLayout = true
this.hidesToolbar = true
return super.onCreateView(inflater, container, savedInstanceState)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel.groupViewType = GroupViewType.PARTY
viewModel.getGroupData().observe(
viewLifecycleOwner,
{
updateGroupUI(it)
}
)
binding?.viewPager?.currentItem = 0
setViewPagerAdapter()
arguments?.let {
val args = PartyFragmentArgs.fromBundle(it)
binding?.viewPager?.currentItem = args.tabToOpen
if (args.partyID?.isNotBlank() == true) {
viewModel.setGroupID(args.partyID ?: "")
}
}
viewModel.loadPartyID()
this.tutorialStepIdentifier = "party"
this.tutorialTexts = listOf(getString(R.string.tutorial_party))
viewModel.retrieveGroup {}
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun updateGroupUI(group: Group?) {
viewPagerAdapter?.notifyDataSetChanged()
if (group == null) {
tabLayout?.visibility = View.GONE
return
} else {
tabLayout?.visibility = View.VISIBLE
}
this.activity?.invalidateOptionsMenu()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
val group = viewModel.getGroupData().value
if (viewModel.isLeader) {
inflater.inflate(R.menu.menu_party_admin, menu)
menu.findItem(R.id.menu_guild_leave).isVisible = group?.memberCount != 1
} else {
inflater.inflate(R.menu.menu_party, menu)
}
}
@Suppress("ReturnCount")
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_invite_item -> {
val intent = Intent(activity, GroupInviteActivity::class.java)
intent.putExtra("groupType", "party")
sendInvitesResult.launch(intent)
return true
}
R.id.menu_guild_edit -> {
this.displayEditForm()
return true
}
R.id.menu_guild_leave -> {
detailFragment?.leaveParty()
return true
}
R.id.menu_guild_refresh -> {
viewModel.retrieveGroup { }
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun displayEditForm() {
val bundle = Bundle()
val group = viewModel.getGroupData().value
bundle.putString("groupID", group?.id)
bundle.putString("name", group?.name)
bundle.putString("groupType", group?.type)
bundle.putString("description", group?.description)
bundle.putString("leader", group?.leaderID)
bundle.putBoolean("leaderCreateChallenge", group?.leaderOnlyChallenges ?: false)
val intent = Intent(activity, GroupFormActivity::class.java)
intent.putExtras(bundle)
intent.flags = Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
groupFormResult.launch(intent)
}
private val groupFormResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
viewModel.updateOrCreateGroup(it.data?.extras)
}
}
private val sendInvitesResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == Activity.RESULT_OK) {
val inviteData = HashMap<String, Any>()
inviteData["inviter"] = viewModel.user.value?.profile?.name ?: ""
val emails = it.data?.getStringArrayExtra(GroupInviteActivity.EMAILS_KEY)
if (emails != null && emails.isNotEmpty()) {
val invites = ArrayList<HashMap<String, String>>()
emails.forEach { email ->
val invite = HashMap<String, String>()
invite["name"] = ""
invite["email"] = email
invites.add(invite)
}
inviteData["emails"] = invites
}
val userIDs = it.data?.getStringArrayExtra(GroupInviteActivity.USER_IDS_KEY)
if (userIDs != null && userIDs.isNotEmpty()) {
val invites = ArrayList<String>()
userIDs.forEach { invites.add(it) }
inviteData["usernames"] = invites
}
viewModel.inviteToGroup(inviteData)
}
}
private fun setViewPagerAdapter() {
val fragmentManager = childFragmentManager
viewPagerAdapter = object : FragmentStateAdapter(fragmentManager, lifecycle) {
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> {
detailFragment = PartyDetailFragment()
detailFragment?.viewModel = viewModel
detailFragment
}
1 -> {
chatFragment = ChatFragment()
chatFragment?.viewModel = viewModel
chatFragment
}
else -> Fragment()
} ?: Fragment()
}
override fun getItemCount(): Int {
return 2
}
}
binding?.viewPager?.adapter = viewPagerAdapter
binding?.viewPager?.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
if (position == 1) {
chatFragment?.setNavigatedToFragment()
}
}
override fun onPageSelected(position: Int) {
if (position == 1) {
chatFragment?.setNavigatedToFragment()
}
}
})
tabLayout?.let {
binding?.viewPager?.let { it1 ->
TabLayoutMediator(it, it1) { tab, position ->
tab.text = when (position) {
0 -> context?.getString(R.string.party)
1 -> context?.getString(R.string.chat)
else -> ""
}
}.attach()
}
}
}
}
| gpl-3.0 | 34b0a7943d2f16525376debdca65d1a8 | 35.140496 | 113 | 0.589564 | 5.450576 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/arrays/collectionAssignGetMultiIndex.kt | 2 | 326 | operator fun ArrayList<String>.get(index1: Int, index2: Int) = this[index1 + index2]
operator fun ArrayList<String>.set(index1: Int, index2: Int, elem: String) {
this[index1 + index2] = elem
}
fun box(): String {
val s = ArrayList<String>(1)
s.add("")
s[1, -1] = "O"
s[2, -2] += "K"
return s[2, -2]
}
| apache-2.0 | 9f2a8c3f387c60e385eaaa9b67079322 | 26.166667 | 84 | 0.592025 | 2.672131 | false | false | false | false |
Cognifide/APM | app/aem/core/src/main/kotlin/com/cognifide/apm/core/endpoints/ScriptMoveForm.kt | 1 | 1347 | /*
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 Wunderman Thompson Technology
* %%
* 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.
* =========================LICENSE_END==================================
*/
package com.cognifide.apm.core.endpoints
import com.cognifide.apm.core.endpoints.params.RequestParameter
import org.apache.sling.api.SlingHttpServletRequest
import org.apache.sling.models.annotations.Model
import javax.inject.Inject
@Model(adaptables = [SlingHttpServletRequest::class])
class ScriptMoveForm @Inject constructor(
@param:RequestParameter("path") val path: String,
@param:RequestParameter("dest") val dest: String,
@param:RequestParameter("rename") val rename: String
) | apache-2.0 | a9a790efc609f4f1da67704e8dbfee1d | 38.878788 | 75 | 0.668894 | 4.550676 | false | false | false | false |
saletrak/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/notificationslist/notification/NotificationsListActivity.kt | 1 | 2779 | package io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.notification
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import io.github.feelfreelinux.wykopmobilny.R
import io.github.feelfreelinux.wykopmobilny.WykopApp
import io.github.feelfreelinux.wykopmobilny.models.dataclass.Notification
import io.github.feelfreelinux.wykopmobilny.models.fragments.DataFragment
import io.github.feelfreelinux.wykopmobilny.models.fragments.PagedDataModel
import io.github.feelfreelinux.wykopmobilny.models.fragments.getDataFragmentInstance
import io.github.feelfreelinux.wykopmobilny.models.fragments.removeDataFragment
import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.BaseNotificationsListActivity
import io.github.feelfreelinux.wykopmobilny.utils.isVisible
import kotlinx.android.synthetic.main.activity_notifications_list.*
import javax.inject.Inject
fun Context.startNotificationsListActivity() {
val intent = Intent(this, NotificationsListActivity::class.java)
startActivity(intent)
}
class NotificationsListActivity : BaseNotificationsListActivity() {
private lateinit var entryFragmentData : DataFragment<PagedDataModel<List<Notification>>>
companion object {
val DATA_FRAGMENT_TAG = "NOTIFICATIONS_LIST_ACTIVITY"
}
override fun loadMore() {
presenter.loadData(false)
}
override fun onRefresh() {
presenter.loadData(true)
}
@Inject lateinit var presenter : NotificationsListPresenter
override fun onCreate(savedInstanceState: Bundle?) {
WykopApp.uiInjector.inject(this)
presenter.subscribe(this)
super.onCreate(savedInstanceState)
supportActionBar?.setTitle(R.string.notifications_title)
entryFragmentData = supportFragmentManager.getDataFragmentInstance(DATA_FRAGMENT_TAG)
if (entryFragmentData.data != null && entryFragmentData.data!!.model.isNotEmpty()) {
loadingView.isVisible = false
presenter.page = entryFragmentData.data!!.page
notificationAdapter.addData(entryFragmentData.data!!.model, true)
} else {
loadingView.isVisible = true
onRefresh()
}
}
override fun markAsRead() {
presenter.readNotifications()
}
override fun onDestroy() {
super.onDestroy()
presenter.unsubscribe()
}
override fun onPause() {
super.onPause()
if (isFinishing) supportFragmentManager.removeDataFragment(entryFragmentData)
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
entryFragmentData.data = PagedDataModel(presenter.page, notificationAdapter.data)
}
} | mit | 275205e78cb65a0dbcc01bf1f569c507 | 36.066667 | 102 | 0.754588 | 5.20412 | false | false | false | false |
Heiner1/AndroidAPS | rileylink/src/main/java/info/nightscout/androidaps/plugins/pump/common/hw/rileylink/service/RileyLinkServiceData.kt | 1 | 3109 | package info.nightscout.androidaps.plugins.pump.common.hw.rileylink.service
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.pump.common.events.EventRileyLinkDeviceStatusChange
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkFirmwareVersion
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.defs.RileyLinkTargetFrequency
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.data.RLHistoryItem
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkError
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkServiceState
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkTargetDevice
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
/**
* Created by andy on 16/05/2018.
*/
@Singleton
class RileyLinkServiceData @Inject constructor() {
@Inject lateinit var aapsLogger: AAPSLogger
@Inject lateinit var rileyLinkUtil: RileyLinkUtil
@Inject lateinit var rxBus: RxBus
var tuneUpDone = false
var rileyLinkError: RileyLinkError? = null
var rileyLinkServiceState: RileyLinkServiceState = RileyLinkServiceState.NotStarted
private set
var lastServiceStateChange = 0L
private set
// here we have "compatibility level" version
@JvmField var firmwareVersion: RileyLinkFirmwareVersion? = null
@JvmField var rileyLinkTargetFrequency: RileyLinkTargetFrequency? = null
@JvmField var rileyLinkAddress: String? = null
@JvmField var rileyLinkName: String? = null
@JvmField var batteryLevel: Int? = null
var showBatteryLevel = false
var lastTuneUpTime = 0L
var lastGoodFrequency: Double? = null
// bt version
var versionBLE113: String? = null
// radio version
@JvmField var versionCC110: String? = null
// orangeLink
var isOrange = false
var versionOrangeFirmware: String? = null
var versionOrangeHardware: String? = null
@JvmField var targetDevice: RileyLinkTargetDevice? = null
// Medtronic Pump
var pumpID: String? = null
var pumpIDBytes: ByteArray = byteArrayOf(0, 0, 0)
fun setPumpID(pumpId: String?, pumpIdBytes: ByteArray) {
pumpID = pumpId
pumpIDBytes = pumpIdBytes
}
@Synchronized
fun setServiceState(newState: RileyLinkServiceState, errorCode: RileyLinkError? = null) {
rileyLinkServiceState = newState
lastServiceStateChange = System.currentTimeMillis()
rileyLinkError = errorCode
aapsLogger.info(LTag.PUMP, String.format(Locale.ENGLISH, "RileyLink State Changed: $newState - Error State: ${errorCode?.name}"))
rileyLinkUtil.rileyLinkHistory.add(RLHistoryItem(rileyLinkServiceState, errorCode, targetDevice))
rxBus.send(EventRileyLinkDeviceStatusChange(targetDevice!!, newState, errorCode))
}
} | agpl-3.0 | 07e89d1cb00bf75047482733e76f3082 | 41.027027 | 137 | 0.770666 | 4.675188 | false | false | false | false |
CherryPerry/Amiami-kotlin-backend | src/main/kotlin/com/cherryperry/amiami/model/currency/CurrencyRepositoryImpl.kt | 1 | 3234 | package com.cherryperry.amiami.model.currency
import com.cherryperry.amiami.model.lastmodified.LastModifiedValue
import com.cherryperry.amiami.util.readProperty
import org.apache.logging.log4j.LogManager
import org.springframework.stereotype.Repository
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicReference
import java.util.concurrent.locks.ReentrantLock
@Repository
class CurrencyRepositoryImpl : CurrencyRepository {
companion object {
private const val CURRENCY_JPY = "JPY"
private const val CURRENCY_EUR = "EUR"
private const val PROPERTIES_FILE = "secure.properties"
private const val PROPERTIES_KEY = "fixer.key"
private val INTERNAL_ERROR_RESPONSE =
CurrencyResponse(success = false, error = CurrencyErrorResponse(0, "Internal error"))
}
private val log = LogManager.getLogger(CurrencyRepositoryImpl::class.java)
private val accessKey: String = readProperty(PROPERTIES_FILE) {
if (!containsKey(PROPERTIES_KEY)) {
throw IllegalStateException("No $PROPERTIES_KEY in $PROPERTIES_FILE found!")
}
getProperty(PROPERTIES_KEY)
}
private val cachedResult = AtomicReference<CurrencyResponse?>()
private val lock = ReentrantLock()
private val lastModifiedValue = LastModifiedValue()
private val currencyRestClient = CurrencyRestClient()
override val lastModified: Long
get() = lastModifiedValue.value
@Suppress("ReturnCount")
override fun get(): CurrencyResponse {
log.trace("get")
try {
lock.lock()
val cached = cachedResult.get()
log.info("cached $cached")
if (cached != null && cached.isUpToDate(TimeUnit.DAYS, 1)) {
log.info("cache is valid")
return cached
}
log.info("cache is invalid")
val result = currencyRestClient.currency(accessKey)
if (result.success) {
val jpyRate = result.rates?.get(CURRENCY_JPY)
if (result.base != CURRENCY_EUR || jpyRate == null) {
log.error("invalid response $result")
return INTERNAL_ERROR_RESPONSE
}
log.info("valid response $result")
val newRates = result.rates.mapValues { it.value / jpyRate }
val newResult = CurrencyResponse(
success = true,
timestamp = result.timestamp,
date = result.date,
base = CURRENCY_JPY,
rates = newRates,
)
log.info("calculated response $newResult")
cachedResult.set(newResult)
lastModifiedValue.update()
return newResult
} else {
log.info("currency api returns error $result")
return cached ?: result
}
} catch (expected: Exception) {
log.error("currency api throws exception", expected)
val cached = cachedResult.get()
return cached ?: INTERNAL_ERROR_RESPONSE
} finally {
lock.unlock()
}
}
}
| apache-2.0 | 443a37be01e4ad1bec1b6c7b44e82cc7 | 38.439024 | 97 | 0.605133 | 5.092913 | false | false | false | false |
elsiff/MoreFish | src/main/kotlin/me/elsiff/morefish/command/MainCommand.kt | 1 | 6472 | package me.elsiff.morefish.command
import co.aikar.commands.BaseCommand
import co.aikar.commands.annotation.CommandAlias
import co.aikar.commands.annotation.CommandPermission
import co.aikar.commands.annotation.Default
import co.aikar.commands.annotation.Subcommand
import me.elsiff.morefish.MoreFish
import me.elsiff.morefish.configuration.Config
import me.elsiff.morefish.configuration.Lang
import me.elsiff.morefish.fishing.competition.FishingCompetition
import me.elsiff.morefish.fishing.competition.FishingCompetitionHost
import me.elsiff.morefish.shop.FishShop
import org.bukkit.ChatColor
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import org.bukkit.plugin.PluginDescriptionFile
/**
* Created by elsiff on 2018-12-26.
*/
@CommandAlias("morefish|mf|fish")
class MainCommand(
private val moreFish: MoreFish,
private val competitionHost: FishingCompetitionHost,
private val fishShop: FishShop
) : BaseCommand() {
private val pluginInfo: PluginDescriptionFile = moreFish.description
private val competition: FishingCompetition = competitionHost.competition
@Default
@Subcommand("help")
@CommandPermission("morefish.help")
fun help(sender: CommandSender) {
val pluginName = pluginInfo.name
val prefix = "${ChatColor.AQUA}[$pluginName]${ChatColor.RESET} "
sender.sendMessage(
prefix +
"${ChatColor.DARK_AQUA}> ===== " +
"${ChatColor.AQUA}${ChatColor.BOLD}$pluginName ${ChatColor.AQUA}v${pluginInfo.version}" +
"${ChatColor.DARK_AQUA} ===== <"
)
val label = execCommandLabel
sender.sendMessage("$prefix/$label help")
sender.sendMessage("$prefix/$label begin [runningTime(sec)]")
sender.sendMessage("$prefix/$label suspend")
sender.sendMessage("$prefix/$label end")
sender.sendMessage("$prefix/$label rewards")
sender.sendMessage("$prefix/$label clear")
sender.sendMessage("$prefix/$label reload")
sender.sendMessage("$prefix/$label top")
sender.sendMessage("$prefix/$label shop [player]")
}
@Subcommand("begin|start")
@CommandPermission("morefish.admin")
fun begin(sender: CommandSender, args: Array<String>) {
if (!competition.isEnabled()) {
if (args.size == 1) {
try {
val runningTime = args[0].toLong()
if (runningTime < 0) {
sender.sendMessage(Lang.text("not-positive"))
} else {
competitionHost.openCompetitionFor(runningTime * 20)
if (!Config.standard.boolean("messages.broadcast-start")) {
val msg = Lang.format("contest-start-timer")
.replace("%time%" to Lang.time(runningTime)).output()
sender.sendMessage(msg)
}
}
} catch (e: NumberFormatException) {
val msg = Lang.format("not-number").replace("%s" to args[0]).output()
sender.sendMessage(msg)
}
} else {
competitionHost.openCompetition()
if (!Config.standard.boolean("messages.broadcast-start")) {
sender.sendMessage(Lang.text("contest-start"))
}
}
} else {
sender.sendMessage(Lang.text("already-ongoing"))
}
}
@Subcommand("suspend")
@CommandPermission("morefish.admin")
fun suspend(sender: CommandSender) {
if (!competition.isDisabled()) {
competitionHost.closeCompetition(suspend = true)
if (!Config.standard.boolean("messages.broadcast-stop")) {
sender.sendMessage(Lang.text("contest-stop"))
}
} else {
sender.sendMessage(Lang.text("already-stopped"))
}
}
@Subcommand("end")
@CommandPermission("morefish.admin")
fun end(sender: CommandSender) {
if (!competition.isDisabled()) {
competitionHost.closeCompetition()
if (!Config.standard.boolean("messages.broadcast-stop")) {
sender.sendMessage(Lang.text("contest-stop"))
}
} else {
sender.sendMessage(Lang.text("already-stopped"))
}
}
@Subcommand("top|ranking")
@CommandPermission("morefish.top")
fun top(sender: CommandSender) {
competitionHost.informAboutRanking(sender)
}
@Subcommand("clear")
@CommandPermission("morefish.admin")
fun clear(sender: CommandSender) {
competition.clearRecords()
sender.sendMessage(Lang.text("clear-records"))
}
@Subcommand("reload")
@CommandPermission("morefish.admin")
fun reload(sender: CommandSender) {
try {
moreFish.applyConfig()
sender.sendMessage(Lang.text("reload-config"))
} catch (e: Exception) {
e.printStackTrace()
sender.sendMessage(Lang.text("failed-to-reload"))
}
}
@Subcommand("shop")
fun shop(sender: CommandSender, args: Array<String>) {
val guiUser: Player = if (args.size == 1) {
if (!sender.hasPermission("morefish.admin")) {
sender.sendMessage(Lang.text("no-permission"))
return
}
val target = sender.server.getPlayerExact(args[0]) ?: null
if (target == null) {
val msg = Lang.format("player-not-found").replace("%s" to args[0]).output()
sender.sendMessage(msg)
return
} else {
target
}
} else {
if (!sender.hasPermission("morefish.shop")) {
sender.sendMessage(Lang.text("no-permission"))
return
}
if (sender !is Player) {
sender.sendMessage(Lang.text("in-game-command"))
return
}
sender
}
if (!fishShop.enabled) {
sender.sendMessage(Lang.text("shop-disabled"))
} else {
fishShop.openGuiTo(guiUser)
if (guiUser != sender) {
val msg = Lang.format("forced-player-to-shop").replace("%s" to guiUser.name).output()
sender.sendMessage(msg)
}
}
}
} | mit | ecede4d374920a553ee68a5199478bf2 | 34.565934 | 109 | 0.581273 | 4.751836 | false | false | false | false |
kpavlov/jreactive-8583 | src/main/kotlin/com/github/kpavlov/jreactive8583/ConnectorConfiguration.kt | 1 | 9289 | package com.github.kpavlov.jreactive8583
/**
* Default read/write idle timeout in seconds (ping interval) = 30 sec.
*
* @see .getIdleTimeout
*/
private const val DEFAULT_IDLE_TIMEOUT_SECONDS = 30
/**
* Default [.maxFrameLength] (max message length) = 8192
*
* @see .getMaxFrameLength
*/
private const val DEFAULT_MAX_FRAME_LENGTH = 8192
/**
* Default [.frameLengthFieldLength] (length of TCP Frame length) = 2
*
* @see .getFrameLengthFieldLength
*/
private const val DEFAULT_FRAME_LENGTH_FIELD_LENGTH = 2
/**
* Default [.frameLengthFieldAdjust] (compensation value to add to the value of the length field) = 0
*
* @see .getFrameLengthFieldAdjust
*/
private const val DEFAULT_FRAME_LENGTH_FIELD_ADJUST = 0
/**
* Default [.frameLengthFieldOffset] (the offset of the length field) = 0
*
* @see .getFrameLengthFieldOffset
*/
private const val DEFAULT_FRAME_LENGTH_FIELD_OFFSET = 0
public abstract class ConnectorConfiguration protected constructor(b: Builder<*>) {
public val addEchoMessageListener: Boolean
/**
* The maximum length of the frame.
*/
public val maxFrameLength: Int
/**
* Set channel read/write idle timeout in seconds.
*
* If no message was received/sent during specified time interval then `Echo` message will be sent.
*
* @return timeout in seconds
*/
public val idleTimeout: Int
/**
* Returns number of threads in worker [EventLoopGroup].
*
*
* Default value is `Runtime.getRuntime().availableProcessors() * 16`.
*
* @return Number of Netty worker threads
*/
public val workerThreadsCount: Int
public val replyOnError: Boolean
public val addLoggingHandler: Boolean
public val logSensitiveData: Boolean
/**
* Returns field numbers to be treated as sensitive data.
* Use `null` to use default ones
*
* Array of ISO8583 sensitive field numbers to be masked, or `null` to use default fields.
* @see IsoMessageLoggingHandler
*/
public val sensitiveDataFields: IntArray
public val logFieldDescription: Boolean
/**
* Returns length of TCP frame length field.
*
*
* Default value is `2`.
*
* @return Length of TCP frame length field.
* @see LengthFieldBasedFrameDecoder
*/
public val frameLengthFieldLength: Int
/**
* Returns the offset of the length field.
*
* Default value is `0`.
* @see LengthFieldBasedFrameDecoder
*
* @return The offset of the length field.
*/
public val frameLengthFieldOffset: Int
/**
* Returns the compensation value to add to the value of the length field.
*
*
* Default value is `0`.
*
* @return The compensation value to add to the value of the length field
* @see LengthFieldBasedFrameDecoder
*/
public val frameLengthFieldAdjust: Int
/**
* If <code>true</code> then the length header is to be encoded as a String, as opposed to the default binary
*/
public val encodeFrameLengthAsString: Boolean
/**
* Allows to add default echo message listener to [AbstractIso8583Connector].
*
* @return true if [EchoMessageListener] should be added to [CompositeIsoMessageHandler]
*/
public fun shouldAddEchoMessageListener(): Boolean {
return addEchoMessageListener
}
/**
* Returns true is [IsoMessageLoggingHandler]
*
* Allows to disable adding default logging handler to [ChannelPipeline].
*
* @return true if [IsoMessageLoggingHandler] should be added.
*/
public fun addLoggingHandler(): Boolean {
return addLoggingHandler
}
/**
* Whether to reply with administrative message in case of message syntax errors. Default value is `false.`
*
* @return true if reply message should be sent in case of error parsing the message.
*/
public fun replyOnError(): Boolean {
return replyOnError
}
/**
* Returns `true` if sensitive information like PAN, CVV/CVV2, and Track2 should be printed to log.
*
*
* Default value is `true` (sensitive data is printed).
*
*
* @return `true` if sensitive data should be printed to log
*/
public fun logSensitiveData(): Boolean {
return logSensitiveData
}
public fun logFieldDescription(): Boolean {
return logFieldDescription
}
/**
* Returns <code>true</code> if the length header is to be encoded as a String,
* as opposed to the default binary
*
* Default value is <code>false</code> (frame length header is binary encoded).
*
* Used with @link frameLengthFieldLength, [#frameLengthFieldOffset]
* and [#frameLengthFieldAdjust]
*
* @return <code>true</code> if frame length header is string-encoded
* @return Number of Netty worker threads
*/
public fun encodeFrameLengthAsString(): Boolean = this.encodeFrameLengthAsString
init {
this.addEchoMessageListener = b.addEchoMessageListener
this.addLoggingHandler = b.addLoggingHandler
this.encodeFrameLengthAsString = b.encodeFrameLengthAsString
this.frameLengthFieldAdjust = b.frameLengthFieldAdjust
this.frameLengthFieldLength = b.frameLengthFieldLength
this.frameLengthFieldOffset = b.frameLengthFieldOffset
this.idleTimeout = b.idleTimeout
this.logFieldDescription = b.logFieldDescription
this.logSensitiveData = b.logSensitiveData
this.maxFrameLength = b.maxFrameLength
this.replyOnError = b.replyOnError
this.sensitiveDataFields = b.sensitiveDataFields
this.workerThreadsCount = b.workerThreadsCount
}
@Suppress("UNCHECKED_CAST")
public open class Builder<B : Builder<B>> {
internal var addLoggingHandler = false
internal var addEchoMessageListener = false
internal var logFieldDescription = true
internal var logSensitiveData = true
internal var replyOnError = false
internal var idleTimeout = DEFAULT_IDLE_TIMEOUT_SECONDS
internal var maxFrameLength = DEFAULT_MAX_FRAME_LENGTH
internal var workerThreadsCount = 0 // use netty default
internal var sensitiveDataFields: IntArray = IntArray(0)
internal var frameLengthFieldLength = DEFAULT_FRAME_LENGTH_FIELD_LENGTH
internal var frameLengthFieldOffset = DEFAULT_FRAME_LENGTH_FIELD_OFFSET
internal var frameLengthFieldAdjust = DEFAULT_FRAME_LENGTH_FIELD_ADJUST
internal var encodeFrameLengthAsString = false
/**
* @param shouldAddEchoMessageListener `true` to add echo message handler.
*/
public fun addEchoMessageListener(shouldAddEchoMessageListener: Boolean = true): B = apply {
addEchoMessageListener = shouldAddEchoMessageListener
} as B
/**
* @param length Maximum frame length.
*/
public fun maxFrameLength(length: Int): B = apply {
maxFrameLength = length
} as B
public fun idleTimeout(timeout: Int): B = apply {
idleTimeout = timeout
} as B
public fun replyOnError(doReply: Boolean = true): B = apply {
replyOnError = doReply
} as B
/**
* @param addLoggingHandler `true` if [IsoMessageLoggingHandler] should be added to Netty pipeline.
*/
public fun addLoggingHandler(value: Boolean = true): B = apply {
addLoggingHandler = value
} as B
/**
* Should log sensitive data (unmasked) or not.
*
*
* **Don't use on production!**
*
* @param logSensitiveData `true` to log sensitive data via logger
*/
public fun logSensitiveData(logSensitiveData: Boolean = true): B = apply {
this.logSensitiveData = logSensitiveData
} as B
/**
* @param logFieldDescription `true` to print ISO field descriptions in the log
*/
public fun describeFieldsInLog(shouldDescribe: Boolean = true): B = apply {
logFieldDescription = shouldDescribe
} as B
/**
* @param sensitiveDataFields Array of sensitive fields
*/
public fun sensitiveDataFields(vararg sensitiveDataFields: Int): B = apply {
this.sensitiveDataFields = sensitiveDataFields
} as B
public fun frameLengthFieldLength(frameLengthFieldLength: Int): B = apply {
this.frameLengthFieldLength = frameLengthFieldLength
} as B
public fun frameLengthFieldOffset(frameLengthFieldOffset: Int): B = apply {
this.frameLengthFieldOffset = frameLengthFieldOffset
} as B
public fun frameLengthFieldAdjust(frameLengthFieldAdjust: Int): B = apply {
this.frameLengthFieldAdjust = frameLengthFieldAdjust
} as B
public fun encodeFrameLengthAsString(encodeFrameLengthAsString: Boolean): B = apply {
this.encodeFrameLengthAsString = encodeFrameLengthAsString
} as B
public fun workerThreadsCount(numberOfThreads: Int): B = apply {
workerThreadsCount = numberOfThreads
} as B
}
}
| apache-2.0 | b03ec61d30d62f3f61a00ab41019f2b4 | 31.365854 | 113 | 0.659597 | 5.160556 | false | false | false | false |
ingokegel/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/core/stackFrame/CapturedValuesSearcher.kt | 1 | 4959 | // 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.kotlin.idea.debugger.core.stackFrame
import com.intellij.debugger.impl.descriptors.data.DescriptorData
import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl
import com.sun.jdi.Field
import com.sun.jdi.ObjectReference
import com.sun.jdi.Value
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.idea.debugger.base.util.safeFields
import java.util.*
private sealed class PendingValue {
class Ordinary(val name: String, val field: Field, val container: Container) : PendingValue() {
override fun addTo(existingVariables: ExistingVariables): CapturedValueData? {
if (!existingVariables.add(ExistingVariable.Ordinary(name))) {
return null
}
return CapturedValueData(name, container.value, field)
}
}
class This(val label: String, val value: Value?) : PendingValue() {
override fun addTo(existingVariables: ExistingVariables): DescriptorData<out ValueDescriptorImpl>? {
val thisName = if (existingVariables.hasThisVariables) {
if (!existingVariables.add(ExistingVariable.LabeledThis(label))) {
// Avoid item duplication
return null
}
getThisName(label)
} else {
if (!existingVariables.add(ExistingVariable.LabeledThis(label))) {
return null
}
AsmUtil.THIS
}
return LabeledThisData(label, thisName, value)
}
}
class Container(val value: ObjectReference) : PendingValue() {
fun getChildren(): List<PendingValue> {
return value.referenceType().safeFields()
.filter { it.isApplicable() }
.mapNotNull { createPendingValue(this, it) }
}
private fun Field.isApplicable(): Boolean {
val name = name()
return name.startsWith(AsmUtil.CAPTURED_PREFIX) || name == AsmUtil.CAPTURED_THIS_FIELD
}
override fun addTo(existingVariables: ExistingVariables): DescriptorData<out ValueDescriptorImpl>? {
throw IllegalStateException("Should not be called on a container")
}
}
abstract fun addTo(existingVariables: ExistingVariables): DescriptorData<out ValueDescriptorImpl>?
}
internal fun attachCapturedValues(
containerValue: ObjectReference,
existingVariables: ExistingVariables,
collector: (DescriptorData<out ValueDescriptorImpl>) -> Unit
) {
val values = collectPendingValues(PendingValue.Container(containerValue))
for (value in values) {
val descriptorData = value.addTo(existingVariables) ?: continue
collector(descriptorData)
}
}
private fun collectPendingValues(container: PendingValue.Container): List<PendingValue> {
val queue = ArrayDeque<PendingValue>()
queue.offer(container)
val values = mutableListOf<PendingValue>()
collectValuesBfs(queue, values)
return values
}
private tailrec fun collectValuesBfs(queue: Deque<PendingValue>, consumer: MutableList<PendingValue>) {
val deeperValues = ArrayDeque<PendingValue>()
while (queue.isNotEmpty()) {
val value = queue.removeFirst() ?: break
if (value is PendingValue.Container) {
val children = value.getChildren()
deeperValues.addAll(children)
continue
}
consumer += value
}
if (deeperValues.isNotEmpty()) {
collectValuesBfs(deeperValues, consumer)
}
}
private fun createPendingValue(container: PendingValue.Container, field: Field): PendingValue? {
val name = field.name()
if (name == AsmUtil.CAPTURED_THIS_FIELD) {
/*
* Captured entities.
* In case of captured lambda, we just add values captured to the lambda to the list.
* In case of captured this (outer this, for example), we add the 'this' value.
*/
val value = container.value.getValue(field) as? ObjectReference ?: return null
return when (val label = getThisValueLabel(value)) {
null -> PendingValue.Container(value)
else -> PendingValue.This(label, value)
}
} else if (name.startsWith(AsmUtil.CAPTURED_LABELED_THIS_FIELD)) {
// Extension receivers for a new scheme ($this_<label>)
val value = container.value.getValue(field)
val label = name.drop(AsmUtil.CAPTURED_LABELED_THIS_FIELD.length).takeIf { it.isNotEmpty() } ?: return null
return PendingValue.This(label, value)
}
// Ordinary values (everything but 'this')
assert(name.startsWith(AsmUtil.CAPTURED_PREFIX))
val capturedValueName = name.drop(1).takeIf { it.isNotEmpty() } ?: return null
return PendingValue.Ordinary(capturedValueName, field, container)
} | apache-2.0 | 7a79d64464f615a1b245587364ece13f | 36.862595 | 120 | 0.66465 | 4.795938 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/UnusedDataClassCopyResultInspection.kt | 1 | 1726 | // 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.codeInspection.ProblemsHolder
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.callExpressionVisitor
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelectorOrThis
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class UnusedDataClassCopyResultInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = callExpressionVisitor(fun(call) {
val callee = call.calleeExpression ?: return
if (callee.text != "copy") return
val context = call.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
val descriptor = call.getResolvedCall(context)?.resultingDescriptor ?: return
val receiver = descriptor.dispatchReceiverParameter ?: descriptor.extensionReceiverParameter ?: return
if ((receiver.value as? ImplicitClassReceiver)?.classDescriptor?.isData != true) return
if (call.getQualifiedExpressionForSelectorOrThis().isUsedAsExpression(context)) return
holder.registerProblem(callee, KotlinBundle.message("inspection.unused.result.of.data.class.copy"))
})
}
| apache-2.0 | ab0d2cfd71c3a67489dae2379b2b644b | 60.642857 | 158 | 0.806489 | 4.988439 | false | false | false | false |
PhilippeBoisney/Material | app/src/main/java/io/philippeboisney/material/animation/BottomAppBarAnimatableTransition.kt | 1 | 2251 | package io.philippeboisney.material.animation
import android.animation.*
import android.content.Context
import android.util.AttributeSet
import android.annotation.TargetApi
import android.graphics.drawable.Animatable
import android.os.Build
import android.view.View
import androidx.core.view.forEach
import com.google.android.material.bottomappbar.BottomAppBar
import androidx.vectordrawable.graphics.drawable.AnimatedVectorDrawableCompat
import androidx.core.view.get
import io.philippeboisney.material.R
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class BottomAppBarAnimatableTransition(context: Context, attrs: AttributeSet) : BaseForcedTransition(context, attrs) {
private var onAppear: Boolean = false
init {
val a = context.obtainStyledAttributes(attrs, R.styleable.BottomAppBarAnimatable)
onAppear = a.getBoolean(R.styleable.BottomAppBarAnimatable_onAppear, onAppear)
a.recycle()
}
override fun getAnimator(view: View): Animator
= createAnimation(view)
// ---
private fun createAnimation(view: View): ValueAnimator {
val bottomAppBar = view as BottomAppBar
val context = bottomAppBar.context
if (onAppear) {
bottomAppBar.menu[2].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_search_to_more)
bottomAppBar.menu[1].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_delete_scale_up)
bottomAppBar.menu[0].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_star_scale_up)
} else {
bottomAppBar.menu[2].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_more_to_search)
bottomAppBar.menu[1].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_delete_scale_down)
bottomAppBar.menu[0].icon = AnimatedVectorDrawableCompat.create(context, R.drawable.avd_star_scale_down)
}
val transition = ValueAnimator.ofInt(0, 1)
transition.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
bottomAppBar.menu.forEach { (it.icon as? Animatable)?.start() }
}
})
return transition!!
}
} | apache-2.0 | 0def50e8809633d513768471673de39a | 41.490566 | 118 | 0.730342 | 4.52008 | false | false | false | false |
mdaniel/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/extensions/common/highlighter/CodeFenceCopyButtonBrowserExtension.kt | 4 | 3145 | // 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.intellij.plugins.markdown.extensions.common.highlighter
import com.intellij.icons.AllIcons
import com.intellij.lang.LangBundle
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.ide.CopyPasteManager
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.wm.WindowManager
import org.intellij.plugins.markdown.extensions.MarkdownBrowserPreviewExtension
import org.intellij.plugins.markdown.extensions.MarkdownExtensionsUtil
import org.intellij.plugins.markdown.ui.preview.BrowserPipe
import org.intellij.plugins.markdown.ui.preview.MarkdownHtmlPanel
import org.intellij.plugins.markdown.ui.preview.ResourceProvider
import java.awt.datatransfer.StringSelection
import javax.swing.Icon
internal class CodeFenceCopyButtonBrowserExtension(panel: MarkdownHtmlPanel, browserPipe: BrowserPipe): MarkdownBrowserPreviewExtension, ResourceProvider {
init {
browserPipe.subscribe("copy-button/copy") {
CopyPasteManager.getInstance().setContents(StringSelection(it))
val project = panel.project ?: return@subscribe
invokeLater {
val statusBar = WindowManager.getInstance().getStatusBar(project)
val text = StringUtil.shortenTextWithEllipsis(it, 32, 0)
statusBar?.info = LangBundle.message("status.bar.text.reference.has.been.copied", "'$text'")
}
}
}
override val resourceProvider = this
override val styles = listOf(STYLE_NAME)
override val scripts = listOf(SCRIPT_NAME)
override fun canProvide(resourceName: String): Boolean {
return resourceName in resources
}
override fun loadResource(resourceName: String): ResourceProvider.Resource? {
return when (resourceName) {
STYLE_NAME -> ResourceProvider.loadInternalResource<CodeFenceCopyButtonBrowserExtension>(STYLE_NAME)
SCRIPT_NAME -> ResourceProvider.loadInternalResource<CodeFenceCopyButtonBrowserExtension>(SCRIPT_NAME)
COPY_ICON_NAME -> loadIconAsResource(AllIcons.General.InlineCopy)
COPY_ICON_HOVERED_NAME -> loadIconAsResource(AllIcons.General.InlineCopyHover)
else -> null
}
}
override fun dispose() = Unit
class Provider: MarkdownBrowserPreviewExtension.Provider {
override fun createBrowserExtension(panel: MarkdownHtmlPanel): MarkdownBrowserPreviewExtension? {
return panel.browserPipe?.let { CodeFenceCopyButtonBrowserExtension(panel, it) }
}
}
companion object {
private const val STYLE_NAME = "copy-button.css"
private const val SCRIPT_NAME = "copy-button.js"
private const val COPY_ICON_NAME = "copy-button-copy-icon.png"
private const val COPY_ICON_HOVERED_NAME = "copy-button-copy-icon-hovered.png"
private val resources = listOf(
STYLE_NAME,
SCRIPT_NAME,
COPY_ICON_NAME,
COPY_ICON_HOVERED_NAME
)
private fun loadIconAsResource(icon: Icon): ResourceProvider.Resource {
return ResourceProvider.Resource(MarkdownExtensionsUtil.loadIcon(icon, "png"))
}
}
}
| apache-2.0 | a8a8644705c31b858f5232e46f3a8a38 | 40.381579 | 158 | 0.770747 | 4.659259 | false | false | false | false |
micolous/metrodroid | src/commonMain/kotlin/au/id/micolous/metrodroid/transit/seq_go/SeqGoData.kt | 1 | 2226 | /*
* SeqGoData.kt
*
* Copyright 2015-2016 Michael Farrell <[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, see <http://www.gnu.org/licenses/>.
*/
package au.id.micolous.metrodroid.transit.seq_go
import au.id.micolous.metrodroid.multi.R
import au.id.micolous.metrodroid.multi.StringResource
import au.id.micolous.metrodroid.multi.VisibleForTesting
/**
* Constants used in Go card
*/
object SeqGoData {
const val SEQ_GO_STR = "seq_go"
internal const val VEHICLE_RAIL = 5
internal const val VEHICLE_GLINK = 32
/* Airtrain */
@VisibleForTesting
internal const val DOMESTIC_AIRPORT = 9
private const val INTERNATIONAL_AIRPORT = 10
internal val AIRPORT_STATIONS = listOf(DOMESTIC_AIRPORT, INTERNATIONAL_AIRPORT)
// https://github.com/micolous/metrodroid/wiki/Go-(SEQ)#ticket-types
// TODO: Discover child and seniors card type.
internal val TICKET_TYPES = mapOf(
// Adult Go seeQ (2019), comes up as "Adult Explore" on TVMs
0xf to TicketType.ADULT_EXPLORE,
// Adult (2011)
0x0801 to TicketType.ADULT,
// Adult (2016)
0x0c01 to TicketType.ADULT,
// Concession (2016)
0x08a5 to TicketType.CONCESSION)
enum class TicketType constructor(val description: StringResource) {
UNKNOWN(R.string.unknown),
ADULT(R.string.seqgo_ticket_type_adult),
ADULT_EXPLORE(R.string.seqgo_ticket_type_adult_explore),
CHILD(R.string.seqgo_ticket_type_child),
CONCESSION(R.string.seqgo_ticket_type_concession),
SENIOR(R.string.seqgo_ticket_type_senior)
}
}
| gpl-3.0 | 51ae7a03cc2182a9312d95b7998d94d5 | 33.78125 | 83 | 0.695867 | 3.792164 | false | false | false | false |
siarhei-luskanau/android-iot-doorbell | ui/ui_image_list/src/main/kotlin/siarhei/luskanau/iot/doorbell/ui/imagelist/ImageListFragment.kt | 1 | 5929 | package siarhei.luskanau.iot.doorbell.ui.imagelist
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import coil.compose.rememberAsyncImagePainter
import coil.request.ImageRequest
import siarhei.luskanau.iot.doorbell.data.model.ImageData
import siarhei.luskanau.iot.doorbell.ui.common.BaseFragment
import siarhei.luskanau.iot.doorbell.ui.common.ErrorItem
import siarhei.luskanau.iot.doorbell.ui.common.LoadingItem
import siarhei.luskanau.iot.doorbell.ui.common.R
import siarhei.luskanau.iot.doorbell.ui.imagelist.databinding.FragmentImageListBinding
class ImageListFragment(
presenterProvider: (fragment: Fragment) -> ImageListPresenter
) : BaseFragment<ImageListPresenter>(presenterProvider) {
private lateinit var fragmentBinding: FragmentImageListBinding
private lateinit var normalStateCompose: ComposeView
private val camerasAdapter = CameraAdapter()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
fragmentBinding = FragmentImageListBinding.inflate(
inflater,
container,
false
)
normalStateCompose = ComposeView(inflater.context).apply {
setContent {
MaterialTheme {
ImageListComposable(
items = presenter.doorbellListFlow.collectAsLazyPagingItems(),
onItemClickListener = { imageData ->
imageData?.let { presenter.onImageClicked(it) }
}
)
}
}
}
fragmentBinding.containerContent.addView(normalStateCompose)
return fragmentBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
fragmentBinding.camerasRecyclerView.adapter = camerasAdapter
camerasAdapter.onItemClickListener = { _, _, position ->
presenter.onCameraClicked(camerasAdapter.getItem(position))
}
}
override fun observeDataSources() {
super.observeDataSources()
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
camerasAdapter.submitList(presenter.getCameraList())
}
}
}
@Composable
@Suppress("FunctionNaming", "EmptyFunctionBlock", "UnusedPrivateMember")
fun ImageListComposable(
items: LazyPagingItems<ImageData>,
onItemClickListener: (ImageData?) -> Unit
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
contentPadding = PaddingValues(all = 12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
items(
items = items,
key = { imageData ->
imageData.imageId
}
) { imageData ->
imageData?.let {
ImageDataItem(
imageData = imageData,
onItemClickListener = onItemClickListener
)
}
}
when (val loadState = items.loadState.append) {
is LoadState.Error -> item { ErrorItem(loadState.error.message ?: "error") }
LoadState.Loading -> item { LoadingItem() }
is LoadState.NotLoading -> item {
if (items.itemCount <= 0) {
Text(text = "no data")
}
}
}
when (val loadState = items.loadState.refresh) {
is LoadState.Error -> item { ErrorItem(loadState.error.message ?: "error") }
LoadState.Loading -> item { LoadingItem() }
is LoadState.NotLoading -> Unit
}
}
}
@Composable
@Suppress("FunctionNaming")
fun ImageDataItem(
imageData: ImageData,
onItemClickListener: (ImageData?) -> Unit
) {
val painter =
rememberAsyncImagePainter(
model = ImageRequest.Builder(LocalContext.current)
.data(imageData.imageUri)
.crossfade(durationMillis = 1000)
.error(R.drawable.ic_error_outline)
.placeholder(R.drawable.ic_image)
.build()
)
Surface(
shape = MaterialTheme.shapes.medium,
modifier = Modifier
.padding(vertical = 4.dp, horizontal = 8.dp)
.clickable { onItemClickListener.invoke(imageData) },
color = MaterialTheme.colors.background,
elevation = 2.dp,
border = if (MaterialTheme.colors.isLight) {
null
} else {
BorderStroke(1.dp, MaterialTheme.colors.surface)
}
) {
Image(
modifier = Modifier.fillMaxSize(),
painter = painter,
contentDescription = "Unsplash Image",
contentScale = ContentScale.Crop
)
}
}
| mit | 8d8f8fb139effc05029f0d6e218b8bf1 | 34.716867 | 88 | 0.661157 | 5.205443 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/changeSignature/usages/KotlinComponentUsageInDestructuring.kt | 3 | 3525 | // 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.refactoring.changeSignature.usages
import com.intellij.usageView.UsageInfo
import org.jetbrains.kotlin.idea.base.codeInsight.KotlinNameSuggestionProvider
import org.jetbrains.kotlin.idea.core.CollectingNameValidator
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNameSuggester
import org.jetbrains.kotlin.idea.base.fe10.codeInsight.newDeclaration.Fe10KotlinNewDeclarationNameValidator
import org.jetbrains.kotlin.idea.refactoring.changeSignature.KotlinChangeInfo
import org.jetbrains.kotlin.idea.refactoring.replaceListPsiAndKeepDelimiters
import org.jetbrains.kotlin.psi.KtDestructuringDeclaration
import org.jetbrains.kotlin.psi.KtDestructuringDeclarationEntry
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.buildDestructuringDeclaration
import org.jetbrains.kotlin.psi.psiUtil.PsiChildRange
import org.jetbrains.kotlin.utils.ifEmpty
class KotlinComponentUsageInDestructuring(element: KtDestructuringDeclarationEntry) :
KotlinUsageInfo<KtDestructuringDeclarationEntry>(element) {
override fun processUsage(
changeInfo: KotlinChangeInfo,
element: KtDestructuringDeclarationEntry,
allUsages: Array<out UsageInfo>
): Boolean {
if (!changeInfo.isParameterSetOrOrderChanged) return true
val declaration = element.parent as KtDestructuringDeclaration
val currentEntries = declaration.entries
val newParameterInfos = changeInfo.getNonReceiverParameters()
val newDestructuring = KtPsiFactory(element).buildDestructuringDeclaration {
val lastIndex = newParameterInfos.indexOfLast { it.oldIndex in currentEntries.indices }
val nameValidator = CollectingNameValidator(
filter = Fe10KotlinNewDeclarationNameValidator(
declaration.parent.parent,
null,
KotlinNameSuggestionProvider.ValidatorTarget.VARIABLE
)
)
appendFixedText("val (")
for (i in 0..lastIndex) {
if (i > 0) {
appendFixedText(", ")
}
val paramInfo = newParameterInfos[i]
val oldIndex = paramInfo.oldIndex
if (oldIndex >= 0 && oldIndex < currentEntries.size) {
appendChildRange(PsiChildRange.singleElement(currentEntries[oldIndex]))
} else {
appendFixedText(Fe10KotlinNameSuggester.suggestNameByName(paramInfo.name, nameValidator))
}
}
appendFixedText(")")
}
replaceListPsiAndKeepDelimiters(
changeInfo,
declaration,
newDestructuring,
{
apply {
val oldEntries = entries.ifEmpty { return@apply }
val firstOldEntry = oldEntries.first()
val lastOldEntry = oldEntries.last()
val newEntries = it.entries
if (newEntries.isNotEmpty()) {
addRangeBefore(newEntries.first(), newEntries.last(), firstOldEntry)
}
deleteChildRange(firstOldEntry, lastOldEntry)
}
},
{ entries }
)
return true
}
} | apache-2.0 | 2f78119a7a7e493bbb4f59d3f094ea55 | 43.632911 | 158 | 0.664397 | 5.875 | false | false | false | false |
SpineEventEngine/base | base/src/test/kotlin/io/spine/io/ResourceDirectoryTest.kt | 1 | 4419 | /*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.io
import java.io.File
import java.nio.file.Files.exists
import java.nio.file.Path
import java.nio.file.Paths
import java.util.function.Predicate
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.io.TempDir
class `'ResourceDirectory' should` {
private lateinit var directory: ResourceDirectory
private lateinit var target: Path
private companion object {
const val resourceName = "directory"
val allFiles = listOf(
".dot-file",
"file1.txt",
"subdir/.dot-file",
"subdir/file1.txt",
"subdir/file2.txt",
"subdir/sub-sub-dir/.dot-file",
"subdir/sub-sub-dir/file1.txt",
"subdir/sub-sub-dir/file2.txt",
"subdir/sub-sub-dir/file3.txt",
)
val dotNamed: Predicate<String> = Predicate { s -> s.contains(File.separator + ".dot") }
val noSubSub: Predicate<String> = Predicate { s -> !s.contains("-sub-") }
}
@BeforeEach
fun obtainDirectory(@TempDir tempDir: Path) {
directory = ResourceDirectory.get(resourceName, javaClass.classLoader)
target = tempDir
}
@Test
fun `copy all content to a target directory`() {
directory.copyContentTo(target)
allFiles.forEach { p -> assertExists(p) }
}
@Test
fun `copy content matching a predicate`() {
val condition = dotNamed.and(noSubSub)
directory.copyContentTo(target) { path -> condition.test(path.toString()) }
allFiles
.filter { name -> condition.test(name) }
.forEach { p -> assertExists(p) }
val reverse = dotNamed.negate().and(noSubSub.negate())
allFiles
.filter { name -> reverse.test(name) }
.forEach { p -> assertNotExists(p) }
}
@Test
fun `copy the directory to file system`() {
directory.copyTo(target)
assertExists(resourceName)
allFiles.forEach { p -> assertExists(nestedPath(p)) }
}
@Test
fun `copy the directory with filtering`() {
val condition = dotNamed.and(noSubSub)
directory.copyTo(target) { path -> condition.test(path.toString()) }
assertExists(resourceName)
allFiles
.filter { name -> condition.test(name) }
.forEach { p -> assertExists(nestedPath(p)) }
val reverse = dotNamed.negate().and(noSubSub.negate())
allFiles
.filter { name -> reverse.test(name) }
.forEach { p -> assertNotExists(nestedPath(p)) }
}
private fun nestedPath(p: String) = Paths.get(resourceName, p).toString()
private fun assertExists(relativePath: String) {
val fullPath = target.resolve(relativePath)
assertTrue(exists(fullPath), "Expected to exist: `${fullPath}`.")
}
private fun assertNotExists(relativePath: String) {
val fullPath = target.resolve(relativePath)
assertFalse(exists(fullPath), "Expected to NOT exist: `${fullPath}`.")
}
}
| apache-2.0 | 897c29125719b669d154bed82be1a2c4 | 33.523438 | 96 | 0.660783 | 4.240883 | false | true | false | false |
MiniMineCraft/MiniBus | src/main/kotlin/me/camdenorrb/minibus/listener/table/ListenerTable.kt | 1 | 3221 | @file:Suppress("UNCHECKED_CAST")
package me.camdenorrb.minibus.listener.table
import me.camdenorrb.kcommons.ext.isGenericSupertypeOf
import me.camdenorrb.minibus.listener.ListenerAction
import me.camdenorrb.minibus.listener.ListenerAction.Lambda
import me.camdenorrb.minibus.listener.ListenerEntry
import me.camdenorrb.minibus.listener.ListenerPriority
import me.camdenorrb.minibus.listener.ListenerPriority.NORMAL
import java.util.concurrent.ConcurrentSkipListSet
import kotlin.reflect.KCallable
import kotlin.reflect.KFunction
import kotlin.reflect.KType
import kotlin.reflect.typeOf
//private typealias ListenerMapEntry = Map.Entry<KClass<out Any>, TreeMap<ListenerPriority, MutableList<ListenerAction<Any>>>>
class ListenerTable {
val map = mutableMapOf<KType, ConcurrentSkipListSet<ListenerEntry<Any>>>()
inline fun <reified T> find(): List<ListenerEntry<Any>>? {
val type = typeOf<T>()
return map.filterKeys { it == type || it.isGenericSupertypeOf(type) }.values.flatten()
}
inline fun <reified T : Any> entries(): Set<ListenerEntry<Any>>? {
return map[typeOf<T>()]
}
inline fun <reified T : Any> entries(priority: ListenerPriority): List<ListenerEntry<Any>>? {
return entries<T>()?.filter { it.priority == priority }
}
inline fun <reified T> get(): Set<ListenerEntry<Any>>? {
return map[typeOf<T>()]
}
inline fun <reified T> get(priority: ListenerPriority): List<ListenerEntry<Any>>? {
return map[typeOf<T>()]?.filter { it.priority == priority }
}
//inline operator fun <reified T> get() = map[typeOf<T>()]
inline fun <reified T> call(event: Any) {
/*map.forEach {
println("${it.key} [${it.value.joinToString { it.action.callable.toString() }}]")
}
println("----")*/
find<T>()?.forEach {
it.action(event)
}
//println()
}
inline fun <reified T> remove(): Set<ListenerEntry<Any>>? {
return map.remove(typeOf<T>())
}
inline fun <reified T> remove(priority: ListenerPriority): Boolean? {
return map[typeOf<T>()]?.removeIf { it.priority == priority }
}
fun remove(action: ListenerAction<*>) = map.values.removeIf { value ->
value.removeIf { it.action == action }
value.isEmpty()
}
fun remove(callable: KCallable<*>) = map.values.removeIf { value ->
value.removeIf { it.action.callable == callable }
value.isEmpty()
}
inline fun <reified T : Any> add(action: ListenerAction<T>, priority: ListenerPriority = NORMAL) {
this.add(typeOf<T>(), action as ListenerAction<Any>, priority)
}
inline fun <reified T : Any> add(instance: Any, function: KFunction<Any>, priority: ListenerPriority = NORMAL) {
this.add<T>(ListenerAction.Function(instance, function), priority)
}
inline fun <reified T : Any> add(priority: ListenerPriority = NORMAL, noinline block: Lambda<T>.(T) -> Unit) {
this.add<T>(Lambda(block) as Lambda<Any>, priority)
}
fun add(type: KType, instance: Any, function: KFunction<Any>, priority: ListenerPriority = NORMAL) {
this.add(type, ListenerAction.Function(instance, function), priority)
}
fun add(type: KType, action: ListenerAction<Any>, priority: ListenerPriority = NORMAL) {
map.getOrPut(type) { ConcurrentSkipListSet() }.add(ListenerEntry(priority, action))
}
} | apache-2.0 | e340bb516a4571c6fe6de517c096f8e7 | 25.85 | 126 | 0.714995 | 3.693807 | false | false | false | false |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/primitives/PointCloud.kt | 2 | 5745 | package graphics.scenery.primitives
import graphics.scenery.BufferUtils
import graphics.scenery.Mesh
import graphics.scenery.OrientedBoundingBox
import graphics.scenery.ShaderMaterial
import graphics.scenery.geometry.GeometryType
import org.joml.Vector3f
import java.nio.FloatBuffer
import java.nio.file.FileSystems
import java.nio.file.Files
/**
* Constructs a point cloud, with a given base [pointRadius].
*
* @author Kyle Harrington <[email protected]>
* @author Ulrik Günther <[email protected]>
*/
open class PointCloud(var pointRadius: Float = 1.0f, override var name: String = "PointCloud") : Mesh(name) {
init {
geometry {
/** [PointCloud]s are rendered as point geometry. */
geometryType = GeometryType.POINTS
}
renderable {
// PointClouds do not get billboarded.
isBillboard = false
// we are going to use shader files whose name is derived from the class name.
// -> PointCloud.vert, PointCloud.frag
}
setMaterial(ShaderMaterial.fromClass(this::class.java)) {
blending.transparent = true
}
}
/**
* Sets up normal and texcoord buffers from the vertex buffers.
*/
fun setupPointCloud() {
geometry {
if( this.texcoords.limit() == 0 ) {// Only preinitialize if texcoords has not been preinialized
this.texcoords = BufferUtils.allocateFloat(vertices.limit() / 3 * 2)
var i = 0
while (i < this.texcoords.limit() - 1) {
this.texcoords.put(i, pointRadius)
this.texcoords.put(i + 1, pointRadius)
i += 2
}
}
if( this.normals.limit() == 0 ) {// Only preinitialize if need be
this.normals = BufferUtils.allocateFloatAndPut(FloatArray(vertices.limit(), { 1.0f }))
}
}
}
/**
* Reads the [PointCloud] from [filename], assuming the ThunderSTORM format.
* See http://www.neurocytolab.org/tscolumns/ for format documentation.
*
* This function automatically determines the used separator char, and supports
* comma (,), semicolon (;), and tab as separators.
*/
fun readFromPALM(filename: String) {
geometry {
val count = Files.lines(FileSystems.getDefault().getPath(filename)).count()
this.vertices = BufferUtils.allocateFloat(count.toInt() * 3)
this.normals = BufferUtils.allocateFloat(count.toInt() * 3)
this.texcoords = BufferUtils.allocateFloat(count.toInt() * 2)
logger.info("Reading ${count/3} locations from $filename...")
val boundingBoxCoords = floatArrayOf(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f)
var separator = ""
Files.lines(FileSystems.getDefault().getPath(filename)).forEach {
// try to figure out separator char
if(separator == "") {
separator = when {
it.split(",").size >= 6 -> ","
it.split("\t").size >= 6 -> "\t"
it.split(";").size >= 6 -> ";"
else -> throw IllegalStateException("Could not determine separator char for file $filename.")
}
logger.debug("Determined <$separator> as separator char for $filename.")
}
val arr = it.split(separator)
if (!arr[0].startsWith("\"")) {
this.vertices.put(arr[1].toFloat())
this.vertices.put(arr[2].toFloat())
this.vertices.put(arr[3].toFloat())
boundingBoxCoords[0] = minOf(arr[1].toFloat(), boundingBoxCoords[0])
boundingBoxCoords[2] = minOf(arr[2].toFloat(), boundingBoxCoords[2])
boundingBoxCoords[4] = minOf(arr[3].toFloat(), boundingBoxCoords[4])
boundingBoxCoords[1] = maxOf(arr[1].toFloat(), boundingBoxCoords[1])
boundingBoxCoords[3] = maxOf(arr[2].toFloat(), boundingBoxCoords[3])
boundingBoxCoords[5] = maxOf(arr[3].toFloat(), boundingBoxCoords[5])
this.normals.put(arr[1].toFloat())
this.normals.put(arr[2].toFloat())
this.normals.put(arr[3].toFloat())
this.texcoords.put(arr[4].toFloat())
this.texcoords.put(arr[5].toFloat())
}
}
logger.info("Finished reading. Found ${vertices.capacity()/3} locations.")
this.vertices.flip()
this.normals.flip()
this.texcoords.flip()
boundingBox = OrientedBoundingBox(this@PointCloud, boundingBoxCoords)
}
}
/**
* Sets the [color] for all vertices.
*/
fun setColor(color: Vector3f) {
val colorBuffer = FloatBuffer.allocate(geometry().vertices.capacity())
while(colorBuffer.hasRemaining()) {
color.get(colorBuffer)
}
}
companion object {
/**
* Creates a point cloud from an [array] of floats.
*/
fun fromArray(array: FloatArray): PointCloud {
val p = PointCloud()
p.geometry().vertices = FloatBuffer.wrap(array)
p.setupPointCloud()
return p
}
/**
* Creates a point cloud from a [buffer] of floats.
*/
fun fromBuffer(buffer: FloatBuffer): PointCloud {
val p = PointCloud()
p.geometry().vertices = buffer.duplicate()
p.setupPointCloud()
return p
}
}
}
| lgpl-3.0 | e8e9e74e48debc6ddfebcc0a4cd60fb6 | 35.820513 | 117 | 0.557451 | 4.639742 | false | false | false | false |
senyuyuan/Gluttony | gluttony-realm/src/main/java/sen/yuan/dao/gluttony_realm/realm_find.kt | 1 | 3659 | package sen.yuan.dao.gluttony_realm
import io.realm.RealmObject
import io.realm.RealmQuery
import io.realm.RealmResults
import io.realm.Sort
import kotlin.reflect.declaredMemberProperties
/**
* Created by Administrator on 2016/11/24.
*/
inline fun <reified T : RealmObject> T.findOneByKey(propertyValue: Any): T? {
val mClass = this.javaClass.kotlin
val name = "${mClass.simpleName}"
var propertyName: String? = null
mClass.declaredMemberProperties.forEach {
if (it.annotations.map { it.annotationClass }.contains(GluttonyPrimaryKey::class)) {
propertyName = it.name
}
}
if (propertyName == null) {
throw Exception("$name 类没有设置PrimaryKey")
}
return Gluttony.realm.where(this.javaClass)
.apply {
when (propertyValue) {
is String -> equalTo(propertyName, propertyValue)
is Int -> equalTo(propertyName, propertyValue)
is Byte -> equalTo(propertyName, propertyValue)
is Short -> equalTo(propertyName, propertyValue)
is Long -> equalTo(propertyName, propertyValue)
else -> throw Exception("$name 类设置了错误的PrimaryKey的类型")
}
}
.findFirst()
}
//
///**
// * 对单例模式数据的支持:寻找
// *
// * 注意:必须有@Singleton注解的Int字段
// * */
//inline fun <reified T : RealmObject> T.findSingleton(): T? {
// val mClass = this.javaClass.kotlin
// val name = "${mClass.simpleName}"
// var propertyName: String? = null
// mClass.declaredMemberProperties.forEach {
// if (it.annotations.map { it.annotationClass }.contains(Singleton::class)) {
// propertyName = it.name
// }
// }
// if (propertyName == null) {
// throw Exception("$name 类没有设置 @Singleton 注解的 Int 字段")
// }
//
// return Gluttony.realm.where(this.javaClass)
// .apply {
// equalTo(propertyName, 1)
// }
// .findFirst()
//}
inline fun <reified T : RealmObject> T.findOne(optionFunctor: RealmFinder.() -> Unit): T? {
val realmFinder = RealmFinder().apply { optionFunctor() }
return Gluttony.realm.where([email protected])
.apply {
realmFinder.conditionFunctor?.invoke(this)
}.findFirst()
}
inline fun <reified T : RealmObject> T.findAll(optionFunctor: RealmFinder.() -> Unit): RealmResults<T> {
val realmFinder = RealmFinder().apply { optionFunctor() }
return Gluttony.realm.where([email protected])
.apply {
realmFinder.conditionFunctor?.invoke(this)
}.findAll()
.let {
it.apply {
realmFinder.orderFunctor?.invoke(this)
}
}
}
class RealmFinder() {
var orderFunctor: (RealmResults<*>.() -> RealmResults<*>)? = null
var conditionFunctor: (RealmQuery<*>.() -> Unit)? = null
inline fun condition(crossinline functor: RealmCondition.() -> RealmCondition): RealmFinder {
conditionFunctor = {
RealmCondition().apply { functor().functorArray.forEach { it() } }
}
return this
}
inline fun <reified T : RealmObject> RealmResults<T>.orderBy(propertyName: String, orderMode: OrderMode): RealmResults<T> {
orderFunctor = {
sort(propertyName, when (orderMode) {
OrderMode.ASC -> Sort.ASCENDING
OrderMode.DESC -> Sort.DESCENDING
})
}
return this
}
}
| apache-2.0 | 5841f2bc6470f6ecb4d3c43f5d28105f | 28.221311 | 127 | 0.58878 | 4.478643 | false | false | false | false |
stanfy/helium | codegen/objc/objc-entities/src/main/kotlin/com/stanfy/helium/handler/codegen/objectivec/entity/builder/ObjCDefaultFileStructureBuilder.kt | 1 | 1735 | package com.stanfy.helium.handler.codegen.objectivec.entity.builder
import com.stanfy.helium.handler.codegen.objectivec.entity.ObjCEntitiesOptions
import com.stanfy.helium.handler.codegen.objectivec.entity.classtree.ObjCProjectClassesTree
import com.stanfy.helium.handler.codegen.objectivec.entity.filetree.ObjCHeaderFile
import com.stanfy.helium.handler.codegen.objectivec.entity.filetree.ObjCImplementationFile
import com.stanfy.helium.handler.codegen.objectivec.entity.filetree.ObjCProjectFilesStructure
/**
* Created by paultaykalo on 12/17/15.
* Transforms classes tree to the structure of source files
*/
class ObjCDefaultFileStructureBuilder : ObjCBuilder<ObjCProjectClassesTree, ObjCProjectFilesStructure> {
override fun build(from: ObjCProjectClassesTree, options: ObjCEntitiesOptions?): ObjCProjectFilesStructure {
val result = ObjCProjectFilesStructure()
result.addFiles(
from.classes.flatMap { objcClass ->
val headerBuilder = ObjCHeaderFileBuilder()
val headerFile = ObjCHeaderFile(objcClass.name, headerBuilder.build(objcClass, options))
val implementationFile = ObjCImplementationFile(objcClass.name, objcClass.implementation.asString())
listOf(headerFile, implementationFile)
}
)
result.addFiles(
from.pregeneratedClasses
.filter { objClass -> objClass.header != null }
.map { objcClass -> ObjCHeaderFile(objcClass.name, objcClass.header!!) }
)
result.addFiles(
from.pregeneratedClasses
.filter { objClass -> objClass.implementation != null }
.map { objcClass -> ObjCImplementationFile(objcClass.name, objcClass.implementation!!) }
)
return result
}
} | apache-2.0 | 2370908754c8463c62c6e18ad1cc84b0 | 39.372093 | 110 | 0.749856 | 4.589947 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/view/GradientCircleNumberView.kt | 2 | 1530 | package org.wikipedia.feed.view
import android.content.Context
import android.graphics.LinearGradient
import android.graphics.Shader.TileMode
import android.graphics.drawable.GradientDrawable
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import androidx.core.content.ContextCompat
import org.wikipedia.R
import org.wikipedia.databinding.ViewGradientCircleNumberBinding
import org.wikipedia.util.ResourceUtil
class GradientCircleNumberView constructor(context: Context, attrs: AttributeSet? = null) : FrameLayout(context, attrs) {
private val binding = ViewGradientCircleNumberBinding.inflate(LayoutInflater.from(context), this)
private val gradientColor1 = ResourceUtil.getThemedColor(context, R.attr.colorAccent)
private val gradientColor2 = ContextCompat.getColor(context, R.color.green50)
private fun applyGradient() {
val textShader = LinearGradient(0f, 0f, 0f, binding.numberView.textSize,
intArrayOf(gradientColor2, gradientColor1, gradientColor2),
floatArrayOf(0f, 0.5f, 1f), TileMode.CLAMP)
val gradientDrawable = GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, intArrayOf(gradientColor1, gradientColor2))
gradientDrawable.cornerRadius = 90f
binding.numberView.paint.shader = textShader
binding.baseNumberView.background = gradientDrawable
}
fun setNumber(number: Int) {
binding.numberView.text = number.toString()
applyGradient()
}
}
| apache-2.0 | 5f28c037df991ff858c1da6359b03693 | 42.714286 | 132 | 0.777124 | 4.678899 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/dalatlaptop/ux/SplashActivity.kt | 1 | 2851 | package com.tungnui.dalatlaptop.ux
import android.app.Activity
import android.app.ProgressDialog
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.view.View
import com.facebook.appevents.AppEventsLogger
import com.tungnui.dalatlaptop.MyApplication
import com.tungnui.dalatlaptop.R
import com.tungnui.dalatlaptop.libraryhelper.Utils
import kotlinx.android.synthetic.main.activity_splash.*
import timber.log.Timber
class SplashActivity : AppCompatActivity() {
private var activity: Activity? = null
private lateinit var progressDialog: ProgressDialog
private var layoutCreated = false
private var windowDetached = false
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.tag(TAG)
activity = this
// init loading dialog
progressDialog = Utils.generateProgressDialog(this, false)
init()
}
private fun init() {
// Check if data connected.
if (MyApplication.instance?.isDataConnected == false) {
progressDialog.hide()
initSplashLayout()
splash_content.visibility = View.VISIBLE
splash_intro_screen.visibility = View.GONE
splash_content_no_connection.visibility = View.VISIBLE
} else {
progressDialog.hide()
startMainActivity(null)
}
}
private fun initSplashLayout() {
if (!layoutCreated) {
setContentView(R.layout.activity_splash)
splash_re_run_btn.setOnClickListener {
progressDialog.show()
Handler().postDelayed({ init() }, 600)
}
layoutCreated=true
} else {
Timber.d("%s screen is already created.", this.javaClass.simpleName)
}
}
private fun startMainActivity(bundle: Bundle?) {
val mainIntent = Intent(this@SplashActivity, MainActivity::class.java)
startActivity(mainIntent)
finish()
}
override fun onResume() {
super.onResume()
AppEventsLogger.activateApp(this)
}
override fun onPause() {
super.onPause()
AppEventsLogger.deactivateApp(this)
}
override fun onStop() {
progressDialog.cancel()
splash_intro_screen.visibility = View.GONE
splash_content.visibility = View.VISIBLE
super.onStop()
}
override fun onAttachedToWindow() {
windowDetached = false
super.onAttachedToWindow()
}
override fun onDetachedFromWindow() {
windowDetached = true
super.onDetachedFromWindow()
}
companion object {
val REFERRER = "referrer"
private val TAG = SplashActivity::class.java.simpleName
}
}
| mit | 778f55dfa554f5de613ac1ac24f2301c | 27.227723 | 80 | 0.655209 | 4.958261 | false | false | false | false |
dkandalov/katas | kotlin/src/katas/kotlin/leetcode/wildcard_matching/v4/WildcardMatching.kt | 1 | 1830 | package katas.kotlin.leetcode.wildcard_matching.v4
import datsok.shouldEqual
import org.junit.Test
typealias Matcher = (String) -> Set<String>
fun char(char: Char): Matcher = { s ->
if (s.firstOrNull() == char) setOf(s.drop(1)) else emptySet()
}
fun anyChar(): Matcher = { s ->
if (s.isNotEmpty()) setOf(s.drop(1)) else emptySet()
}
fun anyChars(): Matcher = { s ->
(0..s.length).mapTo(HashSet()) { s.drop(it) }
}
fun isMatch(s: String, pattern: String): Boolean {
val matchers = pattern.map {
when (it) {
'?' -> anyChar()
'*' -> anyChars()
else -> char(it)
}
}
return matchers
.fold(setOf(s)) { outputs, matcher -> outputs.flatMapTo(HashSet()) { matcher(it) } }
.any { output -> output.isEmpty() }
}
// ✅
class WildcardMatching {
@Test fun `some examples`() {
isMatch("a", "a") shouldEqual true
isMatch("a", "b") shouldEqual false
isMatch("aa", "aa") shouldEqual true
isMatch("aa", "a") shouldEqual false
isMatch("a", "aa") shouldEqual false
isMatch("", "*") shouldEqual true
isMatch("a", "*") shouldEqual true
isMatch("aa", "*") shouldEqual true
isMatch("aa", "**") shouldEqual true
isMatch("aa", "***") shouldEqual true
isMatch("aa", "*a") shouldEqual true
isMatch("aa", "a*") shouldEqual true
isMatch("aa", "*aa") shouldEqual true
isMatch("aa", "a*a") shouldEqual true
isMatch("aa", "aa*") shouldEqual true
isMatch("aa", "*b") shouldEqual false
isMatch("aa", "b*") shouldEqual false
isMatch("adceb", "*a*b") shouldEqual true
isMatch("a", "?") shouldEqual true
isMatch("cb", "?a") shouldEqual false
isMatch("acdcb", "a*c?b") shouldEqual false
}
}
| unlicense | c20acf27d6930322e2c066e9fe6a4db2 | 28.967213 | 92 | 0.565646 | 3.922747 | false | false | false | false |
theapache64/Mock-API | src/com/theah64/mock_api/servlets/GetRandomServlet.kt | 1 | 2622 | package com.theah64.mock_api.servlets
import com.theah64.mock_api.utils.APIResponse
import com.theah64.webengine.utils.PathInfo
import com.theah64.webengine.utils.Request
import com.thedeanda.lorem.Lorem
import com.thedeanda.lorem.LoremIpsum
import org.json.JSONException
import javax.servlet.annotation.WebServlet
import java.io.IOException
import java.sql.SQLException
@WebServlet(urlPatterns = ["/v1/get_random"])
class GetRandomServlet : AdvancedBaseServlet() {
override val isSecureServlet: Boolean
get() = false
override val requiredParameters: Array<String>?
@Throws(Request.RequestException::class)
get() = arrayOf(KEY_RANDOM_WHAT, KEY_COUNT)
@Throws(Request.RequestException::class, IOException::class, JSONException::class, SQLException::class, PathInfo.PathInfoException::class)
override fun doAdvancedPost() {
val randomWhat = getStringParameter(KEY_RANDOM_WHAT)
val count = getIntParameter(KEY_COUNT, 1)
val output: String
val lorem = LoremIpsum.getInstance()
when (randomWhat) {
TYPE_WORDS -> output = capitalize(lorem.getWords(count, count))
TYPE_PARAGRAPHS -> output = lorem.getParagraphs(count, count)
TYPE_NAME -> output = lorem.name
TYPE_PHONE -> output = lorem.phone
TYPE_CITY -> output = lorem.city
TYPE_STATE -> output = lorem.stateFull
TYPE_COUNTRY -> output = lorem.country
TYPE_MALE_NAME -> output = lorem.nameMale
TYPE_FEMALE_NAME -> output = lorem.nameFemale
TYPE_FIRST_NAME -> output = lorem.firstName
TYPE_LAST_NAME -> output = lorem.lastName
else -> throw Request.RequestException("Invalid randomWhat: $randomWhat")
}
writer!!.write(APIResponse("Done", "random_output", output).response)
}
private fun capitalize(line: String): String {
return Character.toUpperCase(line[0]) + line.substring(1)
}
companion object {
private val KEY_RANDOM_WHAT = "random_what"
private val KEY_COUNT = "count"
private val TYPE_WORDS = "words"
private val TYPE_PARAGRAPHS = "paragraphs"
private val TYPE_NAME = "name"
private val TYPE_PHONE = "phone"
private val TYPE_CITY = "city"
private val TYPE_STATE = "state"
private val TYPE_COUNTRY = "country"
private val TYPE_MALE_NAME = "male_name"
private val TYPE_FEMALE_NAME = "female_name"
private val TYPE_FIRST_NAME = "first_name"
private val TYPE_LAST_NAME = "last_name"
}
}
| apache-2.0 | a870c641df6358cdd8d2f19b4c3a95c5 | 35.929577 | 142 | 0.660946 | 4.181818 | false | false | false | false |
dahlstrom-g/intellij-community | jvm/jvm-analysis-tests/src/com/intellij/codeInspection/tests/UastInspectionTestBase.kt | 3 | 3863 | package com.intellij.codeInspection.tests
import com.intellij.codeInspection.InspectionProfileEntry
import com.intellij.codeInspection.InspectionsBundle
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.roots.LanguageLevelProjectExtension
import com.intellij.pom.java.LanguageLevel
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.InspectionTestUtil
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.fixtures.JavaCodeInsightTestFixture
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import java.io.File
abstract class UastInspectionTestBase : LightJavaCodeInsightFixtureTestCase() {
override fun getTestDataPath(): String = PathManager.getCommunityHomePath().replace(File.separatorChar, '/') + basePath
abstract val inspection: InspectionProfileEntry
open val languageLevel = LanguageLevel.JDK_11
open val sdkLevel = LanguageLevel.JDK_11
override fun setUp() {
super.setUp()
myFixture.enableInspections(inspection)
LanguageLevelProjectExtension.getInstance(project).languageLevel = languageLevel
}
override fun getProjectDescriptor(): LightProjectDescriptor = ProjectDescriptor(sdkLevel)
protected fun JavaCodeInsightTestFixture.setLanguageLevel(languageLevel: LanguageLevel) {
LanguageLevelProjectExtension.getInstance(project).languageLevel = languageLevel
IdeaTestUtil.setModuleLanguageLevel(myFixture.module, languageLevel, testRootDisposable)
}
protected fun JavaCodeInsightTestFixture.testHighlighting(
lang: ULanguage,
text: String,
fileName: String = generateFileName()
) {
configureByText("$fileName${lang.ext}", text)
checkHighlighting()
}
protected fun JavaCodeInsightTestFixture.testQuickFix(
lang: ULanguage,
before: String,
after: String,
vararg hints: String = arrayOf(InspectionsBundle.message(
"fix.all.inspection.problems.in.file", InspectionTestUtil.instantiateTool(inspection.javaClass).displayName
)),
fileName: String = generateFileName()
) {
configureByText("$fileName${lang.ext}", before)
hints.forEach { runQuickFix(it) }
checkResult(after)
}
protected fun JavaCodeInsightTestFixture.testQuickFix(file: String, hint: String = InspectionsBundle.message(
"fix.all.inspection.problems.in.file", InspectionTestUtil.instantiateTool(inspection.javaClass).displayName
)) {
configureByFile(file)
runQuickFix(hint)
checkResultByFile(file.replace(".", ".after."))
}
private fun JavaCodeInsightTestFixture.runQuickFix(hint: String) {
val action = getAvailableIntention(hint) ?: throw AssertionError("Quickfix '$hint' is not available.")
launchAction(action)
}
protected fun JavaCodeInsightTestFixture.testQuickFixUnavailable(
lang: ULanguage,
text: String,
hint: String = InspectionsBundle.message(
"fix.all.inspection.problems.in.file", InspectionTestUtil.instantiateTool(inspection.javaClass).displayName
),
fileName: String = generateFileName()
) {
configureByText("$fileName${lang.ext}", text)
assertEmpty("Quickfix '$hint' is available but should not.", myFixture.filterAvailableIntentions(hint))
}
protected fun JavaCodeInsightTestFixture.testQuickFixUnavailable(file: String, hint: String = InspectionsBundle.message(
"fix.all.inspection.problems.in.file", InspectionTestUtil.instantiateTool(inspection.javaClass).displayName
)) {
configureByFile(file)
assertEmpty("Quickfix '$hint' is available but should not.", myFixture.filterAvailableIntentions(hint))
}
private fun generateFileName() = getTestName(false).replace("[^a-zA-Z0-9\\.\\-]", "_")
override fun tearDown() {
try {
myFixture.disableInspections(inspection)
}
finally {
super.tearDown()
}
}
} | apache-2.0 | c5bb0b48658a3a74c0a1b78abda973cd | 36.882353 | 122 | 0.774786 | 5.306319 | false | true | false | false |
phylame/jem | jem-crawler/src/main/kotlin/jem/crawler/CrawlerSpec.kt | 1 | 3299 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jem.crawler
import jclp.KeyedService
import jclp.ServiceManager
import jclp.setting.Settings
import jem.Book
import jem.Chapter
import jem.epm.EpmFactory
import jem.epm.Parser
import jem.epm.ParserException
import java.io.InterruptedIOException
import java.net.URL
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
const val ATTR_CHAPTER_UPDATE_TIME = "updateTime"
const val ATTR_CHAPTER_SOURCE_URL = "sourceUrl"
const val EXT_CRAWLER_BOOK_ID = "jem.ext.crawler.bookId"
const val EXT_CRAWLER_SOURCE_URL = "jem.ext.crawler.sourceUrl"
const val EXT_CRAWLER_SOURCE_SITE = "jem.ext.crawler.sourceSite"
const val EXT_CRAWLER_LAST_CHAPTER = "jem.ext.crawler.lastChapter"
const val EXT_CRAWLER_UPDATE_TIME = "jem.ext.crawler.updateTime"
val Book.crawlerTime: LocalDateTime?
get() = extensions[EXT_CRAWLER_UPDATE_TIME]?.let {
when (it) {
is LocalDateTime -> it
is LocalDate -> it.atTime(8, 0)
is LocalTime -> it.atDate(LocalDate.now())
else -> throw IllegalStateException("Invalid value for $EXT_CRAWLER_UPDATE_TIME")
}
}
interface Crawler {
fun getBook(url: String, settings: Settings?): Book
fun getText(url: String, settings: Settings?): String {
throw NotImplementedError()
}
}
interface CrawlerFactory : KeyedService {
fun getCrawler(): Crawler
}
object CrawlerManager : ServiceManager<CrawlerFactory>(CrawlerFactory::class.java) {
fun getCrawler(host: String) = get(host)?.getCrawler()
fun fetchBook(url: String, settings: Settings?) = getCrawler(URL(url).host)?.getBook(url, settings)
}
abstract class ReusableCrawler : Crawler, CrawlerFactory {
override fun getCrawler(): Crawler = this
protected fun Chapter.setText(url: String, settings: Settings?) {
text = CrawlerText(url, this, this@ReusableCrawler, settings)
this[ATTR_CHAPTER_SOURCE_URL] = url
}
protected open fun fetchPage(page: Int, arg: Any): Int {
throw NotImplementedError()
}
protected fun fetchContents(arg: Any) {
for (i in 2 until fetchPage(1, arg)) {
if (Thread.interrupted()) throw InterruptedIOException()
fetchPage(i, arg)
}
}
}
class CrawlerParser : Parser, EpmFactory {
override val name = "Book Crawler"
override val keys = setOf("crawler", "net")
override val hasParser = true
override val parser = this
override fun parse(input: String, arguments: Settings?): Book {
return CrawlerManager.fetchBook(input, arguments) ?: throw ParserException(M.tr("err.crawler.unsupported", input))
}
}
| apache-2.0 | 946f12c0f6d97465081f86e829b3d7b1 | 30.721154 | 122 | 0.707184 | 3.993947 | false | false | false | false |
github/codeql | java/ql/test/kotlin/library-tests/exprs/exprs.kt | 1 | 8158 | import java.awt.Polygon
import java.awt.Rectangle
import kotlin.experimental.*
fun topLevelMethod(x: Int, y: Int,
byx: Byte, byy: Byte,
sx: Short, sy: Short,
lx: Long, ly: Long,
dx: Double, dy: Double,
fx: Float, fy: Float,
): Int {
val i1 = 1
val i2 = x + y
val i3 = x - y
val i4 = x / y
val i5 = x % y
val i6 = x shl y
val i7 = x shr y
val i8 = x ushr y
val i9 = x and y
val i10 = x or y
val i11 = x xor y
val i12 = x.inv()
val i13 = x == y
val i14 = x != y
val i15 = x < y
val i16 = x <= y
val i17 = x > y
val i18 = x >= y
val i19 = x === y
val i20 = x !== y
val i21 = x in x .. y
val i22 = x !in x .. y
val by1 = 1.0
val by2 = byx + byy
val by3 = byx - byy
val by4 = byx / byy
val by5 = byx % byy
val by6 = byx == byy
val by7 = byx != byy
val by8 = byx < byy
val by9 = byx <= byy
val by10 = byx > byy
val by11 = byx >= byy
val by12 = byx === byy
val by13 = byx !== byy
val by14 = byx or byy
val by15 = byx and byy
val by16 = byx xor byy
val s1 = 1.0
val s2 = sx + sy
val s3 = sx - sy
val s4 = sx / sy
val s5 = sx % sy
val s6 = sx == sy
val s7 = sx != sy
val s8 = sx < sy
val s9 = sx <= sy
val s10 = sx > sy
val s11 = sx >= sy
val s12 = sx === sy
val s13 = sx !== sy
val s14 = sx or sy
val s15 = sx and sy
val s16 = sx xor sy
val l1 = 1.0
val l2 = lx + ly
val l3 = lx - ly
val l4 = lx / ly
val l5 = lx % ly
val l6 = lx shl y
val l7 = lx shr y
val l8 = lx ushr y
val l9 = lx and ly
val l10 = lx or ly
val l11 = lx xor ly
val l12 = lx.inv()
val l13 = lx == ly
val l14 = lx != ly
val l15 = lx < ly
val l16 = lx <= ly
val l17 = lx > ly
val l18 = lx >= ly
val l19 = lx === ly
val l20 = lx !== ly
val d1 = 1.0
val d2 = dx + dy
val d3 = dx - dy
val d4 = dx / dy
val d5 = dx % dy
val d6 = dx == dy
val d7 = dx != dy
val d8 = dx < dy
val d9 = dx <= dy
val d10 = dx > dy
val d11 = dx >= dy
val d12 = dx === dy
val d13 = dx !== dy
val f1 = 1.0
val f2 = fx + fy
val f3 = fx - fy
val f4 = fx / fy
val f5 = fx % fy
val f6 = fx == fy
val f7 = fx != fy
val f8 = fx < fy
val f9 = fx <= fy
val f10 = fx > fy
val f11 = fx >= fy
val f12 = fx === fy
val f13 = fx !== fy
val b1 = true
val b2 = false
val b3 = b1 && b2
val b4 = b1 || b2
val b5 = !b1
val c = 'x'
val str = "string lit"
val strWithQuote = "string \" lit"
val b6 = i1 is Int
val b7 = i1 !is Int
val b8 = b7 as Boolean
val str1: String = "string lit"
val str2: String? = "string lit"
val str3: String? = null
val str4: String = "foo $str1 bar $str2 baz"
val str5: String = "foo ${str1 + str2} bar ${str2 + str1} baz"
val str6 = str1 + str2
var variable = 10
while (variable > 0) {
variable--
}
return 123 + 456
}
fun getClass() {
val d = true::class
}
class C(val n: Int) {
fun foo(): C { return C(42) }
}
open class Root {}
class Subclass1: Root() {}
class Subclass2: Root() {}
fun typeTests(x: Root, y: Subclass1) {
if(x is Subclass1) {
val x1: Subclass1 = x
}
val y1: Subclass1 = if (x is Subclass1) { x } else { y }
var q = 1
if (x is Subclass1) { q = 2 } else { q = 3 }
}
fun foo(p: Polygon) {
val r = p.getBounds()
if(r != null) {
val r2: Rectangle = r
val height = r2.height
r2.height = 3
}
}
enum class Direction {
NORTH, SOUTH, WEST, EAST
}
enum class Color(val rgb: Int) {
RED(0xFF0000),
GREEN(0x00FF00),
BLUE(0x0000FF)
}
fun enums() {
val south = Direction.SOUTH
val green = Color.GREEN
}
interface Interface1 {}
class Class1 {
val a1 = 1
private fun getObject() : Any {
val a2 = 2
return object : Interface1 {
val a3: String = (a1 + a2).toString()
}
}
}
fun notNullAssertion(x: Any?) {
val y: Any = x!!
}
class Class2 {
fun x(aa: Any?, s: String?) {
val a = aa.toString()
val b0 = s.plus(5)
val b1 = s + 5
val b2 = s!!.plus(5)
val b3 = s!! + 5
val c0 = enumValues<Color>()
val c1 = Color.values()
val d0 = enumValueOf<Color>("GREEN")
val d1 = Color.valueOf("GREEN")
}
}
fun todo() {
TODO()
}
class SomeClass1 {}
fun fnClassRef() {
val x = SomeClass1::class
}
fun equalityTests(notNullPrimitive: Int, nullablePrimitive: Int?, notNullReftype: String, nullableReftype: String?) {
val b1 = notNullPrimitive == notNullPrimitive
val b2 = notNullPrimitive == nullablePrimitive
val b3 = nullablePrimitive == nullablePrimitive
val b4 = notNullReftype == notNullReftype
val b5 = notNullReftype == nullableReftype
val b6 = nullableReftype == nullableReftype
val b7 = notNullPrimitive != notNullPrimitive
val b8 = notNullPrimitive != nullablePrimitive
val b9 = nullablePrimitive != nullablePrimitive
val b10 = notNullReftype != notNullReftype
val b11 = notNullReftype != nullableReftype
val b12 = nullableReftype != nullableReftype
val b13 = notNullPrimitive == null
val b14 = nullablePrimitive == null
val b15 = notNullReftype == null
val b16 = nullableReftype == null
val b17 = notNullPrimitive != null
val b18 = nullablePrimitive != null
val b19 = notNullReftype != null
val b20 = nullableReftype != null
}
fun mulOperators(x: Int, y: Int,
byx: Byte, byy: Byte,
sx: Short, sy: Short,
lx: Long, ly: Long,
dx: Double, dy: Double,
fx: Float, fy: Float) {
val i = x * y
val b = byx * byy
val l = lx * ly
val d = dx * dy
val f = fx * fy
}
fun inPlaceOperators() {
var updated = 0
updated += 1
updated -= 1
updated *= 1
updated /= 1
updated %= 1
}
inline fun <reified T : Enum<T>> getEnumValues() = enumValues<T>()
fun callToEnumValues() {
enumValues<Color>()
getEnumValues<Color>()
}
fun unaryExprs(i: Int, d: Double, b: Byte, s: Short, l: Long, f: Float) {
-i
+i
-d
+d
var i0 = 1
val i1 = 1
i0++
++i0
i0--
--i0
i0.inc()
i0.dec()
i1.inc()
i1.dec()
i.inv()
-b
+b
var b0: Byte = 1
val b1: Byte = 1
b0++
++b0
b0--
--b0
b0.inc()
b0.dec()
b1.inc()
b1.dec()
b.inv()
-s
+s
var s0: Short = 1
val s1: Short = 1
s0++
++s0
s0--
--s0
s0.inc()
s0.dec()
s1.inc()
s1.dec()
s.inv()
-l
+l
var l0: Long = 1
val l1: Long = 1
l0++
++l0
l0--
--l0
l0.inc()
l0.dec()
l1.inc()
l1.dec()
l.inv()
+f
-f
}
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Byte.dec in java.lang.Byte %
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Byte.inc in java.lang.Byte %
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Byte.toInt in java.lang.Byte %
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Int.dec in java.lang.Integer %
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Int.inc in java.lang.Integer %
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Int.rangeTo in java.lang.Integer %
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Short.inc in java.lang.Short %
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Short.dec in java.lang.Short %
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Short.toInt in java.lang.Short %
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Long.dec in java.lang.Long %
// Diagnostic Matches: % Couldn't find a Java equivalent function to kotlin.Long.inc in java.lang.Long %
| mit | 02cdb3eef5f35e939fb54a30e80f4aac | 21.787709 | 117 | 0.548051 | 3.190458 | false | false | false | false |
flesire/ontrack | ontrack-repository-support/src/main/java/net/nemerosa/ontrack/repository/support/store/EntityDataStoreFilter.kt | 1 | 1931 | package net.nemerosa.ontrack.repository.support.store
import net.nemerosa.ontrack.model.structure.ProjectEntity
import java.time.LocalDateTime
class EntityDataStoreFilter
@JvmOverloads
constructor(
val entity: ProjectEntity? = null,
val category: String? = null,
val name: String? = null,
val group: String? = null,
val beforeTime: LocalDateTime? = null,
val offset: Int = 0,
val count: Int = 20
) {
fun withEntity(entity: ProjectEntity?) = EntityDataStoreFilter(
entity,
category,
name,
group,
beforeTime,
offset,
count
)
fun withCategory(category: String?) = EntityDataStoreFilter(
entity,
category,
name,
group,
beforeTime,
offset,
count
)
fun withName(name: String?) = EntityDataStoreFilter(
entity,
category,
name,
group,
beforeTime,
offset,
count
)
fun withGroup(group: String?) = EntityDataStoreFilter(
entity,
category,
name,
group,
beforeTime,
offset,
count
)
fun withBeforeTime(beforeTime: LocalDateTime?) = EntityDataStoreFilter(
entity,
category,
name,
group,
beforeTime,
offset,
count
)
fun withOffset(offset: Int) = EntityDataStoreFilter(
entity,
category,
name,
group,
beforeTime,
offset,
count
)
fun withCount(count: Int) = EntityDataStoreFilter(
entity,
category,
name,
group,
beforeTime,
offset,
count
)
} | mit | 92d115942708dec897d6840a79dd5920 | 21.465116 | 75 | 0.494045 | 5.597101 | false | false | false | false |
kindraywind/Recorda | app/src/main/kotlin/com/octtoplus/proj/recorda/JSONBuilder.kt | 1 | 4258 | package com.octtoplus.proj.recorda
import org.json.JSONObject
class JSON private constructor() {
companion object {
fun create(block: JSONBuilder.() -> Unit) = JSONBuilder(block).build()
}
class JSONBuilder private constructor() {
constructor(init: JSONBuilder.() -> Unit) : this() {
init()
}
var addedCount: Int? = null
var beforeText: CharSequence? = null
var className: CharSequence? = null
var contentDescription: CharSequence? = null
var currentItemIndex: Int? = null
var eventText: CharSequence? = null
var eventTime: Long? = null
var eventType: CharSequence? = null
var resourceIdName: CharSequence? = null
var fromIndex: Int? = null
var isChecked: Boolean? = null
var isEnable: Boolean? = null
var isPassword: Boolean? = null
var itemCount: Int? = null
var packageName: CharSequence? = null
var scrollX: Int? = null
var scrollY: Int? = null
var toIndex: Int? = null
var removedCount: Int? = null
var resource_id: CharSequence? = null
fun className(block: JSONBuilder.() -> CharSequence) = apply { className = block() }
fun contentDescription(block: JSONBuilder.() -> CharSequence) = apply { contentDescription = block() }
fun eventTime(block: JSONBuilder.() -> Long) = apply { eventTime = block() }
fun eventType(block: JSONBuilder.() -> CharSequence) = apply { eventType = block() }
fun resourceIdName(block: JSONBuilder.() -> CharSequence) = apply { resourceIdName = block() }
fun build() = JSONObject().build(this)
/*
put("className", event.className)
put("contentDescription", event.contentDescription)
put("eventText", getEventText(event))
put("eventTime", java.lang.Long.toString(event.eventTime))
put("eventType", AccessibilityEvent.eventTypeToString(event.eventType))
put("fromIndex", event.fromIndex)
put("isChecked", event.isChecked)
put("isEnable", event.isEnabled)
put("isPassword", event.isPassword)
put("itemCount", event.itemCount)
put("packageName", event.packageName)
put("toIndex", event.toIndex)
put("resource-id", event.source.viewIdResourceName)
*/
}
}
fun JSONObject.build(builder: JSON.JSONBuilder): JSONObject {
apply {
builder.addedCount?.let {
put("addedCount", it.toString())
}
builder.beforeText?.let {
put("beforeText", it.toString())
}
builder.className?.let {
put("className", it.toString())
}
builder.contentDescription?.let {
put("contentDescription", it.toString())
}
builder.currentItemIndex?.let {
put("currentItemIndex", it.toString())
}
builder.eventText?.let {
put("eventText", it.toString())
}
builder.eventTime?.let {
put("eventTime", it.toString())
}
builder.eventType?.let {
put("eventType", it.toString())
}
builder.resourceIdName?.let {
put("resource-id", it.toString())
}
builder.fromIndex?.let {
put("fromIndex", it.toString())
}
builder.isChecked?.let {
put("isChecked", it.toString())
}
builder.isEnable?.let {
put("isEnable", it.toString())
}
builder.isPassword?.let {
put("isPassword", it.toString())
}
builder.itemCount?.let {
put("itemCount", it.toString())
}
builder.packageName?.let {
put("packageName", it.toString())
}
builder.scrollX?.let {
put("scrollX", it.toString())
}
builder.scrollY.let {
put("scrollY", it.toString())
}
builder.toIndex?.let{
put("toIndex", it.toString())
}
builder.removedCount?.let {
put("removedCount", it.toString())
}
builder.resource_id?.let {
put("resource-id", it.toString())
}
}
return this
} | mit | 209a1ae7b94b4ec4550c9251501bc11b | 31.022556 | 110 | 0.564819 | 4.736374 | false | false | false | false |
paplorinc/intellij-community | plugins/gradle/src/org/jetbrains/plugins/gradle/statistics/GradleSettingsCollector.kt | 2 | 3404 | // 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.plugins.gradle.statistics
import com.intellij.internal.statistic.beans.ConvertUsagesUtil
import com.intellij.internal.statistic.beans.UsageDescriptor
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.internal.statistic.utils.getBooleanUsage
import com.intellij.internal.statistic.utils.getEnumUsage
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.SdkType
import org.jetbrains.plugins.gradle.service.settings.GradleSettingsService
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
import org.jetbrains.plugins.gradle.settings.GradleSettings
class GradleSettingsCollector : ProjectUsagesCollector() {
override fun getGroupId() = "build.gradle.state"
override fun getUsages(project: Project): Set<UsageDescriptor> {
val gradleSettings = GradleSettings.getInstance(project)
val projectsSettings = gradleSettings.linkedProjectsSettings
if (projectsSettings.isEmpty()) {
return emptySet()
}
val usages = mutableSetOf<UsageDescriptor>()
// global settings
usages.add(getBooleanUsage("offlineWork", gradleSettings.isOfflineWork))
usages.add(getBooleanUsage("showSelectiveImportDialogOnInitialImport", gradleSettings.showSelectiveImportDialogOnInitialImport()))
val settingsService = GradleSettingsService.getInstance(project)
// project settings
for (setting in gradleSettings.linkedProjectsSettings) {
val projectPath = setting.externalProjectPath
usages.add(getYesNoUsage("isCompositeBuilds", setting.compositeBuild != null))
usages.add(getEnumUsage("distributionType", setting.distributionType))
usages.add(getEnumUsage("storeProjectFilesExternally", setting.storeProjectFilesExternally))
usages.add(getBooleanUsage("disableWrapperSourceDistributionNotification", setting.isDisableWrapperSourceDistributionNotification))
usages.add(getBooleanUsage("createModulePerSourceSet", setting.isResolveModulePerSourceSet))
usages.add(UsageDescriptor("gradleJvm." + ConvertUsagesUtil.escapeDescriptorName(getGradleJvmName(setting, project) ?: "empty"), 1))
val gradleVersion = setting.resolveGradleVersion()
if(gradleVersion.isSnapshot) {
usages.add(UsageDescriptor("gradleVersion." + gradleVersion.baseVersion.version + ".SNAPSHOT", 1))
} else {
usages.add(UsageDescriptor("gradleVersion." + gradleVersion.version, 1))
}
usages.add(getBooleanUsage("delegateBuildRun", settingsService.isDelegatedBuildEnabled(projectPath)))
usages.add(getEnumUsage("preferredTestRunner", settingsService.getTestRunner(projectPath)))
}
return usages
}
private fun getGradleJvmName(setting: GradleProjectSettings, project: Project): String? {
val jdk = ExternalSystemJdkUtil.getJdk(project, setting.gradleJvm)
val sdkType = jdk?.sdkType
return if (sdkType is SdkType) {
sdkType.suggestSdkName(null, jdk.homePath)
}
else setting.gradleJvm
}
private fun getYesNoUsage(key: String, value: Boolean): UsageDescriptor {
return UsageDescriptor(key + if (value) ".yes" else ".no", 1)
}
}
| apache-2.0 | 9c23cd1e728599072c9b322a151ce0e4 | 51.369231 | 140 | 0.787603 | 5.050445 | false | false | false | false |
noboru-i/SlideViewer | modules/infra/src/main/java/hm/orz/chaos114/android/slideviewer/infra/repository/TalkRepository.kt | 1 | 3390 | package hm.orz.chaos114.android.slideviewer.infra.repository
import android.content.Context
import com.j256.ormlite.dao.Dao
import hm.orz.chaos114.android.slideviewer.infra.dao.TalkDao
import hm.orz.chaos114.android.slideviewer.infra.model.Slide
import hm.orz.chaos114.android.slideviewer.infra.model.Talk
import hm.orz.chaos114.android.slideviewer.infra.model.TalkMetaData
import hm.orz.chaos114.android.slideviewer.infra.util.DatabaseHelper
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.MaybeOnSubscribe
import java.io.IOException
import java.sql.SQLException
import java.util.*
class TalkRepository(private val mContext: Context) {
fun findByUrl(url: String): Maybe<Talk> {
return Maybe.create(MaybeOnSubscribe { emitter ->
val helper = DatabaseHelper(mContext)
try {
val dao = helper.getDao<Dao<Talk, Int>, Talk>(Talk::class.java)
val talks = dao.queryForEq("url", url)
if (talks.isEmpty()) {
emitter.onComplete()
return@MaybeOnSubscribe
}
val talk = talks[0]
setTalkInfo(talk)
emitter.onSuccess(talk)
emitter.onComplete()
} catch (e: SQLException) {
throw RuntimeException(e)
} finally {
helper.close()
}
})
}
fun list(): Flowable<List<Talk>> {
return Flowable.create({ emitter ->
val helper = DatabaseHelper(mContext)
try {
val dao = helper.getDao<Dao<Talk, Int>, Talk>(Talk::class.java)
val talks = dao.query(dao.queryBuilder().orderBy("id", false).limit(50L).prepare())
for (talk in talks) {
setTalkInfo(talk)
}
emitter.onNext(talks)
} catch (e: SQLException) {
throw RuntimeException(e)
} finally {
helper.close()
}
}, BackpressureStrategy.LATEST)
}
fun count(): Long {
val helper = DatabaseHelper(mContext)
try {
val dao = helper.getDao<Dao<Talk, Int>, Talk>(Talk::class.java)
return dao.countOf()
} catch (e: SQLException) {
throw RuntimeException(e)
} finally {
helper.close()
}
}
fun deleteByUrl(url: String) {
val dao = TalkDao(mContext)
dao.deleteByUrl(url)
}
fun findMetaData(talk: Talk): TalkMetaData? {
val dao = TalkDao(mContext)
return dao.findMetaData(talk)
}
fun saveIfNotExists(talk: Talk, slides: List<Slide>, talkMetaData: TalkMetaData) {
val dao = TalkDao(mContext)
dao.saveIfNotExists(talk, slides, talkMetaData)
}
private fun setTalkInfo(talk: Talk) {
val iterator = talk.slideCollection!!.closeableIterator()
try {
val slides = ArrayList<Slide>()
while (iterator.hasNext()) {
val slide = iterator.next()
slides.add(slide)
}
talk.slides = slides
} finally {
try {
iterator.close()
} catch (e: IOException) {
// no-op
}
}
}
}
| mit | 7a39202a54690357ac50acf6af93f08b | 30.981132 | 99 | 0.567552 | 4.466403 | false | false | false | false |
imageprocessor/cv4j | app/src/main/java/com/cv4j/app/fragment/TemplateMatchFragment.kt | 1 | 2588 | package com.cv4j.app.fragment
import android.content.res.Resources
import android.graphics.*
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.cv4j.app.R
import com.cv4j.app.app.BaseFragment
import com.cv4j.core.datamodel.CV4JImage
import com.cv4j.core.datamodel.Point
import com.cv4j.core.tpl.TemplateMatch
import com.cv4j.image.util.Tools
import kotlinx.android.synthetic.main.fragment_template_match.*
/**
*
* @FileName:
* com.cv4j.app.fragment.TemplateMatchFragment
* @author: Tony Shen
* @date: 2020-05-04 13:12
* @version: V1.0 <描述当前版本功能>
*/
class TemplateMatchFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View = inflater.inflate(R.layout.fragment_template_match, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initData()
}
private fun initData() {
val res: Resources = resources
val bitmap1 = BitmapFactory.decodeResource(res, R.drawable.test_tpl_target)
target_image.setImageBitmap(bitmap1)
val bitmap2 = BitmapFactory.decodeResource(res, R.drawable.tpl)
template_image.setImageBitmap(bitmap2)
val targetCV4J = CV4JImage(bitmap1)
val targetImageProcessor = targetCV4J.convert2Gray().processor
val templateCV4J = CV4JImage(bitmap2)
val templateProcessor = templateCV4J.convert2Gray().processor
val match = TemplateMatch()
val floatProcessor = match.match(targetImageProcessor, templateProcessor, TemplateMatch.TM_CCORR_NORMED)
val points = Tools.getMinMaxLoc(floatProcessor.gray, floatProcessor.width, floatProcessor.height)
var resultPoint: Point? = null
if (points != null) {
resultPoint = points[0]
val resultBitmap = bitmap1.copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas(resultBitmap)
val rect = Rect()
val sx = resultPoint.x + templateProcessor.width / 2
val sy = resultPoint.y - templateProcessor.height / 2
rect[sx, sy, sx + templateProcessor.width] = sy + templateProcessor.height
val paint = Paint()
paint.style = Paint.Style.STROKE
paint.strokeWidth = 4.0.toFloat()
paint.color = Color.RED
canvas.drawRect(rect, paint)
result.setImageBitmap(resultBitmap)
}
}
} | apache-2.0 | aeefdeb475fd0dab20d16a057ce15cdc | 38.584615 | 184 | 0.695568 | 4.01875 | false | false | false | false |
paplorinc/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/FieldExpression.kt | 7 | 2227 | // 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 com.intellij.lang.java.actions
import com.intellij.codeInsight.completion.JavaLookupElementBuilder
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.template.Expression
import com.intellij.codeInsight.template.ExpressionContext
import com.intellij.codeInsight.template.Result
import com.intellij.codeInsight.template.TextResult
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.util.createSmartPointer
import com.intellij.ui.LayeredIcon
import javax.swing.Icon
internal class FieldExpression(
project: Project,
target: PsiClass,
private val fieldName: String,
private val typeText: () -> String
) : Expression() {
companion object {
private val newFieldIcon: Icon = LayeredIcon.create(AllIcons.Nodes.Field, AllIcons.Actions.New)
}
private val myClassPointer = target.createSmartPointer(project)
private val myFactory = JavaPsiFacade.getElementFactory(project)
override fun calculateResult(context: ExpressionContext): Result? = TextResult(fieldName)
override fun calculateQuickResult(context: ExpressionContext): Result? = calculateResult(context)
override fun calculateLookupItems(context: ExpressionContext): Array<LookupElement> {
val psiClass = myClassPointer.element ?: return LookupElement.EMPTY_ARRAY
val userType = myFactory.createTypeFromText(typeText(), psiClass)
val result = LinkedHashSet<LookupElement>()
if (psiClass.findFieldByName(fieldName, false) == null) {
result += LookupElementBuilder.create(fieldName).withIcon(newFieldIcon).withTypeText(userType.presentableText)
}
for (field in psiClass.fields) {
val fieldType = field.type
if (userType == fieldType) {
result += JavaLookupElementBuilder.forField(field).withTypeText(fieldType.presentableText)
}
}
return if (result.size < 2) LookupElement.EMPTY_ARRAY else result.toTypedArray()
}
}
| apache-2.0 | e89f629de0544e2dcc2a8e493ce9da0e | 40.240741 | 140 | 0.789852 | 4.678571 | false | false | false | false |
google/intellij-community | python/python-psi-impl/src/com/jetbrains/python/psi/types/PyTypedDictType.kt | 6 | 13847 | // Copyright 2000-2019 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.jetbrains.python.psi.types
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.codeInsight.typing.TDFields
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.impl.PyPsiUtils
import java.util.*
class PyTypedDictType @JvmOverloads constructor(private val name: String,
val fields: LinkedHashMap<String, FieldTypeAndTotality>,
private val inferred: Boolean,
private val dictClass: PyClass,
private val definitionLevel: DefinitionLevel,
private val ancestors: List<PyTypedDictType>,
private val declaration: PyQualifiedNameOwner? = null) : PyClassTypeImpl(dictClass,
definitionLevel != DefinitionLevel.INSTANCE), PyCollectionType {
override fun getElementTypes(): List<PyType?> {
return listOf(if (!inferred || fields.isNotEmpty()) PyBuiltinCache.getInstance(dictClass).strType else null, getValuesType())
}
override fun getIteratedItemType(): PyType? {
return PyBuiltinCache.getInstance(dictClass).strType
}
private fun getValuesType(): PyType? {
return PyUnionType.union(fields.map { it.value.type })
}
fun getElementType(key: String): PyType? {
return fields[key]?.type
}
override fun getCallType(context: TypeEvalContext, callSite: PyCallSiteExpression): PyType? {
if (definitionLevel == DefinitionLevel.NEW_TYPE) {
return toInstance()
}
return null
}
override fun isDefinition(): Boolean {
return definitionLevel == DefinitionLevel.NEW_TYPE
}
override fun toInstance(): PyClassType {
return if (definitionLevel == DefinitionLevel.NEW_TYPE)
PyTypedDictType(name, fields, inferred, dictClass,
DefinitionLevel.INSTANCE, ancestors,
declaration)
else
this
}
override fun toClass(): PyClassLikeType {
return if (definitionLevel == DefinitionLevel.INSTANCE)
PyTypedDictType(name, fields, inferred, dictClass,
DefinitionLevel.NEW_TYPE, ancestors,
declaration)
else
this
}
override fun getName(): String {
return name
}
override fun isBuiltin(): Boolean {
return inferred // if TD is inferred then it's a dict with str-only keys
}
override fun isCallable(): Boolean {
return definitionLevel != DefinitionLevel.INSTANCE
}
override fun getParameters(context: TypeEvalContext): List<PyCallableParameter>? {
return if (isCallable)
if (fields.isEmpty()) emptyList()
else {
val elementGenerator = PyElementGenerator.getInstance(dictClass.project)
val singleStarParameter = PyCallableParameterImpl.psi(elementGenerator.createSingleStarParameter())
val ellipsis = elementGenerator.createEllipsis()
listOf(singleStarParameter) + fields.map {
if (it.value.isRequired) PyCallableParameterImpl.nonPsi(it.key, it.value.type)
else PyCallableParameterImpl.nonPsi(it.key, it.value.type, ellipsis)
}
}
else null
}
fun getKeysToValueTypes(): Map<String, PyType?> {
return fields.mapValues { it.value.type }
}
fun getKeysToValuesWithTypes(): Map<String, Pair<PyExpression?, PyType?>> {
return fields.mapValues { Pair(it.value.value, it.value.type) }
}
override fun toString(): String {
return "PyTypedDictType: $name"
}
override fun equals(other: Any?): Boolean {
if (other === this) return true
if (other == null || javaClass != other.javaClass) return false
val otherTypedDict = other as? PyTypedDictType ?: return false
return name == otherTypedDict.name
&& fields == otherTypedDict.fields
&& inferred == otherTypedDict.inferred
&& definitionLevel == otherTypedDict.definitionLevel
&& ancestors == otherTypedDict.ancestors
&& declaration == otherTypedDict.declaration
}
override fun hashCode(): Int {
return Objects.hash(super.hashCode(), name, fields, inferred, definitionLevel, ancestors, declaration)
}
enum class DefinitionLevel {
NEW_TYPE,
INSTANCE
}
/**
* Checks whether this is an actual TypedDict type or [PyDictLiteralExpression] with all str keys
*/
fun isInferred(): Boolean {
return inferred
}
override fun getDeclarationElement(): PyQualifiedNameOwner = declaration ?: super<PyClassTypeImpl>.getDeclarationElement()
class FieldTypeAndTotality @JvmOverloads constructor(val value: PyExpression?, val type: PyType?, val isRequired: Boolean = true)
companion object {
const val TYPED_DICT_NAME_PARAMETER = "name"
const val TYPED_DICT_FIELDS_PARAMETER = "fields"
const val TYPED_DICT_TOTAL_PARAMETER = "total"
fun createFromKeysToValueTypes(anchor: PsiElement,
keysToValueTypes: Map<String, Pair<PyExpression?, PyType?>>): PyTypedDictType? {
val dict = PyBuiltinCache.getInstance(anchor).dictType?.pyClass
return if (dict != null) {
val fields = TDFields(keysToValueTypes.entries.associate {
it.key to FieldTypeAndTotality(it.value.first, it.value.second)
})
PyTypedDictType("TypedDict", fields, true, dict, DefinitionLevel.INSTANCE, emptyList())
}
else null
}
/**
* [actual] matches [expected] if:
* * all required keys from [expected] are present in [actual]
* * all keys from [actual] are present in [expected]
* * each key has the same value type in [expected] and [actual]
*/
fun checkTypes(expected: PyType,
actual: PyTypedDictType,
context: TypeEvalContext,
value: PyExpression?): TypeCheckingResult? {
if (!actual.isInferred()) {
val match = checkStructuralCompatibility(expected, actual, context)
if (match != null) {
return match
}
}
if (expected !is PyTypedDictType) return null
val mandatoryArguments = expected.fields.filterValues { it.isRequired }.mapValues { Pair(it.value.value, it.value.type) }
val actualArguments = actual.getKeysToValuesWithTypes()
val expectedArguments = expected.getKeysToValuesWithTypes()
return match(mandatoryArguments, expectedArguments, actualArguments, context, value, expected.name)
}
private fun match(mandatoryArguments: Map<String, Pair<PyExpression?, PyType?>>,
expectedArguments: Map<String, Pair<PyExpression?, PyType?>>,
actualArguments: Map<String, Pair<PyExpression?, PyType?>>,
context: TypeEvalContext,
actualTypedDict: PyExpression?,
expectedTypedDictName: String): TypeCheckingResult {
val valueTypeErrors = mutableListOf<ValueTypeError>()
val missingKeys = mutableListOf<MissingKeysError>()
val extraKeys = mutableListOf<ExtraKeyError>()
var match = true
val containedExpression = PyPsiUtils.flattenParens(
if (actualTypedDict is PyKeywordArgument) actualTypedDict.valueExpression else actualTypedDict)
val typedDictInstanceCreation = containedExpression is PyDictLiteralExpression ||
containedExpression is PyCallExpression && containedExpression.callee?.textMatches(
PyNames.DICT) ?: false
actualArguments.forEach {
val actualValue = it.value.first
val key = it.key
if (!expectedArguments.containsKey(key)) {
if (typedDictInstanceCreation) {
val extraKeyToHighlight = PsiTreeUtil.getParentOfType(actualValue, PyKeyValueExpression::class.java)
?: PsiTreeUtil.getParentOfType(actualValue, PyKeywordArgument::class.java)
?: actualValue
extraKeys.add(ExtraKeyError(extraKeyToHighlight, expectedTypedDictName, key))
match = false
}
else {
return TypeCheckingResult(false, emptyList(), emptyList(), emptyList())
}
}
val expectedType = expectedArguments[key]?.second
val actualType = it.value.second
if (expectedType is PyTypedDictType && actualType is PyTypedDictType) {
val res = checkTypes(expectedType, actualType, context, actualValue)
if (res != null && !res.match) {
val (innerMatch, innerValueTypeErrors, innerMissingKeys, innerExtraKeys) = res
if (typedDictInstanceCreation) {
if (!innerMatch && innerExtraKeys.isEmpty() && innerMissingKeys.isEmpty() && innerValueTypeErrors.isEmpty()) {
match = false
valueTypeErrors.add(ValueTypeError(actualValue, expectedType,
actualType)) // inner TypedDict didn't match, but it's not a dict definition
}
match = false
valueTypeErrors.addAll(innerValueTypeErrors)
extraKeys.addAll(innerExtraKeys)
missingKeys.addAll(innerMissingKeys)
}
else if (!innerMatch) {
return TypeCheckingResult(false, emptyList(), emptyList(), emptyList())
}
}
}
val matchResult: Boolean = strictUnionMatch(
expectedType,
if (actualValue != null) PyLiteralType.promoteToLiteral(actualValue, expectedType, context, null) ?: context.getType(actualValue)
else it.value.second,
context
)
if (!matchResult && (expectedType !is PyTypedDictType || actualType !is PyTypedDictType)) {
if (typedDictInstanceCreation) {
valueTypeErrors.add(
ValueTypeError(actualValue, expectedType, it.value.second))
match = false
}
else {
return TypeCheckingResult(false, emptyList(), emptyList(), emptyList())
}
}
}
if (!actualArguments.keys.containsAll(mandatoryArguments.keys)) {
if (typedDictInstanceCreation) {
missingKeys.add(MissingKeysError(actualTypedDict, expectedTypedDictName, mandatoryArguments.keys.filter {
!actualArguments.containsKey(it)
}))
match = false
}
else {
return TypeCheckingResult(false, emptyList(), emptyList(), emptyList())
}
}
return if (typedDictInstanceCreation) TypeCheckingResult(match, valueTypeErrors, missingKeys, extraKeys)
else TypeCheckingResult(true, emptyList(), emptyList(), emptyList())
}
private fun strictUnionMatch(expected: PyType?, actual: PyType?, context: TypeEvalContext): Boolean {
return PyTypeUtil.toStream(actual).allMatch { type -> PyTypeChecker.match(expected, type, context) }
}
/**
* Rules for type-checking TypedDicts are described in PEP-589
* @see <a href=https://www.python.org/dev/peps/pep-0589/#type-consistency>PEP-589</a>
*/
fun checkStructuralCompatibility(expected: PyType?,
actual: PyTypedDictType,
context: TypeEvalContext): TypeCheckingResult? {
if (expected is PyCollectionType && PyTypingTypeProvider.MAPPING == expected.classQName) {
val builtinCache = PyBuiltinCache.getInstance(actual.dictClass)
val elementTypes = expected.elementTypes
return TypeCheckingResult(elementTypes.size == 2
&& builtinCache.strType == elementTypes[0]
&& (elementTypes[1] == null || PyNames.OBJECT == elementTypes[1].name), emptyList(),
emptyList(), emptyList())
}
if (expected !is PyTypedDictType) return null
expected.fields.forEach {
val expectedTypeAndTotality = it.value
val actualTypeAndTotality = actual.fields[it.key]
if (actualTypeAndTotality == null
|| !strictUnionMatch(expectedTypeAndTotality.type, actualTypeAndTotality.type, context)
|| !strictUnionMatch(actualTypeAndTotality.type, expectedTypeAndTotality.type, context)
|| expectedTypeAndTotality.isRequired.xor(actualTypeAndTotality.isRequired)) {
return TypeCheckingResult(false, emptyList(), emptyList(), emptyList())
}
if (!actual.fields.containsKey(it.key)) {
return TypeCheckingResult(false, emptyList(), emptyList(), emptyList())
}
}
return TypeCheckingResult(true, emptyList(), emptyList(), emptyList())
}
}
data class MissingKeysError(val actualExpression: PyExpression?, val expectedTypedDictName: String, val missingKeys: List<String>)
data class ExtraKeyError(val actualExpression: PyExpression?, val expectedTypedDictName: String, val key: String)
data class ValueTypeError(val actualExpression: PyExpression?, val expectedType: PyType?, val actualType: PyType?)
data class TypeCheckingResult(val match: Boolean,
val valueTypeErrors: List<ValueTypeError>,
val missingKeys: List<MissingKeysError>,
val extraKeys: List<ExtraKeyError>)
}
| apache-2.0 | 59c92d75fd822bcf4d199ed188277caa | 42.003106 | 185 | 0.641872 | 5.455871 | false | false | false | false |
google/intellij-community | plugins/kotlin/gradle/gradle-java/tests/test/org/jetbrains/kotlin/idea/codeInsight/gradle/KotlinGradlePluginVersions.kt | 1 | 734 | // 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.kotlin.idea.codeInsight.gradle
import org.jetbrains.kotlin.tooling.core.KotlinToolingVersion
import org.jetbrains.kotlin.tooling.core.isStable
object KotlinGradlePluginVersions {
val V_1_4_32 = KotlinToolingVersion(1, 4, 32, null)
val V_1_5_32 = KotlinToolingVersion(1, 5, 32, null)
val V_1_6_21 = KotlinToolingVersion(1, 6, 21, null)
val latest = KotlinToolingVersion("1.8.0-dev-2023")
val all = listOf(
V_1_4_32,
V_1_5_32,
V_1_6_21,
latest
)
val allStable = all.filter { it.isStable }
val lastStable = allStable.max()
}
| apache-2.0 | 71d2a8ae2a51f77e1061536baa74a46d | 30.913043 | 120 | 0.688011 | 3.382488 | false | true | false | false |
aquatir/remember_java_api | code-sample-kotlin/code-sample-kotlin-basics/src/main/kotlin/codesample/kotlin/sandbox/classes/Classes.kt | 1 | 2512 | package codesample.kotlin.sandbox.classes
typealias StringSet = Set<String>
fun printSetOfString(setOfStrings: Set<String>) {
setOfStrings.forEach { println(it) }
}
/** Everything is Kotlin is final by default, so we have to declare class as open for inheritance */
open class TheSuper(val name: String) {
constructor() : this("default_name")
/* The same goes for methods */
open fun printName() {
println(name)
}
class InnerStatic {
private val innerStaticName: String = "Static Blah-blah"
fun printInnerStatic() {
println(innerStaticName)
}
}
inner class Inner {
private val innerName: String = "Inner Blah-blah"
fun printInner() {
println(innerName)
}
}
}
class TheSub : TheSuper(), Runnnnable {
override var myVar: String = "initialized!"
override fun printName() {
println("The sub calls for you, $name")
}
override fun run() {
println("TheSub si running!")
}
}
class Other(str: String) {
var str: String = str
get() = field.toUpperCase()
set(value) { field = value.toLowerCase() }
}
interface Runnnnable {
fun run()
var myVar: String // Kotlin properties may also be defined and initialized in subclasses
}
// Properties not defined in primary constructor in data classes will not be in toString()
data class Person(val name: String) {
var age: Int = 0
constructor(name: String, age: Int): this(name) {
this.age = age
}
}
fun main(args: Array<String>) {
val innerStatic = TheSuper.InnerStatic()
innerStatic.printInnerStatic()
val inner = TheSuper().Inner()
inner.printInner()
val human: Runnnnable = object : Runnnnable {
override var myVar = "topkek"
override fun run() {
println("I RUN LIKE A HUMAN")
}
}
human.run()
/* Kotlin supports type aliases. It also supports passing named parameters to function */
val strSet: StringSet = setOf("one", "two", "three")
printSetOfString(setOfStrings = strSet)
val superb = TheSuper("My name is IVAAAAAn")
superb.printName()
val sub = TheSub()
sub.printName()
sub.run()
with(Other("aaa")) {
println(str)
str = "bbb"
println(str)
}
// Will only print name becase only primary constructor parameters for data class are printed in Kotlin
val person = Person("privet", 1)
println(person.toString())
}
| mit | f706f220a3b940a3ae5634cc270c3e01 | 22.476636 | 107 | 0.627389 | 4.038585 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/editor/stage/PresentationModeStage.kt | 2 | 8414 | package io.github.chrislo27.rhre3.editor.stage
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.utils.Align
import io.github.chrislo27.rhre3.RHRE3
import io.github.chrislo27.rhre3.editor.Editor
import io.github.chrislo27.rhre3.screen.EditorScreen
import io.github.chrislo27.rhre3.track.Remix
import io.github.chrislo27.rhre3.util.Swing
import io.github.chrislo27.toolboks.ui.*
import io.github.chrislo27.toolboks.util.gdxutils.drawRect
import io.github.chrislo27.toolboks.util.gdxutils.fillRect
import kotlin.math.max
import kotlin.properties.Delegates
class PresentationModeStage(val editor: Editor, val palette: UIPalette, parent: EditorStage, camera: OrthographicCamera)
: Stage<EditorScreen>(parent, camera) {
private val backgroundPane = ColourPane(this, this).apply {
this.location.set(0f, 0f, 1f, 1f)
}
private val remix: Remix
get() = editor.remix
private val themePalette: UIPalette = palette.copy(textColor = Color(palette.textColor))
private val infoTextPalette: UIPalette = palette.copy(textColor = Color(palette.textColor))
private val progressBar: UIElement<EditorScreen>
private val timeLabel: TextLabel<EditorScreen>
private val durationLabel: TextLabel<EditorScreen>
private val bpmLabel: TextLabel<EditorScreen>
private var progress = 0f
init {
// this.elements += backgroundPane
this.elements += ColourPane(this, this).apply {
this.colour.set(Editor.TRANSLUCENT_BLACK)
this.location.set(0f, 0f, 1f, 1f)
this.visible = false
}
val fontScale = 0.8f
this.elements += TextLabel(infoTextPalette, this, this).apply {
this.location.set(screenHeight = 0.125f, screenY = 0.0f)
this.textWrapping = false
this.isLocalizationKey = false
this.textAlign = Align.center
this.text = RHRE3.GITHUB_SHORTLINK
this.fontScaleMultiplier = fontScale
}
this.elements += TextLabel(infoTextPalette, this, this).apply {
this.location.set(screenHeight = 0.125f, screenY = 0.125f)
this.textWrapping = false
this.isLocalizationKey = false
this.textAlign = Align.center
this.text = "Made with the Rhythm Heaven Remix Editor, which is licensed under GPL-3.0"
this.fontScaleMultiplier = fontScale
}
val aboveText = 0.125f + 0.125f
progressBar = object : UIElement<EditorScreen>(this, this) {
override fun render(screen: EditorScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) {
val oldColor = batch.packedColor
batch.color = themePalette.textColor
val line = 3f
val lineX = line * Gdx.graphics.width / RHRE3.WIDTH
val lineY = line * Gdx.graphics.height / RHRE3.HEIGHT
batch.drawRect(location.realX, location.realY, location.realWidth, location.realHeight, lineX, lineY)
batch.fillRect(location.realX + lineX * 2,
location.realY + lineY * 2,
(location.realWidth - lineX * 4) * progress.coerceIn(0f, 1f),
location.realHeight - lineY * 4)
batch.packedColor = oldColor
}
}.apply {
this.location.set(screenX = 0.25f, screenY = aboveText + 0.05f, screenWidth = 0.5f, screenHeight = 0.15f)
}
this.elements += progressBar
timeLabel = TextLabel(themePalette, this, this).apply {
this.textWrapping = false
this.isLocalizationKey = false
this.textAlign = Align.right
this.text = "0:00"
this.location.set(screenX = 0f, screenY = progressBar.location.screenY,
screenWidth = progressBar.location.screenX - 0.0125f,
screenHeight = progressBar.location.screenHeight)
}
this.elements += timeLabel
durationLabel = TextLabel(themePalette, this, this).apply {
this.textWrapping = false
this.isLocalizationKey = false
this.textAlign = Align.left
this.text = "0:00"
this.location.set(screenX = progressBar.location.screenX + progressBar.location.screenWidth + 0.0125f,
screenY = progressBar.location.screenY,
screenHeight = progressBar.location.screenHeight)
this.location.set(screenWidth = 1f - (this.location.screenX))
}
this.elements += durationLabel
val gameDisplay = object : GameDisplayStage(editor, themePalette, this@PresentationModeStage,
[email protected]) {
override fun getFont(): BitmapFont {
return themePalette.font
}
}.apply {
[email protected]()
this.location.set(screenX = progressBar.location.screenX,
screenY = progressBar.location.screenY + progressBar.location.screenHeight + 0.0125f,
screenHeight = progressBar.location.screenHeight * 1.5f)
this.location.set(screenWidth = 1 / 3f)
this.updatePositions()
}
this.elements += gameDisplay
bpmLabel = object : TextLabel<EditorScreen>(themePalette, this, this) {
// override fun getFont(): BitmapFont {
// return editor.main.defaultBorderedFont
// }
}.apply {
this.textWrapping = false
this.isLocalizationKey = false
this.textAlign = Align.right
this.text = "X BPM"
this.fontScaleMultiplier = GameDisplayStage.FONT_SCALE
this.location.set(screenX = gameDisplay.location.screenX + gameDisplay.location.screenWidth,
screenY = gameDisplay.location.screenY,
screenHeight = gameDisplay.location.screenHeight)
this.location.set(
screenWidth = (progressBar.location.screenX + progressBar.location.screenWidth) - (this.location.screenX))
}
this.elements += bpmLabel
this.updatePositions()
}
private fun secondsToText(seconds: Int): String {
val sec = seconds % 60
return "${seconds / 60}:${if (sec < 10) "0" else ""}${max(0, sec)}"
}
private var timeSeconds: Int by Delegates.observable(0) { _, old, new ->
if (new != old) {
timeLabel.text = secondsToText(new)
}
}
private var durationSeconds: Int by Delegates.observable(0) { _, old, new ->
if (new != old) {
durationLabel.text = secondsToText(new)
}
}
private var bpm: Float by Delegates.observable(Float.NEGATIVE_INFINITY) { _, old, new ->
if (new != old) {
setBpmLabelText()
}
}
private var swing: Swing by Delegates.observable(Swing.STRAIGHT) { _, old, new ->
if (new != old) {
setBpmLabelText()
}
}
private fun setBpmLabelText() {
bpmLabel.text = (if (swing != Swing.STRAIGHT) "${swing.getNoteSymbol()} ${swing.getSwingName()}\n" else "") + "${String.format("%.1f", bpm)} BPM"
}
override fun render(screen: EditorScreen, batch: SpriteBatch, shapeRenderer: ShapeRenderer) {
backgroundPane.colour.set(screen.editor.theme.background)
backgroundPane.colour.a = 1f
themePalette.textColor.set(editor.theme.trackLine)
infoTextPalette.textColor.set(themePalette.textColor)
infoTextPalette.textColor.a = 0.75f
timeSeconds = remix.tempos.beatsToSeconds(remix.beat).toInt()
durationSeconds = remix.tempos.beatsToSeconds(remix.lastPoint).toInt()
bpm = remix.tempos.tempoAt(remix.beat)
swing = remix.tempos.swingAt(remix.beat)
progress = (remix.seconds / remix.tempos.beatsToSeconds(remix.lastPoint)).coerceIn(0f, 1f)
super.render(screen, batch, shapeRenderer)
}
} | gpl-3.0 | 5c8986fd4a96d3af024da5f037cd805b | 41.5 | 153 | 0.624198 | 4.538296 | false | false | false | false |
ahjsrhj/ShareToQRCode | app/src/main/java/cn/imrhj/sharetoqrcode/util/ImageUtils.kt | 1 | 1605 | package cn.imrhj.sharetoqrcode.util
import android.graphics.Bitmap
import android.media.Image
import android.net.Uri
import android.provider.MediaStore
import cn.imrhj.sharetoqrcode.App
import java.io.File
import java.io.FileOutputStream
/**
* Created by rhj on 2017/9/12.
*/
fun save(src: Bitmap, file: File): Boolean {
if (isEmptyBitmap(src) || !createOrExistsFile(file)) {
return false
}
var ret = false
FileOutputStream(file).use {
ret = src.compress(Bitmap.CompressFormat.JPEG, 100, it)
it.flush()
it.close()
}
return ret
}
fun file2bitmap(src: File): Bitmap? {
if (src.exists()) {
return MediaStore.Images.Media.getBitmap(App.instance().contentResolver, Uri.fromFile(src))
}
return null
}
fun isEmptyBitmap(src: Bitmap?): Boolean = src == null || src.width == 0 || src.height == 0
fun saveTmpBitmap(src: Bitmap): Boolean {
val file = File(App.instance().externalCacheDir, "${System.currentTimeMillis()}.jpg")
return save(src, file)
}
fun image2bitmap(image: Image): Bitmap {
val width = image.width
val height = image.height
val planes = image.planes
val buffer = planes[0].buffer
val pixelStride = planes[0].pixelStride
val rowStride = planes[0].rowStride
val rowPadding = rowStride - pixelStride * width;
var bitmap = Bitmap.createBitmap(width + rowPadding / pixelStride, height, Bitmap.Config.ARGB_8888)
bitmap.copyPixelsFromBuffer(buffer)
bitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height)
saveTmpBitmap(bitmap)
image.close()
return bitmap
} | apache-2.0 | 594f4e3b1def4fa81ed765f07d73bcbf | 26.689655 | 103 | 0.689097 | 3.723898 | false | false | false | false |
allotria/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/FileHistoryColorManager.kt | 2 | 1536 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.log.history
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.vcs.log.VcsLogDataPack
import com.intellij.vcs.log.history.FileHistoryPaths.filePaths
import com.intellij.vcs.log.ui.VcsLogColorManager
import com.intellij.vcs.log.ui.VcsLogColorManagerImpl
import com.intellij.vcsUtil.VcsFileUtil
import it.unimi.dsi.fastutil.objects.ObjectLinkedOpenCustomHashSet
import java.awt.Color
internal class FileHistoryColorManager(private val root: VirtualFile, private val path: FilePath) : VcsLogColorManager {
private var baseColorManager = VcsLogColorManagerImpl(setOf(path))
override fun getPathColor(path: FilePath): Color {
return baseColorManager.getPathColor(path)
}
fun update(pack: VcsLogDataPack) {
val pathsFromPack = pack.filePaths()
if (pathsFromPack.isEmpty()) {
baseColorManager = VcsLogColorManagerImpl(setOf(path))
}
else {
val newPaths = ObjectLinkedOpenCustomHashSet(baseColorManager.paths, FILE_PATH_HASHING_STRATEGY)
newPaths.retainAll(pathsFromPack)
newPaths.addAll(pathsFromPack)
baseColorManager = VcsLogColorManagerImpl(newPaths)
}
}
override fun getPaths(): Collection<FilePath> {
return baseColorManager.paths
}
override fun getLongName(path: FilePath): String {
return VcsFileUtil.relativePath(root, path)
}
}
| apache-2.0 | 3daf80f9d17567d7b9ed9bb575694f17 | 36.463415 | 140 | 0.78125 | 4.491228 | false | false | false | false |
allotria/intellij-community | plugins/git4idea/src/git4idea/branch/GitCreateBranchOperation.kt | 2 | 3859 | /*
* Copyright 2000-2017 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 git4idea.branch
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.openapi.vcs.VcsNotifier
import git4idea.GitNotificationIdsHolder.Companion.BRANCH_CREATE_ROLLBACK_ERROR
import git4idea.GitNotificationIdsHolder.Companion.BRANCH_CREATE_ROLLBACK_SUCCESS
import git4idea.commands.Git
import git4idea.commands.GitCompoundResult
import git4idea.i18n.GitBundle
import git4idea.repo.GitRepository
import git4idea.util.GitUIUtil.bold
import git4idea.util.GitUIUtil.code
import org.jetbrains.annotations.Nls
internal class GitCreateBranchOperation(
project: Project,
git: Git,
uiHandler: GitBranchUiHandler,
private val branchName: String,
private val startPoints: Map<GitRepository, String>,
private val force: Boolean) : GitBranchOperation(project, git, uiHandler, startPoints.keys) {
public override fun execute() {
var fatalErrorHappened = false
while (hasMoreRepositories() && !fatalErrorHappened) {
val repository = next()
val result = myGit.branchCreate(repository, branchName, startPoints[repository]!!, force)
if (result.success()) {
repository.update()
markSuccessful(repository)
}
else {
fatalError(GitBundle.message("create.branch.operation.could.not.create.new.branch", branchName), result.errorOutputAsJoinedString)
fatalErrorHappened = true
}
}
if (!fatalErrorHappened) {
notifySuccess()
updateRecentBranch()
}
}
override fun rollback() {
val repositories = successfulRepositories
val deleteResult = GitCompoundResult(myProject)
for (repository in repositories) {
deleteResult.append(repository, myGit.branchDelete(repository, branchName, false))
repository.update()
}
val vcsNotifier = VcsNotifier.getInstance(myProject)
if (deleteResult.totalSuccess()) {
vcsNotifier.notifySuccess(BRANCH_CREATE_ROLLBACK_SUCCESS,
GitBundle.message("create.branch.operation.rollback.successful"),
GitBundle.message("create.branch.operation.deleted.branch", branchName))
}
else {
vcsNotifier.notifyError(BRANCH_CREATE_ROLLBACK_ERROR,
GitBundle.message("create.branch.operation.error.during.rollback"),
deleteResult.errorOutputWithReposIndication,
true)
}
}
override fun getSuccessMessage(): String = GitBundle.message("create.branch.operation.branch.created",
bold(code(branchName)))
override fun getRollbackProposal(): String =
HtmlBuilder()
.append(GitBundle.message("create.branch.operation.however.the.branch.was.created.in.the.following.repositories",
successfulRepositories.size))
.br()
.appendRaw(successfulRepositoriesJoined())
.br()
.append(GitBundle.message("create.branch.operation.you.may.rollback.not.to.let.branches.diverge", branchName))
.toString()
override fun getOperationName(): @Nls String = GitBundle.message("create.branch.operation.name")
}
| apache-2.0 | 1349cbe0e847151d4c5f0eb05d95e062 | 38.377551 | 138 | 0.706141 | 4.594048 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-test/jvm/test/MultithreadingTest.kt | 1 | 3777 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
import kotlinx.coroutines.*
import kotlinx.coroutines.test.*
import kotlin.concurrent.*
import kotlin.coroutines.*
import kotlin.test.*
class MultithreadingTest {
@Test
fun incorrectlyCalledRunBlocking_doesNotHaveSameInterceptor() = runBlockingTest {
// this code is an error as a production test, please do not use this as an example
// this test exists to document this error condition, if it's possible to make this code work please update
val outerInterceptor = coroutineContext[ContinuationInterceptor]
// runBlocking always requires an argument to pass the context in tests
runBlocking {
assertNotSame(coroutineContext[ContinuationInterceptor], outerInterceptor)
}
}
@Test
fun testSingleThreadExecutor() = runBlocking {
val mainThread = Thread.currentThread()
Dispatchers.setMain(Dispatchers.Unconfined)
newSingleThreadContext("testSingleThread").use { threadPool ->
withContext(Dispatchers.Main) {
assertSame(mainThread, Thread.currentThread())
}
Dispatchers.setMain(threadPool)
withContext(Dispatchers.Main) {
assertNotSame(mainThread, Thread.currentThread())
}
assertSame(mainThread, Thread.currentThread())
withContext(Dispatchers.Main.immediate) {
assertNotSame(mainThread, Thread.currentThread())
}
assertSame(mainThread, Thread.currentThread())
Dispatchers.setMain(Dispatchers.Unconfined)
withContext(Dispatchers.Main.immediate) {
assertSame(mainThread, Thread.currentThread())
}
assertSame(mainThread, Thread.currentThread())
}
}
@Test
fun whenDispatchCalled_runsOnCurrentThread() {
val currentThread = Thread.currentThread()
val subject = TestCoroutineDispatcher()
val scope = TestCoroutineScope(subject)
val deferred = scope.async(Dispatchers.Default) {
withContext(subject) {
assertNotSame(currentThread, Thread.currentThread())
3
}
}
runBlocking {
// just to ensure the above code terminates
assertEquals(3, deferred.await())
}
}
@Test
fun whenAllDispatchersMocked_runsOnSameThread() {
val currentThread = Thread.currentThread()
val subject = TestCoroutineDispatcher()
val scope = TestCoroutineScope(subject)
val deferred = scope.async(subject) {
withContext(subject) {
assertSame(currentThread, Thread.currentThread())
3
}
}
runBlocking {
// just to ensure the above code terminates
assertEquals(3, deferred.await())
}
}
/** Tests that resuming the coroutine of [runTest] asynchronously in reasonable time succeeds. */
@Test
fun testResumingFromAnotherThread() = runTest {
suspendCancellableCoroutine<Unit> { cont ->
thread {
Thread.sleep(10)
cont.resume(Unit)
}
}
}
/** Tests that [StandardTestDispatcher] is confined to the thread that interacts with the scheduler. */
@Test
fun testStandardTestDispatcherIsConfined() = runTest {
val initialThread = Thread.currentThread()
withContext(Dispatchers.IO) {
val ioThread = Thread.currentThread()
assertNotSame(initialThread, ioThread)
}
assertEquals(initialThread, Thread.currentThread())
}
}
| apache-2.0 | cc76d5d6996354f250cf1edfc4925907 | 32.723214 | 115 | 0.628541 | 5.603858 | false | true | false | false |
leafclick/intellij-community | platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/SdkPopupFactoryImpl.kt | 1 | 10085 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.roots.ui.configuration
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.service
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkTypeId
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.ui.configuration.projectRoot.ProjectSdksModel
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.util.Condition
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiFile
import com.intellij.ui.AnActionButton
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.popup.list.ComboBoxPopup
import java.awt.Component
import java.awt.Point
import java.awt.Window
import java.util.function.Consumer
import javax.swing.JComponent
import javax.swing.JFrame
import javax.swing.JPanel
private data class SdkPopupBuilderImpl(
val project: Project? = null,
val projectSdksModel: ProjectSdksModel? = null,
val sdkListModelBuilder: SdkListModelBuilder? = null,
val sdkTypeFilter: Condition<SdkTypeId>? = null,
val sdkTypeCreateFilter: Condition<SdkTypeId>? = null,
val sdkFilter: Condition<Sdk>? = null,
val registerNewSdk : Boolean = false,
val updateProjectSdk : Boolean = false,
val updateSdkForVirtualFile: VirtualFile? = null,
val updateSdkForPsiFile: PsiFile? = null,
val onItemSelected: Consumer<SdkListItem>? = null,
val onSdkSelected: Consumer<Sdk>? = null,
val onPopupClosed: Runnable? = null
) : SdkPopupBuilder {
override fun registerNewSdk() = copy(registerNewSdk = true)
override fun updateProjectSdkFromSelection() = copy(updateProjectSdk = true)
override fun updateSdkForFile(file: PsiFile) = copy(updateSdkForPsiFile = file)
override fun updateSdkForFile(file: VirtualFile) = copy(updateSdkForVirtualFile = file)
override fun withProject(project: Project?) = copy(project = project)
override fun withProjectSdksModel(projectSdksModel: ProjectSdksModel) = copy(projectSdksModel = projectSdksModel)
override fun withSdkListModelBuilder(sdkListModelBuilder: SdkListModelBuilder) = copy(sdkListModelBuilder = sdkListModelBuilder)
override fun withSdkType(type: SdkTypeId) = withSdkTypeFilter(Condition { sdk -> sdk == type })
override fun withSdkTypeFilter(filter: Condition<SdkTypeId>) = copy(sdkTypeFilter = filter)
override fun withSdkTypeCreateFilter(filter: Condition<SdkTypeId>) = copy(sdkTypeCreateFilter = filter)
override fun withSdkFilter(filter: Condition<Sdk>) = copy(sdkFilter = filter)
override fun onItemSelected(onItemSelected: Consumer<SdkListItem>) = copy(onItemSelected = onItemSelected)
override fun onPopupClosed(onClosed: Runnable) = copy(onPopupClosed = onClosed)
override fun onSdkSelected(onSdkSelected: Consumer<Sdk>) = copy(onSdkSelected = onSdkSelected)
override fun buildPopup() = service<SdkPopupFactory>().createPopup(copy())
}
private interface SdkPopupListener {
fun onClosed()
/**
* Executed when a new item was created via a user action
* and added to the model, called after model is refreshed
*/
fun onNewItemAddedAndSelected(item: SdkListItem)
/**
* Executed when an existing selectable item was selected
* in the popup, it does mean no new items were created
* by a user
*/
fun onExistingItemSelected(item: SdkListItem)
}
internal class PlatformSdkPopupFactory : SdkPopupFactory {
override fun createBuilder(): SdkPopupBuilder = SdkPopupBuilderImpl()
override fun createPopup(builder: SdkPopupBuilder): SdkPopup = (builder as SdkPopupBuilderImpl).copy().run {
val (sdksModel, ownsModel) = if (projectSdksModel != null) {
projectSdksModel to false
}
else {
ProjectSdksModel() to true
}
val modelBuilder = if (sdkListModelBuilder != null) {
require(sdkTypeFilter == null) { "sdkListModelBuilder was set explicitly via " + ::withSdkListModelBuilder.name }
require(sdkTypeCreateFilter == null) { "sdkListModelBuilder was set explicitly via " + ::withSdkListModelBuilder.name }
require(sdkFilter == null) { "sdkListModelBuilder was set explicitly via " + ::withSdkListModelBuilder.name }
sdkListModelBuilder
}
else {
SdkListModelBuilder(
project,
sdksModel,
sdkTypeFilter,
sdkTypeCreateFilter,
sdkFilter
)
}
if (updateProjectSdk && project == null) {
require(false) { "Cannot update project SDK when project was not set" }
}
val popupListener = object : SdkPopupListener {
override fun onNewItemAddedAndSelected(item: SdkListItem) {
val addToJdkTable = registerNewSdk || updateProjectSdk || updateSdkForPsiFile != null || updateSdkForVirtualFile != null
if (addToJdkTable && item is SdkListItem.SdkItem) {
val sdk = item.sdk
runWriteAction {
val jdkTable = ProjectJdkTable.getInstance()
if (jdkTable.findJdk(sdk.name) == null) {
jdkTable.addJdk(sdk)
}
}
}
onItemSelected(item)
}
override fun onExistingItemSelected(item: SdkListItem) {
onItemSelected(item)
}
private fun onItemSelected(item: SdkListItem) {
onItemSelected?.accept(item)
if (item is SdkListItem.SdkItem) {
onSdkSelected(item.sdk)
}
}
private fun onSdkSelected(sdk: Sdk) {
onSdkSelected?.accept(sdk)
if (updateProjectSdk) {
runWriteAction {
requireNotNull(project) { "project must be set to use " + SdkPopupBuilder::updateProjectSdkFromSelection.name }
ProjectRootManager.getInstance(project).projectSdk = sdk
}
}
if (updateSdkForPsiFile != null || updateSdkForVirtualFile != null) {
requireNotNull(project) { "project must be set to use " + ::updateProjectSdkFromSelection.name }
runWriteAction {
val moduleToUpdateSdk = when {
updateSdkForVirtualFile != null -> ModuleUtilCore.findModuleForFile(updateSdkForVirtualFile, project)
updateSdkForPsiFile != null -> ModuleUtilCore.findModuleForFile(updateSdkForPsiFile)
else -> null
}
if (moduleToUpdateSdk != null) {
val roots = ModuleRootManager.getInstance(moduleToUpdateSdk)
if (!roots.isSdkInherited) {
roots.modifiableModel.also {
it.sdk = sdk
it.commit()
}
return@runWriteAction
}
}
ProjectRootManager.getInstance(project).projectSdk = sdk
}
}
}
override fun onClosed() {
onPopupClosed?.run()
}
}
return createSdkPopup(project, sdksModel, ownsModel, modelBuilder, popupListener)
}
private fun createSdkPopup(
project: Project?,
projectSdksModel: ProjectSdksModel,
ownsProjectSdksModel: Boolean,
myModelBuilder: SdkListModelBuilder,
listener: SdkPopupListener
): SdkPopup {
lateinit var popup: SdkPopupImpl
val context = SdkListItemContext(project)
val onItemSelected = Consumer<SdkListItem> { value ->
myModelBuilder.processSelectedElement(popup.popupOwner, value,
listener::onNewItemAddedAndSelected,
listener::onExistingItemSelected
)
}
popup = SdkPopupImpl(context, onItemSelected)
val modelListener: SdkListModelBuilder.ModelListener = object : SdkListModelBuilder.ModelListener {
override fun syncModel(model: SdkListModel) {
context.myModel = model
popup.syncWithModelChange()
}
}
myModelBuilder.addModelListener(modelListener)
popup.addListener(object : JBPopupListener {
override fun beforeShown(event: LightweightWindowEvent) {
if (ownsProjectSdksModel) {
projectSdksModel.reset(project)
}
myModelBuilder.reloadActions()
myModelBuilder.detectItems(popup.list, popup)
myModelBuilder.reloadSdks()
}
override fun onClosed(event: LightweightWindowEvent) {
myModelBuilder.removeListener(modelListener)
listener.onClosed()
}
})
return popup
}
}
private class SdkPopupImpl(
context: SdkListItemContext,
onItemSelected: Consumer<SdkListItem>
) : ComboBoxPopup<SdkListItem>(context, null, onItemSelected), SdkPopup {
val popupOwner: JComponent
get() {
val owner = myOwner
if (owner is JComponent) {
return owner
}
if (owner is JFrame) {
owner.rootPane?.let { return it }
}
if (owner is Window) {
owner.components.first { it is JComponent }?.let { return it as JComponent }
}
return JPanel()
}
override fun showPopup(e: AnActionEvent) {
if (e is AnActionButton.AnActionEventWrapper) {
e.showPopup(this)
}
else {
showInBestPositionFor(e.dataContext)
}
}
override fun showUnderneathToTheRightOf(component: Component) {
val popupWidth = list.preferredSize.width
show(RelativePoint(component, Point(component.width - popupWidth, component.height)))
}
}
private class SdkListItemContext(
private val myProject: Project?
) : ComboBoxPopup.Context<SdkListItem> {
var myModel = SdkListModel.emptyModel()
private val myRenderer = SdkListPresenter { myModel }
override fun getProject() = myProject
override fun getMaximumRowCount() = 30
override fun getModel() = myModel
override fun getRenderer() = myRenderer
}
| apache-2.0 | 33a2f32bc2512c9d721162ce722431c9 | 34.510563 | 140 | 0.703322 | 4.96798 | false | false | false | false |
zdary/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/impl/ProjectManagerExImpl.kt | 1 | 18392 | // 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:Suppress("ReplaceNegatedIsEmptyWithIsNotEmpty")
package com.intellij.openapi.project.impl
import com.intellij.conversion.ConversionResult
import com.intellij.conversion.ConversionService
import com.intellij.diagnostic.Activity
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.runActivity
import com.intellij.featureStatistics.fusCollectors.LifecycleUsageTriggerCollector
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.GeneralSettings
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.ide.impl.OpenProjectTask
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.impl.setTrusted
import com.intellij.ide.lightEdit.LightEditCompatible
import com.intellij.ide.startup.impl.StartupManagerImpl
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.components.ComponentManagerEx
import com.intellij.openapi.components.StorageScheme
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.getProjectDataPathRoot
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame
import com.intellij.platform.PlatformProjectOpenProcessor
import com.intellij.project.ProjectStoreOwner
import com.intellij.projectImport.ProjectAttachProcessor
import com.intellij.projectImport.ProjectOpenedCallback
import com.intellij.ui.GuiUtils
import com.intellij.ui.IdeUICustomization
import com.intellij.util.io.delete
import org.jetbrains.annotations.ApiStatus
import java.awt.event.InvocationEvent
import java.io.IOException
import java.nio.file.*
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import java.util.function.BiFunction
@ApiStatus.Internal
open class ProjectManagerExImpl : ProjectManagerImpl() {
final override fun createProject(name: String?, path: String): Project? {
return newProject(toCanonicalName(path), OpenProjectTask(isNewProject = true, runConfigurators = false, projectName = name))
}
final override fun newProject(projectName: String?, path: String, useDefaultProjectAsTemplate: Boolean, isDummy: Boolean): Project? {
return newProject(toCanonicalName(path), OpenProjectTask(isNewProject = true,
useDefaultProjectAsTemplate = useDefaultProjectAsTemplate,
projectName = projectName))
}
final override fun loadAndOpenProject(originalFilePath: String): Project? {
return openProject(toCanonicalName(originalFilePath), OpenProjectTask())
}
final override fun openProject(projectStoreBaseDir: Path, options: OpenProjectTask): Project? {
return openProjectAsync(projectStoreBaseDir, options).get(30, TimeUnit.MINUTES)
}
final override fun openProjectAsync(projectStoreBaseDir: Path, options: OpenProjectTask): CompletableFuture<Project?> {
if (LOG.isDebugEnabled && !ApplicationManager.getApplication().isUnitTestMode) {
LOG.debug("open project: $options", Exception())
}
if (options.project != null && isProjectOpened(options.project)) {
return CompletableFuture.completedFuture(null)
}
val activity = StartUpMeasurer.startActivity("project opening preparation")
if (!options.forceOpenInNewFrame) {
val openProjects = openProjects
if (!openProjects.isEmpty()) {
var projectToClose = options.projectToClose
if (projectToClose == null) {
// if several projects are opened, ask to reuse not last opened project frame, but last focused (to avoid focus switching)
val lastFocusedFrame = IdeFocusManager.getGlobalInstance().lastFocusedFrame
projectToClose = lastFocusedFrame?.project
if (projectToClose == null || projectToClose is LightEditCompatible) {
projectToClose = openProjects.last()
}
}
// this null assertion is required to overcome bug in new version of KT compiler: KT-40034
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
if (checkExistingProjectOnOpen(projectToClose!!, options.callback, projectStoreBaseDir, this)) {
return CompletableFuture.completedFuture(null)
}
}
}
return doOpenAsync(options, projectStoreBaseDir, activity)
}
private fun doOpenAsync(options: OpenProjectTask,
projectStoreBaseDir: Path,
activity: Activity): CompletableFuture<Project?> {
val frameAllocator = if (ApplicationManager.getApplication().isHeadlessEnvironment) ProjectFrameAllocator(options)
else ProjectUiFrameAllocator(options, projectStoreBaseDir)
val disableAutoSaveToken = SaveAndSyncHandler.getInstance().disableAutoSave()
return frameAllocator.run { indicator ->
activity.end()
val result: PrepareProjectResult
if (options.project == null) {
result = prepareProject(options, projectStoreBaseDir) ?: return@run null
}
else {
result = PrepareProjectResult(options.project, null)
}
val project = result.project
if (!addToOpened(project)) {
return@run null
}
frameAllocator.projectLoaded(project)
try {
openProject(project, indicator, isRunStartUpActivitiesEnabled(project)).join()
}
catch (e: ProcessCanceledException) {
ApplicationManager.getApplication().invokeAndWait {
closeProject(project, /* saveProject = */false, /* dispose = */true, /* checkCanClose = */false)
}
ApplicationManager.getApplication().messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed()
return@run null
}
frameAllocator.projectOpened(project)
result
}
.handle(BiFunction { result, error ->
disableAutoSaveToken.finish()
if (error != null) {
throw error
}
if (result == null) {
frameAllocator.projectNotLoaded(error = null)
if (options.showWelcomeScreen) {
WelcomeFrame.showIfNoProjectOpened()
}
return@BiFunction null
}
val project = result.project
if (options.callback != null) {
options.callback!!.projectOpened(project, result.module ?: ModuleManager.getInstance(project).modules[0])
}
project
})
}
override fun openProject(project: Project): Boolean {
val store = if (project is ProjectStoreOwner) (project as ProjectStoreOwner).componentStore else null
if (store != null) {
val projectFilePath = if (store.storageScheme == StorageScheme.DIRECTORY_BASED) store.directoryStorePath!! else store.projectFilePath
for (p in openProjects) {
if (ProjectUtil.isSameProject(projectFilePath, p)) {
GuiUtils.invokeLaterIfNeeded({ ProjectUtil.focusProjectWindow(p, false) }, ModalityState.NON_MODAL)
return false
}
}
}
if (!addToOpened(project)) {
return false
}
val app = ApplicationManager.getApplication()
if (!app.isUnitTestMode && app.isDispatchThread) {
LOG.warn("Do not open project in EDT")
}
try {
openProject(project, ProgressManager.getInstance().progressIndicator, isRunStartUpActivitiesEnabled(project)).join()
}
catch (e: ProcessCanceledException) {
app.invokeAndWait { closeProject(project, /* saveProject = */false, /* dispose = */true, /* checkCanClose = */false) }
app.messageBus.syncPublisher(AppLifecycleListener.TOPIC).projectOpenFailed()
if (!app.isUnitTestMode) {
WelcomeFrame.showIfNoProjectOpened()
}
return false
}
return true
}
override fun newProject(projectFile: Path, options: OpenProjectTask): Project? {
removeProjectConfigurationAndCaches(projectFile)
val project = instantiateProject(projectFile, options)
try {
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
initProject(projectFile, project, options.isRefreshVfsNeeded, options.preloadServices, template,
ProgressManager.getInstance().progressIndicator)
project.setTrusted(true)
return project
}
catch (t: Throwable) {
handleErrorOnNewProject(t)
return null
}
}
protected open fun handleErrorOnNewProject(t: Throwable) {
LOG.warn(t)
try {
val errorMessage = message(t)
ApplicationManager.getApplication().invokeAndWait {
Messages.showErrorDialog(errorMessage, ProjectBundle.message("project.load.default.error"))
}
}
catch (e: NoClassDefFoundError) {
// error icon not loaded
LOG.info(e)
}
}
protected open fun instantiateProject(projectStoreBaseDir: Path, options: OpenProjectTask): ProjectImpl {
val activity = StartUpMeasurer.startActivity("project instantiation")
val project = ProjectExImpl(projectStoreBaseDir, options.projectName)
activity.end()
options.beforeInit?.invoke(project)
return project
}
private fun prepareProject(options: OpenProjectTask, projectStoreBaseDir: Path): PrepareProjectResult? {
val project: Project?
val indicator = ProgressManager.getInstance().progressIndicator
if (options.isNewProject) {
removeProjectConfigurationAndCaches(projectStoreBaseDir)
project = instantiateProject(projectStoreBaseDir, options)
val template = if (options.useDefaultProjectAsTemplate) defaultProject else null
initProject(projectStoreBaseDir, project, options.isRefreshVfsNeeded, options.preloadServices, template, indicator)
}
else {
var conversionResult: ConversionResult? = null
if (options.runConversionBeforeOpen) {
val conversionService = ConversionService.getInstance()
if (conversionService != null) {
indicator?.text = IdeUICustomization.getInstance().projectMessage("progress.text.project.checking.configuration")
conversionResult = runActivity("project conversion") {
conversionService.convert(projectStoreBaseDir)
}
if (conversionResult.openingIsCanceled()) {
return null
}
indicator?.text = ""
}
}
project = instantiateProject(projectStoreBaseDir, options)
// template as null here because it is not a new project
initProject(projectStoreBaseDir, project, options.isRefreshVfsNeeded, options.preloadServices, null, indicator)
if (conversionResult != null && !conversionResult.conversionNotNeeded()) {
StartupManager.getInstance(project).runAfterOpened {
conversionResult.postStartupActivity(project)
}
}
}
@Suppress("UNNECESSARY_NOT_NULL_ASSERTION")
if (options.beforeOpen != null && !options.beforeOpen!!(project)) {
return null
}
if (options.runConfigurators && (options.isNewProject || ModuleManager.getInstance(project).modules.isEmpty())) {
val module = PlatformProjectOpenProcessor.runDirectoryProjectConfigurators(projectStoreBaseDir, project,
options.isProjectCreatedWithWizard)
options.preparedToOpen?.invoke(module)
return PrepareProjectResult(project, module)
}
else {
return PrepareProjectResult(project, module = null)
}
}
protected open fun isRunStartUpActivitiesEnabled(project: Project): Boolean = true
}
@NlsSafe
private fun message(e: Throwable): String {
var message = e.message ?: e.localizedMessage
if (message != null) {
return message
}
message = e.toString()
val causeMessage = message(e.cause ?: return message)
return "$message (cause: $causeMessage)"
}
private fun checkExistingProjectOnOpen(projectToClose: Project,
callback: ProjectOpenedCallback?,
projectDir: Path?,
projectManager: ProjectManagerExImpl): Boolean {
val settings = GeneralSettings.getInstance()
val isValidProject = projectDir != null && ProjectUtil.isValidProjectPath(projectDir)
var result = false
// modality per thread, it means that we cannot use invokeLater, because after getting result from EDT, we MUST continue execution
// in ORIGINAL thread
ApplicationManager.getApplication().invokeAndWait task@{
if (projectDir != null && ProjectAttachProcessor.canAttachToProject() &&
(!isValidProject || settings.confirmOpenNewProject == GeneralSettings.OPEN_PROJECT_ASK)) {
val exitCode = ProjectUtil.confirmOpenOrAttachProject()
if (exitCode == -1) {
result = true
return@task
}
else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
if (!projectManager.closeAndDispose(projectToClose)) {
result = true
return@task
}
}
else if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW_ATTACH) {
if (PlatformProjectOpenProcessor.attachToProject(projectToClose, projectDir, callback)) {
result = true
return@task
}
}
// process all pending events that can interrupt focus flow
// todo this can be removed after taming the focus beast
IdeEventQueue.getInstance().flushQueue()
}
else {
val exitCode = ProjectUtil.confirmOpenNewProject(false)
if (exitCode == GeneralSettings.OPEN_PROJECT_SAME_WINDOW) {
if (!projectManager.closeAndDispose(projectToClose)) {
result = true
return@task
}
}
else if (exitCode != GeneralSettings.OPEN_PROJECT_NEW_WINDOW) {
// not in a new window
result = true
return@task
}
}
result = false
}
return result
}
private fun openProject(project: Project, indicator: ProgressIndicator?, runStartUpActivities: Boolean): CompletableFuture<*> {
val waitEdtActivity = StartUpMeasurer.startActivity("placing calling projectOpened on event queue")
if (indicator != null) {
indicator.text = if (ApplicationManager.getApplication().isInternal) "Waiting on event queue..." // NON-NLS (internal mode)
else ProjectBundle.message("project.preparing.workspace")
indicator.isIndeterminate = true
}
// invokeLater cannot be used for now
ApplicationManager.getApplication().invokeAndWait {
waitEdtActivity.end()
if (indicator != null && ApplicationManager.getApplication().isInternal) {
indicator.text = "Running project opened tasks..." // NON-NLS (internal mode)
}
ProjectManagerImpl.LOG.debug("projectOpened")
LifecycleUsageTriggerCollector.onProjectOpened(project)
val activity = StartUpMeasurer.startActivity("project opened callbacks")
runActivity("projectOpened event executing") {
ApplicationManager.getApplication().messageBus.syncPublisher(ProjectManager.TOPIC).projectOpened(project)
}
@Suppress("DEPRECATION")
(project as ComponentManagerEx)
.processInitializedComponents(com.intellij.openapi.components.ProjectComponent::class.java) { component, pluginDescriptor ->
ProgressManager.checkCanceled()
try {
val componentActivity = StartUpMeasurer.startActivity(component.javaClass.name, ActivityCategory.PROJECT_OPEN_HANDLER,
pluginDescriptor.pluginId.idString)
component.projectOpened()
componentActivity.end()
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: Throwable) {
ProjectManagerImpl.LOG.error(e)
}
}
activity.end()
ProjectImpl.ourClassesAreLoaded = true
}
if (runStartUpActivities) {
(StartupManager.getInstance(project) as StartupManagerImpl).projectOpened(indicator)
}
return CompletableFuture.completedFuture(null)
}
// allow `invokeAndWait` inside startup activities
internal fun waitAndProcessInvocationEventsInIdeEventQueue(startupManager: StartupManagerImpl) {
val eventQueue = IdeEventQueue.getInstance()
while (true) {
// getNextEvent() will block until an event has been posted by another thread, so,
// peekEvent() is used to check that there is already some event in the queue
if (eventQueue.peekEvent() == null) {
if (startupManager.postStartupActivityPassed()) {
break
}
else {
continue
}
}
val event = eventQueue.nextEvent
if (event is InvocationEvent) {
eventQueue.dispatchEvent(event)
}
}
}
private data class PrepareProjectResult(val project: Project, val module: Module?)
private fun toCanonicalName(filePath: String): Path {
val file = Paths.get(filePath)
try {
if (SystemInfoRt.isWindows && FileUtil.containsWindowsShortName(filePath)) {
return file.toRealPath(LinkOption.NOFOLLOW_LINKS)
}
}
catch (e: InvalidPathException) {
}
catch (e: IOException) {
// OK. File does not yet exist, so its canonical path will be equal to its original path.
}
return file
}
private fun removeProjectConfigurationAndCaches(projectFile: Path) {
try {
if (Files.isRegularFile(projectFile)) {
Files.deleteIfExists(projectFile)
}
else {
Files.newDirectoryStream(projectFile.resolve(Project.DIRECTORY_STORE_FOLDER)).use { directoryStream ->
for (file in directoryStream) {
file!!.delete()
}
}
}
}
catch (ignored: IOException) {
}
try {
getProjectDataPathRoot(projectFile).delete()
}
catch (ignored: IOException) {
}
}
| apache-2.0 | 8f2126730ee533158b7cd7fdec003baa | 37.801688 | 140 | 0.709602 | 5.272936 | false | false | false | false |
leafclick/intellij-community | plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/build/DelegateBuildRunner.kt | 1 | 1757 | // Copyright 2000-2019 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.idea.maven.execution.build
import com.intellij.execution.configurations.RunProfileState
import com.intellij.execution.impl.DefaultJavaProgramRunner
import com.intellij.execution.runners.ExecutionEnvironment
import com.intellij.execution.runners.ProgramRunner
import com.intellij.execution.runners.RunContentBuilder
import com.intellij.execution.ui.RunContentDescriptor
internal class DelegateBuildRunner : DefaultJavaProgramRunner() {
override fun getRunnerId() = ID
override fun doExecute(state: RunProfileState, environment: ExecutionEnvironment): RunContentDescriptor? {
val executionResult = state.execute(environment.executor, this) ?: return null
val runContentBuilder = RunContentBuilder(executionResult, environment)
val runContentDescriptor = runContentBuilder.showRunContent(environment.contentToReuse) ?: return null
val descriptor = object : RunContentDescriptor(runContentDescriptor.executionConsole, runContentDescriptor.processHandler,
runContentDescriptor.component, runContentDescriptor.displayName,
runContentDescriptor.icon, null,
runContentDescriptor.restartActions) {
override fun isHiddenContent() = true
}
descriptor.runnerLayoutUi = runContentDescriptor.runnerLayoutUi
return descriptor
}
companion object {
private const val ID = "MAVEN_DELEGATE_BUILD_RUNNER"
@JvmStatic
fun getDelegateRunner(): ProgramRunner<*>? = ProgramRunner.findRunnerById(ID)
}
}
| apache-2.0 | 9d278d8d3a1dca569e2a942f1560af3e | 47.805556 | 140 | 0.742174 | 5.79868 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/delegatedProperty/genericDelegate.kt | 5 | 425 | import kotlin.reflect.KProperty
class Delegate<T>(var inner: T) {
operator fun getValue(t: Any?, p: KProperty<*>): T = inner
operator fun setValue(t: Any?, p: KProperty<*>, i: T) { inner = i }
}
class A {
inner class B {
var prop: Int by Delegate(1)
}
}
fun box(): String {
val c = A().B()
if(c.prop != 1) return "fail get"
c.prop = 2
if (c.prop != 2) return "fail set"
return "OK"
}
| apache-2.0 | c0f64be5f21af9a4f77c9f757ff913cb | 20.25 | 71 | 0.571765 | 3.035714 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/caches/resolve/Java9MultiModuleHighlightingTest.kt | 2 | 2931 | // 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.caches.resolve
import com.intellij.openapi.module.Module
import com.intellij.testFramework.IdeaTestUtil
import org.jetbrains.kotlin.config.JvmTarget
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.test.KotlinCompilerStandalone
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.junit.internal.runners.JUnit38ClassRunner
import org.junit.runner.RunWith
import java.io.File
@RunWith(JUnit38ClassRunner::class)
class Java9MultiModuleHighlightingTest : AbstractMultiModuleHighlightingTest() {
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("multiModuleHighlighting/java9")
private fun module(name: String): Module = super.module(name, false) { IdeaTestUtil.getMockJdk9() }
fun testSimpleModuleExportsPackage() {
module("main").addDependency(module("dependency"))
checkHighlightingInProject()
}
fun testSimpleLibraryExportsPackage() {
val sources = listOf(File(testDataPath, getTestName(true) + "/library"))
// -Xallow-kotlin-package to avoid "require kotlin.stdlib" in module-info.java
val extraOptions = listOf("-jdk-home", KotlinTestUtils.getAtLeastJdk9Home().path, "-Xallow-kotlin-package")
val libraryJar = KotlinCompilerStandalone(
sources,
platform = KotlinCompilerStandalone.Platform.Jvm(JvmTarget.JVM_9),
options = extraOptions
).compile()
module("main").addLibrary(libraryJar, "library")
checkHighlightingInProject()
}
fun testNamedDependsOnUnnamed() {
module("main").addDependency(module("dependency"))
checkHighlightingInProject()
}
fun testUnnamedDependsOnNamed() {
module("main").addDependency(module("dependency"))
checkHighlightingInProject()
}
fun testDeclarationKinds() {
module("main").addDependency(module("dependency"))
checkHighlightingInProject()
}
fun testExportsTo() {
val d = module("dependency")
module("first").addDependency(d)
module("second").addDependency(d)
module("unnamed").addDependency(d)
checkHighlightingInProject()
}
fun testExportedPackageIsInaccessibleWithoutRequires() {
module("main").addDependency(module("dependency"))
checkHighlightingInProject()
}
fun testTypealiasToUnexported() {
module("main").addDependency(module("dependency"))
checkHighlightingInProject()
}
fun testCyclicDependency() {
val a = module("moduleA")
val b = module("moduleB")
val c = module("moduleC")
module("main").addDependency(a).addDependency(b).addDependency(c)
checkHighlightingInProject()
}
}
| apache-2.0 | 9e0b0d0009609f780fb82d7d09482ec7 | 35.6375 | 158 | 0.70522 | 4.917785 | false | true | false | false |
LouisCAD/Splitties | modules/intents/src/androidMain/kotlin/splitties/intents/IntentSpec.kt | 1 | 2375 | /*
* Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.intents
import android.app.Activity
import android.app.Service
import splitties.bundle.BundleSpec
import splitties.exceptions.unsupported
import android.content.BroadcastReceiver as BR
/**
* @see ActivityIntentSpec
* @see BroadcastReceiverIntentSpec
* @see ServiceIntentSpec
*/
interface IntentSpec<T, out ExtrasSpec : BundleSpec> {
val klass: Class<T>
val extrasSpec: ExtrasSpec
}
interface ActivityIntentSpec<T : Activity, out ExtrasSpec : BundleSpec> : IntentSpec<T, ExtrasSpec>
interface BroadcastReceiverIntentSpec<T : BR, out ExtrasSpec : BundleSpec> :
IntentSpec<T, ExtrasSpec>
interface ServiceIntentSpec<T : Service, out ExtrasSpec : BundleSpec> : IntentSpec<T, ExtrasSpec>
// Activity Intent
inline fun <reified T : Activity, ExtrasSpec : BundleSpec> activitySpec(
extrasSpec: ExtrasSpec
) = object : ActivityIntentSpec<T, ExtrasSpec> {
override val klass = T::class.java
override val extrasSpec = extrasSpec
}
inline fun <reified T : Activity> activityWithoutExtrasSpec(): ActivityIntentSpec<T, Nothing> {
return object : ActivityIntentSpec<T, Nothing> {
override val klass = T::class.java
override val extrasSpec get() = unsupported()
}
}
// BroadcastReceiver Intent
inline fun <reified T : BR, ExtrasSpec : BundleSpec> receiverSpec(
extrasSpec: ExtrasSpec
) = object : BroadcastReceiverIntentSpec<T, ExtrasSpec> {
override val klass = T::class.java
override val extrasSpec = extrasSpec
}
inline fun <reified T : BR> receiverWithoutExtrasSpec(): BroadcastReceiverIntentSpec<T, Nothing> {
return object : BroadcastReceiverIntentSpec<T, Nothing> {
override val klass = T::class.java
override val extrasSpec get() = unsupported()
}
}
// Service Intent
inline fun <reified T : Service, ExtrasSpec : BundleSpec> serviceSpec(
extrasSpec: ExtrasSpec
) = object : ServiceIntentSpec<T, ExtrasSpec> {
override val klass = T::class.java
override val extrasSpec = extrasSpec
}
inline fun <reified T : Service> serviceWithoutExtrasSpec(): ServiceIntentSpec<T, Nothing> {
return object : ServiceIntentSpec<T, Nothing> {
override val klass = T::class.java
override val extrasSpec get() = unsupported()
}
}
| apache-2.0 | 9d5620be5e9848fc7a21b073b5d138f9 | 31.094595 | 109 | 0.735158 | 4.549808 | false | false | false | false |
MilosKozak/AndroidAPS | app/src/main/java/info/nightscout/androidaps/dialogs/ProfileViewerDialog.kt | 3 | 4315 | package info.nightscout.androidaps.dialogs
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import androidx.fragment.app.DialogFragment
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.plugins.treatments.TreatmentsPlugin
import info.nightscout.androidaps.utils.DateUtil
import kotlinx.android.synthetic.main.close.*
import kotlinx.android.synthetic.main.dialog_profileviewer.*
import org.json.JSONObject
class ProfileViewerDialog : DialogFragment() {
private var time: Long = 0
enum class Mode(val i: Int) {
RUNNING_PROFILE(1),
CUSTOM_PROFILE(2)
}
private var mode: Mode = Mode.RUNNING_PROFILE
private var customProfileJson: String = ""
private var customProfileName: String = ""
private var customProfileUnits: String = Constants.MGDL
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// load data from bundle
(savedInstanceState ?: arguments)?.let { bundle ->
time = bundle.getLong("time", 0)
mode = Mode.values()[bundle.getInt("mode", Mode.RUNNING_PROFILE.ordinal)]
customProfileJson = bundle.getString("customProfile", "")
customProfileUnits = bundle.getString("customProfileUnits", Constants.MGDL)
customProfileName = bundle.getString("customProfileName", "")
}
dialog?.window?.requestFeature(Window.FEATURE_NO_TITLE)
dialog?.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
isCancelable = true
dialog?.setCanceledOnTouchOutside(false)
return inflater.inflate(R.layout.dialog_profileviewer, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
close.setOnClickListener { dismiss() }
val profile: Profile?
val profileName: String?
val date: String?
when (mode) {
Mode.RUNNING_PROFILE -> {
profile = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(time)?.profileObject
profileName = TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(time)?.customizedName
date = DateUtil.dateAndTimeString(TreatmentsPlugin.getPlugin().getProfileSwitchFromHistory(time)?.date
?: 0)
profileview_datelayout.visibility = View.VISIBLE
}
Mode.CUSTOM_PROFILE -> {
profile = Profile(JSONObject(customProfileJson), customProfileUnits)
profileName = customProfileName
date = ""
profileview_datelayout.visibility = View.GONE
}
}
profileview_noprofile.visibility = View.VISIBLE
profile?.let {
profileview_units.text = it.units
profileview_dia.text = MainApp.gs(R.string.format_hours, it.dia)
profileview_activeprofile.text = profileName
profileview_date.text = date
profileview_ic.text = it.icList
profileview_isf.text = it.isfList
profileview_basal.text = it.basalList
profileview_target.text = it.targetList
basal_graph.show(it)
profileview_noprofile.visibility = View.GONE
profileview_invalidprofile.visibility = if (it.isValid("ProfileViewDialog")) View.GONE else View.VISIBLE
}
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
}
override fun onSaveInstanceState(bundle: Bundle) {
super.onSaveInstanceState(bundle)
bundle.putLong("time", time)
bundle.putInt("mode", mode.ordinal)
bundle.putString("customProfile", customProfileJson)
bundle.putString("customProfileName", customProfileName)
bundle.putString("customProfileUnits", customProfileUnits)
}
}
| agpl-3.0 | 537093e152e73831ff02630f084eefc6 | 38.953704 | 118 | 0.678331 | 4.988439 | false | false | false | false |
cmaier/7tools | seventools/src/test/java/me/sieben/seventools/functions/BooleanActionTest.kt | 1 | 4812 | package me.sieben.seventools.functions
import io.kotest.core.spec.style.WordSpec
import io.kotest.matchers.shouldBe
class BooleanActionTest : WordSpec() {
init {
"Boolean?.onTrue" should {
"run the block if the Boolean is true" {
var checkpoint = false
true as Boolean? onTrue { checkpoint = true }
checkpoint shouldBe true
}
"do not run the block if the Boolean is false" {
var checkpoint = false
false as Boolean? onTrue { checkpoint = true }
checkpoint shouldBe false
}
"do not run the block if the Boolean is null" {
var checkpoint = false
null as Boolean? onTrue { checkpoint = true }
checkpoint shouldBe false
}
"only the `true'-Block" {
var checkpointTrue = false
var checkpointFalse = false
var checkpointNull = false
true as Boolean? onTrue {
checkpointTrue = true
} onFalse {
checkpointFalse = true
} onNull {
checkpointNull = true
}
checkpointTrue shouldBe true
checkpointFalse shouldBe false
checkpointNull shouldBe false
}
}
"Boolean.onTrue" should {
"run the block if the Boolean is true" {
var checkpoint = false
true onTrue { checkpoint = true }
checkpoint shouldBe true
}
"do not run the block if the Boolean is false" {
var checkpoint = false
false onTrue { checkpoint = true }
checkpoint shouldBe false
}
}
"Boolean?.onFalse" should {
"run the block if the Boolean is false" {
var checkpoint = false
false as Boolean? onFalse { checkpoint = true }
checkpoint shouldBe true
}
"do not run the block if the Boolean is true" {
var checkpoint = false
true as Boolean? onFalse { checkpoint = true }
checkpoint shouldBe false
}
"do not run the block if the Boolean is null" {
var checkpoint = false
null as Boolean? onFalse { checkpoint = true }
checkpoint shouldBe false
}
"only the `false'-Block" {
var checkpointTrue = false
var checkpointFalse = false
var checkpointNull = false
false as Boolean? onTrue {
checkpointTrue = true
} onFalse {
checkpointFalse = true
} onNull {
checkpointNull = true
}
checkpointTrue shouldBe false
checkpointFalse shouldBe true
checkpointNull shouldBe false
}
}
"Boolean.onFalse" should {
"run the block if the Boolean is false" {
var checkpoint = false
false onFalse { checkpoint = true }
checkpoint shouldBe true
}
"do not run the block if the Boolean is true" {
var checkpoint = false
true onFalse { checkpoint = true }
checkpoint shouldBe false
}
}
"Boolean?.onNull" should {
"run the block if the Boolean is null" {
var checkpoint = false
null onNull { checkpoint = true }
checkpoint shouldBe true
}
"do not run the block if the Boolean is true" {
var checkpoint = false
true onNull { checkpoint = true }
checkpoint shouldBe false
}
"do not run the block if the Boolean is false" {
var checkpoint = false
false onNull { checkpoint = true }
checkpoint shouldBe false
}
"only the `null'-Block" {
var checkpointTrue = false
var checkpointFalse = false
var checkpointNull = false
null onTrue {
checkpointTrue = true
} onFalse {
checkpointFalse = true
} onNull {
checkpointNull = true
}
checkpointTrue shouldBe false
checkpointFalse shouldBe false
checkpointNull shouldBe true
}
}
}
}
| apache-2.0 | 5c7804e0bdf42b8433b8561f24637942 | 30.657895 | 63 | 0.478387 | 6.529172 | false | false | false | false |
meltwater/rabbit-puppy | src/main/kotlin/com/meltwater/puppy/rest/RabbitRestClient.kt | 1 | 10383 | package com.meltwater.puppy.rest
import com.google.common.collect.ImmutableMap.of
import com.google.gson.Gson
import com.meltwater.puppy.config.*
import org.slf4j.LoggerFactory
import java.util.*
import javax.ws.rs.client.Entity.entity
import javax.ws.rs.core.MediaType
import javax.ws.rs.core.Response
import javax.ws.rs.core.Response.Status
class RestClientException : Exception {
constructor(s: String, e: Exception) : super(s, e)
constructor(s: String) : super(s)
}
open class RabbitRestClient(brokerAddress: String, brokerUsername: String, brokerPassword: String) {
private val log = LoggerFactory.getLogger(RabbitRestClient::class.java)
companion object {
val PATH_OVERVIEW = "api/overview"
public val PATH_VHOSTS = "api/vhosts"
val PATH_VHOSTS_SINGLE = "api/vhosts/{vhost}"
val PATH_USERS = "api/users"
val PATH_USERS_SINGLE = "api/users/{user}"
val PATH_PERMISSIONS = "api/permissions"
val PATH_PERMISSIONS_SINGLE = "api/permissions/{vhost}/{user}"
val PATH_EXCHANGES_SINGLE = "api/exchanges/{vhost}/{exchange}"
val PATH_QUEUES_SINGLE = "api/queues/{vhost}/{queue}"
val PATH_BINDINGS_VHOST = "api/bindings/{vhost}"
val PATH_BINDING_QUEUE = "api/bindings/{vhost}/e/{exchange}/q/{to}"
val PATH_BINDING_EXCHANGE = "api/bindings/{vhost}/e/{exchange}/e/{to}"
}
private val requestBuilder: RestRequestBuilder
private val parser = RabbitRestResponseParser()
private val gson = Gson()
init {
this.requestBuilder = RestRequestBuilder(brokerAddress, kotlin.Pair(brokerUsername, brokerPassword))
.withHeader("content-type", "application/json")
}
open fun ping(): Boolean {
try {
val response = requestBuilder.request(PATH_OVERVIEW).get()
return response.status == Status.OK.statusCode
} catch (e: Exception) {
return false
}
}
open fun getUsername(): String = requestBuilder.getAuthUser()
open fun getPassword(): String = requestBuilder.getAuthPass()
@Throws(RestClientException::class)
open fun getPermissions(): Map<String, PermissionsData> = parser.permissions(
expect(requestBuilder.request(PATH_PERMISSIONS).get(),
Status.OK.statusCode))
@Throws(RestClientException::class)
open fun getExchange(vhost: String,
exchange: String,
user: String,
pass: String): Optional<ExchangeData> = parser.exchange(
expectOrEmpty(requestBuilder.nextWithAuthentication(user, pass).request(PATH_EXCHANGES_SINGLE, of(
"vhost", vhost,
"exchange", exchange)).get(),
Status.OK.statusCode,
Status.NOT_FOUND.statusCode))
@Throws(RestClientException::class)
open fun getQueue(vhost: String,
queue: String,
user: String,
pass: String): Optional<QueueData> = parser.queue(
expectOrEmpty(requestBuilder.nextWithAuthentication(user, pass).request(PATH_QUEUES_SINGLE, of(
"vhost", vhost,
"queue", queue)).get(),
Status.OK.statusCode,
Status.NOT_FOUND.statusCode))
@Throws(RestClientException::class)
open fun getBindings(vhost: String,
user: String,
pass: String): Map<String, List<BindingData>> {
if (getVirtualHosts().contains(vhost)) {
return parser.bindings(
expect(requestBuilder.nextWithAuthentication(user, pass).request(PATH_BINDINGS_VHOST, of(
"vhost", vhost)).get(),
Status.OK.statusCode))
} else {
return HashMap()
}
}
@Throws(RestClientException::class)
open fun getVirtualHosts(): Map<String, VHostData> = parser.vhosts(
expect(requestBuilder.request(PATH_VHOSTS).get(),
Status.OK.statusCode))
@Throws(RestClientException::class)
open fun getUsers(): Map<String, UserData> = parser.users(
expect(requestBuilder.request(PATH_USERS).get(),
Status.OK.statusCode))
@Throws(RestClientException::class)
open fun createVirtualHost(virtualHost: String, vHostData: VHostData) {
expect(requestBuilder.request(PATH_VHOSTS_SINGLE, of("vhost", virtualHost)).put(entity(gson.toJson(vHostData), MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
}
@Throws(RestClientException::class)
open fun createUser(user: String, userData: UserData) {
require("User", user, "password", userData.password)
expect(requestBuilder.request(PATH_USERS_SINGLE, of("user", user)).put(entity(gson.toJson(of(
"password", userData.password,
"tags", if (userData.admin) "administrator" else "")), MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
}
@Throws(RestClientException::class)
open fun createPermissions(user: String, vhost: String, permissionsData: PermissionsData) {
require("Permissions", "$user@$vhost", "configure", permissionsData.configure)
require("Permissions", "$user@$vhost", "write", permissionsData.write)
require("Permissions", "$user@$vhost", "read", permissionsData.read)
expect(requestBuilder.request(PATH_PERMISSIONS_SINGLE, of(
"vhost", vhost,
"user", user)).put(entity(gson.toJson(permissionsData), MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
}
@Throws(RestClientException::class)
open fun createExchange(vhost: String,
exchange: String,
exchangeData: ExchangeData,
user: String,
pass: String) {
require("Exchange", exchange + "@" + vhost, "type", exchangeData.type)
expect(requestBuilder.nextWithAuthentication(user, pass).request(PATH_EXCHANGES_SINGLE, of(
"vhost", vhost,
"exchange", exchange)).put(entity(gson.toJson(exchangeData), MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
}
@Throws(RestClientException::class)
open fun createQueue(vhost: String, queue: String,
queueData: QueueData,
user: String,
pass: String) {
expect(requestBuilder
.nextWithAuthentication(user, pass)
.request(PATH_QUEUES_SINGLE, of(
"vhost", vhost,
"queue", queue))
.put(entity(gson.toJson(queueData),
MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
}
@Throws(RestClientException::class)
open fun createBinding(vhost: String,
exchange: String,
bindingData: BindingData,
user: String,
pass: String) {
require("Binding", "$user@$vhost", "destination", bindingData.destination)
require("Binding", "$user@$vhost", "destination_type", bindingData.destination_type)
require("Binding", "$user@$vhost", "routing_key", bindingData.routing_key)
if (bindingData.destination_type == DestinationType.queue) {
expect(requestBuilder
.nextWithAuthentication(user, pass)
.request(PATH_BINDING_QUEUE, of<String, String>(
"vhost", vhost,
"exchange", exchange,
"to", bindingData.destination))
.post(entity(gson.toJson(of<String, Any>(
"routing_key", bindingData.routing_key,
"arguments", bindingData.arguments)),
MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
} else if (bindingData.destination_type == DestinationType.exchange) {
expect(requestBuilder.nextWithAuthentication(user, pass).request(PATH_BINDING_EXCHANGE, of<String, String>(
"vhost", vhost,
"exchange", exchange,
"to", bindingData.destination)).post(entity(gson.toJson(of<String, Any>(
"routing_key", bindingData.routing_key,
"arguments", bindingData.arguments)),
MediaType.APPLICATION_JSON_TYPE)),
Status.CREATED.statusCode)
} else {
val error = "No destination_type specified for binding at $exchange@$vhost: ${bindingData.destination}"
log.error(error)
throw RestClientException(error)
}
}
@Throws(RestClientException::class)
private fun expect(response: Response, statusExpected: Int): Response {
if (response.status != statusExpected) {
val error = "Response with HTTP status %d %s, expected status code %d".format(response.status, response.statusInfo.reasonPhrase, statusExpected)
log.error(error)
throw RestClientException(error)
}
return response
}
@Throws(RestClientException::class)
private fun expectOrEmpty(response: Response,
statusExpected: Int,
statusEmpty: Int): Optional<Response> {
if (response.status == statusExpected) {
return Optional.of(response)
} else if (response.status == statusEmpty) {
return Optional.empty<Response>()
} else {
val error = "Response with HTTP status %d %s, expected status code %d or %s".format(response.status, response.statusInfo.reasonPhrase, statusExpected, statusEmpty)
log.error(error)
throw RestClientException(error)
}
}
@Throws(RestClientException::class)
private fun <D> require(type: String, name: String, property: String, value: D?) {
if (value == null) {
val error = "$type $name missing required field: $property"
log.error(error)
throw RestClientException(error)
}
}
}
| mit | d61ea670481b987b695fdf2946822d2c | 42.082988 | 175 | 0.598286 | 4.76503 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/symbols/utils.kt | 2 | 2890 | // 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.kotlin.nj2k.symbols
import com.intellij.lang.jvm.JvmModifier
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiEnumConstant
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiModifierListOwner
import org.jetbrains.kotlin.idea.base.psi.kotlinFqName
import org.jetbrains.kotlin.idea.search.KotlinSearchUsagesSupport.Companion.findDeepestSuperMethodsNoWrapping
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.nj2k.isObjectOrCompanionObject
import org.jetbrains.kotlin.nj2k.psi
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
val JKSymbol.isUnresolved
get() = this is JKUnresolvedSymbol
fun JKSymbol.getDisplayFqName(): String {
fun JKSymbol.isDisplayable() = this is JKClassSymbol || this is JKPackageSymbol
if (this !is JKUniverseSymbol<*>) return fqName
return generateSequence(declaredIn?.takeIf { it.isDisplayable() }) { symbol ->
symbol.declaredIn?.takeIf { it.isDisplayable() }
}.fold(name) { acc, symbol -> "${symbol.name}.$acc" }
}
fun JKSymbol.deepestFqName(): String {
fun Any.deepestFqNameForTarget(): String? =
when (this) {
is PsiMethod -> (findDeepestSuperMethods().firstOrNull() ?: this).kotlinFqName?.asString()
is KtNamedFunction -> findDeepestSuperMethodsNoWrapping(this).firstOrNull()?.kotlinFqName?.asString()
is JKMethod -> psi<PsiElement>()?.deepestFqNameForTarget()
else -> null
}
return target.deepestFqNameForTarget() ?: fqName
}
val JKSymbol.containingClass
get() = declaredIn as? JKClassSymbol
val JKSymbol.isStaticMember
get() = when (val target = target) {
is PsiModifierListOwner -> target.hasModifier(JvmModifier.STATIC)
is KtElement -> target.getStrictParentOfType<KtClassOrObject>()
?.safeAs<KtObjectDeclaration>()
?.isCompanion() == true
is JKTreeElement ->
target.safeAs<JKOtherModifiersOwner>()?.hasOtherModifier(OtherModifier.STATIC) == true
|| target.parentOfType<JKClass>()?.isObjectOrCompanionObject == true
else -> false
}
val JKSymbol.isEnumConstant
get() = when (target) {
is JKEnumConstant -> true
is PsiEnumConstant -> true
is KtEnumEntry -> true
else -> false
}
val JKSymbol.isUnnamedCompanion
get() = when (val target = target) {
is JKClass -> target.classKind == JKClass.ClassKind.COMPANION
is KtObjectDeclaration -> target.isCompanion() && target.name == SpecialNames.DEFAULT_NAME_FOR_COMPANION_OBJECT.toString()
else -> false
}
| apache-2.0 | c3924f8ebea4abd1672cc0a3cfc12d4e | 39.138889 | 130 | 0.715917 | 4.683955 | false | false | false | false |
bydzodo1/batch-lemmatize-processor | src/main/kt/cz/bydzodo1/batchLemmatizationProcessor/model/generatingOutput/OutputFileProvider.kt | 1 | 2763 | package cz.bydzodo1.batchLemmatizationProcessor.model.generatingOutput
import cz.bydzodo1.batchLemmatizationProcessor.model.CommandResult
import cz.bydzodo1.batchLemmatizationProcessor.model.Settings
import cz.bydzodo1.batchLemmatizationProcessor.model.xmlContent.Token
import java.io.File
import java.io.PrintWriter
import java.util.*
class OutputFileProvider {
val sep = ";"
val date = Date().time.toString()
val fileName = "Result$date.csv"
lateinit var writer: PrintWriter
var columns: MutableList<Column> = mutableListOf()
fun outputFile(commandResults: HashMap<String, CommandResult>, outputFile: File? = null) {
var file: File? = null
if (outputFile == null){
writer = PrintWriter(fileName, "UTF-8")
file = File(fileName)
} else {
writer = PrintWriter(outputFile, "UTF-8")
file = outputFile
}
createColumns(commandResults.map { it.value })
writeHeader()
writeBody(commandResults)
println("Result file has been saved - ${file.absolutePath}")
writer.close()
}
private fun writeHeader(){
writer.print("NAZEV${sep}POVET VET${sep}POCET SLOV")
columns.forEach({
writer.print(sep + "${it.index + 1}:${it.char}")
})
writer.println()
}
private fun writeBody(commandResults: HashMap<String, CommandResult>){
commandResults.forEach({
writeRow(it.key, it.value)
})
}
private fun writeRow(fileName: String, commandResult: CommandResult){
val allTokens = mutableListOf<Token>()
commandResult.sentences.forEach({allTokens.addAll(it.tokens)})
writer.print(fileName + sep + commandResult.sentences.size + sep + allTokens.size)
columns.forEach({
val column = it
val count = allTokens.map(Token::getTags).filter { it[column.index] == column.char }.size
writer.print(sep + count)
})
writer.println()
}
private fun createColumns(commandResults: List<CommandResult>){
val allTokens = mutableListOf<Token>()
commandResults.forEach({it.sentences.forEach({allTokens.addAll(it.tokens)})})
val tagColumns = HashMap<Int, MutableSet<Char>>()
allTokens.forEach({
for (i in it.getTags().indices) {
if (tagColumns[i] == null){
tagColumns[i] = mutableSetOf()
}
tagColumns[i]!!.add(it.tag[i])
}
})
tagColumns.forEach({
val index = it.key
val tags = it.value.sorted()
for(tag in tags){
columns.add(Column(index, tag))
}
})
}
} | mpl-2.0 | 2a9afbf7ecaba2d5c8751a13737896f6 | 30.05618 | 101 | 0.605501 | 4.392687 | false | false | false | false |
siosio/intellij-community | java/java-impl/src/com/intellij/codeInsight/completion/ml/JavaCompletionFeatures.kt | 1 | 9291 | // 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.codeInsight.completion.ml
import com.intellij.codeInsight.template.macro.MacroUtil
import com.intellij.internal.ml.WordsSplitter
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.CommonClassNames.JAVA_LANG_STRING
import com.intellij.psi.scope.util.PsiScopesUtil
import com.intellij.psi.util.InheritanceUtil
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.psi.util.TypeConversionUtil
import org.jetbrains.annotations.ApiStatus
import java.util.*
@ApiStatus.Internal
object JavaCompletionFeatures {
private val VARIABLES_KEY: Key<VariablesInfo> = Key.create("java.ml.completion.variables")
private val PACKAGES_KEY: Key<PackagesInfo> = Key.create("java.ml.completion.packages")
private val CHILD_CLASS_WORDS_KEY: Key<List<String>> = Key.create("java.ml.completion.child.class.name.words")
private val wordsSplitter: WordsSplitter = WordsSplitter.Builder.identifiers().build()
enum class JavaKeyword {
ABSTRACT,
BOOLEAN,
BREAK,
CASE,
CATCH,
CHAR,
CLASS,
CONST,
CONTINUE,
DOUBLE,
ELSE,
EXTENDS,
FINAL,
FINALLY,
FLOAT,
FOR,
IF,
IMPLEMENTS,
IMPORT,
INSTANCEOF,
INT,
INTERFACE,
LONG,
NEW,
PRIVATE,
PROTECTED,
PUBLIC,
RETURN,
STATIC,
SUPER,
SWITCH,
THIS,
THROW,
THROWS,
TRY,
VOID,
WHILE,
TRUE,
FALSE,
NULL,
ANOTHER;
companion object {
private val ALL_VALUES: Map<String, JavaKeyword> = values().associateBy { it.toString() }
fun getValue(text: String): JavaKeyword? = ALL_VALUES[text]
}
override fun toString(): String = name.toLowerCase(Locale.ENGLISH)
}
enum class JavaType {
VOID,
BOOLEAN,
NUMERIC,
STRING,
CHAR,
ENUM,
ARRAY,
COLLECTION,
MAP,
THROWABLE,
ANOTHER;
companion object {
fun getValue(type: PsiType): JavaType {
return when {
type == PsiType.VOID -> VOID
type == PsiType.CHAR -> CHAR
type.equalsToText(JAVA_LANG_STRING) -> STRING
TypeConversionUtil.isBooleanType(type) -> BOOLEAN
TypeConversionUtil.isNumericType(type) -> NUMERIC
type is PsiArrayType -> ARRAY
InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_COLLECTION) -> COLLECTION
InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_UTIL_MAP) -> MAP
InheritanceUtil.isInheritor(type, CommonClassNames.JAVA_LANG_THROWABLE) -> THROWABLE
TypeConversionUtil.isEnumType(type) -> ENUM
else -> ANOTHER
}
}
}
}
fun asKeyword(text: String): JavaKeyword? = JavaKeyword.getValue(text)
fun asJavaType(type: PsiType): JavaType = JavaType.getValue(type)
fun calculateChildClassWords(environment: CompletionEnvironment, childClass: PsiElement) {
val childClassWords = wordsSplitter.split(childClass.text)
environment.putUserData(CHILD_CLASS_WORDS_KEY, childClassWords)
}
fun getChildClassTokensMatchingFeature(contextFeatures: ContextFeatures, baseClassName: String): MLFeatureValue? {
contextFeatures.getUserData(CHILD_CLASS_WORDS_KEY)?.let { childClassTokens ->
val baseClassTokens = wordsSplitter.split(baseClassName)
if (baseClassTokens.isNotEmpty()) {
return MLFeatureValue.numerical(baseClassTokens.count(childClassTokens::contains).toDouble() / baseClassTokens.size)
}
}
return null
}
fun calculateVariables(environment: CompletionEnvironment) = try {
val parentClass = PsiTreeUtil.getParentOfType(environment.parameters.position, PsiClass::class.java)
val variables = getVariablesInScope(environment.parameters.position, parentClass)
val names = variables.mapNotNull { it.name }.toSet()
val types = variables.map { it.type }.toSet()
val names2types = variables.mapNotNull { variable -> variable.name?.let { Pair(it, variable.type) } }.toSet()
environment.putUserData(VARIABLES_KEY, VariablesInfo(names, types, names2types))
} catch (ignored: PsiInvalidElementAccessException) {}
fun getArgumentsVariablesMatchingFeatures(contextFeatures: ContextFeatures, method: PsiMethod): Map<String, MLFeatureValue> {
val result = mutableMapOf<String, MLFeatureValue>()
val parameters = method.parameterList.parameters
result["args_count"] = MLFeatureValue.numerical(parameters.size)
val names2types = parameters.map { Pair(it.name, it.type) }
contextFeatures.getUserData(VARIABLES_KEY)?.let { variables ->
result["args_vars_names_matches"] = MLFeatureValue.numerical(names2types.count { it.first in variables.names })
result["args_vars_types_matches"] = MLFeatureValue.numerical(names2types.count { it.second in variables.types })
result["args_vars_names_types_matches"] = MLFeatureValue.numerical(names2types.count { it in variables.names2types })
}
return result
}
fun isInQualifierExpression(environment: CompletionEnvironment): Boolean {
val parentExpressions = mutableSetOf<PsiExpression>()
var curParent = environment.parameters.position.context
while (curParent is PsiExpression) {
if (curParent is PsiReferenceExpression && parentExpressions.contains(curParent.qualifierExpression)) {
return true
}
parentExpressions.add(curParent)
curParent = curParent.parent
}
return false
}
fun isAfterMethodCall(environment: CompletionEnvironment): Boolean {
val context = environment.parameters.position.context
if (context is PsiReferenceExpression) {
val qualifier = context.qualifierExpression
return qualifier is PsiNewExpression || qualifier is PsiMethodCallExpression
}
return false
}
fun collectPackages(environment: CompletionEnvironment) {
val file = environment.parameters.originalFile as? PsiJavaFile ?: return
val packageTrie = FqnTrie.withFqn(file.packageName)
val importsTrie = FqnTrie.create()
file.importList?.importStatements?.mapNotNull { it.qualifiedName }?.forEach { importsTrie.addFqn(it) }
file.importList?.importStaticStatements?.mapNotNull { it.importReference?.qualifiedName }?.forEach { importsTrie.addFqn(it) }
environment.putUserData(PACKAGES_KEY, PackagesInfo(packageTrie, importsTrie))
}
fun getPackageMatchingFeatures(contextFeatures: ContextFeatures, psiClass: PsiClass): Map<String, MLFeatureValue> {
val packagesInfo = contextFeatures.getUserData(PACKAGES_KEY) ?: return emptyMap()
val packageName = PsiUtil.getPackageName(psiClass)
if (packageName == null || packageName.isEmpty()) return emptyMap()
val packagePartsCount = packageName.split(".").size
val result = mutableMapOf<String, MLFeatureValue>()
val packageMatchedParts = packagesInfo.packageName.matchedParts(packageName)
if (packageMatchedParts != 0) {
result["package_matched_parts"] = MLFeatureValue.numerical(packageMatchedParts)
result["package_matched_parts_relative"] = MLFeatureValue.numerical(packageMatchedParts.toDouble() / packagePartsCount)
}
val maxImportMatchedParts = packagesInfo.importPackages.matchedParts(packageName)
if (maxImportMatchedParts != 0) {
result["imports_max_matched_parts"] = MLFeatureValue.numerical(maxImportMatchedParts)
result["imports_max_matched_parts_relative"] = MLFeatureValue.numerical(maxImportMatchedParts.toDouble() / packagePartsCount)
}
return result
}
private fun getVariablesInScope(position: PsiElement, maxScope: PsiElement?, maxVariables: Int = 100): List<PsiVariable> {
val variables = mutableListOf<PsiVariable>()
val variablesProcessor = object : MacroUtil.VisibleVariablesProcessor(position, "", variables) {
override fun execute(pe: PsiElement, state: ResolveState): Boolean {
return variables.size < maxVariables && super.execute(pe, state)
}
}
PsiScopesUtil.treeWalkUp(variablesProcessor, position, maxScope)
return variables
}
private data class VariablesInfo(
val names: Set<String>,
val types: Set<PsiType>,
val names2types: Set<Pair<String, PsiType>>
)
private data class PackagesInfo(
val packageName: FqnTrie,
val importPackages: FqnTrie
)
class FqnTrie private constructor(private val level: Int) {
companion object {
fun create(): FqnTrie = FqnTrie(0)
fun withFqn(name: String): FqnTrie = create().also { it.addFqn(name) }
}
private val children = mutableMapOf<String, FqnTrie>()
fun addFqn(name: String) {
if (name.isEmpty()) return
val (prefix, postfix) = split(name)
children.getOrPut(prefix) { FqnTrie(level + 1) }.addFqn(postfix)
}
fun matchedParts(name: String): Int {
if (name.isEmpty()) return level
val (prefix, postfix) = split(name)
return children[prefix]?.matchedParts(postfix) ?: return level
}
private fun split(value: String): Pair<String, String> {
val index = value.indexOf('.')
return if (index < 0) Pair(value, "") else Pair(value.substring(0, index), value.substring(index + 1))
}
}
} | apache-2.0 | 923f275b78beb6559fd434b4c3646a4c | 36.619433 | 140 | 0.718545 | 4.484073 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/services/MarkCompletedService.kt | 1 | 1072 | package com.simplemobiletools.calendar.pro.services
import android.app.IntentService
import android.content.Intent
import com.simplemobiletools.calendar.pro.extensions.cancelNotification
import com.simplemobiletools.calendar.pro.extensions.cancelPendingIntent
import com.simplemobiletools.calendar.pro.extensions.eventsDB
import com.simplemobiletools.calendar.pro.extensions.updateTaskCompletion
import com.simplemobiletools.calendar.pro.helpers.ACTION_MARK_COMPLETED
import com.simplemobiletools.calendar.pro.helpers.EVENT_ID
class MarkCompletedService : IntentService("MarkCompleted") {
@Deprecated("Deprecated in Java")
override fun onHandleIntent(intent: Intent?) {
if (intent != null && intent.action == ACTION_MARK_COMPLETED) {
val taskId = intent.getLongExtra(EVENT_ID, 0L)
val task = eventsDB.getTaskWithId(taskId)
if (task != null) {
updateTaskCompletion(task, true)
cancelPendingIntent(task.id!!)
cancelNotification(task.id!!)
}
}
}
}
| gpl-3.0 | b89674e3e286ed2609c6e425bdd95ec6 | 40.230769 | 73 | 0.729478 | 4.681223 | false | false | false | false |
stefanmedack/cccTV | app/src/main/java/de/stefanmedack/ccctv/ui/events/EventsActivity.kt | 1 | 2096 | package de.stefanmedack.ccctv.ui.events
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.ActivityOptionsCompat
import de.stefanmedack.ccctv.R
import de.stefanmedack.ccctv.persistence.entities.Conference
import de.stefanmedack.ccctv.ui.base.BaseInjectableActivity
import de.stefanmedack.ccctv.util.FRAGMENT_ARGUMENTS
import de.stefanmedack.ccctv.util.addFragmentInTransaction
class EventsActivity : BaseInjectableActivity() {
private val EVENTS_TAG = "EVENTS_TAG"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.fragment_activity)
if (savedInstanceState == null) {
addFragmentInTransaction(
fragment = EventsFragment().apply { arguments = intent.getBundleExtra(FRAGMENT_ARGUMENTS) },
containerId = R.id.fragment,
tag = EVENTS_TAG)
}
}
companion object {
fun startForConference(activity: Activity, conference: Conference) {
val intent = Intent(activity.baseContext, EventsActivity::class.java)
intent.putExtra(FRAGMENT_ARGUMENTS, EventsFragment.getBundleForConference(
conferenceAcronym = conference.acronym,
title = conference.title,
conferenceLogoUrl = conference.logoUrl
))
activity.startActivity(intent, ActivityOptionsCompat.makeSceneTransitionAnimation(activity).toBundle())
}
fun startWithSearch(activity: Activity, searchQuery: String) {
val intent = Intent(activity.baseContext, EventsActivity::class.java)
intent.putExtra(FRAGMENT_ARGUMENTS, EventsFragment.getBundleForSearch(
searchQuery = searchQuery,
title = activity.getString(R.string.events_view_search_result_header, searchQuery)
))
activity.startActivity(intent, ActivityOptionsCompat.makeSceneTransitionAnimation(activity).toBundle())
}
}
}
| apache-2.0 | 8e72cf69e8c8c8b829f15d1384efe801 | 40.92 | 115 | 0.690363 | 5.200993 | false | false | false | false |
JetBrains/intellij-community | spellchecker/src/com/intellij/spellchecker/quickfixes/ChangeTo.kt | 1 | 3531 | // 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 com.intellij.spellchecker.quickfixes
import com.intellij.codeInsight.daemon.impl.UpdateHighlightersUtil
import com.intellij.codeInsight.intention.FileModifier
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInsight.intention.choice.ChoiceTitleIntentionAction
import com.intellij.codeInsight.intention.choice.ChoiceVariantIntentionAction
import com.intellij.codeInsight.intention.choice.DefaultIntentionActionWithChoice
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.SmartPointerManager
import com.intellij.refactoring.suggested.startOffset
import com.intellij.spellchecker.util.SpellCheckerBundle
class ChangeTo(typo: String, element: PsiElement, private val range: TextRange) : DefaultIntentionActionWithChoice, LazySuggestions(typo) {
private val pointer = SmartPointerManager.getInstance(element.project).createSmartPsiElementPointer(element, element.containingFile)
companion object {
@JvmStatic
val fixName: String by lazy {
SpellCheckerBundle.message("change.to.title")
}
}
private object ChangeToTitleAction : ChoiceTitleIntentionAction(fixName, fixName), HighPriorityAction
override fun getTitle(): ChoiceTitleIntentionAction = ChangeToTitleAction
private inner class ChangeToVariantAction(
override val index: Int
) : ChoiceVariantIntentionAction(), HighPriorityAction {
@NlsSafe
private var suggestion: String? = null
override fun getName(): String = suggestion ?: ""
override fun getTooltipText(): String = SpellCheckerBundle.message("change.to.tooltip", suggestion)
override fun getFamilyName(): String = fixName
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean {
val suggestions = getSuggestions(project)
if (suggestions.size <= index) return false
if (getRange(file.viewProvider.document) == null) return false
suggestion = suggestions[index]
return true
}
override fun applyFix(project: Project, file: PsiFile, editor: Editor?) {
val suggestion = suggestion ?: return
val document = file.viewProvider.document
val myRange = getRange(document) ?: return
UpdateHighlightersUtil.removeHighlightersWithExactRange(document, project, myRange)
document.replaceString(myRange.startOffset, myRange.endOffset, suggestion)
}
private fun getRange(document: Document): TextRange? {
val element = pointer.element ?: return null
val range = range.shiftRight(element.startOffset)
if (range.startOffset < 0 || range.endOffset > document.textLength) return null
val text = document.getText(range)
if (text != typo) return null
return range
}
override fun getFileModifierForPreview(target: PsiFile): FileModifier {
return this
}
override fun startInWriteAction(): Boolean = true
}
override fun getVariants(): List<ChoiceVariantIntentionAction> {
val limit = Registry.intValue("spellchecker.corrections.limit")
return (0 until limit).map { ChangeToVariantAction(it) }
}
} | apache-2.0 | f5c4f4475bbc64e6f1670309a486f6e6 | 37.391304 | 140 | 0.770603 | 4.897365 | false | false | false | false |
androidx/androidx | compose/integration-tests/macrobenchmark/src/androidTest/java/androidx/compose/integration/macrobenchmark/LazyBoxWithConstraintsScrollBenchmark.kt | 3 | 3163 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.integration.macrobenchmark
import android.content.Intent
import android.graphics.Point
import androidx.benchmark.macro.CompilationMode
import androidx.benchmark.macro.FrameTimingMetric
import androidx.benchmark.macro.junit4.MacrobenchmarkRule
import androidx.test.filters.LargeTest
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.By
import androidx.test.uiautomator.UiDevice
import androidx.test.uiautomator.Until
import androidx.testutils.createCompilationParams
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@LargeTest
@RunWith(Parameterized::class)
class LazyBoxWithConstraintsScrollBenchmark(
private val compilationMode: CompilationMode
) {
@get:Rule
val benchmarkRule = MacrobenchmarkRule()
private lateinit var device: UiDevice
@Before
fun setUp() {
val instrumentation = InstrumentationRegistry.getInstrumentation()
device = UiDevice.getInstance(instrumentation)
}
@Test
fun start() {
benchmarkRule.measureRepeated(
packageName = PACKAGE_NAME,
metrics = listOf(FrameTimingMetric()),
compilationMode = compilationMode,
iterations = 10,
setupBlock = {
val intent = Intent()
intent.action = ACTION
startActivityAndWait(intent)
}
) {
val lazyColumn = device.findObject(By.desc(CONTENT_DESCRIPTION))
// Setting a gesture margin is important otherwise gesture nav is triggered.
lazyColumn.setGestureMargin(device.displayWidth / 5)
for (i in 1..10) {
// From center we scroll 2/3 of it which is 1/3 of the screen.
lazyColumn.drag(Point(lazyColumn.visibleCenter.x, lazyColumn.visibleCenter.y / 3))
device.wait(Until.findObject(By.desc(COMPOSE_IDLE)), 3000)
}
}
}
companion object {
private const val PACKAGE_NAME = "androidx.compose.integration.macrobenchmark.target"
private const val ACTION =
"androidx.compose.integration.macrobenchmark.target.LAZY_BOX_WITH_CONSTRAINTS_ACTIVITY"
private const val CONTENT_DESCRIPTION = "IamLazy"
private const val COMPOSE_IDLE = "COMPOSE-IDLE"
@Parameterized.Parameters(name = "compilation={0}")
@JvmStatic
fun parameters() = createCompilationParams()
}
}
| apache-2.0 | 00790bd4d6a603dc8e591dc306052128 | 34.943182 | 99 | 0.702814 | 4.821646 | false | true | false | false |
androidx/androidx | bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/BluetoothClass.kt | 3 | 15211 | /*
* 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.bluetooth.core
import android.bluetooth.BluetoothClass as FwkBluetoothClass
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
/**
* Represents a Bluetooth class, which describes general characteristics
* and capabilities of a device. For example, a Bluetooth class will
* specify the general device type such as a phone, a computer, or
* headset, and whether it's capable of services such as audio or telephony.
*
* <p>Every Bluetooth class is composed of zero or more service classes, and
* exactly one device class. The device class is further broken down into major
* and minor device class components.
*
* <p>{@link BluetoothClass} is useful as a hint to roughly describe a device
* (for example to show an icon in the UI), but does not reliably describe which
* Bluetooth profiles or services are actually supported by a device. Accurate
* service discovery is done through SDP requests, which are automatically
* performed when creating an RFCOMM socket with {@link
* BluetoothDevice#createRfcommSocketToServiceRecord} and {@link
* BluetoothAdapter#listenUsingRfcommWithServiceRecord}</p>
*
* <p>Use {@link BluetoothDevice#getBluetoothClass} to retrieve the class for
* a remote device.
*
* <!--
* The Bluetooth class is a 32 bit field. The format of these bits is defined at
* http://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
* (login required). This class contains that 32 bit field, and provides
* constants and methods to determine which Service Class(es) and Device Class
* are encoded in that field.
* -->
*
* @hide
*/
class BluetoothClass internal constructor(private val fwkBluetoothClass: FwkBluetoothClass) :
Bundleable {
companion object {
const val PROFILE_HEADSET = 0 // FwkBluetoothClass.PROFILE_HEADSET
const val PROFILE_A2DP = 1 // FwkBluetoothClass.PROFILE_A2DP
const val PROFILE_HID = 3 // FwkBluetoothClass.PROFILE_HID
const val PROFILE_OPP = 2
const val PROFILE_PANU = 4
private const val PROFILE_NAP = 5
private const val PROFILE_A2DP_SINK = 6
internal const val FIELD_FWK_BLUETOOTH_CLASS = 1
internal fun keyForField(field: Int): String {
return field.toString(Character.MAX_RADIX)
}
val CREATOR: Bundleable.Creator<BluetoothClass> =
object : Bundleable.Creator<BluetoothClass> {
override fun fromBundle(bundle: Bundle): BluetoothClass {
val fwkBluetoothClass = Utils.getParcelableFromBundle(
bundle,
keyForField(FIELD_FWK_BLUETOOTH_CLASS),
FwkBluetoothClass::class.java
) ?: throw IllegalArgumentException(
"Bundle doesn't include " +
"BluetoothClass instance"
)
return BluetoothClass(fwkBluetoothClass)
}
}
}
/**
* Defines all service class constants.
*
* Each [BluetoothClass] encodes zero or more service classes.
*/
object Service {
const val LIMITED_DISCOVERABILITY = FwkBluetoothClass.Service.LIMITED_DISCOVERABILITY
/** Represent devices LE audio service */
const val LE_AUDIO = FwkBluetoothClass.Service.LE_AUDIO
const val POSITIONING = FwkBluetoothClass.Service.POSITIONING
const val NETWORKING = FwkBluetoothClass.Service.NETWORKING
const val RENDER = FwkBluetoothClass.Service.RENDER
const val CAPTURE = FwkBluetoothClass.Service.CAPTURE
const val OBJECT_TRANSFER = FwkBluetoothClass.Service.OBJECT_TRANSFER
const val AUDIO = FwkBluetoothClass.Service.AUDIO
const val TELEPHONY = FwkBluetoothClass.Service.TELEPHONY
const val INFORMATION = FwkBluetoothClass.Service.INFORMATION
}
/**
* Defines all device class constants.
*
* Each [BluetoothClass] encodes exactly one device class, with
* major and minor components.
*
* The constants in [ ] represent a combination of major and minor
* device components (the complete device class). The constants in [ ] represent only major
* device classes.
*
* See [BluetoothClass.Service] for service class constants.
*/
object Device {
// Devices in the COMPUTER major class
const val COMPUTER_UNCATEGORIZED = FwkBluetoothClass.Device.COMPUTER_UNCATEGORIZED
const val COMPUTER_DESKTOP = FwkBluetoothClass.Device.COMPUTER_DESKTOP
const val COMPUTER_SERVER = FwkBluetoothClass.Device.COMPUTER_SERVER
const val COMPUTER_LAPTOP = FwkBluetoothClass.Device.COMPUTER_LAPTOP
const val COMPUTER_HANDHELD_PC_PDA = FwkBluetoothClass.Device.COMPUTER_HANDHELD_PC_PDA
const val COMPUTER_PALM_SIZE_PC_PDA = FwkBluetoothClass.Device.COMPUTER_PALM_SIZE_PC_PDA
const val COMPUTER_WEARABLE = FwkBluetoothClass.Device.COMPUTER_WEARABLE
// Devices in the PHONE major class
const val PHONE_UNCATEGORIZED = FwkBluetoothClass.Device.PHONE_UNCATEGORIZED
const val PHONE_CELLULAR = FwkBluetoothClass.Device.PHONE_CELLULAR
const val PHONE_CORDLESS = FwkBluetoothClass.Device.PHONE_CORDLESS
const val PHONE_SMART = FwkBluetoothClass.Device.PHONE_SMART
const val PHONE_MODEM_OR_GATEWAY = FwkBluetoothClass.Device.PHONE_MODEM_OR_GATEWAY
const val PHONE_ISDN = FwkBluetoothClass.Device.PHONE_ISDN
// Minor classes for the AUDIO_VIDEO major class
const val AUDIO_VIDEO_UNCATEGORIZED = FwkBluetoothClass.Device.AUDIO_VIDEO_UNCATEGORIZED
const val AUDIO_VIDEO_WEARABLE_HEADSET =
FwkBluetoothClass.Device.AUDIO_VIDEO_WEARABLE_HEADSET
const val AUDIO_VIDEO_HANDSFREE = FwkBluetoothClass.Device.AUDIO_VIDEO_HANDSFREE
const val AUDIO_VIDEO_MICROPHONE = FwkBluetoothClass.Device.AUDIO_VIDEO_MICROPHONE
const val AUDIO_VIDEO_LOUDSPEAKER = FwkBluetoothClass.Device.AUDIO_VIDEO_LOUDSPEAKER
const val AUDIO_VIDEO_HEADPHONES = FwkBluetoothClass.Device.AUDIO_VIDEO_HEADPHONES
const val AUDIO_VIDEO_PORTABLE_AUDIO =
FwkBluetoothClass.Device.AUDIO_VIDEO_PORTABLE_AUDIO
const val AUDIO_VIDEO_CAR_AUDIO = FwkBluetoothClass.Device.AUDIO_VIDEO_CAR_AUDIO
const val AUDIO_VIDEO_SET_TOP_BOX = FwkBluetoothClass.Device.AUDIO_VIDEO_SET_TOP_BOX
const val AUDIO_VIDEO_HIFI_AUDIO = FwkBluetoothClass.Device.AUDIO_VIDEO_HIFI_AUDIO
const val AUDIO_VIDEO_VCR = FwkBluetoothClass.Device.AUDIO_VIDEO_VCR
const val AUDIO_VIDEO_VIDEO_CAMERA = FwkBluetoothClass.Device.AUDIO_VIDEO_VIDEO_CAMERA
const val AUDIO_VIDEO_CAMCORDER = FwkBluetoothClass.Device.AUDIO_VIDEO_CAMCORDER
const val AUDIO_VIDEO_VIDEO_MONITOR = FwkBluetoothClass.Device.AUDIO_VIDEO_VIDEO_MONITOR
const val AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER =
FwkBluetoothClass.Device.AUDIO_VIDEO_VIDEO_DISPLAY_AND_LOUDSPEAKER
const val AUDIO_VIDEO_VIDEO_CONFERENCING =
FwkBluetoothClass.Device.AUDIO_VIDEO_VIDEO_CONFERENCING
const val AUDIO_VIDEO_VIDEO_GAMING_TOY =
FwkBluetoothClass.Device.AUDIO_VIDEO_VIDEO_GAMING_TOY
// Devices in the WEARABLE major class
const val WEARABLE_UNCATEGORIZED = FwkBluetoothClass.Device.WEARABLE_UNCATEGORIZED
const val WEARABLE_WRIST_WATCH = FwkBluetoothClass.Device.WEARABLE_WRIST_WATCH
const val WEARABLE_PAGER = FwkBluetoothClass.Device.WEARABLE_PAGER
const val WEARABLE_JACKET = FwkBluetoothClass.Device.WEARABLE_JACKET
const val WEARABLE_HELMET = FwkBluetoothClass.Device.WEARABLE_HELMET
const val WEARABLE_GLASSES = FwkBluetoothClass.Device.WEARABLE_GLASSES
// Devices in the TOY major class
const val TOY_UNCATEGORIZED = FwkBluetoothClass.Device.TOY_UNCATEGORIZED
const val TOY_ROBOT = FwkBluetoothClass.Device.TOY_ROBOT
const val TOY_VEHICLE = FwkBluetoothClass.Device.TOY_VEHICLE
const val TOY_DOLL_ACTION_FIGURE = FwkBluetoothClass.Device.TOY_DOLL_ACTION_FIGURE
const val TOY_CONTROLLER = FwkBluetoothClass.Device.TOY_CONTROLLER
const val TOY_GAME = FwkBluetoothClass.Device.TOY_GAME
// Devices in the HEALTH major class
const val HEALTH_UNCATEGORIZED = FwkBluetoothClass.Device.HEALTH_UNCATEGORIZED
const val HEALTH_BLOOD_PRESSURE = FwkBluetoothClass.Device.HEALTH_BLOOD_PRESSURE
const val HEALTH_THERMOMETER = FwkBluetoothClass.Device.HEALTH_THERMOMETER
const val HEALTH_WEIGHING = FwkBluetoothClass.Device.HEALTH_WEIGHING
const val HEALTH_GLUCOSE = FwkBluetoothClass.Device.HEALTH_GLUCOSE
const val HEALTH_PULSE_OXIMETER = FwkBluetoothClass.Device.HEALTH_PULSE_OXIMETER
const val HEALTH_PULSE_RATE = FwkBluetoothClass.Device.HEALTH_PULSE_RATE
const val HEALTH_DATA_DISPLAY = FwkBluetoothClass.Device.HEALTH_DATA_DISPLAY
// Devices in PERIPHERAL major class
const val PERIPHERAL_NON_KEYBOARD_NON_POINTING =
0x0500 // FwkBluetoothClass.Device.PERIPHERAL_NON_KEYBOARD_NON_POINTING
const val PERIPHERAL_KEYBOARD =
0x0540 // FwkBluetoothClass.Device.PERIPHERAL_KEYBOARD
const val PERIPHERAL_POINTING =
0x0580 // FwkBluetoothClass.Device.PERIPHERAL_POINTING
const val PERIPHERAL_KEYBOARD_POINTING =
0x05C0 // FwkBluetoothClass.Device.PERIPHERAL_KEYBOARD_POINTING
/**
* Defines all major device class constants.
*
* See [BluetoothClass.Device] for minor classes.
*/
object Major {
const val MISC = FwkBluetoothClass.Device.Major.MISC
const val COMPUTER = FwkBluetoothClass.Device.Major.COMPUTER
const val PHONE = FwkBluetoothClass.Device.Major.PHONE
const val NETWORKING = FwkBluetoothClass.Device.Major.NETWORKING
const val AUDIO_VIDEO = FwkBluetoothClass.Device.Major.AUDIO_VIDEO
const val PERIPHERAL = FwkBluetoothClass.Device.Major.PERIPHERAL
const val IMAGING = FwkBluetoothClass.Device.Major.IMAGING
const val WEARABLE = FwkBluetoothClass.Device.Major.WEARABLE
const val TOY = FwkBluetoothClass.Device.Major.TOY
const val HEALTH = FwkBluetoothClass.Device.Major.HEALTH
const val UNCATEGORIZED = FwkBluetoothClass.Device.Major.UNCATEGORIZED
}
}
/**
* Return the major device class component of this [BluetoothClass].
*
* Values returned from this function can be compared with the
* public constants in [BluetoothClass.Device.Major] to determine
* which major class is encoded in this Bluetooth class.
*
* @return major device class component
*/
val majorDeviceClass: Int
get() = fwkBluetoothClass.majorDeviceClass
/**
* Return the (major and minor) device class component of this
* [BluetoothClass].
*
* Values returned from this function can be compared with the
* public constants in [BluetoothClass.Device] to determine which
* device class is encoded in this Bluetooth class.
*
* @return device class component
*/
val deviceClass: Int
get() = fwkBluetoothClass.deviceClass
/**
* Return true if the specified service class is supported by this
* [BluetoothClass].
*
* Valid service classes are the public constants in
* [BluetoothClass.Service]. For example, [ ][BluetoothClass.Service.AUDIO].
*
* @param service valid service class
* @return true if the service class is supported
*/
fun hasService(service: Int): Boolean {
return fwkBluetoothClass.hasService(service)
}
override fun toBundle(): Bundle {
val bundle = Bundle()
bundle.putParcelable(keyForField(FIELD_FWK_BLUETOOTH_CLASS), fwkBluetoothClass)
return bundle
}
@SuppressLint("ClassVerificationFailure") // fwkBluetoothClass.doesClassMatch(profile)
fun doesClassMatch(profile: Int): Boolean {
if (Build.VERSION.SDK_INT >= 33) {
// TODO: change to Impl hierarchy when additional SDK checks are needed
return fwkBluetoothClass.doesClassMatch(profile)
}
return when (profile) {
PROFILE_A2DP -> {
if (hasService(Service.RENDER)) {
return true
}
when (deviceClass) {
Device.AUDIO_VIDEO_HIFI_AUDIO, Device.AUDIO_VIDEO_HEADPHONES,
Device.AUDIO_VIDEO_LOUDSPEAKER, Device.AUDIO_VIDEO_CAR_AUDIO -> true
else -> false
}
}
PROFILE_A2DP_SINK -> {
if (hasService(Service.CAPTURE)) {
return true
}
when (deviceClass) {
Device.AUDIO_VIDEO_HIFI_AUDIO, Device.AUDIO_VIDEO_SET_TOP_BOX,
Device.AUDIO_VIDEO_VCR -> true
else -> false
}
}
PROFILE_HEADSET -> {
if (hasService(Service.RENDER)) {
return true
}
when (deviceClass) {
Device.AUDIO_VIDEO_HANDSFREE, Device.AUDIO_VIDEO_WEARABLE_HEADSET,
Device.AUDIO_VIDEO_CAR_AUDIO -> true
else -> false
}
}
PROFILE_OPP -> {
if (hasService(Service.OBJECT_TRANSFER)) {
return true
}
when (deviceClass) {
Device.COMPUTER_UNCATEGORIZED, Device.COMPUTER_DESKTOP, Device.COMPUTER_SERVER,
Device.COMPUTER_LAPTOP, Device.COMPUTER_HANDHELD_PC_PDA,
Device.COMPUTER_PALM_SIZE_PC_PDA, Device.COMPUTER_WEARABLE,
Device.PHONE_UNCATEGORIZED, Device.PHONE_CELLULAR, Device.PHONE_CORDLESS,
Device.PHONE_SMART, Device.PHONE_MODEM_OR_GATEWAY, Device.PHONE_ISDN -> true
else -> false
}
}
PROFILE_HID -> {
majorDeviceClass == Device.Major.PERIPHERAL
}
PROFILE_NAP, PROFILE_PANU -> {
if (hasService(Service.NETWORKING)) {
true
} else majorDeviceClass == Device.Major.NETWORKING
}
else -> false
}
}
} | apache-2.0 | f3325227dd4a0ba5656bfc286d5a2503 | 45.237082 | 99 | 0.669778 | 4.895719 | false | false | false | false |
androidx/androidx | benchmark/benchmark-common/src/main/java/androidx/benchmark/IsolationActivity.kt | 3 | 7368 | /*
* 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.benchmark
import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Process
import android.util.Log
import android.view.WindowManager
import android.widget.TextView
import androidx.annotation.AnyThread
import androidx.annotation.RestrictTo
import androidx.annotation.WorkerThread
import androidx.test.platform.app.InstrumentationRegistry
import java.util.concurrent.atomic.AtomicReference
import kotlin.concurrent.thread
/**
* Simple opaque activity used to reduce benchmark interference from other windows.
*
* For example, sources of potential interference:
* - live wallpaper rendering
* - homescreen widget updates
* - hotword detection
* - status bar repaints
* - running in background (some cores may be foreground-app only)
*
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
public class IsolationActivity : android.app.Activity() {
private var destroyed = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.isolation_activity)
// disable launch animation
overridePendingTransition(0, 0)
if (firstInit) {
if (!CpuInfo.locked && isSustainedPerformanceModeSupported()) {
@Suppress("SyntheticAccessor")
sustainedPerformanceModeInUse = true
}
application.registerActivityLifecycleCallbacks(activityLifecycleCallbacks)
// trigger the one missed lifecycle event, from registering the callbacks late
activityLifecycleCallbacks.onActivityCreated(this, savedInstanceState)
if (sustainedPerformanceModeInUse) {
// Keep at least one core busy. Together with a single threaded benchmark, this
// makes the process get multi-threaded setSustainedPerformanceMode.
//
// We want to keep to the relatively lower clocks of the multi-threaded benchmark
// mode to avoid any benchmarks running at higher clocks than any others.
//
// Note, thread names have 15 char max in Systrace
thread(name = "BenchSpinThread") {
Process.setThreadPriority(Process.THREAD_PRIORITY_LOWEST)
while (true) {
}
}
}
firstInit = false
}
val old = singleton.getAndSet(this)
if (old != null && !old.destroyed && !old.isFinishing) {
throw IllegalStateException("Only one IsolationActivity should exist")
}
findViewById<TextView>(R.id.clock_state).text = when {
CpuInfo.locked -> "Locked Clocks"
sustainedPerformanceModeInUse -> "Sustained Performance Mode"
else -> ""
}
}
override fun onResume() {
super.onResume()
@Suppress("SyntheticAccessor")
resumed = true
}
override fun onPause() {
super.onPause()
@Suppress("SyntheticAccessor")
resumed = false
}
override fun onDestroy() {
super.onDestroy()
destroyed = true
}
/** finish is ignored! we defer until [actuallyFinish] is called. */
override fun finish() {
}
public fun actuallyFinish() {
// disable close animation
overridePendingTransition(0, 0)
super.finish()
}
public companion object {
private const val TAG = "Benchmark"
internal val singleton = AtomicReference<IsolationActivity>()
private var firstInit = true
internal var sustainedPerformanceModeInUse = false
private set
public var resumed: Boolean = false
private set
@WorkerThread
public fun launchSingleton() {
val intent = Intent(Intent.ACTION_MAIN).apply {
Log.d(TAG, "launching Benchmark IsolationActivity")
setClassName(
InstrumentationRegistry.getInstrumentation().targetContext.packageName,
IsolationActivity::class.java.name
)
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP)
}
InstrumentationRegistry.getInstrumentation().startActivitySync(intent)
}
@AnyThread
public fun finishSingleton() {
Log.d(TAG, "Benchmark runner being destroyed, tearing down activities")
singleton.getAndSet(null)?.apply {
runOnUiThread {
actuallyFinish()
}
}
}
internal fun isSustainedPerformanceModeSupported(): Boolean =
if (Build.VERSION.SDK_INT >= 24) {
InstrumentationRegistry
.getInstrumentation()
.isSustainedPerformanceModeSupported()
} else {
false
}
private val activityLifecycleCallbacks = object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, bundle: Bundle?) {
if (sustainedPerformanceModeInUse && Build.VERSION.SDK_INT >= 24) {
activity.setSustainedPerformanceMode(true)
}
// Forcibly wake the device, and keep the screen on to prevent benchmark failures.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
activity.requestDismissKeyguard()
activity.setShowWhenLocked()
activity.setTurnScreenOn()
activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
} else {
@Suppress("DEPRECATION")
activity.window.addFlags(
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
or WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
or WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
or WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
)
}
}
override fun onActivityDestroyed(activity: Activity) {}
override fun onActivitySaveInstanceState(activity: Activity, bundle: Bundle) {}
override fun onActivityStarted(activity: Activity) {}
override fun onActivityStopped(activity: Activity) {}
override fun onActivityPaused(activity: Activity) {}
override fun onActivityResumed(activity: Activity) {}
}
}
} | apache-2.0 | 0675ac5930c78d1e8b5ad92f1b551928 | 36.406091 | 98 | 0.623914 | 5.527382 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ExplicitThisInspection.kt | 5 | 5744 | // 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.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.descriptors.impl.LocalVariableDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
class ExplicitThisInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitExpression(expression: KtExpression) {
val thisExpression = expression.thisAsReceiverOrNull() ?: return
if (hasExplicitThis(expression)) {
holder.registerProblem(
thisExpression,
KotlinBundle.message("redundant.explicit.this"),
ExplicitThisExpressionFix(thisExpression.text)
)
}
}
}
companion object {
fun KtExpression.thisAsReceiverOrNull() = when (this) {
is KtCallableReferenceExpression -> receiverExpression as? KtThisExpression
is KtDotQualifiedExpression -> receiverExpression as? KtThisExpression
else -> null
}
fun hasExplicitThis(expression: KtExpression): Boolean {
val thisExpression = expression.thisAsReceiverOrNull() ?: return false
val reference = when (expression) {
is KtCallableReferenceExpression -> expression.callableReference
is KtDotQualifiedExpression -> expression.selectorExpression as? KtReferenceExpression
else -> null
} ?: return false
val context = expression.analyze()
val scope = expression.getResolutionScope(context) ?: return false
val referenceExpression = reference as? KtNameReferenceExpression ?: reference.getChildOfType() ?: return false
val receiverType = context[BindingContext.EXPRESSION_TYPE_INFO, thisExpression]?.type ?: return false
//we avoid overload-related problems by enforcing that there is only one candidate
val name = referenceExpression.getReferencedNameAsName()
val candidates = if (reference is KtCallExpression
|| (expression is KtCallableReferenceExpression && reference.mainReference.resolve() is KtFunction)
) {
scope.getAllAccessibleFunctions(name) +
scope.getAllAccessibleVariables(name).filter { it is LocalVariableDescriptor && it.canInvoke() }
} else {
scope.getAllAccessibleVariables(name)
}
if (referenceExpression.getCallableDescriptor() is SyntheticJavaPropertyDescriptor) {
if (candidates.map { it.containingDeclaration }.distinct().size != 1) return false
} else {
val candidate = candidates.singleOrNull() ?: return false
val extensionType = candidate.extensionReceiverParameter?.type
if (extensionType != null && extensionType != receiverType && receiverType.isSubtypeOf(extensionType)) return false
}
val expressionFactory = scope.getFactoryForImplicitReceiverWithSubtypeOf(receiverType) ?: return false
val label = thisExpression.getLabelName() ?: ""
if (!expressionFactory.matchesLabel(label)) return false
return true
}
private fun VariableDescriptor.canInvoke(): Boolean {
val declarationDescriptor = this.type.constructor.declarationDescriptor as? LazyClassDescriptor ?: return false
return declarationDescriptor.declaredCallableMembers.any { (it as? FunctionDescriptor)?.isOperator == true }
}
private fun ReceiverExpressionFactory.matchesLabel(label: String): Boolean {
val implicitLabel = expressionText.substringAfter("@", "")
return label == implicitLabel || (label == "" && isImmediate)
}
}
}
class ExplicitThisExpressionFix(private val text: String) : LocalQuickFix {
override fun getFamilyName(): String = KotlinBundle.message("explicit.this.expression.fix.family.name", text)
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val thisExpression = descriptor.psiElement as? KtThisExpression ?: return
removeExplicitThisExpression(thisExpression)
}
companion object {
fun removeExplicitThisExpression(thisExpression: KtThisExpression) {
when (val parent = thisExpression.parent) {
is KtDotQualifiedExpression -> parent.replace(parent.selectorExpression ?: return)
is KtCallableReferenceExpression -> thisExpression.delete()
}
}
}
}
| apache-2.0 | 05a57aeba15a19d4fa76f239b5e323a6 | 49.385965 | 131 | 0.70282 | 5.873211 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/slicer/AbstractSlicerMultiplatformTest.kt | 4 | 1372 | // 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.slicer
import com.intellij.psi.PsiDocumentManager
import org.jetbrains.kotlin.idea.multiplatform.setupMppProjectFromDirStructure
import org.jetbrains.kotlin.idea.stubs.AbstractMultiModuleTest
import org.jetbrains.kotlin.idea.test.IDEA_TEST_DATA_DIR
import org.jetbrains.kotlin.idea.test.extractMarkerOffset
import org.jetbrains.kotlin.idea.test.findFileWithCaret
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.idea.test.KotlinTestUtils
import java.io.File
abstract class AbstractSlicerMultiplatformTest : AbstractMultiModuleTest() {
override fun getTestDataDirectory() = IDEA_TEST_DATA_DIR.resolve("slicer/mpp")
protected fun doTest(filePath: String) {
val testRoot = File(filePath)
setupMppProjectFromDirStructure(testRoot)
val file = project.findFileWithCaret() as KtFile
val document = PsiDocumentManager.getInstance(myProject).getDocument(file)!!
val offset = document.extractMarkerOffset(project, "<caret>")
testSliceFromOffset(file, offset) { _, rootNode ->
KotlinTestUtils.assertEqualsToFile(testRoot.resolve("results.txt"), buildTreeRepresentation(rootNode))
}
}
}
| apache-2.0 | 18e70dd5be2cc1d85e5bf7d7051fb351 | 44.733333 | 158 | 0.777697 | 4.635135 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/unboxParam.kt | 13 | 318 | package unboxParam
fun main(args: Array<String>) {
val nullableInt = fooNullableInt()
if (nullableInt == null) {
return
}
// EXPRESSION: fooInt(nullableInt)
// RESULT: 1: I
//Breakpoint!
val a = fooInt(nullableInt)
}
fun fooNullableInt(): Int? = 1
fun fooInt(param: Int) = param | apache-2.0 | 724db08e45964dfe66a7f3f8395634f7 | 17.764706 | 38 | 0.625786 | 3.613636 | false | false | false | false |
GunoH/intellij-community | plugins/full-line/java/test/org/jetbrains/completion/full/line/java/formatters/JavaFilesPsiCodeFormatterTest.kt | 2 | 3161 | package org.jetbrains.completion.full.line.java.formatters
internal sealed class JavaFilesPsiCodeFormatterTest : JavaPsiCodeFormatterTest() {
protected abstract val folder: String
protected fun doTest(vararg tokens: String) {
testFile("$folder/${getTestName(true)}.java", tokens.asList(), "java")
}
internal class InsideFunctionTests : JavaFilesPsiCodeFormatterTest() {
override val folder = "inside-function"
fun testData1() = doTest("f")
fun testData2() = doTest("System", ".", "out", ".", "println", "(")
fun testData3() = doTest("f", "(", ")")
fun testData4() = doTest("System", ".", "out", ".", "println", "(", "\"main functio")
fun testData5() = doTest("in")
fun testData6() = doTest()
fun testData7() = doTest("int", "y", "=")
fun testData8() = doTest("int", "y", "=")
fun testData9() = doTest("Stream", ".", "of", "(", "1", ",", "2", ")", ".", "map", "(", "x", "->", "x", ")", ".", "forEach", "(")
fun testData10() = doTest("int", "y", "=")
fun testData11() = doTest("for", "(", "int", "i", "=", "0", ";", "i", "<", "10", ";")
fun testData12() = doTest()
fun testData13() = doTest("this", ".", "x")
fun testData14() = doTest("f", "(", ")")
fun testData15() = doTest()
}
internal class InsideClass : JavaFilesPsiCodeFormatterTest() {
override val folder = "inside-class"
fun testData1() = doTest("public", "seco")
fun testData2() = doTest("private", "int")
fun testData3() = doTest("pr")
fun testData4() = doTest()
fun testData5() = doTest("private")
fun testData6() = doTest()
fun testData7() = doTest("pri")
fun testData8() = doTest("int")
fun testData9() = doTest("in")
fun testData10() = doTest("vo")
fun testData11() = doTest("public", "vo")
fun testData12() = doTest("public", "vo")
fun testData13() = doTest("vo")
fun testData14() = doTest("void", "f", "(")
fun testData15() = doTest("void", "f", "(", "0", "<", "1", ",", "10", ",")
// TODO optimize prefix
fun testData16() = doTest("@", "Annotation1", "@", "Annotation2")
// TODO optimize prefix
fun testData17() = doTest("@", "Annotation1", "@", "Annotati")
fun testData18() = doTest("vo")
fun testData19() = doTest("public", "vo")
fun testData20() = doTest("public", "void", "g")
fun testData21() = doTest("private", "int", "x")
// TODO keep javadoc in json
fun testData22() = doTest("public", "static", "void", "mai")
}
internal class InsideFile : JavaFilesPsiCodeFormatterTest() {
override val folder = "inside-file"
fun testData1() = doTest()
fun testData2() = doTest("package", "mock_data", ".")
fun testData3() = doTest()
fun testData4() = doTest()
fun testData5() = doTest("import", "java", ".")
fun testData6() = doTest("public", "class", "Ma")
fun testData7() = doTest("public", "class", "List")
fun testData8() = doTest("public", "class", "List", "extend")
fun testData9() = doTest("public", "class", "List", "extends")
fun testData10() = doTest("imp")
fun testData11() = doTest("import")
}
}
| apache-2.0 | 9bfb45aac16b48e2dae1899b253d5d2e | 25.123967 | 133 | 0.56944 | 3.803851 | false | true | false | false |
danielgindi/android-helpers | Helpers/src/main/java/com/dg/controls/SwipeRefreshLayoutEx.kt | 1 | 1350 | package com.dg.controls
import android.content.Context
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import android.util.AttributeSet
@Suppress("unused")
class SwipeRefreshLayoutEx : SwipeRefreshLayout
{
private var mMeasured = false
private var mHasPostponedSetRefreshing = false
private var mPreMeasureRefreshing = false
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
// There's a bug where setRefreshing(...) before onMeasure() has no effect at all.
if (!mMeasured)
{
mMeasured = true
if (mHasPostponedSetRefreshing)
{
isRefreshing = mPreMeasureRefreshing
}
}
}
override fun setRefreshing(refreshing: Boolean)
{
if (mMeasured)
{
mHasPostponedSetRefreshing = false
super.setRefreshing(refreshing)
}
else
{
// onMeasure was not called yet, so we postpone the setRefreshing until after onMeasure
mHasPostponedSetRefreshing = true
mPreMeasureRefreshing = refreshing
}
}
}
| mit | a40866251d2a9ab809b0000d11eb0091 | 27.125 | 99 | 0.654074 | 5.232558 | false | false | false | false |
jwren/intellij-community | notebooks/visualization/src/org/jetbrains/plugins/notebooks/visualization/outputs/impl/SurroundingComponent.kt | 2 | 1761 | package org.jetbrains.plugins.notebooks.visualization.outputs.impl
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.ui.IdeBorderFactory
import org.jetbrains.plugins.notebooks.visualization.outputs.NotebookOutputComponentWrapper
import org.jetbrains.plugins.notebooks.visualization.outputs.getEditorBackground
import org.jetbrains.plugins.notebooks.visualization.ui.registerEditorSizeWatcher
import org.jetbrains.plugins.notebooks.visualization.ui.textEditingAreaWidth
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.Insets
import javax.swing.JPanel
internal class SurroundingComponent private constructor(private val innerComponent: InnerComponent) : JPanel(
BorderLayout()) {
private var presetWidth = 0
init {
border = IdeBorderFactory.createEmptyBorder(Insets(10, 0, 0, 0))
add(innerComponent, BorderLayout.CENTER)
}
override fun updateUI() {
super.updateUI()
isOpaque = true
background = getEditorBackground()
}
override fun getPreferredSize(): Dimension = super.getPreferredSize().also {
it.width = presetWidth
// No need to show anything for the empty component
if (innerComponent.preferredSize.height == 0) {
it.height = 0
}
}
companion object {
@JvmStatic
fun create(
editor: EditorImpl,
innerComponent: InnerComponent,
) = SurroundingComponent(innerComponent).also {
registerEditorSizeWatcher(it) {
val oldWidth = it.presetWidth
it.presetWidth = editor.textEditingAreaWidth
if (oldWidth != it.presetWidth) {
innerComponent.revalidate()
}
}
for (wrapper in NotebookOutputComponentWrapper.EP_NAME.extensionList) {
wrapper.wrap(it)
}
}
}
} | apache-2.0 | 414338f103df2972d6ca50d261bb099c | 30.464286 | 109 | 0.742192 | 4.550388 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/AddBracesIntention.kt | 3 | 4985 | // 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.openapi.editor.Editor
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.refactoring.getLineNumber
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
class AddBracesIntention : SelfTargetingIntention<KtElement>(KtElement::class.java, KotlinBundle.lazyMessage("add.braces")) {
override fun isApplicableTo(element: KtElement, caretOffset: Int): Boolean {
val expression = element.getTargetExpression(caretOffset) ?: return false
if (expression is KtBlockExpression) return false
return when (val parent = expression.parent) {
is KtContainerNode -> {
val description = parent.description() ?: return false
setTextGetter(KotlinBundle.lazyMessage("add.braces.to.0.statement", description))
true
}
is KtWhenEntry -> {
setTextGetter(KotlinBundle.lazyMessage("add.braces.to.when.entry"))
true
}
else -> {
false
}
}
}
override fun applyTo(element: KtElement, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val expression = element.getTargetExpression(editor.caretModel.offset) ?: return
addBraces(element, expression)
}
private fun KtElement.getTargetExpression(caretLocation: Int): KtExpression? {
return when (this) {
is KtIfExpression -> {
val thenExpr = then ?: return null
val elseExpr = `else`
if (elseExpr != null && caretLocation >= (elseKeyword?.startOffset ?: return null)) {
elseExpr
} else {
thenExpr
}
}
is KtLoopExpression -> body
is KtWhenEntry -> expression
else -> null
}
}
companion object {
fun addBraces(element: KtElement, expression: KtExpression) {
val psiFactory = KtPsiFactory(element)
val semicolon = element.getNextSiblingIgnoringWhitespaceAndComments()?.takeIf { it.node.elementType == KtTokens.SEMICOLON }
if (semicolon != null) {
val afterSemicolon = semicolon.getNextSiblingIgnoringWhitespace()
if (semicolon.getLineNumber() == afterSemicolon?.getLineNumber())
semicolon.replace(psiFactory.createNewLine())
else
semicolon.delete()
}
val nextComment = when {
element is KtDoWhileExpression -> null // bound to the closing while
element is KtIfExpression && expression === element.then && element.`else` != null -> null // bound to else
else -> {
val nextSibling = element.getNextSiblingIgnoringWhitespace() ?: element.parent.getNextSiblingIgnoringWhitespace()
nextSibling.takeIf { it is PsiComment && it.getLineNumber() == element.getLineNumber(start = false) }
}
}
nextComment?.delete()
val allChildren = element.allChildren
val (first, last) = when (element) {
is KtIfExpression -> element.rightParenthesis to allChildren.last
is KtForExpression -> element.rightParenthesis to allChildren.last
is KtWhileExpression -> element.rightParenthesis to allChildren.last
is KtWhenEntry -> element.arrow to allChildren.last
is KtDoWhileExpression -> allChildren.first to element.whileKeyword
else -> null to null
}
val saver = if (first != null && last != null) {
val range = PsiChildRange(first, last)
CommentSaver(range).also {
range.filterIsInstance<PsiComment>().toList().forEach { it.delete() }
}
} else {
null
}
val result = expression.replace(psiFactory.createSingleStatementBlock(expression, nextComment = nextComment?.text))
when (element) {
is KtDoWhileExpression ->
// remove new line between '}' and while
(element.body?.parent?.nextSibling as? PsiWhiteSpace)?.delete()
is KtIfExpression ->
(result?.parent?.nextSibling as? PsiWhiteSpace)?.delete()
}
saver?.restore(result, forceAdjustIndent = false)
}
}
}
| apache-2.0 | d06f7616a57644e1ff3f4f6ee8c0f361 | 43.508929 | 158 | 0.601204 | 5.677677 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/ArgumentNameHints.kt | 3 | 5639 | // 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.parameterInfo
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.prevLeafs
import org.jetbrains.kotlin.builtins.extractParameterNameFromFunctionTypeArgument
import org.jetbrains.kotlin.builtins.functions.FunctionInvokeDescriptor
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.core.resolveCandidates
import org.jetbrains.kotlin.idea.intentions.AddNamesInCommentToJavaCallArgumentsIntention.Companion.toCommentedParameterName
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.descriptors.JavaClassConstructorDescriptor
import org.jetbrains.kotlin.load.java.descriptors.JavaMethodDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.util.getCall
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.isAnnotationConstructor
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
fun provideArgumentNameHints(element: KtCallElement): List<InlayInfo> {
if (element.valueArguments.none { it.getArgumentExpression()?.isUnclearExpression() == true }) return emptyList()
val ctx = element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val call = element.getCall(ctx) ?: return emptyList()
val resolvedCall = call.getResolvedCall(ctx)
if (resolvedCall != null) {
return getArgumentNameHintsForCallCandidate(resolvedCall, call.valueArgumentList)
}
val candidates = call.resolveCandidates(ctx, element.getResolutionFacade())
if (candidates.isEmpty()) return emptyList()
candidates.singleOrNull()?.let { return getArgumentNameHintsForCallCandidate(it, call.valueArgumentList) }
return candidates.map { getArgumentNameHintsForCallCandidate(it, call.valueArgumentList) }.reduce { infos1, infos2 ->
for (index in infos1.indices) {
if (index >= infos2.size || infos1[index] != infos2[index]) {
return@reduce infos1.subList(0, index)
}
}
infos1
}
}
private fun getArgumentNameHintsForCallCandidate(
resolvedCall: ResolvedCall<out CallableDescriptor>,
valueArgumentList: KtValueArgumentList?
): List<InlayInfo> {
val resultingDescriptor = resolvedCall.resultingDescriptor
if (resultingDescriptor.hasSynthesizedParameterNames() && resultingDescriptor !is FunctionInvokeDescriptor) {
return emptyList()
}
if (resultingDescriptor.valueParameters.size == 1
&& resultingDescriptor.name == resultingDescriptor.valueParameters.single().name
) {
// method name equals to single parameter name
return emptyList()
}
return resolvedCall.valueArguments.mapNotNull { (valueParam: ValueParameterDescriptor, resolvedArg) ->
if (resultingDescriptor.isAnnotationConstructor() && valueParam.name.asString() == "value") {
return@mapNotNull null
}
if (resultingDescriptor is FunctionInvokeDescriptor &&
valueParam.type.extractParameterNameFromFunctionTypeArgument() == null
) {
return@mapNotNull null
}
if (resolvedArg == resolvedCall.valueArgumentsByIndex?.firstOrNull()
&& resultingDescriptor.valueParameters.firstOrNull()?.name == resultingDescriptor.name) {
// first argument with the same name as method name
return@mapNotNull null
}
resolvedArg.arguments.firstOrNull()?.let { arg ->
arg.getArgumentExpression()?.let { argExp ->
if (!arg.isNamed() && !argExp.isAnnotatedWithComment(valueParam, resultingDescriptor) && !valueParam.name.isSpecial && argExp.isUnclearExpression()) {
val prefix = if (valueParam.varargElementType != null) "..." else ""
val offset = if (arg == valueArgumentList?.arguments?.firstOrNull() && valueParam.varargElementType != null)
valueArgumentList.leftParenthesis?.textRange?.endOffset ?: argExp.startOffset
else
arg.getSpreadElement()?.startOffset ?: argExp.startOffset
return@mapNotNull InlayInfo(prefix + valueParam.name.identifier + ":", offset)
}
}
}
null
}
}
private fun KtExpression.isUnclearExpression() = when (this) {
is KtConstantExpression, is KtThisExpression, is KtBinaryExpression, is KtStringTemplateExpression -> true
is KtPrefixExpression -> baseExpression is KtConstantExpression && (operationToken == KtTokens.PLUS || operationToken == KtTokens.MINUS)
else -> false
}
private fun KtExpression.isAnnotatedWithComment(valueParameter: ValueParameterDescriptor, descriptor: CallableDescriptor): Boolean =
(descriptor is JavaMethodDescriptor || descriptor is JavaClassConstructorDescriptor) &&
prevLeafs
.takeWhile { it is PsiWhiteSpace || it is PsiComment }
.any { it is PsiComment && it.text == valueParameter.toCommentedParameterName() } | apache-2.0 | f3cc0a1c1f3a9e8b997b5d718eea5b16 | 51.222222 | 166 | 0.735237 | 5.324835 | false | false | false | false |
jwren/intellij-community | platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ExternalSystemModulePropertyManagerBridge.kt | 2 | 7651 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.externalSystem.service.project
import com.intellij.openapi.application.WriteAction
import com.intellij.openapi.externalSystem.ExternalSystemModulePropertyManager
import com.intellij.openapi.externalSystem.model.ProjectSystemId
import com.intellij.openapi.externalSystem.model.project.ModuleData
import com.intellij.openapi.externalSystem.model.project.ProjectData
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.isExternalStorageEnabled
import com.intellij.openapi.roots.ExternalProjectSystemRegistry
import com.intellij.workspaceModel.ide.JpsFileEntitySource
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerBridgeImpl.Companion.findModuleEntity
import com.intellij.workspaceModel.ide.legacyBridge.ModuleBridge
import com.intellij.workspaceModel.storage.WorkspaceEntityStorage
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageBuilder
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.ExternalSystemModuleOptionsEntity
import com.intellij.workspaceModel.storage.bridgeEntities.ModifiableExternalSystemModuleOptionsEntity
import com.intellij.workspaceModel.storage.bridgeEntities.externalSystemOptions
import com.intellij.workspaceModel.storage.bridgeEntities.getOrCreateExternalSystemModuleOptions
class ExternalSystemModulePropertyManagerBridge(private val module: Module) : ExternalSystemModulePropertyManager() {
private fun findEntity(): ExternalSystemModuleOptionsEntity? {
val modelsProvider = module.getUserData(IdeModifiableModelsProviderImpl.MODIFIABLE_MODELS_PROVIDER_KEY)
val storage = if (modelsProvider != null) modelsProvider.actualStorageBuilder else (module as ModuleBridge).entityStorage.current
val moduleEntity = storage.findModuleEntity(module as ModuleBridge)
return moduleEntity?.externalSystemOptions
}
@Synchronized
private fun editEntity(action: ModifiableExternalSystemModuleOptionsEntity.() -> Unit) {
editEntity(getModuleDiff(), action)
}
@Synchronized
private fun editEntity(moduleDiff: WorkspaceEntityStorageDiffBuilder?, action: ModifiableExternalSystemModuleOptionsEntity.() -> Unit) {
module as ModuleBridge
if (moduleDiff != null) {
val moduleEntity = (moduleDiff as WorkspaceEntityStorage).findModuleEntity(module) ?: return
val options = moduleDiff.getOrCreateExternalSystemModuleOptions(moduleEntity, moduleEntity.entitySource)
moduleDiff.modifyEntity(ModifiableExternalSystemModuleOptionsEntity::class.java, options, action)
}
else {
WriteAction.runAndWait<RuntimeException> {
WorkspaceModel.getInstance(module.project).updateProjectModel { builder ->
val moduleEntity = builder.findModuleEntity(module) ?: return@updateProjectModel
val options = builder.getOrCreateExternalSystemModuleOptions(moduleEntity, moduleEntity.entitySource)
builder.modifyEntity(ModifiableExternalSystemModuleOptionsEntity::class.java, options, action)
}
}
}
}
@Synchronized
private fun updateSource() {
updateSource(getModuleDiff())
}
@Synchronized
private fun updateSource(storageBuilder: WorkspaceEntityStorageBuilder?) {
module as ModuleBridge
val storage = storageBuilder ?: module.entityStorage.current
val moduleEntity = storage.findModuleEntity(module) ?: return
val externalSystemId = moduleEntity.externalSystemOptions?.externalSystem
val entitySource = moduleEntity.entitySource
if (externalSystemId == null && entitySource is JpsFileEntitySource ||
externalSystemId != null && (entitySource as? JpsImportedEntitySource)?.externalSystemId == externalSystemId &&
entitySource.storedExternally == module.project.isExternalStorageEnabled ||
entitySource !is JpsFileEntitySource && entitySource !is JpsImportedEntitySource) {
return
}
val newSource = if (externalSystemId == null) {
(entitySource as JpsImportedEntitySource).internalFile
}
else {
val internalFile = entitySource as? JpsFileEntitySource ?: (entitySource as JpsImportedEntitySource).internalFile
JpsImportedEntitySource(internalFile, externalSystemId, module.project.isExternalStorageEnabled)
}
ModuleManagerBridgeImpl.changeModuleEntitySource(module, storage, newSource, storageBuilder)
}
override fun getExternalSystemId(): String? = findEntity()?.externalSystem
override fun getExternalModuleType(): String? = findEntity()?.externalSystemModuleType
override fun getExternalModuleVersion(): String? = findEntity()?.externalSystemModuleVersion
override fun getExternalModuleGroup(): String? = findEntity()?.externalSystemModuleGroup
override fun getLinkedProjectId(): String? = findEntity()?.linkedProjectId
override fun getRootProjectPath(): String? = findEntity()?.rootProjectPath
override fun getLinkedProjectPath(): String? = findEntity()?.linkedProjectPath
override fun isMavenized(): Boolean = getExternalSystemId() == ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID
override fun setMavenized(mavenized: Boolean) {
setMavenized(mavenized, getModuleDiff())
}
fun setMavenized(mavenized: Boolean, storageBuilder: WorkspaceEntityStorageBuilder?) {
if (mavenized) {
unlinkExternalOptions(storageBuilder)
}
editEntity(storageBuilder) {
externalSystem = if (mavenized) ExternalProjectSystemRegistry.MAVEN_EXTERNAL_SOURCE_ID else null
}
updateSource(storageBuilder)
}
override fun unlinkExternalOptions() {
unlinkExternalOptions(getModuleDiff())
}
private fun unlinkExternalOptions(storageBuilder: WorkspaceEntityStorageBuilder?) {
editEntity(storageBuilder) {
externalSystem = null
externalSystemModuleVersion = null
externalSystemModuleGroup = null
linkedProjectId = null
linkedProjectPath = null
rootProjectPath = null
}
updateSource(storageBuilder)
}
override fun setExternalOptions(id: ProjectSystemId, moduleData: ModuleData, projectData: ProjectData?) {
editEntity {
externalSystem = id.toString()
linkedProjectId = moduleData.id
linkedProjectPath = moduleData.linkedExternalProjectPath
rootProjectPath = projectData?.linkedExternalProjectPath ?: ""
externalSystemModuleGroup = moduleData.group
externalSystemModuleVersion = moduleData.version
}
updateSource()
}
override fun setExternalId(id: ProjectSystemId) {
editEntity {
externalSystem = id.id
}
updateSource()
}
override fun setLinkedProjectPath(path: String?) {
editEntity {
linkedProjectPath = path
}
}
override fun setRootProjectPath(path: String?) {
editEntity {
rootProjectPath = path
}
}
override fun setExternalModuleType(type: String?) {
editEntity {
externalSystemModuleType = type
}
}
override fun swapStore() {
}
private fun getModuleDiff(): WorkspaceEntityStorageBuilder? {
val modelsProvider = module.getUserData(IdeModifiableModelsProviderImpl.MODIFIABLE_MODELS_PROVIDER_KEY)
return if (modelsProvider != null) modelsProvider.actualStorageBuilder else (module as ModuleBridge).diff as? WorkspaceEntityStorageBuilder
}
} | apache-2.0 | daa95e581e596fc54b432e367ae2febf | 44.011765 | 143 | 0.788916 | 6.038674 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/wordSelection/KotlinCodeBlockSelectioner.kt | 7 | 2700 | // 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.kotlin.idea.editor.wordSelection
import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtWhenExpression
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
/**
* Originally from IDEA platform: CodeBlockOrInitializerSelectioner
*/
class KotlinCodeBlockSelectioner : ExtendWordSelectionHandlerBase() {
companion object {
fun canSelect(e: PsiElement) = isTarget(e) || (isBrace(e) && isTarget(e.parent))
private fun isTarget(e: PsiElement) = e is KtBlockExpression || e is KtWhenExpression
private fun isBrace(e: PsiElement): Boolean {
val elementType = e.node.elementType
return elementType == KtTokens.LBRACE || elementType == KtTokens.RBRACE
}
}
override fun canSelect(e: PsiElement) = KotlinCodeBlockSelectioner.canSelect(e)
override fun select(e: PsiElement, editorText: CharSequence, cursorOffset: Int, editor: Editor): List<TextRange> {
val result = ArrayList<TextRange>()
val block = if (isBrace(e)) e.parent else e
val start = findBlockContentStart(block)
val end = findBlockContentEnd(block)
if (end > start) {
result.addAll(expandToWholeLine(editorText, TextRange(start, end)))
}
result.addAll(expandToWholeLine(editorText, block.textRange!!))
return result
}
private fun findBlockContentStart(block: PsiElement): Int {
val element = block.allChildren
.dropWhile { it.node.elementType != KtTokens.LBRACE } // search for '{'
.drop(1) // skip it
.dropWhile { it is PsiWhiteSpace } // and skip all whitespaces
.firstOrNull() ?: block
return element.startOffset
}
private fun findBlockContentEnd(block: PsiElement): Int {
val element = block.allChildren
.toList()
.asReversed()
.asSequence()
.dropWhile { it.node.elementType != KtTokens.RBRACE } // search for '}'
.drop(1) // skip it
.dropWhile { it is PsiWhiteSpace } // and skip all whitespaces
.firstOrNull() ?: block
return element.endOffset
}
}
| apache-2.0 | 5af81c1add6aea0ece4d79ba10f73247 | 38.130435 | 120 | 0.688519 | 4.655172 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/move/kotlin/moveNestedClass/nonInnerToOuterClass2/after/test.kt | 13 | 787 | package test
inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
class A {
class X {
}
companion object {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
object O {
class Y
fun foo(n: Int) {}
val bar = 1
fun Int.extFoo(n: Int) {}
val Int.extBar: Int get() = 1
}
class B {
}
class C {
fun test() {
X()
Y()
foo(bar)
//1.extFoo(1.extBar) // conflict
O.Y()
O.foo(O.bar)
with (O) {
Y()
foo(bar)
1.extFoo(1.extBar)
}
}
}
} | apache-2.0 | a5001e99fdf6911a8b580190edcf9c7f | 13.327273 | 75 | 0.369759 | 3.67757 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/FunctionWithLambdaExpressionBodyInspection.kt | 1 | 4600 | // 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.codeInspection.*
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.search.searches.ReferencesSearch
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.intentions.SpecifyExplicitLambdaSignatureIntention
import org.jetbrains.kotlin.idea.quickfix.SpecifyTypeExplicitlyFix
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.types.typeUtil.isNothing
class FunctionWithLambdaExpressionBodyInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : KtVisitorVoid() {
override fun visitNamedFunction(function: KtNamedFunction) {
check(function)
}
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
if (accessor.isSetter) return
if (accessor.returnTypeReference != null) return
check(accessor)
}
private fun check(element: KtDeclarationWithBody) {
val callableDeclaration = element.getNonStrictParentOfType<KtCallableDeclaration>() ?: return
if (callableDeclaration.typeReference != null) return
val lambda = element.bodyExpression as? KtLambdaExpression ?: return
val functionLiteral = lambda.functionLiteral
if (functionLiteral.arrow != null || functionLiteral.valueParameterList != null) return
val lambdaBody = functionLiteral.bodyBlockExpression ?: return
val used = ReferencesSearch.search(callableDeclaration).any()
val fixes = listOfNotNull(
IntentionWrapper(SpecifyTypeExplicitlyFix()),
IntentionWrapper(AddArrowIntention()),
if (!used &&
lambdaBody.statements.size == 1 &&
lambdaBody.allChildren.none { it is PsiComment }
)
RemoveBracesFix()
else
null,
if (!used) WrapRunFix() else null
)
holder.registerProblem(
lambda,
KotlinBundle.message("inspection.function.with.lambda.expression.body.display.name"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
*fixes.toTypedArray()
)
}
}
private class AddArrowIntention : SpecifyExplicitLambdaSignatureIntention() {
override fun allowCaretInsideElement(element: PsiElement) = true
}
private class RemoveBracesFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("remove.braces.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val lambda = descriptor.psiElement as? KtLambdaExpression ?: return
val singleStatement = lambda.functionLiteral.bodyExpression?.statements?.singleOrNull() ?: return
val replaced = lambda.replaced(singleStatement)
replaced.setTypeIfNeed()
}
}
private class WrapRunFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("wrap.run.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val lambda = descriptor.psiElement as? KtLambdaExpression ?: return
val body = lambda.functionLiteral.bodyExpression ?: return
val replaced = lambda.replaced(KtPsiFactory(lambda).createExpressionByPattern("run { $0 }", body.allChildren))
replaced.setTypeIfNeed()
}
}
}
private fun KtExpression.setTypeIfNeed() {
val declaration = getStrictParentOfType<KtCallableDeclaration>() ?: return
val type = (declaration.resolveToDescriptorIfAny() as? CallableDescriptor)?.returnType
if (type?.isNothing() == true) {
declaration.setType(type)
}
}
| apache-2.0 | 657b65b7c924dfe721690a3af3c5766a | 43.660194 | 158 | 0.695217 | 5.502392 | false | false | false | false |
zielu/GitToolBox | src/main/kotlin/zielu/gittoolbox/changes/ChangesTrackerServiceImpl.kt | 1 | 4969 | package zielu.gittoolbox.changes
import com.intellij.openapi.Disposable
import com.intellij.openapi.project.Project
import com.intellij.serviceContainer.NonInjectable
import com.jetbrains.rd.util.getOrCreate
import git4idea.repo.GitRepository
import gnu.trove.TObjectIntHashMap
import zielu.gittoolbox.util.Count
import zielu.intellij.util.ZDisposeGuard
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentMap
internal class ChangesTrackerServiceImpl
@NonInjectable
constructor(private val facade: ChangesTrackerServiceFacade) : ChangesTrackerService, Disposable {
constructor(project: Project) : this(ChangesTrackerServiceFacade(project))
private val changeCounters: ConcurrentMap<GitRepository, ChangeCounters> = ConcurrentHashMap()
private val disposeGuard = ZDisposeGuard()
init {
facade.registerDisposable(this, facade)
facade.registerDisposable(this, disposeGuard)
}
override fun changeListChanged(changeListData: ChangeListData) {
if (disposeGuard.isActive()) {
if (changeListData.hasChanges) {
facade.getNotEmptyChangeListTimer().timeKt { handleNonEmptyChangeList(changeListData) }
} else {
handleEmptyChangeList(changeListData.id)
}
}
}
private fun handleEmptyChangeList(id: String) {
changeListRemoved(id)
}
private fun handleNonEmptyChangeList(changeListData: ChangeListData) {
val newCounts = getCountsForChangeList(changeListData)
var changed = false
// clean up committed changes
val reposNotInChangeList: MutableSet<GitRepository> = HashSet(changeCounters.keys)
reposNotInChangeList.removeAll(newCounts.keys)
reposNotInChangeList.forEach { repoNotInList ->
changeCounters.computeIfPresent(repoNotInList) { _, counters ->
if (counters.remove(changeListData.id)) {
changed = true
}
counters
}
}
// update counts
newCounts.forEach { (repo, aggregator) ->
val oldTotal = changeCounters[repo]?.total ?: 0
val newCounters = changeCounters.merge(repo, aggregator.toCounters(), this::mergeCounters)
val difference = newCounters!!.total != oldTotal
if (difference) {
changed = true
}
}
if (changed) {
facade.fireChangeCountsUpdated()
}
}
private fun getCountsForChangeList(changeListData: ChangeListData): Map<GitRepository, ChangeCountersAggregator> {
val changeCounters = HashMap<GitRepository, ChangeCountersAggregator>()
changeListData.changes
.mapNotNull { getRepoForChange(it) }
.forEach { changeCounters.getOrCreate(it, { ChangeCountersAggregator() }).increment(changeListData.id) }
return changeCounters
}
private fun getRepoForChange(change: ChangeData): GitRepository? {
return facade.getRepoForPath(change.filePath)
}
private fun mergeCounters(existingCounters: ChangeCounters, newCounters: ChangeCounters): ChangeCounters {
return existingCounters.merge(newCounters)
}
override fun changeListRemoved(id: String) {
if (disposeGuard.isActive()) {
facade.getChangeListRemovedTimer().timeKt { handleChangeListRemoved(id) }
}
}
private fun handleChangeListRemoved(id: String) {
val modified = changeCounters.values.stream()
.map { it.remove(id) }
.filter { it }
.count()
if (modified > 0) {
facade.fireChangeCountsUpdated()
}
}
override fun getChangesCount(repository: GitRepository): Count {
if (disposeGuard.isActive()) {
return changeCounters[repository]?.let { Count(it.total) } ?: Count.ZERO
}
return Count.ZERO
}
override fun getTotalChangesCount(): Count {
if (disposeGuard.isActive()) {
val total = changeCounters.values
.map { it.total }
.sum()
return Count(total)
}
return Count.ZERO
}
override fun dispose() {
changeCounters.clear()
}
}
private class ChangeCountersAggregator {
private val changeCounters = TObjectIntHashMap<String>()
fun increment(id: String) {
if (!changeCounters.increment(id)) {
changeCounters.put(id, 1)
}
}
fun toCounters(): ChangeCounters = ChangeCounters(changeCounters)
}
private class ChangeCounters(private val changeCounters: TObjectIntHashMap<String>) {
private var totalCount: Int = changeCounters.values.sum()
val total: Int
get() = totalCount
fun remove(id: String): Boolean {
synchronized(changeCounters) {
val removed = changeCounters.remove(id)
totalCount -= removed
return removed != 0
}
}
fun hasId(id: String): Boolean {
synchronized(changeCounters) {
return changeCounters.containsKey(id)
}
}
fun merge(other: ChangeCounters): ChangeCounters {
synchronized(changeCounters) {
other.changeCounters.forEachEntry { listId, count ->
changeCounters.put(listId, count)
true
}
totalCount = changeCounters.values.sum()
return this
}
}
}
| apache-2.0 | 9a2703696646e745789bb1c97fc711e5 | 28.754491 | 116 | 0.715033 | 4.678908 | false | false | false | false |
LouisCAD/Splitties | modules/views-dsl-material/src/androidMain/kotlin/splitties/views/dsl/material/styles/ButtonMaterialComponentsStyles.kt | 1 | 5736 | /*
* Copyright 2019-2020 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license.
*/
package splitties.views.dsl.material.styles
import android.content.Context
import android.view.View
import androidx.annotation.IdRes
import androidx.annotation.StyleRes
import com.google.android.material.button.MaterialButton
import splitties.views.dsl.core.NO_THEME
import splitties.views.dsl.core.styles.styledView
import splitties.views.dsl.material.R
import kotlin.contracts.InvocationKind
import kotlin.contracts.contract
@JvmInline
value class ButtonMaterialComponentsStyles @PublishedApi internal constructor(
@PublishedApi internal val ctx: Context
) {
inline fun filled(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button,
id = id,
theme = theme,
initView = initView
)
}
inline fun filledWithIcon(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_Icon,
id = id,
theme = theme,
initView = initView
)
}
inline fun filledUnelevated(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_UnelevatedButton,
id = id,
theme = theme,
initView = initView
)
}
inline fun filledUnelevatedWithIcon(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_UnelevatedButton_Icon,
id = id,
theme = theme,
initView = initView
)
}
inline fun outlined(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_OutlinedButton,
id = id,
theme = theme,
initView = initView
)
}
inline fun outlinedWithIcon(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_OutlinedButton_Icon,
id = id,
theme = theme,
initView = initView
)
}
inline fun text(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_TextButton,
id = id,
theme = theme,
initView = initView
)
}
inline fun textWithIcon(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_TextButton_Icon,
id = id,
theme = theme,
initView = initView
)
}
inline fun textDialog(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_TextButton_Dialog,
id = id,
theme = theme,
initView = initView
)
}
inline fun textDialogWithIcon(
@IdRes id: Int = View.NO_ID,
@StyleRes theme: Int = NO_THEME,
initView: MaterialButton.() -> Unit = {}
): MaterialButton {
contract { callsInPlace(initView, InvocationKind.EXACTLY_ONCE) }
return ctx.styledView(
newViewRef = ::MaterialButton,
styleAttr = R.attr.Widget_MaterialComponents_Button_TextButton_Dialog_Icon,
id = id,
theme = theme,
initView = initView
)
}
}
| apache-2.0 | 659878bfd2637c976f268da572c16563 | 32.54386 | 114 | 0.598501 | 4.78798 | false | false | false | false |
sg26565/hott-transmitter-config | MdlViewer/src/main/kotlin/de/treichels/hott/mdlviewer/javafx/SelectFromSdCard.kt | 1 | 5981 | /**
* HoTT Transmitter Config Copyright (C) 2013 Oliver Treichel
*
* 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:></http:>//www.gnu.org/licenses/>.
*/
package de.treichels.hott.mdlviewer.javafx
import de.treichels.hott.mdlviewer.javafx.Model.Companion.loadModel
import de.treichels.hott.serial.FileInfo
import de.treichels.hott.serial.FileType
import javafx.beans.binding.BooleanBinding
import javafx.concurrent.Task
import javafx.event.EventType
import javafx.scene.control.SelectionMode
import javafx.scene.control.TreeCell
import javafx.scene.control.TreeItem
import javafx.scene.control.TreeView
import javafx.scene.image.ImageView
import javafx.util.Callback
import tornadofx.*
/**
* @author Oliver Treichel <[email protected]>
*/
class SelectFromSdCard : SelectFromTransmitter() {
/**
* Root [TreeItem] that loads it's children dynamically.
*/
private val rootItem: TreeItem<FileInfo> = TreeItem(FileInfo.root).apply {
isExpanded = false
loading()
// Update children of this tree item when the node is expanded
addEventHandler(branchExpandedEvent) { event ->
runLater {
treeView.runAsyncWithOverlay {
transmitter!!.listDir(event.treeItem.value.path).map {
TreeItem(transmitter!!.getFileInfo(it))
}
}.success { list ->
event.treeItem.children.clear()
event.treeItem.children.addAll(list)
}
}
}
// clear all children - reload on expand
addEventHandler(branchCollapsedEvent) { event ->
event.treeItem.loading()
}
}
/**
* [TreeView] with a single root node.
*/
private val treeView = treeview(rootItem) {
cellFactory = Callback { FileInfoTreeCell() }
selectionModel.selectionMode = SelectionMode.SINGLE
setOnMouseClicked { handleDoubleClick(it) }
}
/**
* This dialog is ready when the user selects [FileInfo] node representing a .mdl file with a valid file size.
*/
override fun isReady() = object : BooleanBinding() {
override fun computeValue(): Boolean {
val item = treeView.selectionModel.selectedItem?.value
return item != null && item.type == FileType.File && item.name.endsWith(".mdl") && item.size <= 0x3000 && item.size >= 0x2000
}
init {
// invalidate this BooleanBinding when treeView selection changes
treeView.selectionModel.selectedItemProperty().addListener { _ -> invalidate() }
}
}
/**
* A [Task] that retrieves the model data for the provided [FileInfo] from the SD card in the transmitter.
*/
override fun getResult(): Task<Model>? {
val fileInfo = treeView.selectionModel.selectedItem?.value
val serialPort = this.transmitter
return if (isReady().value && fileInfo != null && serialPort != null) runAsync { loadModel(fileInfo, serialPort) } else null
}
/**
* Reload the [TreeView]
*/
override fun refreshUITask() = treeView.runAsyncWithOverlay {
rootItem.isExpanded = false
rootItem.loading()
runLater {
rootItem.isExpanded = true
}
}
init {
title = messages["select_from_sdcard_title"]
root.center = treeView
}
companion object {
private val resources = ResourceLookup(TreeFileInfo)
private val fileImage = resources.image("/File.gif")
private val openFolderImage = resources.image("/Folder_open.gif")
private val closedFolderImage = resources.image("/Folder_closed.gif")
private val rootFolderImage = resources.image("/Root.gif")
private val branchExpandedEvent: EventType<TreeItem.TreeModificationEvent<FileInfo>> = TreeItem.branchExpandedEvent()
private val branchCollapsedEvent: EventType<TreeItem.TreeModificationEvent<FileInfo>> = TreeItem.branchCollapsedEvent()
}
/**
* Add a dummy "loading ..." node
*/
private fun TreeItem<FileInfo>.loading() {
// add loading pseudo child
children.clear()
children.add(null)
}
/**
* Format [FileInfo] items in the [TreeView]
*/
private inner class FileInfoTreeCell : TreeCell<FileInfo>() {
override fun updateItem(item: FileInfo?, empty: Boolean) {
super.updateItem(item, empty)
when {
empty -> {
graphic = null
text = null
}
item == null -> {
graphic = null
text = messages["loading"]
}
item.isRoot -> {
graphic = ImageView(rootFolderImage)
text = messages["root"]
}
item.isDir -> {
if (treeItem.isExpanded) {
graphic = ImageView(openFolderImage)
} else {
graphic = ImageView(closedFolderImage)
treeItem.loading()
}
text = item.name
}
item.isFile -> {
graphic = ImageView(fileImage)
text = item.name
}
}
}
}
}
| lgpl-3.0 | 34629e21387083962dc099a5cf70b810 | 33.773256 | 160 | 0.604247 | 5.030278 | false | false | false | false |
koma-im/koma | src/main/kotlin/koma/gui/element/control/skin/KListViewSkin.kt | 1 | 12436 | package koma.gui.element.control.skin
import javafx.beans.Observable
import javafx.beans.WeakInvalidationListener
import javafx.collections.ListChangeListener
import javafx.collections.MapChangeListener
import javafx.collections.ObservableList
import javafx.collections.WeakListChangeListener
import javafx.event.EventHandler
import javafx.scene.AccessibleAction
import javafx.scene.Node
import javafx.scene.control.Label
import javafx.scene.control.ListCell
import javafx.scene.control.ListView
import javafx.scene.input.MouseEvent
import koma.gui.element.control.KListView
import koma.gui.element.control.behavior.ListViewBehavior
import link.continuum.desktop.gui.StackPane
import mu.KotlinLogging
private val logger = KotlinLogging.logger {}
class KListViewSkin<T, I>(
control: ListView<T>,
private val kListView: KListView<T, I>
): KVirtualContainerBase<ListView<T>, I, T>(control)
where I: ListCell<T>{
public override val flow = KVirtualFlow<I, T>(
cellCreator = ::createCell,
kListView = kListView,
fixedCellSize = control.fixedCellSize.let { if (it > 0) it else null})
/**
* Region placed over the top of the flow (and possibly the header row) if
* there is no data.
*/
private var placeholderRegion: StackPane? = null
private var placeholderNode: Node? = null
private var listViewItems: ObservableList<T>? = null
private val itemsChangeListener = { _: Observable -> updateListViewItems() }
private var needCellsRebuilt = true
private var needCellsReconfigured = false
override var itemCount = -1
private val behavior: ListViewBehavior<T>?
private val propertiesMapListener = MapChangeListener<Any,Any> { c: MapChangeListener.Change<out Any, out Any> ->
val RECREATE = "recreateKey"
if (!c.wasAdded()) {
} else if (RECREATE.equals(c.getKey())) {
needCellsRebuilt = true
skinnable.requestLayout()
skinnable.properties.remove(RECREATE)
}
}
private val listViewItemsListener = ListChangeListener<T> { c ->
while (c.next()) {
if (c.wasReplaced()) {
// RT-28397: Support for when an item is replaced with itself (but
// updated internal values that should be shown visually).
// This code was updated for RT-36714 to not update all cells,
// just those affected by the change
for (i in c.from until c.to) {
flow.setCellDirty(i)
}
break
} else if (c.removedSize == itemCount) {
// RT-22463: If the user clears out an items list then we
// should reset all cells (in particular their contained
// items) such that a subsequent addition to the list of
// an item which equals the old item (but is rendered
// differently) still displays as expected (i.e. with the
// updated display, not the old display).
itemCount = 0
break
}
}
// fix for RT-37853
skinnable.edit(-1)
markItemCountDirty()
skinnable.requestLayout()
}
private val weakListViewItemsListener = WeakListChangeListener(listViewItemsListener)
private val RECREATE = "recreateKey"
init {
// install default input map for the ListView control
behavior = ListViewBehavior(control)
// control.setInputMap(behavior.getInputMap());
// init the behavior 'closures'
behavior.setOnFocusPreviousRow(Runnable { onFocusPreviousCell() })
behavior.setOnFocusNextRow (Runnable{ onFocusNextCell() })
behavior.setOnMoveToFirstCell (Runnable{
logger.debug { "KListViewSkin behavior onMoveToFirstCell" }
onMoveToFirstCell()
})
behavior.setOnMoveToLastCell (Runnable{
logger.debug { "KListViewSkin behavior onMoveToLastCell" }
onMoveToLastCell()
})
behavior.setOnSelectPreviousRow (Runnable{ onSelectPreviousCell() })
behavior.setOnSelectNextRow (Runnable{ onSelectNextCell() })
behavior.onScrollPageDown = {
logger.debug { "KListViewSkin behavior onScrollPageDown" }
flow.scrollRatio(0.8f)
}
behavior.onScrollPageUp = {
logger.debug { "KListViewSkin behavior onScrollPage up" }
flow.scrollRatio(-0.8f)
}
updateListViewItems()
// init the VirtualFlow
flow.id = "virtual-flow"
flow.isPannable = IS_PANNABLE
children.add(flow)
val ml: EventHandler<MouseEvent> = EventHandler {
// RT-15127: cancel editing on scroll. This is a bit extreme
// (we are cancelling editing on touching the scrollbars).
// This can be improved at a later date.
if (control.editingIndex > -1) {
control.edit(-1)
}
// This ensures that the list maintains the focus, even when the vbar
// and hbar controls inside the flow are clicked. Without this, the
// focus border will not be shown when the user interacts with the
// scrollbars, and more importantly, keyboard navigation won't be
// available to the user.
if (control.isFocusTraversable) {
control.requestFocus()
}
}
flow.vbar.addEventFilter(MouseEvent.MOUSE_PRESSED, ml)
updateItemCount()
control.itemsProperty().addListener(WeakInvalidationListener(itemsChangeListener))
val properties = control.properties
properties.remove(RECREATE)
properties.addListener(propertiesMapListener)
// Register listeners
registerChangeListener(control.itemsProperty()) { updateListViewItems() }
registerChangeListener(control.parentProperty()) { _ ->
if (control.parent != null && control.isVisible) {
control.requestLayout()
}
}
registerChangeListener(control.placeholderProperty()) { _ -> updatePlaceholderRegionVisibility() }
}
override fun dispose() {
super.dispose()
behavior?.dispose()
}
override fun layoutChildren(x: Double, y: Double,
w: Double, h: Double) {
super.layoutChildren(x, y, w, h)
if (needCellsRebuilt) {
flow.rebuildCells()
} else if (needCellsReconfigured) {
flow.reconfigureCells()
}
needCellsRebuilt = false
needCellsReconfigured = false
if (itemCount == 0) {
// show message overlay instead of empty listview
placeholderRegion?.apply {
isVisible = w > 0 && h > 0
resizeRelocate(x, y, w, h)
}
} else {
flow.resizeRelocate(x, y, w, h)
}
}
override fun computePrefWidth(height: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double): Double {
checkState()
if (itemCount == 0) {
if (placeholderRegion == null) {
updatePlaceholderRegionVisibility()
}
if (placeholderRegion != null) {
return placeholderRegion!!.prefWidth(height) + leftInset + rightInset
}
}
return computePrefHeight(-1.0, topInset, rightInset, bottomInset, leftInset) * 0.618033987
}
override fun computePrefHeight(width: Double, topInset: Double, rightInset: Double, bottomInset: Double, leftInset: Double): Double {
return 400.0
}
override fun updateItemCount() {
val oldCount = itemCount
val newCount = if (listViewItems == null) 0 else listViewItems!!.size
itemCount = newCount
flow.setCellCount(newCount)
updatePlaceholderRegionVisibility()
if (newCount != oldCount) {
requestRebuildCells()
} else {
needCellsReconfigured = true
}
}
override fun executeAccessibleAction(action: AccessibleAction, vararg parameters: Any) {
when (action) {
AccessibleAction.SHOW_ITEM -> {
val item = parameters[0] as Node
if (item is ListCell<*>) {
val cell = item as ListCell<T>
flow.scrollTo(cell.index)
}
}
AccessibleAction.SET_SELECTED_ITEMS -> {
val items = parameters[0] as ObservableList<Node>
val sm = skinnable.selectionModel
if (sm != null) {
sm.clearSelection()
for (item in items) {
if (item is ListCell<*>) {
val cell = item as ListCell<T>
sm.select(cell.index)
}
}
}
}
else -> super.executeAccessibleAction(action, parameters)
}
}
private fun createCell(): I {
val cell: I = kListView.cellCreator()
cell.updateListView(skinnable)
return cell
}
private fun updateListViewItems() {
if (listViewItems != null) {
listViewItems!!.removeListener(weakListViewItemsListener)
}
this.listViewItems = skinnable.items
if (listViewItems != null) {
listViewItems!!.addListener(weakListViewItemsListener)
}
markItemCountDirty()
skinnable.requestLayout()
}
private fun updatePlaceholderRegionVisibility() {
val visible = itemCount == 0
if (visible) {
placeholderNode = skinnable.placeholder
if (placeholderNode == null && !EMPTY_LIST_TEXT.isEmpty()) {
placeholderNode = Label()
(placeholderNode as Label).setText(EMPTY_LIST_TEXT)
}
if (placeholderNode != null) {
if (placeholderRegion == null) {
placeholderRegion = StackPane()
placeholderRegion!!.styleClass.setAll("placeholder")
children.add(placeholderRegion)
}
placeholderRegion!!.children.setAll(placeholderNode)
}
}
flow.isVisible = !visible
if (placeholderRegion != null) {
placeholderRegion!!.isVisible = visible
}
}
private fun onFocusPreviousCell() {
val fm = skinnable.focusModel ?: return
flow.scrollTo(fm.focusedIndex)
}
private fun onFocusNextCell() {
val fm = skinnable.focusModel ?: return
flow.scrollTo(fm.focusedIndex)
}
private fun onSelectPreviousCell() {
val sm = skinnable.selectionModel ?: return
val pos = sm.selectedIndex
if (pos < 0) return
flow.scrollTo(pos)
// Fix for RT-11299
val cell = flow.firstVisibleCell
if (cell == null || pos < cell.index) {
val p = pos / itemCount.toDouble()
flow.setPosition(p)
}
}
private fun onSelectNextCell() {
val sm = skinnable.selectionModel ?: return
val pos = sm.selectedIndex
flow.scrollTo(pos)
// Fix for RT-11299
val cell = flow.lastVisibleCell
if (cell == null || cell.index < pos) {
flow.setPosition ( pos / itemCount.toDouble())
}
}
private fun onMoveToFirstCell() {
flow.scrollTo(0)
flow.setPosition(0.0)
}
private fun onMoveToLastCell() {
// SelectionModel sm = getSkinnable().getSelectionModel();
// if (sm == null) return;
//
val endPos = itemCount - 1
// sm.select(endPos);
flow.scrollTo(endPos)
flow.setPosition(1.0)
}
companion object {
// RT-34744 : IS_PANNABLE will be false unless
// javafx.scene.control.skin.ListViewSkin.pannable
// is set to true. This is done in order to make ListView functional
// on embedded systems with touch screens which do not generate scroll
// events for touch drag gestures.
private val IS_PANNABLE = false
private const val EMPTY_LIST_TEXT = "ListView.noContent"
}
}
| gpl-3.0 | 9ffbf9ab751704d9bf81babb86e009ac | 32.340483 | 137 | 0.594082 | 4.929053 | false | false | false | false |
Nicologies/Hedwig | hedwig-server/src/main/java/com/nicologis/slack/SlackPayload.kt | 2 | 2928 | package com.nicologis.slack
import com.nicologis.teamcity.BuildInfo
import com.google.gson.annotations.Expose
import org.apache.commons.lang.StringUtils
import java.util.ArrayList
class SlackPayload(build: BuildInfo) {
@Expose
private var text: String
@Expose
private lateinit var channel: String
@Expose
private lateinit var username: String
@Expose
private var attachments: MutableList<Attachment>
inner class Attachment {
@Expose
var fallback: String? = null
@Expose
var pretext: String? = null
@Expose
var color: String? = null
@Expose
var fields: MutableList<AttachmentField>? = null
}
inner class AttachmentField(
@field:Expose
private var title: String,
@field:Expose
private var value: String,
@field:Expose
private var isShort: Boolean
)
fun setRecipient(recipient: String) {
this.channel = recipient
}
fun setBotName(botName: String) {
this.username = botName
}
private fun escape(s: String): String {
return s.replace("<", "<").replace(">", ">")
}
private fun escapeNewline(s: String): String {
return s.replace("\n", "\\n")
}
init {
val branch = escape(build.branchName)
val escapedBranch = if (branch.isNotEmpty()) " [$branch]" else ""
val statusText = ("<" + build.getBuildLink { x -> this.escape(x) }
+ "|" + escape(escapeNewline(build.statusText)) + ">")
val statusEmoji: String
val statusColor = build.statusColor
statusEmoji = when (statusColor) {
StatusColor.danger -> ":x: "
StatusColor.warning -> ""
StatusColor.info -> ":information_source: "
else -> ":white_check_mark: "
}
val payloadText = (statusEmoji + build.buildFullName
+ escapedBranch + " #" + build.buildNumber + " " + statusText)
this.text = payloadText
val attachment = Attachment()
attachment.color = statusColor.name
attachment.pretext = "Build Information"
attachment.fallback = payloadText
attachment.fields = ArrayList()
val encodedPrUrl = build.getEncodedPrUrl()
if (StringUtils.isNotEmpty(encodedPrUrl)) {
val prUrlField = AttachmentField("PullRequest URL", encodedPrUrl, false)
attachment.fields!!.add(prUrlField)
}
for ((key, value) in build.messages) {
val field = AttachmentField(key, value, false)
attachment.fields!!.add(field)
}
this.attachments = ArrayList()
if (!attachment.fields!!.isEmpty()) {
this.attachments.add(0, attachment)
}
}
}
| mit | e65192aa1e93af945521a415a50450ec | 28.5 | 84 | 0.574112 | 4.655008 | false | false | false | false |
hannesa2/TouchImageView | app/src/main/java/info/touchimage/demo/SingleTouchImageViewActivity.kt | 1 | 1590 | package info.touchimage.demo
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.ortiz.touchview.TouchImageView
import kotlinx.android.synthetic.main.activity_single_touchimageview.*
import java.text.DecimalFormat
class SingleTouchImageViewActivity : AppCompatActivity() {
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_touchimageview)
// DecimalFormat rounds to 2 decimal places.
val df = DecimalFormat("#.##")
// Set the OnTouchImageViewListener which updates edit texts with zoom and scroll diagnostics.
imageSingle.setOnTouchImageViewListener(object : TouchImageView.OnTouchImageViewListener {
override fun onMove() {
val point = imageSingle.scrollPosition
val rect = imageSingle.zoomedRect
val currentZoom = imageSingle.currentZoom
val isZoomed = imageSingle.isZoomed
scroll_position.text = "x: " + df.format(point.x.toDouble()) + " y: " + df.format(point.y.toDouble())
zoomed_rect.text = ("left: " + df.format(rect.left.toDouble()) + " top: " + df.format(rect.top.toDouble())
+ "\nright: " + df.format(rect.right.toDouble()) + " bottom: " + df.format(rect.bottom.toDouble()))
current_zoom.text = "getCurrentZoom(): $currentZoom isZoomed(): $isZoomed"
}
}
)
}
}
| mit | a3d78b87bb36addf97ff2a4e7d4ccdab | 43.166667 | 123 | 0.662893 | 4.582133 | false | false | false | false |
dtretyakov/teamcity-rust | plugin-rust-agent/src/main/kotlin/jetbrains/buildServer/rust/inspections/ClippyInspectionsParser.kt | 1 | 2070 | /*
* Copyright 2000-2021 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* See LICENSE in the project root for license information.
*/
package jetbrains.buildServer.rust.inspections
import jetbrains.buildServer.agent.inspections.InspectionTypeInfo
class ClippyInspectionsParser {
private lateinit var currentType: InspectionTypeInfo
private lateinit var currentMessage: String
companion object {
val CLIPPY_WARNING = InspectionTypeInfo().apply {
id = "rust-inspection-clippy-warning"
description = "Clippy Warning"
category = "Clippy Inspection"
name = "Clippy Warning"
}
val CLIPPY_ERROR = InspectionTypeInfo().apply {
id = "rust-inspection-clippy-error"
description = "Clippy Error"
category = "Clippy Inspection"
name = "Clippy Error"
}
}
fun processLine(text: String): Inspection? {
return when {
text.startsWith("error: ") -> {
currentType = CLIPPY_ERROR
currentMessage = text.removePrefix("error: ")
null
}
text.startsWith("warning: ") -> {
currentType = CLIPPY_WARNING
currentMessage = text.removePrefix("warning: ")
null
}
text.matches("^\\s+--> .+".toRegex()) -> {
val position = text.replace("^\\s+--> ".toRegex(), "")
val split = position.split(":")
val filename = split.subList(0, split.size-2).joinToString(":")
val line = split[split.size-2]
Inspection(
type = currentType,
message = currentMessage,
file = filename,
line = line.toInt(),
severity = if (currentType == CLIPPY_ERROR) Inspection.Severity.ERROR else Inspection.Severity.WARNING
)
}
else -> null
}
}
} | apache-2.0 | 1acad2dac305e32b49da5fb44cee0f87 | 32.95082 | 122 | 0.542512 | 5.253807 | false | false | false | false |
kpspemu/kpspemu | src/commonMain/kotlin/com/soywiz/kpspemu/hle/SceModule.kt | 1 | 10072 | package com.soywiz.kpspemu.hle
import com.soywiz.kds.*
import com.soywiz.klogger.*
import com.soywiz.kmem.*
import com.soywiz.korio.error.*
import com.soywiz.korio.lang.*
import com.soywiz.kpspemu.*
import com.soywiz.kpspemu.cpu.*
import com.soywiz.kpspemu.hle.error.*
import com.soywiz.kpspemu.hle.manager.*
import com.soywiz.kpspemu.mem.*
import com.soywiz.kpspemu.util.*
import com.soywiz.krypto.encoding.*
import kotlin.coroutines.*
import com.soywiz.korio.lang.invalidOp as invalidOp1
import kotlin.coroutines.intrinsics.*
class RegisterReader {
var pos: Int = 4
lateinit var emulator: Emulator
lateinit var cpu: CpuState
fun reset(cpu: CpuState) {
this.cpu = cpu
this.pos = 4
}
val thread: PspThread get() = cpu.thread
val mem: Memory get() = cpu.mem
val bool: Boolean get() = int != 0
val int: Int get() = this.cpu.getGpr(pos++)
val long: Long
get() {
pos = pos.nextAlignedTo(2) // Ensure register alignment
val low = this.cpu.getGpr(pos++)
val high = this.cpu.getGpr(pos++)
return (high.toLong() shl 32) or (low.toLong() and 0xFFFFFFFF)
}
val ptr: Ptr get() = MemPtr(mem, int)
val ptr8: Ptr8 get() = Ptr8(ptr)
val ptr32: Ptr32 get() = Ptr32(ptr)
val ptr64: Ptr64 get() = Ptr64(ptr)
val str: String? get() = mem.readStringzOrNull(int)
val istr: String get() = mem.readStringzOrNull(int) ?: ""
val strnn: String get() = mem.readStringzOrNull(int) ?: ""
fun <T> ptr(s: StructType<T>) = PtrStruct(s, ptr)
}
data class NativeFunction(
val name: String,
val nid: Long,
val since: Int,
val syscall: Int,
val function: (CpuState) -> Unit
)
abstract class BaseSceModule {
abstract val mmodule: SceModule
abstract val name: String
fun getByNidOrNull(nid: Int): NativeFunction? = mmodule.functions[nid]
fun getByNid(nid: Int): NativeFunction =
getByNidOrNull(nid) ?: invalidOp1("Can't find NID 0x%08X in %s".format(nid, name))
fun UNIMPLEMENTED(nid: Int): Nothing {
val func = getByNid(nid)
TODO("Unimplemented %s:0x%08X:%s".format(this.name, func.nid, func.name))
}
fun UNIMPLEMENTED(nid: Long): Nothing = UNIMPLEMENTED(nid.toInt())
}
abstract class SceSubmodule<out T : SceModule>(override val mmodule: T) : WithEmulator, BaseSceModule() {
override val name: String get() = mmodule.name
override val emulator: Emulator get() = mmodule.emulator
}
abstract class SceModule(
override val emulator: Emulator,
override val name: String,
val flags: Int = 0,
val prxFile: String = "",
val prxName: String = ""
) : WithEmulator, BaseSceModule() {
override val mmodule get() = this
inline fun <reified T : SceModule> getModuleOrNull(): T? = emulator.moduleManager.modulesByClass[T::class] as? T?
inline fun <reified T : SceModule> getModule(): T =
getModuleOrNull<T>() ?: invalidOp1("Expected to get module ${T::class.portableSimpleName}")
val loggerSuspend = Logger("SceModuleSuspend").apply {
//level = LogLevel.TRACE
}
val logger = Logger("SceModule.$name").apply {
//level = LogLevel.TRACE
}
fun registerPspModule() {
registerModule()
}
open fun stopModule() {
}
protected abstract fun registerModule(): Unit
private val rr: RegisterReader = RegisterReader()
val functions = IntMap<NativeFunction>()
fun registerFunctionRaw(function: NativeFunction) {
functions[function.nid.toInt()] = function
if (function.syscall >= 0) {
emulator.syscalls.register(function.syscall, function.name) { cpu, syscall ->
//println("REGISTERED SYSCALL $syscall")
logger.trace { "${this.name}:${function.name}" }
function.function(cpu)
}
}
}
fun registerFunctionRaw(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: (CpuState) -> Unit
) {
registerFunctionRaw(NativeFunction(name, uid, since, syscall, function))
}
fun registerFunctionRR(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: RegisterReader.(CpuState) -> Unit
) {
registerFunctionRaw(name, uid, since, syscall) {
//when (name) {
// "sceGeListUpdateStallAddr", "sceKernelLibcGettimeofday" -> Unit
// else -> println("Calling $name")
//}
try {
if (it._thread?.tracing == true) println("Calling $name from ${it._thread?.name}")
rr.reset(it)
function(rr, it)
} catch (e: Throwable) {
if (e !is EmulatorControlFlowException) {
Console.error("Error while processing '$name' :: at ${it.sPC.hex} :: $e")
}
throw e
}
}
}
fun registerFunctionVoid(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: RegisterReader.(CpuState) -> Unit
) {
registerFunctionRR(name, uid, since, syscall, function)
}
fun registerFunctionInt(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: RegisterReader.(CpuState) -> Int
) {
registerFunctionRR(name, uid, since, syscall) {
this.cpu.r2 = try {
function(it)
} catch (e: SceKernelException) {
e.errorCode
}
}
}
fun registerFunctionFloat(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: RegisterReader.(CpuState) -> Float
) {
registerFunctionRR(name, uid, since, syscall) {
this.cpu.setFpr(0, function(it))
}
}
fun registerFunctionLong(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
function: RegisterReader.(CpuState) -> Long
) {
registerFunctionRR(name, uid, since, syscall) {
val ret = function(it)
this.cpu.r2 = (ret ushr 0).toInt()
this.cpu.r3 = (ret ushr 32).toInt()
}
}
fun <T> registerFunctionSuspendT(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
cb: Boolean = false,
function: suspend RegisterReader.(CpuState) -> T,
resumeHandler: (CpuState, PspThread, T) -> Unit,
convertErrorToT: (Int) -> T
) {
val fullName = "${this.name}:$name"
registerFunctionRR(name, uid, since, syscall) { rrr ->
val rcpu = cpu
val rthread = thread
loggerSuspend.trace { "Suspend $name (${threadManager.summary}) : ${rcpu.summary}" }
val mfunction: suspend (RegisterReader) -> T = { function(it, rcpu) }
try {
val result = mfunction.startCoroutineUninterceptedOrReturn(this, object : Continuation<T> {
override val context: CoroutineContext = coroutineContext
override fun resumeWith(result: Result<T>) {
if (result.isSuccess) {
val value = result.getOrThrow()
resumeHandler(rcpu, thread, value)
rthread.resume()
loggerSuspend.trace { "Resumed $name with value: $value (${threadManager.summary}) : ${rcpu.summary}" }
} else {
val e = result.exceptionOrNull()!!
when (e) {
is SceKernelException -> {
resumeHandler(rcpu, thread, convertErrorToT(e.errorCode))
rthread.resume()
}
else -> {
println("ERROR at registerFunctionSuspendT.resumeWithException")
e.printStackTrace()
throw e
}
}
}
}
})
if (result == COROUTINE_SUSPENDED) {
rthread.markWaiting(WaitObject.COROUTINE(fullName), cb = cb)
if (rthread.tracing) println(" [S] Calling $name")
threadManager.suspendReturnVoid()
} else {
resumeHandler(rthread.state, rthread, result as T)
}
} catch (e: SceKernelException) {
resumeHandler(rthread.state, rthread, convertErrorToT(e.errorCode))
} catch (e: CpuBreakException) {
throw e
} catch (e: Throwable) {
println("ERROR at registerFunctionSuspendT.resumeWithException")
e.printStackTrace()
throw e
}
}
}
fun registerFunctionSuspendInt(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
cb: Boolean = false,
function: suspend RegisterReader.(CpuState) -> Int
) {
registerFunctionSuspendT<Int>(name, uid, since, syscall, cb, function,
resumeHandler = { cpu, thread, value -> cpu.r2 = value },
convertErrorToT = { it }
)
}
fun registerFunctionSuspendLong(
name: String,
uid: Long,
since: Int = 150,
syscall: Int = -1,
cb: Boolean = false,
function: suspend RegisterReader.(CpuState) -> Long
) {
registerFunctionSuspendT<Long>(name, uid, since, syscall, cb, function, resumeHandler = { cpu, thread, value ->
cpu.r2 = (value ushr 0).toInt()
cpu.r3 = (value ushr 32).toInt()
}, convertErrorToT = { it.toLong() })
}
}
| mit | ce7d2b8d3c64e8a4fb5bd74cbf87fef9 | 32.685619 | 131 | 0.547458 | 4.452697 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/ProxerApi.kt | 2 | 10676 | package me.proxer.library
import com.serjltt.moshi.adapters.FallbackEnum
import com.squareup.moshi.Moshi
import me.proxer.library.ProxerApi.Builder
import me.proxer.library.api.anime.AnimeApi
import me.proxer.library.api.apps.AppsApi
import me.proxer.library.api.chat.ChatApi
import me.proxer.library.api.comment.CommentApi
import me.proxer.library.api.forum.ForumApi
import me.proxer.library.api.info.InfoApi
import me.proxer.library.api.list.ListApi
import me.proxer.library.api.manga.MangaApi
import me.proxer.library.api.media.MediaApi
import me.proxer.library.api.messenger.MessengerApi
import me.proxer.library.api.notifications.NotificationsApi
import me.proxer.library.api.ucp.UcpApi
import me.proxer.library.api.user.UserApi
import me.proxer.library.api.users.UsersApi
import me.proxer.library.api.wiki.WikiApi
import me.proxer.library.internal.DefaultLoginTokenManager
import me.proxer.library.internal.adapter.BooleanAdapterFactory
import me.proxer.library.internal.adapter.ConferenceAdapter
import me.proxer.library.internal.adapter.ConferenceInfoAdapter
import me.proxer.library.internal.adapter.DateAdapter
import me.proxer.library.internal.adapter.DelimitedEnumSetAdapterFactory
import me.proxer.library.internal.adapter.DelimitedStringSetAdapterFactory
import me.proxer.library.internal.adapter.EnumRetrofitConverterFactory
import me.proxer.library.internal.adapter.EpisodeInfoAdapter
import me.proxer.library.internal.adapter.FixRatingDetailsAdapter
import me.proxer.library.internal.adapter.HttpUrlAdapter
import me.proxer.library.internal.adapter.NotificationAdapter
import me.proxer.library.internal.adapter.NotificationInfoAdapter
import me.proxer.library.internal.adapter.PageAdapter
import me.proxer.library.internal.adapter.ProxerResponseCallAdapterFactory
import me.proxer.library.internal.adapter.UcpSettingConstraintAdapter
import me.proxer.library.internal.adapter.UnitAdapter
import me.proxer.library.internal.interceptor.HeaderInterceptor
import me.proxer.library.internal.interceptor.HttpsEnforcingInterceptor
import me.proxer.library.internal.interceptor.LoginTokenInterceptor
import me.proxer.library.internal.interceptor.OneShotInterceptor
import me.proxer.library.internal.interceptor.RateLimitInterceptor
import me.proxer.library.util.ProxerUrls
import okhttp3.CertificatePinner
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
/**
* Entry point for access to the various APIs of Proxer.
*
* Before usage, you have to construct an instance through the [Builder].
*
* Note, that this is not a singleton. Each instance is separated from each other; You could even have instances with a
* different api key.
*
* @author Ruben Gees
*/
class ProxerApi private constructor(retrofit: Retrofit) {
companion object {
/** Special api key to enable the test mode. */
const val TEST_KEY = "test"
private val CERTIFICATES = arrayOf(
// https://censys.io/certificates/0687260331a72403d909f105e69bcf0d32e1bd2493ffc6d9206d11bcd6770739
"sha256/Vjs8r4z+80wjNcr1YKepWQboSIRi63WsWXhIMN+eWys=",
// https://censys.io/certificates/16af57a9f676b0ab126095aa5ebadef22ab31119d644ac95cd4b93dbf3f26aeb
"sha256/Y9mvm0exBk1JoQ57f9Vm28jKo5lFm/woKcVxrYxu80o=",
// https://censys.io/certificates/1793927a0614549789adce2f8f34f7f0b66d0f3ae3a3b84d21ec15dbba4fadc7
"sha256/58qRu/uxh4gFezqAcERupSkRYBlBAvfcw7mEjGPLnNU=",
// https://censys.io/certificates/52f0e1c4e58ec629291b60317f074671b85d7ea80d5b07273463534b32b40234
"sha256/grX4Ta9HpZx6tSHkmCrvpApTQGo67CYDnvprLg5yRME=",
// https://censys.io/certificates/96bcec06264976f37460779acf28c5a7cfe8a3c0aae11a8ffcee05c0bddf08c6
"sha256/C5+lpZ7tcVwmwQIMcRtPbsQtWLABXhQzejna0wHFr8M="
)
private const val DEFAULT_USER_AGENT = "ProxerLibJava/" + BuildConfig.VERSION
}
/**
* The respective API.
*/
val notifications = NotificationsApi(retrofit)
@JvmName("notifications") get
/**
* The respective API.
*/
val user = UserApi(retrofit)
@JvmName("user") get
/**
* The respective API.
*/
val users = UsersApi(retrofit)
@JvmName("users") get
/**
* The respective API.
*/
val info = InfoApi(retrofit)
@JvmName("info") get
/**
* The respective API.
*/
val messenger = MessengerApi(retrofit)
@JvmName("messenger") get
/**
* The respective API.
*/
val chat = ChatApi(retrofit)
@JvmName("chat") get
/**
* The respective API.
*/
val list = ListApi(retrofit)
@JvmName("list") get
/**
* The respective API.
*/
val ucp = UcpApi(retrofit)
@JvmName("ucp") get
/**
* The respective API.
*/
val anime = AnimeApi(retrofit)
@JvmName("anime") get
/**
* The respective API.
*/
val manga = MangaApi(retrofit)
@JvmName("manga") get
/**
* The respective API.
*/
val forum = ForumApi(retrofit)
@JvmName("forum") get
/**
* The respective API.
*/
val media = MediaApi(retrofit)
@JvmName("media") get
/**
* The respective API.
*/
val apps = AppsApi(retrofit)
@JvmName("apps") get
/**
* The respective API.
*/
val comment = CommentApi(retrofit)
@JvmName("comment") get
/**
* The respective API.
*/
val wiki = WikiApi(retrofit)
@JvmName("wiki") get
/**
*
* You can set customized instances of the internally used libraries: Moshi, OkHttp and Retrofit.
* Moreover you can specify your own [LoginTokenManager] and user agent.
*
* @constructor Constructs a new instance of the builder, with the passed api key.
*/
class Builder(private val apiKey: String) {
private var loginTokenManager: LoginTokenManager? = null
private var userAgent: String? = null
private var moshi: Moshi? = null
private var client: OkHttpClient? = null
private var retrofit: Retrofit? = null
private var enableRateLimitProtection: Boolean = false
/**
* Sets a custom login token manager.
*/
fun loginTokenManager(loginTokenManager: LoginTokenManager) = this.apply {
this.loginTokenManager = loginTokenManager
}
/**
* Sets a custom user agent.
*
* If not set, it will default to "ProxerLibJava/<version>"
*/
fun userAgent(userAgent: String) = this.apply { this.userAgent = userAgent }
/**
* Sets a custom Moshi instance.
*
* Note that a internally a new instance will be constructed with the adjustments included you did on your
* instance.
*/
fun moshi(moshi: Moshi) = this.apply { this.moshi = moshi }
/**
* Sets a custom OkHttp instance.
*
* Note that internally a new instance will be constructed with the adjustments included you did on your
* instance.
*/
fun client(client: OkHttpClient) = this.apply { this.client = client }
/**
* Sets a custom Retrofit instance.
*
* Note that a internally a new instance will be constructed with the adjustments included you did on your
* instance.
*/
fun retrofit(retrofit: Retrofit) = this.apply { this.retrofit = retrofit }
/**
* Enables the rate limit protection to avoid users having to fill out captchas.
*/
fun enableRateLimitProtection() = this.apply { this.enableRateLimitProtection = true }
/**
* Finally builds the [ProxerApi] with the provided adjustments.
*/
fun build(): ProxerApi {
val moshi = buildMoshi()
return ProxerApi(buildRetrofit(moshi))
}
private fun buildRetrofit(moshi: Moshi): Retrofit {
return (retrofit?.newBuilder() ?: Retrofit.Builder())
.baseUrl(ProxerUrls.apiBase)
.client(buildClient(moshi))
.addCallAdapterFactory(ProxerResponseCallAdapterFactory())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addConverterFactory(EnumRetrofitConverterFactory())
.build()
}
private fun buildClient(moshi: Moshi): OkHttpClient {
return (client?.newBuilder() ?: OkHttpClient.Builder())
.apply {
interceptors().apply {
addAll(
0,
listOf(
HeaderInterceptor(apiKey, buildUserAgent()),
LoginTokenInterceptor(buildLoginTokenManager()),
HttpsEnforcingInterceptor(),
OneShotInterceptor()
)
)
if (enableRateLimitProtection) add(4, RateLimitInterceptor(moshi, client?.cache))
}
certificatePinner(constructCertificatePinner())
}
.build()
}
private fun buildLoginTokenManager(): LoginTokenManager {
return loginTokenManager ?: DefaultLoginTokenManager()
}
private fun buildUserAgent(): String {
return userAgent ?: DEFAULT_USER_AGENT
}
private fun constructCertificatePinner(): CertificatePinner {
return CertificatePinner.Builder()
.apply { CERTIFICATES.forEach { add(ProxerUrls.webBase.host, it) } }
.build()
}
private fun buildMoshi(): Moshi {
return (moshi?.newBuilder() ?: Moshi.Builder())
.add(UnitAdapter())
.add(DateAdapter())
.add(PageAdapter())
.add(HttpUrlAdapter())
.add(ConferenceAdapter())
.add(EpisodeInfoAdapter())
.add(NotificationAdapter())
.add(ConferenceInfoAdapter())
.add(BooleanAdapterFactory())
.add(NotificationInfoAdapter())
.add(FixRatingDetailsAdapter())
.add(UcpSettingConstraintAdapter())
.add(DelimitedEnumSetAdapterFactory())
.add(DelimitedStringSetAdapterFactory())
.add(FallbackEnum.ADAPTER_FACTORY)
.build()
}
}
}
| gpl-3.0 | eb828b0057d802be550bf4e3992a0ca0 | 34.003279 | 119 | 0.644249 | 4.391608 | false | false | false | false |
vicpinm/Kotlin-Realm-Extensions | library-base/src/androidTest/java/com/vicpin/krealmextensions/KRealmExtensionsTests.kt | 1 | 16275 | package com.vicpin.krealmextensions
import android.support.test.runner.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import com.vicpin.krealmextensions.model.TestEntity
import com.vicpin.krealmextensions.model.TestEntityAutoPK
import com.vicpin.krealmextensions.model.TestEntityPK
import com.vicpin.krealmextensions.util.TestRealmConfigurationFactory
import io.realm.Realm
import io.realm.Sort
import io.realm.exceptions.RealmPrimaryKeyConstraintException
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
/**
* Created by victor on 10/1/17.
*/
@RunWith(AndroidJUnit4::class)
class KRealmExtensionsTests {
@get:Rule
var configFactory = TestRealmConfigurationFactory()
lateinit var realm: Realm
lateinit var latch: CountDownLatch
var latchReleased = false
@Before
fun setUp() {
val realmConfig = configFactory.createConfiguration()
realm = Realm.getInstance(realmConfig)
latch = CountDownLatch(1)
}
@After
fun tearDown() {
TestEntity().deleteAll()
TestEntityPK().deleteAll()
TestEntityAutoPK().deleteAll()
realm.close()
latchReleased = false
}
/**
* PERSISTENCE TESTS
*/
@Test
fun testPersistEntityWithCreate() {
TestEntity().create() //No exception expected
}
@Test
fun testPersistEntityWithCreateManaged() {
val result = TestEntity().createManaged(realm) //No exception expected
assertThat(result.isManaged).isTrue()
}
@Test
fun testPersistPKEntityWithCreate() {
TestEntityPK(1).create() //No exception expected
}
@Test
fun testPersistPKEntityWithCreateManaged() {
val result = TestEntityPK(1).createManaged(realm) //No exception expected
assertThat(result.isManaged).isTrue()
}
@Test(expected = IllegalArgumentException::class)
fun testPersistEntityWithCreateOrUpdateMethod() {
TestEntity().createOrUpdate() //Exception expected due to TestEntity has no primary key
}
@Test(expected = IllegalArgumentException::class)
fun testPersistEntityWithCreateOrUpdateMethodManaged() {
TestEntity().createOrUpdateManaged(realm) //Exception expected due to TestEntity has no primary key
}
fun testPersistPKEntityWithCreateOrUpdateMethod() {
TestEntityPK(1).createOrUpdate() //No exception expected
}
fun testPersistPKEntityWithCreateOrUpdateMethodManaged() {
val result = TestEntityPK(1).createOrUpdateManaged(realm) //No exception expected
assertThat(result.isManaged).isTrue()
}
@Test
fun testPersistEntityWithSaveMethod() {
TestEntity().save() //No exception expected
}
@Test
fun testPersistEntityWithSaveMethodManaged() {
val result = TestEntity().saveManaged(realm) //No exception expected
assertThat(result.isManaged)
assertThat(TestEntity().count(realm)).isEqualTo(1)
}
@Test
fun testPersistPKEntityWithSaveMethod() {
TestEntityPK(1).save() //No exception expected
}
@Test
fun testPersistPKEntityWithSaveMethodManaged() {
val result = TestEntityPK(1).saveManaged(realm) //No exception expected
assertThat(result.isManaged).isTrue()
assertThat(TestEntityPK().count(realm)).isEqualTo(1)
}
@Test(expected = RealmPrimaryKeyConstraintException::class)
fun testPersistPKEntityWithCreateMethodAndSamePrimaryKey() {
TestEntityPK(1).create() //No exception expected
TestEntityPK(1).create() //Exception expected
}
@Test(expected = RealmPrimaryKeyConstraintException::class)
fun testPersistPKEntityWithCreateMethodAndSamePrimaryKeyManaged() {
val result = TestEntityPK(1).createManaged(realm) //No exception expected
assertThat(result.isManaged).isTrue()
TestEntityPK(1).createManaged(realm) //Exception expected
}
@Test
fun testPersistPKEntityListWithSaveMethod() {
val list = listOf(TestEntityPK(1), TestEntityPK(2), TestEntityPK(3))
list.saveAll()
}
@Test
fun testPersistPKEntityListWithSaveMethodManaged() {
val list = listOf(TestEntityPK(1), TestEntityPK(2), TestEntityPK(3))
val results = list.saveAllManaged(realm)
results.forEach { assertThat(it.isManaged).isTrue() }
}
@Test
fun testCountPKEntity() {
val list = listOf(TestEntityPK(1), TestEntityPK(2), TestEntityPK(3))
list.saveAll()
assertThat(TestEntityPK().count()).isEqualTo(3)
}
@Test
fun testCountDuplicatePKEntity() {
val list = listOf(TestEntityPK(1), TestEntityPK(1), TestEntityPK(1))
list.saveAll()
assertThat(TestEntityPK().count()).isEqualTo(1)
}
@Test
fun testCountEntity() {
val list = listOf(TestEntity(), TestEntity(), TestEntity())
list.saveAll()
assertThat(TestEntity().count()).isEqualTo(3)
}
/**
* PERSISTENCE TEST WITH AUTO PRIMARY KEY
*/
@Test
fun testPersistAutoPKEntityWithSaveMethod() {
TestEntityAutoPK().save() //No exception expected
}
@Test
fun testPersistAutoPKEntityWithSaveMethodShouldHavePK() {
TestEntityAutoPK().save()
assertThat(TestEntityAutoPK().count()).isEqualTo(1)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(1)
TestEntityAutoPK().save()
assertThat(TestEntityAutoPK().count()).isEqualTo(2)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(2)
TestEntityAutoPK().save()
assertThat(TestEntityAutoPK().count()).isEqualTo(3)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(3)
}
@Test
fun testPersistAutoPkEntityWithPkShouldNotBeOverrided() {
TestEntityAutoPK(4, "").save()
assertThat(TestEntityAutoPK().count()).isEqualTo(1)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(4)
TestEntityAutoPK(10, "").save()
assertThat(TestEntityAutoPK().count()).isEqualTo(2)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(10)
TestEntityAutoPK(12, "").save()
assertThat(TestEntityAutoPK().count()).isEqualTo(3)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(12)
}
@Test
fun testPersistAutoPKEntityWithSaveManagedMethod() {
val result = TestEntityAutoPK().saveManaged(realm)
assertThat(result.isManaged)
assertThat(TestEntityAutoPK().count(realm)).isEqualTo(1)
}
@Test
fun testPersistAutoPKEntityListWithSaveMethod() {
val list = listOf(TestEntityAutoPK(), TestEntityAutoPK(), TestEntityAutoPK())
list.saveAll()
assertThat(TestEntityAutoPK().count()).isEqualTo(3)
assertThat(TestEntityAutoPK().queryFirst()?.id).isEqualTo(1)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(3)
}
@Test
fun testPersistAutoPKEntityArrayWithSaveMethod() {
val list = arrayOf(TestEntityAutoPK(), TestEntityAutoPK(), TestEntityAutoPK())
list.saveAll()
assertThat(TestEntityAutoPK().count()).isEqualTo(3)
assertThat(TestEntityAutoPK().queryFirst()?.id).isEqualTo(1)
assertThat(TestEntityAutoPK().queryLast()?.id).isEqualTo(3)
}
@Test
fun testPersistAutoPKEntityListWithSaveManagedMethod() {
val list = listOf(TestEntityAutoPK(), TestEntityAutoPK(), TestEntityAutoPK())
list.saveAllManaged(realm)
assertThat(TestEntityAutoPK().count(realm)).isEqualTo(3)
}
@Test
fun testPersistAutoPKEntityArrayWithSavemanagedMethod() {
val list = arrayOf(TestEntityAutoPK(), TestEntityAutoPK(), TestEntityAutoPK())
list.saveAllManaged(realm)
assertThat(TestEntityAutoPK().count(realm)).isEqualTo(3)
}
@Test
fun testUpdateEntity() {
TestEntity("test").save()
TestEntity().queryAndUpdate({ equalTo("name", "test") }) {
it.name = "updated"
}
val result = TestEntity().queryFirst { equalTo("name", "updated") }
assertThat(result).isNotNull()
assertThat(result?.name).isEqualTo("updated")
}
@Test
fun testUpdatePKEntity() {
TestEntityPK(1, "test").save()
TestEntityPK().queryAndUpdate({ equalTo("name", "test") }) {
it.name = "updated"
}
val result = TestEntityPK().queryFirst { equalTo("name", "updated") }
assertThat(result).isNotNull()
assertThat(result?.name).isEqualTo("updated")
}
/**
* QUERY TESTS WITH EMPTY DB
*/
@Test
fun testQueryFirstObjectWithEmptyDBShouldReturnNull() {
assertThat(TestEntity().queryFirst()).isNull()
}
@Test
fun testAsyncQueryFirstObjectWithEmptyDBShouldReturnNull() {
block {
TestEntity().queryFirstAsync { assertThat(it).isNull(); release() }
}
}
@Test
fun testQueryLastObjectWithEmptyDBShouldReturnNull() {
assertThat(TestEntity().queryLast()).isNull()
}
@Test
fun testQueryLastObjectWithConditionAndEmptyDBShouldReturnNull() {
assertThat(TestEntity().queryLast { equalTo("name", "test") }).isNull()
}
@Test
fun testAsyncQueryLastObjectWithEmptyDBShouldReturnNull() {
block {
TestEntity().queryLastAsync { assertThat(it).isNull(); release() }
}
}
@Test
fun testAllItemsShouldReturnEmptyCollectionWhenDBIsEmpty() {
assertThat(TestEntity().queryAll()).hasSize(0)
}
@Test
fun testAllItemsAsyncShouldReturnEmptyCollectionWhenDBIsEmpty() {
block {
TestEntity().queryAllAsync { assertThat(it).hasSize(0); release() }
}
}
@Test
fun testQueryConditionalWhenDBIsEmpty() {
val result = TestEntity().query { equalTo("name", "test") }
assertThat(result).hasSize(0)
}
@Test
fun testQueryFirstItemWhenDBIsEmpty() {
val result = TestEntity().queryFirst { equalTo("name", "test") }
assertThat(result).isNull()
}
@Test
fun testQuerySortedWhenDBIsEmpty() {
val result = TestEntity().querySorted("name", Sort.ASCENDING) { equalTo("name", "test") }
assertThat(result).hasSize(0)
}
/**
* QUERY TESTS WITH POPULATED DB
*/
@Test
fun testQueryFirstItemShouldReturnFirstItemWhenDBIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
assertThat(TestEntityPK().queryFirst()).isNotNull()
assertThat(TestEntityPK().queryFirst()?.id).isEqualTo(0)
}
@Test
fun testAsyncQueryFirstItemShouldReturnFirstItemWhenDBIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
block {
TestEntityPK().queryFirstAsync {
assertThat(it).isNotNull()
assertThat(it?.id).isEqualTo(0)
release()
}
}
}
@Test
fun testQueryLastItemShouldReturnLastItemWhenDBIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
assertThat(TestEntityPK().queryLast()?.id).isEqualTo(4)
}
@Test
fun testQueryLastItemWithConditionShouldReturnLastItemWhenDBIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
assertThat(TestEntityPK().queryLast { equalToValue("id", 3) }?.id).isEqualTo(3)
}
@Test
fun testAsyncQueryLastItemShouldReturnLastItemWhenDBIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
block {
TestEntityPK().queryLastAsync {
assertThat(it).isNotNull()
release()
}
}
}
@Test
fun testQueryAllItemsShouldReturnAllItemsWhenDBIsNotEmpty() {
populateDBWithTestEntity(numItems = 5)
assertThat(TestEntity().queryAll()).hasSize(5)
}
@Test
fun testAsyncQueryAllItemsShouldReturnAllItemsWhenDBIsNotEmpty() {
populateDBWithTestEntity(numItems = 5)
block {
TestEntity().queryAllAsync { assertThat(it).hasSize(5); release() }
}
}
@Test
fun testQueryAllItemsAfterSaveCollection() {
val list = listOf(TestEntityPK(1), TestEntityPK(2), TestEntityPK(3))
list.saveAll()
assertThat(TestEntityPK().queryAll()).hasSize(3)
}
/**
* QUERY TESTS WITH WHERE STATEMENT
*/
@Test
fun testWhereQueryShouldReturnExpectedItems() {
populateDBWithTestEntityPK(numItems = 5)
val results = TestEntityPK().query { equalToValue("id", 1) }
assertThat(results).hasSize(1)
assertThat(results.first().id).isEqualTo(1)
}
@Test
fun testAsyncWhereQueryShouldReturnExpectedItems() {
populateDBWithTestEntityPK(numItems = 5)
block {
TestEntityPK().queryAsync({ equalToValue("id", 1) }) { results ->
assertThat(results).hasSize(1)
assertThat(results.first().id).isEqualTo(1)
release()
}
}
}
@Test
fun testWhereQueryShouldNotReturnAnyItem() {
populateDBWithTestEntityPK(numItems = 5)
val results = TestEntityPK().query { equalToValue("id", 6) }
assertThat(results).hasSize(0)
}
@Test
fun testAsyncWhereQueryShouldNotReturnAnyItem() {
populateDBWithTestEntityPK(numItems = 5)
block {
TestEntityPK().queryAsync({ equalToValue("id", 6) }) { results ->
assertThat(results).hasSize(0)
release()
}
}
}
@Test
fun testFirstItemWhenDbIsNotEmpty() {
populateDBWithTestEntityPK(numItems = 5)
val result = TestEntityPK().queryFirst { equalToValue("id", 2) }
assertThat(result).isNotNull()
assertThat(result?.id).isEqualTo(2)
}
@Test
fun testQueryAscendingShouldReturnOrderedResults() {
populateDBWithTestEntityPK(numItems = 5)
val result = TestEntityPK().querySorted("id", Sort.ASCENDING)
assertThat(result).hasSize(5)
assertThat(result.first().id).isEqualTo(0)
assertThat(result.last().id).isEqualTo(4)
}
@Test
fun testQueryDescendingShouldReturnOrderedResults() {
populateDBWithTestEntityPK(numItems = 5)
val result = TestEntityPK().querySorted("id", Sort.DESCENDING)
assertThat(result).hasSize(5)
assertThat(result.first().id).isEqualTo(4)
assertThat(result.last().id).isEqualTo(0)
}
@Test
fun testQueryDescendingWithFilterShouldReturnOrderedResults() {
populateDBWithTestEntityPK(numItems = 5)
val result = TestEntityPK().querySorted("id", Sort.DESCENDING) {
lessThan("id", 3).greaterThan("id", 0)
}
assertThat(result).hasSize(2)
assertThat(result.first().id).isEqualTo(2)
assertThat(result.last().id).isEqualTo(1)
}
/**
* DELETION TESTS
*/
@Test
fun testDeleteEntities() {
populateDBWithTestEntity(numItems = 5)
TestEntity().deleteAll()
assertThat(TestEntity().queryAll()).hasSize(0)
}
@Test
fun testDeleteEntitiesWithPK() {
populateDBWithTestEntityPK(numItems = 5)
TestEntityPK().deleteAll()
assertThat(TestEntityPK().queryAll()).hasSize(0)
}
@Test
fun testDeleteEntitiesWithStatement() {
populateDBWithTestEntityPK(numItems = 5)
TestEntityPK().delete { equalToValue("id", 1) }
assertThat(TestEntityPK().queryAll()).hasSize(4)
}
/**
* UTILITY TEST METHODS
*/
private fun populateDBWithTestEntity(numItems: Int) {
(0..numItems - 1).forEach { TestEntity().save() }
}
private fun populateDBWithTestEntityPK(numItems: Int) {
(0..numItems - 1).forEach { TestEntityPK(it.toLong()).save() }
}
private fun blockLatch() {
if (!latchReleased) {
latch.await()
}
}
private fun release() {
latchReleased = true
latch.countDown()
latch = CountDownLatch(1)
}
fun block(closure: () -> Unit) {
latchReleased = false
closure()
blockLatch()
}
}
| apache-2.0 | 3c186914a56641ea08c6397b3e10e29c | 29.194805 | 107 | 0.650507 | 5.143805 | false | true | false | false |
xCatG/android-UniversalMusicPlayer | common/src/main/java/com/example/android/uamp/media/MusicService.kt | 1 | 27572 | /*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* 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.uamp.media
import android.app.Notification
import android.app.PendingIntent
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.ResultReceiver
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaBrowserCompat.MediaItem
import android.support.v4.media.MediaDescriptionCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaSessionCompat
import android.support.v4.media.session.PlaybackStateCompat
import android.util.Log
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.media.MediaBrowserServiceCompat
import androidx.media.MediaBrowserServiceCompat.BrowserRoot.EXTRA_RECENT
import com.example.android.uamp.media.extensions.album
import com.example.android.uamp.media.extensions.flag
import com.example.android.uamp.media.extensions.id
import com.example.android.uamp.media.extensions.toMediaQueueItem
import com.example.android.uamp.media.extensions.toMediaSource
import com.example.android.uamp.media.extensions.trackNumber
import com.example.android.uamp.media.library.AbstractMusicSource
import com.example.android.uamp.media.library.BrowseTree
import com.example.android.uamp.media.library.JsonSource
import com.example.android.uamp.media.library.MEDIA_SEARCH_SUPPORTED
import com.example.android.uamp.media.library.MusicSource
import com.example.android.uamp.media.library.UAMP_BROWSABLE_ROOT
import com.example.android.uamp.media.library.UAMP_EMPTY_ROOT
import com.example.android.uamp.media.library.UAMP_RECENT_ROOT
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.ControlDispatcher
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.audio.AudioAttributes
import com.google.android.exoplayer2.ext.cast.CastPlayer
import com.google.android.exoplayer2.ext.cast.SessionAvailabilityListener
import com.google.android.exoplayer2.ext.mediasession.MediaSessionConnector
import com.google.android.exoplayer2.ext.mediasession.TimelineQueueNavigator
import com.google.android.exoplayer2.ui.PlayerNotificationManager
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
import com.google.android.gms.cast.MediaQueueItem
import com.google.android.gms.cast.framework.CastContext
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
/**
* This class is the entry point for browsing and playback commands from the APP's UI
* and other apps that wish to play music via UAMP (for example, Android Auto or
* the Google Assistant).
*
* Browsing begins with the method [MusicService.onGetRoot], and continues in
* the callback [MusicService.onLoadChildren].
*
* For more information on implementing a MediaBrowserService,
* visit [https://developer.android.com/guide/topics/media-apps/audio-app/building-a-mediabrowserservice.html](https://developer.android.com/guide/topics/media-apps/audio-app/building-a-mediabrowserservice.html).
*
* This class also handles playback for Cast sessions.
* When a Cast session is active, playback commands are passed to a
* [CastPlayer](https://exoplayer.dev/doc/reference/com/google/android/exoplayer2/ext/cast/CastPlayer.html),
* otherwise they are passed to an ExoPlayer for local playback.
*/
open class MusicService : MediaBrowserServiceCompat() {
private lateinit var notificationManager: UampNotificationManager
private lateinit var mediaSource: MusicSource
private lateinit var packageValidator: PackageValidator
// The current player will either be an ExoPlayer (for local playback) or a CastPlayer (for
// remote playback through a Cast device).
private lateinit var currentPlayer: Player
private val serviceJob = SupervisorJob()
private val serviceScope = CoroutineScope(Dispatchers.Main + serviceJob)
protected lateinit var mediaSession: MediaSessionCompat
protected lateinit var mediaSessionConnector: MediaSessionConnector
private var currentPlaylistItems: List<MediaMetadataCompat> = emptyList()
private lateinit var storage: PersistentStorage
/**
* This must be `by lazy` because the source won't initially be ready.
* See [MusicService.onLoadChildren] to see where it's accessed (and first
* constructed).
*/
private val browseTree: BrowseTree by lazy {
BrowseTree(applicationContext, mediaSource)
}
private val dataSourceFactory: DefaultDataSourceFactory by lazy {
DefaultDataSourceFactory(
/* context= */ this,
Util.getUserAgent(/* context= */ this, UAMP_USER_AGENT), /* listener= */
null
)
}
private var isForegroundService = false
private val remoteJsonSource: Uri =
Uri.parse("https://storage.googleapis.com/uamp/catalog.json")
private val uAmpAudioAttributes = AudioAttributes.Builder()
.setContentType(C.CONTENT_TYPE_MUSIC)
.setUsage(C.USAGE_MEDIA)
.build()
private val playerListener = PlayerEventListener()
/**
* Configure ExoPlayer to handle audio focus for us.
* See [Player.AudioComponent.setAudioAttributes] for details.
*/
private val exoPlayer: ExoPlayer by lazy {
SimpleExoPlayer.Builder(this).build().apply {
setAudioAttributes(uAmpAudioAttributes, true)
setHandleAudioBecomingNoisy(true)
addListener(playerListener)
}
}
/**
* Create a CastPlayer to handle communication with a Cast session.
*/
private val castPlayer: CastPlayer by lazy {
CastPlayer(CastContext.getSharedInstance(this)).apply {
setSessionAvailabilityListener(UampCastSessionAvailabilityListener())
addListener(playerListener)
}
}
@ExperimentalCoroutinesApi
override fun onCreate() {
super.onCreate()
// Build a PendingIntent that can be used to launch the UI.
val sessionActivityPendingIntent =
packageManager?.getLaunchIntentForPackage(packageName)?.let { sessionIntent ->
PendingIntent.getActivity(this, 0, sessionIntent, 0)
}
// Create a new MediaSession.
mediaSession = MediaSessionCompat(this, "MusicService")
.apply {
setSessionActivity(sessionActivityPendingIntent)
isActive = true
}
/**
* In order for [MediaBrowserCompat.ConnectionCallback.onConnected] to be called,
* a [MediaSessionCompat.Token] needs to be set on the [MediaBrowserServiceCompat].
*
* It is possible to wait to set the session token, if required for a specific use-case.
* However, the token *must* be set by the time [MediaBrowserServiceCompat.onGetRoot]
* returns, or the connection will fail silently. (The system will not even call
* [MediaBrowserCompat.ConnectionCallback.onConnectionFailed].)
*/
sessionToken = mediaSession.sessionToken
/**
* The notification manager will use our player and media session to decide when to post
* notifications. When notifications are posted or removed our listener will be called, this
* allows us to promote the service to foreground (required so that we're not killed if
* the main UI is not visible).
*/
notificationManager = UampNotificationManager(
this,
mediaSession.sessionToken,
PlayerNotificationListener()
)
// The media library is built from a remote JSON file. We'll create the source here,
// and then use a suspend function to perform the download off the main thread.
mediaSource = JsonSource(source = remoteJsonSource)
serviceScope.launch {
mediaSource.load()
}
// ExoPlayer will manage the MediaSession for us.
mediaSessionConnector = MediaSessionConnector(mediaSession)
mediaSessionConnector.setPlaybackPreparer(UampPlaybackPreparer())
mediaSessionConnector.setQueueNavigator(UampQueueNavigator(mediaSession))
switchToPlayer(
previousPlayer = null,
newPlayer = if (castPlayer.isCastSessionAvailable) castPlayer else exoPlayer
)
notificationManager.showNotificationForPlayer(currentPlayer)
packageValidator = PackageValidator(this, R.xml.allowed_media_browser_callers)
storage = PersistentStorage.getInstance(applicationContext)
}
/**
* This is the code that causes UAMP to stop playing when swiping the activity away from
* recents. The choice to do this is app specific. Some apps stop playback, while others allow
* playback to continue and allow users to stop it with the notification.
*/
override fun onTaskRemoved(rootIntent: Intent) {
saveRecentSongToStorage()
super.onTaskRemoved(rootIntent)
/**
* By stopping playback, the player will transition to [Player.STATE_IDLE] triggering
* [Player.EventListener.onPlayerStateChanged] to be called. This will cause the
* notification to be hidden and trigger
* [PlayerNotificationManager.NotificationListener.onNotificationCancelled] to be called.
* The service will then remove itself as a foreground service, and will call
* [stopSelf].
*/
currentPlayer.stop(/* reset= */true)
}
override fun onDestroy() {
mediaSession.run {
isActive = false
release()
}
// Cancel coroutines when the service is going away.
serviceJob.cancel()
// Free ExoPlayer resources.
exoPlayer.removeListener(playerListener)
exoPlayer.release()
}
/**
* Returns the "root" media ID that the client should request to get the list of
* [MediaItem]s to browse/play.
*/
override fun onGetRoot(
clientPackageName: String,
clientUid: Int,
rootHints: Bundle?
): BrowserRoot? {
/*
* By default, all known clients are permitted to search, but only tell unknown callers
* about search if permitted by the [BrowseTree].
*/
val isKnownCaller = packageValidator.isKnownCaller(clientPackageName, clientUid)
val rootExtras = Bundle().apply {
putBoolean(
MEDIA_SEARCH_SUPPORTED,
isKnownCaller || browseTree.searchableByUnknownCaller
)
putBoolean(CONTENT_STYLE_SUPPORTED, true)
putInt(CONTENT_STYLE_BROWSABLE_HINT, CONTENT_STYLE_GRID)
putInt(CONTENT_STYLE_PLAYABLE_HINT, CONTENT_STYLE_LIST)
}
return if (isKnownCaller) {
/**
* By default return the browsable root. Treat the EXTRA_RECENT flag as a special case
* and return the recent root instead.
*/
val isRecentRequest = rootHints?.getBoolean(EXTRA_RECENT) ?: false
val browserRootPath = if (isRecentRequest) UAMP_RECENT_ROOT else UAMP_BROWSABLE_ROOT
BrowserRoot(browserRootPath, rootExtras)
} else {
/**
* Unknown caller. There are two main ways to handle this:
* 1) Return a root without any content, which still allows the connecting client
* to issue commands.
* 2) Return `null`, which will cause the system to disconnect the app.
*
* UAMP takes the first approach for a variety of reasons, but both are valid
* options.
*/
BrowserRoot(UAMP_EMPTY_ROOT, rootExtras)
}
}
/**
* Returns (via the [result] parameter) a list of [MediaItem]s that are child
* items of the provided [parentMediaId]. See [BrowseTree] for more details on
* how this is build/more details about the relationships.
*/
override fun onLoadChildren(
parentMediaId: String,
result: Result<List<MediaItem>>
) {
/**
* If the caller requests the recent root, return the most recently played song.
*/
if (parentMediaId == UAMP_RECENT_ROOT) {
result.sendResult(storage.loadRecentSong()?.let { song -> listOf(song) })
} else {
// If the media source is ready, the results will be set synchronously here.
val resultsSent = mediaSource.whenReady { successfullyInitialized ->
if (successfullyInitialized) {
val children = browseTree[parentMediaId]?.map { item ->
MediaItem(item.description, item.flag)
}
result.sendResult(children)
} else {
mediaSession.sendSessionEvent(NETWORK_FAILURE, null)
result.sendResult(null)
}
}
// If the results are not ready, the service must "detach" the results before
// the method returns. After the source is ready, the lambda above will run,
// and the caller will be notified that the results are ready.
//
// See [MediaItemFragmentViewModel.subscriptionCallback] for how this is passed to the
// UI/displayed in the [RecyclerView].
if (!resultsSent) {
result.detach()
}
}
}
/**
* Returns a list of [MediaItem]s that match the given search query
*/
override fun onSearch(
query: String,
extras: Bundle?,
result: Result<List<MediaItem>>
) {
val resultsSent = mediaSource.whenReady { successfullyInitialized ->
if (successfullyInitialized) {
val resultsList = mediaSource.search(query, extras ?: Bundle.EMPTY)
.map { mediaMetadata ->
MediaItem(mediaMetadata.description, mediaMetadata.flag)
}
result.sendResult(resultsList)
}
}
if (!resultsSent) {
result.detach()
}
}
/**
* Load the supplied list of songs and the song to play into the current player.
*/
private fun preparePlaylist(
metadataList: List<MediaMetadataCompat>,
itemToPlay: MediaMetadataCompat?,
playWhenReady: Boolean,
playbackStartPositionMs: Long
) {
// Since the playlist was probably based on some ordering (such as tracks
// on an album), find which window index to play first so that the song the
// user actually wants to hear plays first.
val initialWindowIndex = if (itemToPlay == null) 0 else metadataList.indexOf(itemToPlay)
currentPlaylistItems = metadataList
currentPlayer.playWhenReady = playWhenReady
currentPlayer.stop(/* reset= */ true)
if (currentPlayer == exoPlayer) {
val mediaSource = metadataList.toMediaSource(dataSourceFactory)
exoPlayer.prepare(mediaSource)
exoPlayer.seekTo(initialWindowIndex, playbackStartPositionMs)
} else /* currentPlayer == castPlayer */ {
val items: Array<MediaQueueItem> = metadataList.map {
it.toMediaQueueItem()
}.toTypedArray()
castPlayer.loadItems(
items,
initialWindowIndex,
playbackStartPositionMs,
Player.REPEAT_MODE_OFF
)
}
}
private fun switchToPlayer(previousPlayer: Player?, newPlayer: Player) {
if (previousPlayer == newPlayer) {
return
}
currentPlayer = newPlayer
if (previousPlayer != null) {
val playbackState = previousPlayer.playbackState
if (currentPlaylistItems.isEmpty()) {
// We are joining a playback session. Loading the session from the new player is
// not supported, so we stop playback.
currentPlayer.stop(/* reset= */true)
} else if (playbackState != Player.STATE_IDLE && playbackState != Player.STATE_ENDED) {
preparePlaylist(
metadataList = currentPlaylistItems,
itemToPlay = currentPlaylistItems[previousPlayer.currentWindowIndex],
playWhenReady = previousPlayer.playWhenReady,
playbackStartPositionMs = previousPlayer.currentPosition
)
}
}
mediaSessionConnector.setPlayer(newPlayer)
previousPlayer?.stop(/* reset= */true)
}
private fun saveRecentSongToStorage() {
// Obtain the current song details *before* saving them on a separate thread, otherwise
// the current player may have been unloaded by the time the save routine runs.
val description = currentPlaylistItems[currentPlayer.currentWindowIndex].description
val position = currentPlayer.currentPosition
serviceScope.launch {
storage.saveRecentSong(
description,
position
)
}
}
private inner class UampCastSessionAvailabilityListener : SessionAvailabilityListener {
/**
* Called when a Cast session has started and the user wishes to control playback on a
* remote Cast receiver rather than play audio locally.
*/
override fun onCastSessionAvailable() {
switchToPlayer(currentPlayer, castPlayer)
}
/**
* Called when a Cast session has ended and the user wishes to control playback locally.
*/
override fun onCastSessionUnavailable() {
switchToPlayer(currentPlayer, exoPlayer)
}
}
private inner class UampQueueNavigator(
mediaSession: MediaSessionCompat
) : TimelineQueueNavigator(mediaSession) {
override fun getMediaDescription(player: Player, windowIndex: Int): MediaDescriptionCompat =
currentPlaylistItems[windowIndex].description
}
private inner class UampPlaybackPreparer : MediaSessionConnector.PlaybackPreparer {
/**
* UAMP supports preparing (and playing) from search, as well as media ID, so those
* capabilities are declared here.
*
* TODO: Add support for ACTION_PREPARE and ACTION_PLAY, which mean "prepare/play something".
*/
override fun getSupportedPrepareActions(): Long =
PlaybackStateCompat.ACTION_PREPARE_FROM_MEDIA_ID or
PlaybackStateCompat.ACTION_PLAY_FROM_MEDIA_ID or
PlaybackStateCompat.ACTION_PREPARE_FROM_SEARCH or
PlaybackStateCompat.ACTION_PLAY_FROM_SEARCH
override fun onPrepare(playWhenReady: Boolean) {
val recentSong = storage.loadRecentSong()
if (recentSong != null) {
onPrepareFromMediaId(
recentSong.mediaId!!,
playWhenReady,
recentSong.description.extras
)
}
}
override fun onPrepareFromMediaId(
mediaId: String,
playWhenReady: Boolean,
extras: Bundle?
) {
mediaSource.whenReady {
val itemToPlay: MediaMetadataCompat? = mediaSource.find { item ->
item.id == mediaId
}
if (itemToPlay == null) {
Log.w(TAG, "Content not found: MediaID=$mediaId")
// TODO: Notify caller of the error.
} else {
val playbackStartPositionMs =
extras?.getLong(MEDIA_DESCRIPTION_EXTRAS_START_PLAYBACK_POSITION_MS, C.TIME_UNSET)
?: C.TIME_UNSET
preparePlaylist(
buildPlaylist(itemToPlay),
itemToPlay,
playWhenReady,
playbackStartPositionMs
)
}
}
}
/**
* This method is used by the Google Assistant to respond to requests such as:
* - Play Geisha from Wake Up on UAMP
* - Play electronic music on UAMP
* - Play music on UAMP
*
* For details on how search is handled, see [AbstractMusicSource.search].
*/
override fun onPrepareFromSearch(query: String, playWhenReady: Boolean, extras: Bundle?) {
mediaSource.whenReady {
val metadataList = mediaSource.search(query, extras ?: Bundle.EMPTY)
if (metadataList.isNotEmpty()) {
preparePlaylist(
metadataList,
metadataList[0],
playWhenReady,
playbackStartPositionMs = C.TIME_UNSET
)
}
}
}
override fun onPrepareFromUri(uri: Uri, playWhenReady: Boolean, extras: Bundle?) = Unit
override fun onCommand(
player: Player,
controlDispatcher: ControlDispatcher,
command: String,
extras: Bundle?,
cb: ResultReceiver?
) = false
/**
* Builds a playlist based on a [MediaMetadataCompat].
*
* TODO: Support building a playlist by artist, genre, etc...
*
* @param item Item to base the playlist on.
* @return a [List] of [MediaMetadataCompat] objects representing a playlist.
*/
private fun buildPlaylist(item: MediaMetadataCompat): List<MediaMetadataCompat> =
mediaSource.filter { it.album == item.album }.sortedBy { it.trackNumber }
}
/**
* Listen for notification events.
*/
private inner class PlayerNotificationListener :
PlayerNotificationManager.NotificationListener {
override fun onNotificationPosted(
notificationId: Int,
notification: Notification,
ongoing: Boolean
) {
if (ongoing && !isForegroundService) {
ContextCompat.startForegroundService(
applicationContext,
Intent(applicationContext, [email protected])
)
startForeground(notificationId, notification)
isForegroundService = true
}
}
override fun onNotificationCancelled(notificationId: Int, dismissedByUser: Boolean) {
stopForeground(true)
isForegroundService = false
stopSelf()
}
}
/**
* Listen for events from ExoPlayer.
*/
private inner class PlayerEventListener : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
when (playbackState) {
Player.STATE_BUFFERING,
Player.STATE_READY -> {
notificationManager.showNotificationForPlayer(currentPlayer)
if (playbackState == Player.STATE_READY) {
// When playing/paused save the current media item in persistent
// storage so that playback can be resumed between device reboots.
// Search for "media resumption" for more information.
saveRecentSongToStorage()
if (!playWhenReady) {
// If playback is paused we remove the foreground state which allows the
// notification to be dismissed. An alternative would be to provide a
// "close" button in the notification which stops playback and clears
// the notification.
stopForeground(false)
}
}
}
else -> {
notificationManager.hideNotification()
}
}
}
override fun onPlayerError(error: ExoPlaybackException) {
var message = R.string.generic_error;
when (error.type) {
// If the data from MediaSource object could not be loaded the Exoplayer raises
// a type_source error.
// An error message is printed to UI via Toast message to inform the user.
ExoPlaybackException.TYPE_SOURCE -> {
message = R.string.error_media_not_found;
Log.e(TAG, "TYPE_SOURCE: " + error.sourceException.message)
}
// If the error occurs in a render component, Exoplayer raises a type_remote error.
ExoPlaybackException.TYPE_RENDERER -> {
Log.e(TAG, "TYPE_RENDERER: " + error.rendererException.message)
}
// If occurs an unexpected RuntimeException Exoplayer raises a type_unexpected error.
ExoPlaybackException.TYPE_UNEXPECTED -> {
Log.e(TAG, "TYPE_UNEXPECTED: " + error.unexpectedException.message)
}
// Occurs when there is a OutOfMemory error.
ExoPlaybackException.TYPE_OUT_OF_MEMORY -> {
Log.e(TAG, "TYPE_OUT_OF_MEMORY: " + error.outOfMemoryError.message)
}
// If the error occurs in a remote component, Exoplayer raises a type_remote error.
ExoPlaybackException.TYPE_REMOTE -> {
Log.e(TAG, "TYPE_REMOTE: " + error.message)
}
}
Toast.makeText(
applicationContext,
message,
Toast.LENGTH_LONG
).show()
}
}
}
/*
* (Media) Session events
*/
const val NETWORK_FAILURE = "com.example.android.uamp.media.session.NETWORK_FAILURE"
/** Content styling constants */
private const val CONTENT_STYLE_BROWSABLE_HINT = "android.media.browse.CONTENT_STYLE_BROWSABLE_HINT"
private const val CONTENT_STYLE_PLAYABLE_HINT = "android.media.browse.CONTENT_STYLE_PLAYABLE_HINT"
private const val CONTENT_STYLE_SUPPORTED = "android.media.browse.CONTENT_STYLE_SUPPORTED"
private const val CONTENT_STYLE_LIST = 1
private const val CONTENT_STYLE_GRID = 2
private const val UAMP_USER_AGENT = "uamp.next"
val MEDIA_DESCRIPTION_EXTRAS_START_PLAYBACK_POSITION_MS = "playback_start_position_ms"
private const val TAG = "MusicService"
| apache-2.0 | a08c523c7227738dd00816a917f077cf | 39.968796 | 212 | 0.637277 | 5.327923 | false | false | false | false |
elect86/modern-jogl-examples | src/main/kotlin/main/tut14/basicTexture.kt | 2 | 15364 | package main.tut14
import com.jogamp.newt.event.KeyEvent
import com.jogamp.newt.event.MouseEvent
import com.jogamp.opengl.GL2ES2.GL_RED
import com.jogamp.opengl.GL2ES3.*
import com.jogamp.opengl.GL2GL3.GL_TEXTURE_1D
import com.jogamp.opengl.GL3
import com.jogamp.opengl.GL3.GL_DEPTH_CLAMP
import glNext.*
import glm.*
import glm.mat.Mat4
import glm.quat.Quat
import glm.vec._3.Vec3
import glm.vec._4.Vec4
import main.framework.Framework
import main.framework.Semantic
import main.framework.component.Mesh
import uno.buffer.*
import uno.glm.MatrixStack
import uno.glsl.programOf
import uno.mousePole.*
import uno.time.Timer
import java.nio.ByteBuffer
/**
* Created by elect on 28/03/17.
*/
fun main(args: Array<String>) {
BasicTexture_().setup("Tutorial 14 - Basic Texture")
}
class BasicTexture_ : Framework() {
lateinit var litShaderProg: ProgramData
lateinit var litTextureProg: ProgramData
lateinit var unlit: UnlitProgData
val initialObjectData = ObjectData(
Vec3(0.0f, 0.5f, 0.0f),
Quat(1.0f, 0.0f, 0.0f, 0.0f))
val initialViewData = ViewData(
Vec3(initialObjectData.position),
Quat(0.92387953f, 0.3826834f, 0.0f, 0.0f),
10.0f,
0.0f)
val viewScale = ViewScale(
1.5f, 70.0f,
1.5f, 0.5f,
0.0f, 0.0f, //No camera movement.
90.0f / 250.0f)
val viewPole = ViewPole(initialViewData, viewScale, MouseEvent.BUTTON1)
val objectPole = ObjectPole(initialObjectData, 90.0f / 250.0f, MouseEvent.BUTTON3, viewPole)
lateinit var objectMesh: Mesh
lateinit var cube: Mesh
object Buffer {
val PROJECTION = 0
val LIGHT = 1
val MATERIAL = 2
val MAX = 3
}
val gaussTextures = intBufferBig(NUM_GAUSSIAN_TEXTURES)
val gaussSampler = intBufferBig(1)
val bufferName = intBufferBig(Buffer.MAX)
var drawCameraPos = false
var drawLights = true
var useTexture = false
val specularShininess = 0.2f
val lightHeight = 1.0f
val lightRadius = 3.0f
val halfLightDistance = 25.0f
val lightAttenuation = 1.0f / (halfLightDistance * halfLightDistance)
val lightTimer = Timer(Timer.Type.Loop, 6.0f)
val lightBuffer = byteBufferBig(LightBlock.SIZE)
var currTexture = 0
companion object {
val NUMBER_OF_LIGHTS = 2
val NUM_GAUSSIAN_TEXTURES = 4
}
override fun init(gl: GL3) = with(gl) {
initializePrograms(gl)
objectMesh = Mesh(gl, javaClass, "tut14/Infinity.xml")
cube = Mesh(gl, javaClass, "tut14/UnitCube.xml")
val depthZNear = 0.0f
val depthZFar = 1.0f
glEnable(GL_CULL_FACE)
glCullFace(GL_BACK)
glFrontFace(GL_CW)
glEnable(GL_DEPTH_TEST)
glDepthMask(true)
glDepthFunc(GL_LEQUAL)
glDepthRangef(depthZNear, depthZFar)
glEnable(GL_DEPTH_CLAMP)
//Setup our Uniform Buffers
val mtl = MaterialBlock
mtl.diffuseColor = Vec4(1.0f, 0.673f, 0.043f, 1.0f)
mtl.specularColor = Vec4(1.0f, 0.673f, 0.043f, 1.0f)
mtl.specularShininess = specularShininess
val mtlBuffer = mtl.to(byteBufferBig(MaterialBlock.SIZE))
glGenBuffers(bufferName)
glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.MATERIAL])
glBufferData(GL_UNIFORM_BUFFER, mtlBuffer, GL_STATIC_DRAW)
glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.LIGHT])
glBufferData(GL_UNIFORM_BUFFER, LightBlock.SIZE, GL_DYNAMIC_DRAW)
glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.PROJECTION])
glBufferData(GL_UNIFORM_BUFFER, Mat4.SIZE, GL_DYNAMIC_DRAW)
//Bind the static buffers.
glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.LIGHT, bufferName[Buffer.LIGHT], 0, LightBlock.SIZE.L)
glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.PROJECTION, bufferName[Buffer.PROJECTION], 0, Mat4.SIZE.L)
glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.MATERIAL, bufferName[Buffer.MATERIAL], 0, MaterialBlock.SIZE.L)
glBindBuffer(GL_UNIFORM_BUFFER)
createGaussianTextures(gl)
mtlBuffer.destroy()
}
fun initializePrograms(gl: GL3) {
litShaderProg = ProgramData(gl, "pn.vert", "shader-gaussian.frag")
litTextureProg = ProgramData(gl, "pn.vert", "texture-gaussian.frag")
unlit = UnlitProgData(gl, "unlit")
}
fun createGaussianTextures(gl: GL3) = with(gl) {
glGenTextures(NUM_GAUSSIAN_TEXTURES, gaussTextures)
repeat(NUM_GAUSSIAN_TEXTURES) {
val cosAngleResolution = calcCosAngleResolution(it)
createGaussianTexture(gl, it, cosAngleResolution)
}
glGenSampler(gaussSampler)
glSamplerParameteri(gaussSampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
glSamplerParameteri(gaussSampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
glSamplerParameteri(gaussSampler, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
}
fun calcCosAngleResolution(level: Int): Int {
val cosAngleStart = 64
return cosAngleStart * glm.pow(2f, level.f).i
}
fun createGaussianTexture(gl: GL3, index: Int, cosAngleResolution: Int) = with(gl) {
val textureData = buildGaussianData(cosAngleResolution)
glBindTexture(GL_TEXTURE_1D, gaussTextures[index])
glTexImage1D(GL_TEXTURE_1D, 0, GL_R8, cosAngleResolution, 0, GL_RED, GL_UNSIGNED_BYTE, textureData)
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_BASE_LEVEL, 0)
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAX_LEVEL, 0)
glBindTexture(GL_TEXTURE_1D)
textureData.destroy()
}
fun buildGaussianData(cosAngleResolution: Int): ByteBuffer {
val textureData = byteBufferBig(cosAngleResolution)
repeat(cosAngleResolution) { iCosAng ->
val cosAng = iCosAng / (cosAngleResolution - 1).f
val angle = glm.acos(cosAng)
var exponent = angle / specularShininess
exponent = -(exponent * exponent)
val gaussianTerm = glm.exp(exponent)
textureData[iCosAng] = (gaussianTerm * 255f).b
}
return textureData
}
override fun display(gl: GL3) = with(gl) {
lightTimer.update()
glClearBufferf(GL_COLOR, 0.75f, 0.75f, 1.0f, 1.0f)
glClearBufferf(GL_DEPTH)
val modelMatrix = MatrixStack(viewPole.calcMatrix())
val worldToCamMat = modelMatrix.top()
val globalLightDirection = Vec3(0.707f, 0.707f, 0.0f)
val lightData = LightBlock
lightData.ambientIntensity = Vec4(0.2f, 0.2f, 0.2f, 1.0f)
lightData.lightAttenuation = lightAttenuation
lightData.lights[0].cameraSpaceLightPos = worldToCamMat * Vec4(globalLightDirection, 0.0f)
lightData.lights[0].lightIntensity = Vec4(0.6f, 0.6f, 0.6f, 1.0f)
lightData.lights[1].cameraSpaceLightPos = worldToCamMat * calcLightPosition()
lightData.lights[1].lightIntensity = Vec4(0.4f, 0.4f, 0.4f, 1.0f)
glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.LIGHT])
glBufferSubData(GL_UNIFORM_BUFFER, lightData to lightBuffer)
glBindBuffer(GL_UNIFORM_BUFFER)
run {
glBindBufferRange(GL_UNIFORM_BUFFER, Semantic.Uniform.MATERIAL, bufferName[Buffer.MATERIAL], 0, MaterialBlock.SIZE.L)
modelMatrix run {
applyMatrix(objectPole.calcMatrix())
scale(2.0f)
val normMatrix = top().toMat3()
normMatrix.inverse_().transpose_()
val prog = if (useTexture) litTextureProg else litShaderProg
glUseProgram(prog.theProgram)
glUniformMatrix4f(prog.modelToCameraMatrixUnif, top())
glUniformMatrix3f(prog.normalModelToCameraMatrixUnif, normMatrix)
glActiveTexture(GL_TEXTURE0 + Semantic.Sampler.GAUSSIAN_TEXTURE)
glBindTexture(GL_TEXTURE_1D, gaussTextures[currTexture])
glBindSampler(Semantic.Sampler.GAUSSIAN_TEXTURE, gaussSampler)
objectMesh.render(gl, "lit")
glBindSampler(Semantic.Sampler.GAUSSIAN_TEXTURE)
glBindTexture(GL_TEXTURE_1D)
glUseProgram()
glBindBufferBase(GL_UNIFORM_BUFFER, Semantic.Uniform.MATERIAL)
}
}
if (drawLights)
modelMatrix run {
translate(calcLightPosition())
scale(0.25f)
glUseProgram(unlit.theProgram)
glUniformMatrix4f(unlit.modelToCameraMatrixUnif, top())
val lightColor = Vec4(1.0f)
glUniform4f(unlit.objectColorUnif, lightColor)
cube.render(gl, "flat")
reset()
translate(globalLightDirection * 100.0f)
scale(5.0f)
glUniformMatrix4f(unlit.modelToCameraMatrixUnif, top())
cube.render(gl, "flat")
glUseProgram()
}
if (drawCameraPos)
modelMatrix run {
setIdentity()
translate(0.0f, 0.0f, -viewPole.getView().radius)
scale(0.25f)
glDisable(GL_DEPTH_TEST)
glDepthMask(false)
glUseProgram(unlit.theProgram)
glUniformMatrix4f(unlit.modelToCameraMatrixUnif, top())
glUniform4f(unlit.objectColorUnif, 0.25f, 0.25f, 0.25f, 1.0f)
cube.render(gl, "flat")
glDepthMask(true)
glEnable(GL_DEPTH_TEST)
glUniform4f(unlit.objectColorUnif, 1.0f)
cube.render(gl, "flat")
}
}
fun calcLightPosition(): Vec4 {
val scale = glm.PIf * 2.0f
val timeThroughLoop = lightTimer.getAlpha()
val ret = Vec4(0.0f, lightHeight, 0.0f, 1.0f)
ret.x = glm.cos(timeThroughLoop * scale) * lightRadius
ret.z = glm.sin(timeThroughLoop * scale) * lightRadius
return ret
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
val zNear = 1.0f
val zFar = 1_000f
val perspMatrix = MatrixStack()
val proj = perspMatrix.perspective(45.0f, w.f / h, zNear, zFar).top()
glBindBuffer(GL_UNIFORM_BUFFER, bufferName[Buffer.PROJECTION])
glBufferSubData(GL_UNIFORM_BUFFER, proj)
glBindBuffer(GL_UNIFORM_BUFFER)
glViewport(w, h)
}
override fun mousePressed(e: MouseEvent) {
viewPole.mousePressed(e)
}
override fun mouseDragged(e: MouseEvent) {
viewPole.mouseDragged(e)
}
override fun mouseReleased(e: MouseEvent) {
viewPole.mouseReleased(e)
}
override fun mouseWheelMoved(e: MouseEvent) {
viewPole.mouseWheel(e)
}
override fun keyPressed(e: KeyEvent) {
when (e.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_P -> lightTimer.togglePause()
KeyEvent.VK_MINUS -> lightTimer.rewind(0.5f)
KeyEvent.VK_PLUS -> lightTimer.fastForward(0.5f)
KeyEvent.VK_T -> drawCameraPos = !drawCameraPos
KeyEvent.VK_G -> drawLights = !drawLights
KeyEvent.VK_SPACE -> useTexture = !useTexture
}
if (e.keyCode in KeyEvent.VK_1 .. KeyEvent.VK_9) {
val number = e.keyCode - KeyEvent.VK_1
if (number < NUM_GAUSSIAN_TEXTURES) {
println("Angle Resolution: " + calcCosAngleResolution(number))
currTexture = number
}
}
viewPole.keyPressed(e)
}
override fun end(gl: GL3) = with(gl) {
glDeletePrograms(litShaderProg.theProgram, litTextureProg.theProgram, unlit.theProgram)
glDeleteBuffers(bufferName)
glDeleteSampler(gaussSampler)
glDeleteTextures(gaussTextures)
objectMesh.dispose(gl)
cube.dispose(gl)
destroyBuffers(bufferName, gaussSampler, gaussTextures, lightBuffer)
}
object MaterialBlock {
lateinit var diffuseColor: Vec4
lateinit var specularColor: Vec4
var specularShininess = 0f
var padding = FloatArray(3)
fun to(buffer: ByteBuffer, offset: Int = 0): ByteBuffer {
diffuseColor.to(buffer, offset)
specularColor.to(buffer, offset + Vec4.SIZE)
return buffer.putFloat(offset + 2 * Vec4.SIZE, specularShininess)
}
val SIZE = 3 * Vec4.SIZE
}
class PerLight {
var cameraSpaceLightPos = Vec4()
var lightIntensity = Vec4()
fun to(buffer: ByteBuffer, offset: Int): ByteBuffer {
cameraSpaceLightPos.to(buffer, offset)
return lightIntensity.to(buffer, offset + Vec4.SIZE)
}
companion object {
val SIZE = Vec4.SIZE * 2
}
}
object LightBlock {
lateinit var ambientIntensity: Vec4
var lightAttenuation = 0f
var padding = FloatArray(3)
var lights = arrayOf(PerLight(), PerLight())
infix fun to(buffer: ByteBuffer) = to(buffer, 0)
fun to(buffer: ByteBuffer, offset: Int): ByteBuffer {
ambientIntensity.to(buffer, offset)
buffer.putFloat(offset + Vec4.SIZE, lightAttenuation)
repeat(NUMBER_OF_LIGHTS) { lights[it].to(buffer, offset + 2 * Vec4.SIZE + it * PerLight.SIZE) }
return buffer
}
val SIZE = Vec4.SIZE * 2 + NUMBER_OF_LIGHTS * PerLight.SIZE
}
class ProgramData(gl: GL3, vertex: String, fragment: String) {
var theProgram = programOf(gl, javaClass, "tut14", vertex, fragment)
var modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
var normalModelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "normalModelToCameraMatrix")
init {
with(gl) {
glUniformBlockBinding(
theProgram,
glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
glUniformBlockBinding(
theProgram,
glGetUniformBlockIndex(theProgram, "Material"),
Semantic.Uniform.MATERIAL)
glUniformBlockBinding(
theProgram,
glGetUniformBlockIndex(theProgram, "Light"),
Semantic.Uniform.LIGHT)
glUseProgram(theProgram)
glUniform1i(
glGetUniformLocation(theProgram, "gaussianTexture"),
Semantic.Sampler.GAUSSIAN_TEXTURE)
glUseProgram(theProgram)
}
}
}
inner class UnlitProgData(gl: GL3, shader: String) {
var theProgram = programOf(gl, javaClass, "tut14", shader + ".vert", shader + ".frag")
var objectColorUnif = gl.glGetUniformLocation(theProgram, "objectColor")
var modelToCameraMatrixUnif = gl.glGetUniformLocation(theProgram, "modelToCameraMatrix")
init {
gl.glUniformBlockBinding(
theProgram,
gl.glGetUniformBlockIndex(theProgram, "Projection"),
Semantic.Uniform.PROJECTION)
}
}
} | mit | 0d9f2aa9fde3f9383d46c3a32681ccdf | 31.010417 | 129 | 0.618979 | 4.195522 | false | false | false | false |
YiiGuxing/TranslationPlugin | src/main/kotlin/cn/yiiguxing/plugin/translate/ui/form/SettingsForm.kt | 1 | 13077 | package cn.yiiguxing.plugin.translate.ui.form
import cn.yiiguxing.plugin.translate.TTSSource
import cn.yiiguxing.plugin.translate.TargetLanguageSelection
import cn.yiiguxing.plugin.translate.message
import cn.yiiguxing.plugin.translate.trans.Lang
import cn.yiiguxing.plugin.translate.ui.ActionLink
import cn.yiiguxing.plugin.translate.ui.UI.emptyBorder
import cn.yiiguxing.plugin.translate.ui.UI.fill
import cn.yiiguxing.plugin.translate.ui.UI.fillX
import cn.yiiguxing.plugin.translate.ui.UI.fillY
import cn.yiiguxing.plugin.translate.ui.UI.migLayout
import cn.yiiguxing.plugin.translate.ui.UI.migLayoutVertical
import cn.yiiguxing.plugin.translate.ui.UI.plus
import cn.yiiguxing.plugin.translate.ui.UI.wrap
import cn.yiiguxing.plugin.translate.ui.selected
import cn.yiiguxing.plugin.translate.ui.settings.TranslationEngine
import cn.yiiguxing.plugin.translate.util.IdeVersion
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.*
import com.intellij.ui.components.JBCheckBox
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.util.ui.JBUI
import icons.TranslationIcons
import net.miginfocom.layout.CC
import java.awt.Dimension
import javax.swing.*
import javax.swing.text.AttributeSet
import javax.swing.text.JTextComponent
import javax.swing.text.PlainDocument
abstract class SettingsForm {
protected val wholePanel: JPanel = JPanel()
protected val configureTranslationEngineLink: ActionLink = ActionLink(message("settings.configure.link")) {}
protected val translationEngineComboBox: ComboBox<TranslationEngine> = comboBox<TranslationEngine>().apply {
renderer = SimpleListCellRenderer.create { label, value, _ ->
label.text = value.translatorName
label.icon = value.icon
}
addItemListener {
fixEngineConfigurationComponent()
}
}
protected val primaryLanguageComboBox: ComboBox<Lang> = comboBox<Lang>().apply {
renderer = SimpleListCellRenderer.create { label, lang, _ ->
label.text = lang.langName
}
}
protected val targetLangSelectionComboBox: ComboBox<TargetLanguageSelection> =
comboBox<TargetLanguageSelection>().apply {
renderer = SimpleListCellRenderer.create("") { it.displayName }
}
protected val takeWordCheckBox: JBCheckBox =
JBCheckBox(message("settings.options.take.word.when.translation.dialog.opens"))
protected val takeNearestWordCheckBox: JCheckBox = JCheckBox(message("settings.options.take.single.word"))
protected val keepFormatCheckBox: JBCheckBox = JBCheckBox(message("settings.options.keepFormatting"))
protected lateinit var ignoreRegExp: EditorTextField
protected val checkIgnoreRegExpButton: JButton = JButton(message("settings.button.check"))
protected val ignoreRegExpMsg: JLabel = JLabel()
protected val separatorsTextField: JTextField = JTextField().apply {
document = object : PlainDocument() {
override fun insertString(offset: Int, str: String?, attr: AttributeSet?) {
val text = getText(0, length)
val stringToInsert = str
?.filter { it in ' '..'~' && !Character.isLetterOrDigit(it) && !text.contains(it) }
?.toSet()
?.take(10 - length)
?.joinToString("")
?: return
if (stringToInsert.isNotEmpty()) {
super.insertString(offset, stringToInsert, attr)
}
}
}
}
protected var primaryFontComboBox: FontComboBox = createFontComboBox(filterNonLatin = false)
protected var phoneticFontComboBox: FontComboBox = createFontComboBox(filterNonLatin = true)
protected val primaryFontPreview: JTextComponent = JEditorPane(
"text/plain",
message("settings.font.default.preview.text")
)
protected val phoneticFontPreview: JLabel = JLabel(PHONETIC_CHARACTERS)
protected val restoreDefaultButton = JButton(message("settings.button.restore.default.fonts"))
protected val foldOriginalCheckBox: JBCheckBox = JBCheckBox(message("settings.options.foldOriginal"))
protected val ttsSourceComboBox: ComboBox<TTSSource> =
ComboBox(CollectionComboBoxModel(TTSSource.values().asList())).apply {
renderer = SimpleListCellRenderer.create("") { it.displayName }
preferredSize = Dimension(preferredSize.width, JBUI.scale(26))
}
protected val autoPlayTTSCheckBox: JBCheckBox = JBCheckBox(message("settings.options.autoPlayTTS")).apply {
addItemListener {
ttsSourceComboBox.isEnabled = isSelected
}
}
protected val showWordFormsCheckBox: JBCheckBox = JBCheckBox(message("settings.options.showWordForms"))
protected val autoReplaceCheckBox: JBCheckBox = JBCheckBox(message("settings.options.autoReplace"))
protected val showReplacementActionCheckBox: JBCheckBox =
JBCheckBox(message("settings.options.show.replacement.action"))
protected val selectTargetLanguageCheckBox: JBCheckBox = JBCheckBox(message("settings.options.selectLanguage"))
protected val showWordsOnStartupCheckBox: JBCheckBox = JBCheckBox(message("settings.options.showWordsOnStartup"))
protected val showExplanationCheckBox: JBCheckBox = JBCheckBox(message("settings.options.showExplanation"))
protected val maxHistoriesSizeComboBox: ComboBox<Int> = comboBox(50, 30, 20, 10, 0).apply {
isEditable = true
}
protected val clearHistoriesButton: JButton = JButton(message("settings.clear.history.button"))
protected val cacheSizeLabel: JLabel = JLabel("0KB")
protected val clearCacheButton: JButton = JButton(message("settings.cache.button.clear"))
protected val translateDocumentationCheckBox: JBCheckBox =
JBCheckBox(message("settings.options.translate.documentation"))
protected val showActionsInContextMenuOnlyWithSelectionCheckbox: JBCheckBox =
JBCheckBox(message("settings.options.show.actions.only.with.selection"))
protected val supportLinkLabel: LinkLabel<*> =
LinkLabel<Any>(message("support.or.donate"), TranslationIcons.Support).apply {
border = JBUI.Borders.empty(20, 0, 0, 0)
}
protected fun doLayout() {
val generalPanel = titledPanel(message("settings.panel.title.general")) {
val comboboxGroup = "combobox"
add(JLabel(message("settings.label.translation.engine")))
add(translationEngineComboBox, CC().sizeGroupX(comboboxGroup))
val configurePanel = Box.createHorizontalBox().apply {
add(configureTranslationEngineLink)
fixEngineConfigurationComponent()
}
add(configurePanel, wrap().gapBefore("indent").span(2))
add(JLabel(message("settings.label.primaryLanguage")))
add(primaryLanguageComboBox, wrap().sizeGroupX(comboboxGroup))
add(JLabel(message("settings.label.targetLanguage")))
add(targetLangSelectionComboBox, wrap().sizeGroupX(comboboxGroup))
}
val textSelectionPanel = titledPanel(message("settings.panel.title.text.selection")) {
add(keepFormatCheckBox, wrap().span(4))
add(takeNearestWordCheckBox, wrap().span(4))
add(takeWordCheckBox, wrap().span(4))
add(JLabel(message("settings.label.ignore")))
val ignoreRegexComponent: JComponent =
if (ApplicationManager.getApplication() != null) ignoreRegExp
else JTextField()
add(ignoreRegexComponent)
add(checkIgnoreRegExpButton)
add(ignoreRegExpMsg, wrap())
setMinWidth(ignoreRegexComponent)
}
val fontsPanel = titledPanel(message("settings.panel.title.fonts")) {
add(JLabel(message("settings.font.label.primary")))
add(JLabel(message("settings.font.label.phonetic")), wrap())
add(primaryFontComboBox)
add(phoneticFontComboBox, wrap())
val primaryPreviewPanel = JPanel(migLayout()).apply {
add(primaryFontPreview, fillX())
}
val phoneticPreviewPanel = JPanel(migLayout()).apply {
add(phoneticFontPreview, fillX().dockNorth())
}
add(primaryPreviewPanel, fillX())
add(phoneticPreviewPanel, fill().wrap())
add(restoreDefaultButton)
//compensate custom border of ComboBox
primaryFontPreview.border = emptyBorder(3) + JBUI.Borders.customLine(JBColor.border())
primaryPreviewPanel.border = emptyBorder(3)
phoneticFontPreview.border = emptyBorder(6)
}
val translationPopupPanel = titledPanel(message("settings.panel.title.translation.popup")) {
add(foldOriginalCheckBox, wrap().span(2))
add(showWordFormsCheckBox, wrap().span(2))
add(autoPlayTTSCheckBox)
add(ttsSourceComboBox, wrap())
}
val translateAndReplacePanel = titledPanel(message("settings.panel.title.translate.and.replace")) {
add(showReplacementActionCheckBox, wrap().span(2))
add(selectTargetLanguageCheckBox, wrap().span(2))
add(autoReplaceCheckBox, wrap().span(2))
add(JLabel(message("settings.label.separators")).apply {
toolTipText = message("settings.tip.separators")
})
add(separatorsTextField, wrap())
setMinWidth(separatorsTextField)
}
val wordOfTheDayPanel = titledPanel(message("settings.panel.title.word.of.the.day")) {
add(showWordsOnStartupCheckBox, wrap())
add(showExplanationCheckBox, wrap())
}
val cacheAndHistoryPanel = titledPanel(message("settings.panel.title.cacheAndHistory")) {
add(JPanel(migLayout()).apply {
add(JLabel(message("settings.cache.label.diskCache")))
add(cacheSizeLabel)
add(clearCacheButton, wrap())
}, wrap().span(2))
add(JPanel(migLayout()).apply {
add(JLabel(message("settings.history.label.maxLength")))
add(maxHistoriesSizeComboBox)
add(clearHistoriesButton, wrap())
}, CC().span(2))
setMinWidth(maxHistoriesSizeComboBox)
cacheSizeLabel.border = JBUI.Borders.empty(0, 2, 0, 10)
}
val otherPanel = titledPanel(message("settings.panel.title.other")) {
if (isSupportDocumentTranslation()) {
add(translateDocumentationCheckBox, wrap())
}
add(showActionsInContextMenuOnlyWithSelectionCheckbox, wrap())
}
wholePanel.addVertically(
generalPanel,
fontsPanel,
textSelectionPanel,
translationPopupPanel,
translateAndReplacePanel,
wordOfTheDayPanel,
cacheAndHistoryPanel,
otherPanel,
supportLinkLabel
)
}
fun createMainPanel(): JPanel {
doLayout()
return wholePanel
}
private fun fixEngineConfigurationComponent() {
configureTranslationEngineLink.isVisible = translationEngineComboBox.selected != TranslationEngine.GOOGLE
}
open fun isSupportDocumentTranslation(): Boolean {
// Documentation translation is not supported before Rider 2022.1.
return IdeVersion >= IdeVersion.IDE2022_1 || IdeVersion.buildNumber.productCode != "RD"
}
companion object {
private const val PHONETIC_CHARACTERS = "ˈ'ˌːiɜɑɔuɪeæʌɒʊəaɛpbtdkgfvszθðʃʒrzmnŋhljw"
private const val MIN_ELEMENT_WIDTH = 80
private fun setMinWidth(component: JComponent) = component.apply {
minimumSize = Dimension(MIN_ELEMENT_WIDTH, height)
}
private fun createFontComboBox(filterNonLatin: Boolean): FontComboBox =
FontComboBox(false, filterNonLatin, false)
private fun titledPanel(title: String, body: JPanel.() -> Unit): JComponent {
val innerPanel = JPanel(migLayout())
innerPanel.body()
return JPanel(migLayout()).apply {
border = IdeBorderFactory.createTitledBorder(title)
add(innerPanel)
add(JPanel(), fillX())
}
}
private fun JPanel.addVertically(vararg components: JComponent) {
layout = migLayoutVertical()
components.forEach {
add(it, fillX())
}
add(JPanel(), fillY())
}
private fun <T> comboBox(elements: List<T>): ComboBox<T> = ComboBox(CollectionComboBoxModel(elements))
private fun <T> comboBox(vararg elements: T): ComboBox<T> = comboBox(elements.toList())
private inline fun <reified T : Enum<T>> comboBox(): ComboBox<T> = comboBox(enumValues<T>().toList())
}
} | mit | f633d04cf1b51dcc88d758f0d8b8eaf8 | 41.679739 | 117 | 0.669883 | 4.88918 | false | false | false | false |
jitsi/jibri | src/test/kotlin/org/jitsi/jibri/service/AppDataTest.kt | 1 | 3713 | /*
* Copyright @ 2018 Atlassian Pty 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.jitsi.jibri.service
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.kotest.core.spec.IsolationMode
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.maps.shouldContainExactly
import io.kotest.matchers.maps.shouldContainKey
import io.kotest.matchers.shouldNotBe
internal class AppDataTest : ShouldSpec() {
override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf
init {
context("a json-encoded app data structure") {
val appDataJsonStr = """
{
"file_recording_metadata":
{
"upload_credentials":
{
"service_name":"dropbox",
"token":"XXXXXXXXYYYYYYYYYZZZZZZAAAAAAABBBBBBCCCDDD"
}
}
}
""".trimIndent()
should("be parsed correctly") {
val appData = jacksonObjectMapper().readValue<AppData>(appDataJsonStr)
appData.fileRecordingMetadata shouldNotBe null
appData.fileRecordingMetadata?.shouldContainKey("upload_credentials")
appData.fileRecordingMetadata?.get("upload_credentials") shouldNotBe null
@Suppress("UNCHECKED_CAST")
(appData.fileRecordingMetadata?.get("upload_credentials") as Map<Any, Any>)
.shouldContainExactly(
mapOf<Any, Any>(
"service_name" to "dropbox",
"token" to "XXXXXXXXYYYYYYYYYZZZZZZAAAAAAABBBBBBCCCDDD"
)
)
}
}
context("a json-encoded app data structure with an extra top-level field") {
val appDataJsonStr = """
{
"file_recording_metadata":
{
"upload_credentials":
{
"service_name":"dropbox",
"token":"XXXXXXXXYYYYYYYYYZZZZZZAAAAAAABBBBBBCCCDDD"
}
},
"other_new_field": "hello"
}
""".trimIndent()
should("be parsed correctly and ignore unknown fields") {
val appData = jacksonObjectMapper().readValue<AppData>(appDataJsonStr)
appData.fileRecordingMetadata shouldNotBe null
appData.fileRecordingMetadata?.shouldContainKey("upload_credentials")
appData.fileRecordingMetadata?.get("upload_credentials") shouldNotBe null
@Suppress("UNCHECKED_CAST")
(appData.fileRecordingMetadata?.get("upload_credentials") as Map<Any, Any>)
.shouldContainExactly(
mapOf<Any, Any>(
"service_name" to "dropbox",
"token" to "XXXXXXXXYYYYYYYYYZZZZZZAAAAAAABBBBBBCCCDDD"
)
)
}
}
}
}
| apache-2.0 | 1309e647a7cc27f80dcc8e624a9ec48a | 40.255556 | 91 | 0.571236 | 5.428363 | false | true | false | false |
MichaelRocks/lightsaber | processor/src/main/java/io/michaelrocks/lightsaber/processor/model/InjectionTarget.kt | 1 | 2166 | /*
* Copyright 2019 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.model
import io.michaelrocks.grip.mirrors.Type
import io.michaelrocks.grip.mirrors.isConstructor
import io.michaelrocks.lightsaber.processor.commons.toFieldDescriptor
import io.michaelrocks.lightsaber.processor.commons.toMethodDescriptor
import io.michaelrocks.lightsaber.processor.descriptors.FieldDescriptor
import io.michaelrocks.lightsaber.processor.descriptors.MethodDescriptor
import java.util.HashSet
data class InjectionTarget(
val type: Type.Object,
val injectionPoints: Collection<InjectionPoint>
) {
private val fields: Set<FieldDescriptor>
private val methods: Set<MethodDescriptor>
private val constructors: Set<MethodDescriptor>
init {
val constructors = HashSet<MethodDescriptor>()
val fields = HashSet<FieldDescriptor>()
val methods = HashSet<MethodDescriptor>()
injectionPoints.forEach { injectionPoint ->
when (injectionPoint) {
is InjectionPoint.Field -> fields += injectionPoint.field.toFieldDescriptor()
is InjectionPoint.Method ->
if (injectionPoint.method.isConstructor) constructors += injectionPoint.method.toMethodDescriptor()
else methods += injectionPoint.method.toMethodDescriptor()
}
}
this.constructors = constructors
this.fields = fields
this.methods = methods
}
fun isInjectableField(field: FieldDescriptor) = field in fields
fun isInjectableMethod(method: MethodDescriptor) = method in methods
fun isInjectableConstructor(method: MethodDescriptor) = method in constructors
}
| apache-2.0 | 7001e563261c5ae34af4b334615366c2 | 36.344828 | 109 | 0.768698 | 4.802661 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/ui/main/battery/doze/DozeSettingsFragment.kt | 1 | 10820 | package com.androidvip.hebf.ui.main.battery.doze
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CompoundButton
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.lifecycle.lifecycleScope
import com.androidvip.hebf.R
import com.androidvip.hebf.goAway
import com.androidvip.hebf.runSafeOnUiThread
import com.androidvip.hebf.services.PowerConnectedWork
import com.androidvip.hebf.show
import com.androidvip.hebf.ui.base.BaseFragment
import com.androidvip.hebf.utils.*
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.fragment_doze_settings.*
import kotlinx.coroutines.launch
import java.util.*
@RequiresApi(Build.VERSION_CODES.M)
class DozeSettingsFragment : BaseFragment(), CompoundButton.OnCheckedChangeListener {
private lateinit var fab: FloatingActionButton
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_doze_settings, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
if (isActivityAlive) {
fab = requireActivity().findViewById(R.id.doze_fab)
}
setUpInfoListeners(view)
val savedIdlingMode = prefs.getString(K.PREF.DOZE_IDLING_MODE, Doze.IDLING_MODE_DEEP)
if (savedIdlingMode == Doze.IDLING_MODE_LIGHT) {
setIdlingMode(savedIdlingMode, getString(R.string.doze_record_type_light))
} else {
setIdlingMode(savedIdlingMode, getString(R.string.doze_record_type_deep))
}
setWaitingInterval(prefs.getInt(K.PREF.DOZE_INTERVAL_MINUTES, 20).toString())
lifecycleScope.launch(workerContext) {
val deviceIdleEnabled = Doze.deviceIdleEnabled()
val isIdle = Doze.isInIdleState
val isRooted = isRooted()
runSafeOnUiThread {
dozeProgressSettings.goAway()
dozeScrollSettings.show()
if (!isRooted) {
dozeMasterSwitch.isChecked = true
dozeMasterSwitch.isEnabled = false
dozeChargerSwitch.isEnabled = false
aggressiveDozeSwitch.isEnabled = false
} else {
dozeMasterSwitch.isChecked = deviceIdleEnabled
if (isIdle) {
dozeUnforceButton.isEnabled = true
}
dozeMasterSwitch.setOnCheckedChangeListener(null)
aggressiveDozeSwitch.setOnCheckedChangeListener(null)
dozeChargerSwitch.setOnCheckedChangeListener(null)
dozeMasterSwitch.setOnCheckedChangeListener(this@DozeSettingsFragment)
aggressiveDozeSwitch.isChecked = dozeMasterSwitch.isChecked
&& prefs.getBoolean(K.PREF.DOZE_AGGRESSIVE, false)
dozeChargerSwitch.isChecked = prefs.getBoolean(K.PREF.DOZE_CHARGER, false)
dozeChargerSwitch.isEnabled = isRooted
dozeChargerSwitch.setOnCheckedChangeListener(this@DozeSettingsFragment)
aggressiveDozeSwitch.setOnCheckedChangeListener(this@DozeSettingsFragment)
if (!aggressiveDozeSwitch.isChecked) {
dozeChargerSwitch.isChecked = false
dozeChargerSwitch.isEnabled = false
}
dozeUnforceButton.setOnClickListener { v ->
Doze.unforceIdle()
Logger.logInfo("Unforcing doze", findContext())
Snackbar.make(v, R.string.done, Snackbar.LENGTH_SHORT).show()
}
}
}
}
val idlingModeLayout = view.findViewById<LinearLayout>(R.id.doze_layout_idling_mode)
val waitingIntervalLayout = view.findViewById<LinearLayout>(R.id.doze_layout_waiting_interval)
waitingIntervalLayout.setOnClickListener {
val checkedItem: Int = when (prefs.getInt(K.PREF.DOZE_INTERVAL_MINUTES, 20)) {
10 -> 0
15 -> 1
20 -> 2
30 -> 3
45 -> 4
else -> 2
}
val items = resources.getStringArray(R.array.doze_waiting_intervals)
MaterialAlertDialogBuilder(findContext())
.setTitle(R.string.doze_waiting_interval)
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.setSingleChoiceItems(items, checkedItem) { dialog, which ->
dialog.dismiss()
when (which) {
0 -> setWaitingInterval("10")
1 -> setWaitingInterval("15")
2 -> setWaitingInterval("20")
3 -> setWaitingInterval("30")
4 -> setWaitingInterval("45")
else -> setWaitingInterval("20")
}
}
.show()
}
idlingModeLayout.setOnClickListener {
val checkedItem: Int = when (prefs.getString(K.PREF.DOZE_IDLING_MODE, Doze.IDLING_MODE_DEEP)) {
Doze.IDLING_MODE_LIGHT -> 0
Doze.IDLING_MODE_DEEP -> 1
else -> 1
}
MaterialAlertDialogBuilder(findContext())
.setTitle(R.string.doze_idling_mode)
.setNegativeButton(android.R.string.cancel) { _, _ -> }
.setSingleChoiceItems(resources.getStringArray(R.array.doze_idling_modes), checkedItem) { dialog, which ->
dialog.dismiss()
when (which) {
0 -> setIdlingMode(Doze.IDLING_MODE_LIGHT, getString(R.string.doze_record_type_light))
1 -> setIdlingMode(Doze.IDLING_MODE_DEEP, getString(R.string.doze_record_type_deep))
else -> setIdlingMode(Doze.IDLING_MODE_DEEP, getString(R.string.doze_record_type_deep))
}
}
.show()
}
}
override fun onResume() {
super.onResume()
runCatching {
fab.hide()
fab.setOnClickListener(null)
}
}
override fun onCheckedChanged(compoundButton: CompoundButton, isChecked: Boolean) {
when (compoundButton.id) {
R.id.dozeMasterSwitch -> {
lifecycleScope.launch(workerContext) {
Doze.toggleDeviceIdle(isChecked)
runSafeOnUiThread {
if (isChecked) {
enableEverything()
Logger.logInfo("Enabled doze mode", findContext())
} else {
disableEverything()
Logger.logInfo("Disabled doze mode", findContext())
}
}
}
}
R.id.aggressiveDozeSwitch -> if (isChecked) {
prefs.putBoolean(K.PREF.DOZE_AGGRESSIVE, true)
Snackbar.make(aggressiveDozeSwitch, R.string.aggressive_doze_on, Snackbar.LENGTH_SHORT).show()
Doze.toggleDozeService(true, context)
dozeChargerSwitch.isEnabled = true
Logger.logInfo("Enabled aggressive doze", findContext())
} else {
prefs.putBoolean(K.PREF.DOZE_AGGRESSIVE, false)
Snackbar.make(aggressiveDozeSwitch, R.string.aggressive_doze_off, Snackbar.LENGTH_SHORT).show()
Doze.toggleDozeService(false, context)
dozeChargerSwitch.isEnabled = false
Logger.logInfo("Disabled aggressive doze", findContext())
}
R.id.dozeChargerSwitch -> {
if (isChecked) {
PowerConnectedWork.scheduleJobPeriodic(applicationContext)
prefs.putBoolean(K.PREF.DOZE_CHARGER, true)
} else {
// Don't cancel the service (VIP may depend on it)
prefs.putBoolean(K.PREF.DOZE_CHARGER, false)
}
}
}
}
private fun setIdlingMode(idlingMode: String, newText: String) {
prefs.putString(K.PREF.DOZE_IDLING_MODE, idlingMode)
this.dozeIdlingModeText.text = newText
setWaitingInterval(prefs.getInt(K.PREF.DOZE_INTERVAL_MINUTES, 20).toString())
}
private fun setWaitingInterval(strMinutes: String) {
val minutes = runCatching {
if (strMinutes.toInt() < 10) 20 else strMinutes.toInt()
}.getOrDefault(20)
prefs.putInt(K.PREF.DOZE_INTERVAL_MINUTES, minutes)
dozeWaitingIntervalText.text = String.format(getString(R.string.doze_waiting_interval_sum), strMinutes, dozeIdlingModeText.text)
}
private fun disableEverything() {
aggressiveDozeSwitch.isChecked = false
aggressiveDozeSwitch.isEnabled = false
dozeChargerSwitch.isChecked = false
dozeChargerSwitch.isEnabled = false
}
private fun enableEverything() {
aggressiveDozeSwitch.isEnabled = true
dozeChargerSwitch.isEnabled = true
}
private fun infoDialogListener(message: String): View.OnClickListener {
return View.OnClickListener {
val achievementsSet = userPrefs.getStringSet(K.PREF.ACHIEVEMENT_SET, HashSet())
if (!achievementsSet.contains("help")) {
Utils.addAchievement(requireContext().applicationContext, "help")
Toast.makeText(findContext(), getString(R.string.achievement_unlocked, getString(R.string.achievement_help)), Toast.LENGTH_LONG).show()
}
if (isAdded) {
ModalBottomSheet.newInstance("Info", message).show(parentFragmentManager, "sheet")
}
}
}
private fun setUpInfoListeners(view: View) {
val instantInfo = view.findViewById<ImageView>(R.id.doze_info_instant_doze)
val chargerInfo = view.findViewById<ImageView>(R.id.doze_info_turn_off_charger)
instantInfo.setOnClickListener(infoDialogListener(getString(R.string.aggressive_doze_sum)))
chargerInfo.setOnClickListener(infoDialogListener(getString(R.string.vip_disable_when_connecting_sum)))
}
} | apache-2.0 | fe2f10c3ec6bdc15839f7e611bf7782f | 41.269531 | 151 | 0.603604 | 5.260088 | false | false | false | false |
vanniktech/Emoji | emoji-material/src/androidMain/kotlin/com/vanniktech/emoji/material/EmojiMaterialCheckBox.kt | 1 | 2638 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić 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
*
* 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.vanniktech.emoji.material
import android.content.Context
import android.text.SpannableStringBuilder
import android.util.AttributeSet
import androidx.annotation.AttrRes
import androidx.annotation.CallSuper
import androidx.annotation.DimenRes
import androidx.annotation.Px
import com.google.android.material.checkbox.MaterialCheckBox
import com.vanniktech.emoji.EmojiDisplayable
import com.vanniktech.emoji.EmojiManager
import com.vanniktech.emoji.init
import com.vanniktech.emoji.replaceWithImages
import kotlin.jvm.JvmOverloads
open class EmojiMaterialCheckBox @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
@AttrRes defStyleAttr: Int = com.google.android.material.R.attr.checkboxStyle,
) : MaterialCheckBox(context, attrs, defStyleAttr), EmojiDisplayable {
@Px private var emojiSize: Float
init {
emojiSize = init(attrs, R.styleable.EmojiMaterialCheckBox, R.styleable.EmojiMaterialCheckBox_emojiSize)
}
@CallSuper override fun setText(rawText: CharSequence?, type: BufferType) {
if (isInEditMode) {
super.setText(rawText, type)
return
}
val spannableStringBuilder = SpannableStringBuilder(rawText ?: "")
val fontMetrics = paint.fontMetrics
val defaultEmojiSize = fontMetrics.descent - fontMetrics.ascent
EmojiManager.replaceWithImages(context, spannableStringBuilder, if (emojiSize != 0f) emojiSize else defaultEmojiSize)
super.setText(spannableStringBuilder, type)
}
override fun getEmojiSize() = emojiSize
override fun setEmojiSize(@Px pixels: Int) = setEmojiSize(pixels, true)
override fun setEmojiSize(@Px pixels: Int, shouldInvalidate: Boolean) {
emojiSize = pixels.toFloat()
if (shouldInvalidate) {
text = text
}
}
override fun setEmojiSizeRes(@DimenRes res: Int) = setEmojiSizeRes(res, true)
override fun setEmojiSizeRes(@DimenRes res: Int, shouldInvalidate: Boolean) =
setEmojiSize(resources.getDimensionPixelSize(res), shouldInvalidate)
}
| apache-2.0 | 92dc9855eba8b55fd1ce7708f7f55b67 | 36.126761 | 121 | 0.772382 | 4.568458 | false | false | false | false |
google/xplat | j2kt/jre/java/native/java/util/Random.kt | 1 | 3107 | /*
* Copyright 2009 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.
*/
/*
* 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.
*
* INCLUDES MODIFICATIONS BY RICHARD ZSCHECH AS WELL AS GOOGLE.
*/
package java.util
import kotlin.math.ln
import kotlin.math.sqrt
import kotlin.synchronized
open class Random internal constructor(var ktRandom: kotlin.random.Random) {
var haveNextNextGaussian = false
var nextNextGaussian = 0.0
constructor() : this(kotlin.random.Random.Default)
constructor(seed: Long) : this(kotlin.random.Random(seed))
fun nextBoolean() = ktRandom.nextBoolean()
fun nextBytes(buf: ByteArray) = ktRandom.nextBytes(buf)
fun nextDouble() = ktRandom.nextDouble()
fun nextFloat() = ktRandom.nextFloat()
fun nextGaussian(): Double {
return synchronized(this) {
if (haveNextNextGaussian) {
// if X1 has been returned, return the second Gaussian
haveNextNextGaussian = false
nextNextGaussian
} else {
var s: Double
var v1: Double
var v2: Double
do {
// Generates two independent random variables U1, U2
v1 = 2 * nextDouble() - 1
v2 = 2 * nextDouble() - 1
s = v1 * v1 + v2 * v2
} while (s >= 1)
// See errata for TAOCP vol. 2, 3rd ed. for proper handling of s == 0 case
// (page 5 of http://www-cs-faculty.stanford.edu/~uno/err2.ps.gz)
val norm = if (s == 0.0) 0.0 else sqrt(-2.0 * ln(s) / s)
nextNextGaussian = v2 * norm
haveNextNextGaussian = true
v1 * norm
}
}
}
fun nextInt() = ktRandom.nextInt()
fun nextInt(n: Int) = ktRandom.nextInt(n)
fun nextLong() = ktRandom.nextLong()
fun setSeed(seed: Long) {
synchronized(this) {
haveNextNextGaussian = false
ktRandom = kotlin.random.Random(seed)
}
}
}
| apache-2.0 | 29198ed3772cebff96b8ec9767d43b55 | 31.364583 | 82 | 0.684261 | 4.019405 | false | false | false | false |
ejeinc/Meganekko | library/src/main/java/org/meganekkovr/JoyButton.kt | 1 | 2399 | /*
* Copyright 2015 eje inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.meganekkovr
/**
* Copied from VrAppFramework/Include/Input.h
*/
object JoyButton {
const val BUTTON_A = 1 shl 0
const val BUTTON_B = 1 shl 1
const val BUTTON_X = 1 shl 2
const val BUTTON_Y = 1 shl 3
const val BUTTON_START = 1 shl 4
const val BUTTON_BACK = 1 shl 5
const val BUTTON_SELECT = 1 shl 6
const val BUTTON_MENU = 1 shl 7
const val BUTTON_RIGHT_TRIGGER = 1 shl 8
const val BUTTON_LEFT_TRIGGER = 1 shl 9
const val BUTTON_DPAD_UP = 1 shl 10
const val BUTTON_DPAD_DOWN = 1 shl 11
const val BUTTON_DPAD_LEFT = 1 shl 12
const val BUTTON_DPAD_RIGHT = 1 shl 13
const val BUTTON_LSTICK_UP = 1 shl 14
const val BUTTON_LSTICK_DOWN = 1 shl 15
const val BUTTON_LSTICK_LEFT = 1 shl 16
const val BUTTON_LSTICK_RIGHT = 1 shl 17
const val BUTTON_RSTICK_UP = 1 shl 18
const val BUTTON_RSTICK_DOWN = 1 shl 19
const val BUTTON_RSTICK_LEFT = 1 shl 20
const val BUTTON_RSTICK_RIGHT = 1 shl 21
const val BUTTON_TOUCH = 1 shl 22
const val BUTTON_SWIPE_UP = 1 shl 23
const val BUTTON_SWIPE_DOWN = 1 shl 24
const val BUTTON_SWIPE_FORWARD = 1 shl 25
const val BUTTON_SWIPE_BACK = 1 shl 26
const val BUTTON_TOUCH_WAS_SWIPE = 1 shl 27
const val BUTTON_TOUCH_SINGLE = 1 shl 28
const val BUTTON_TOUCH_DOUBLE = 1 shl 29
const val BUTTON_TOUCH_LONGPRESS = 1 shl 30
/**
* @param buttonState Returned value from `FrameInput#getButtonPressed()`,
* `FrameInput#getButtonReleased()` or
* `FrameInput#getButtonState()`.
* @param code JoyButton.BUTTON_* constant value.
* @return true if `buttonState` contains `code` in bit flags.
*/
@JvmStatic
fun contains(buttonState: Int, code: Int): Boolean {
return buttonState and code > 0
}
}
| apache-2.0 | 8c40e60a4ec35e83cc5e021288a13b54 | 35.348485 | 78 | 0.679867 | 3.74259 | false | false | false | false |
robinverduijn/gradle | buildSrc/subprojects/kotlin-dsl/src/main/kotlin/codegen/GenerateKotlinDependencyExtensions.kt | 1 | 4841 | /*
* Copyright 2016 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 codegen
import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import java.io.File
@Suppress("unused")
abstract class GenerateKotlinDependencyExtensions : CodeGenerationTask() {
@get:Input
abstract val embeddedKotlinVersion: Property<String>
@get:Input
abstract val kotlinDslPluginsVersion: Property<String>
override fun File.writeFiles() {
val kotlinDslPluginsVersion = kotlinDslPluginsVersion.get()
val embeddedKotlinVersion = embeddedKotlinVersion.get()
// IMPORTANT: kotlinDslPluginsVersion should NOT be made a `const` to avoid inlining
writeFile(
"org/gradle/kotlin/dsl/support/KotlinDslPlugins.kt",
"""$licenseHeader
package org.gradle.kotlin.dsl.support
/**
* Expected version of the `kotlin-dsl` plugin for the running Gradle version.
*/
@Suppress("unused")
val expectedKotlinDslPluginsVersion: String
get() = "$kotlinDslPluginsVersion"
""")
writeFile(
"org/gradle/kotlin/dsl/KotlinDependencyExtensions.kt",
"""$licenseHeader
package org.gradle.kotlin.dsl
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.plugin.use.PluginDependenciesSpec
import org.gradle.plugin.use.PluginDependencySpec
/**
* The version of the Kotlin compiler embedded in gradle-kotlin-dsl (currently _${embeddedKotlinVersion}_).
*/
val embeddedKotlinVersion = "$embeddedKotlinVersion"
/**
* Builds the dependency notation for the named Kotlin [module] at the embedded version (currently _${embeddedKotlinVersion}_).
*
* @param module simple name of the Kotlin module, for example "reflect".
*/
fun DependencyHandler.embeddedKotlin(module: String): Any =
kotlin(module, embeddedKotlinVersion)
/**
* Builds the dependency notation for the named Kotlin [module] at the given [version].
*
* @param module simple name of the Kotlin module, for example "reflect".
* @param version optional desired version, unspecified if null.
*/
fun DependencyHandler.kotlin(module: String, version: String? = null): Any =
"org.jetbrains.kotlin:kotlin-${'$'}module${'$'}{version?.let { ":${'$'}version" } ?: ""}"
/**
* Applies the given Kotlin plugin [module].
*
* For example: `plugins { kotlin("jvm") version "$embeddedKotlinVersion" }`
*
* Visit the [plugin portal](https://plugins.gradle.org/search?term=org.jetbrains.kotlin) to see the list of available plugins.
*
* @param module simple name of the Kotlin Gradle plugin module, for example "jvm", "android", "kapt", "plugin.allopen" etc...
*/
fun PluginDependenciesSpec.kotlin(module: String): PluginDependencySpec =
id("org.jetbrains.kotlin.${'$'}module")
/**
* The `embedded-kotlin` plugin.
*
* Equivalent to `id("org.gradle.kotlin.embedded-kotlin") version "$kotlinDslPluginsVersion"`
*
* @see org.gradle.kotlin.dsl.plugins.embedded.EmbeddedKotlinPlugin
*/
val PluginDependenciesSpec.`embedded-kotlin`: PluginDependencySpec
get() = id("org.gradle.kotlin.embedded-kotlin") version "$kotlinDslPluginsVersion"
/**
* The `kotlin-dsl` plugin.
*
* Equivalent to `id("org.gradle.kotlin.kotlin-dsl") version "$kotlinDslPluginsVersion"`
*
* @see org.gradle.kotlin.dsl.plugins.dsl.KotlinDslPlugin
*/
val PluginDependenciesSpec.`kotlin-dsl`: PluginDependencySpec
get() = id("org.gradle.kotlin.kotlin-dsl") version "$kotlinDslPluginsVersion"
/**
* The `kotlin-dsl.base` plugin.
*
* Equivalent to `id("org.gradle.kotlin.kotlin-dsl.base") version "$kotlinDslPluginsVersion"`
*
* @see org.gradle.kotlin.dsl.plugins.base.KotlinDslBasePlugin
*/
val PluginDependenciesSpec.`kotlin-dsl-base`: PluginDependencySpec
get() = id("org.gradle.kotlin.kotlin-dsl.base") version "$kotlinDslPluginsVersion"
/**
* The `kotlin-dsl.precompiled-script-plugins` plugin.
*
* Equivalent to `id("org.gradle.kotlin.kotlin-dsl.precompiled-script-plugins") version "$kotlinDslPluginsVersion"`
*
* @see org.gradle.kotlin.dsl.plugins.precompiled.PrecompiledScriptPlugins
*/
val PluginDependenciesSpec.`kotlin-dsl-precompiled-script-plugins`: PluginDependencySpec
get() = id("org.gradle.kotlin.kotlin-dsl.precompiled-script-plugins") version "$kotlinDslPluginsVersion"
""")
}
}
| apache-2.0 | 31502dd4e772f8b0ddb86bc154870b5a | 31.489933 | 127 | 0.73332 | 4.250219 | false | false | false | false |
spark/photon-tinker-android | meshui/src/main/java/io/particle/mesh/ui/setup/barcodescanning/LivePreviewActivity.kt | 1 | 6045 | // 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
//
// 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.particle.mesh.ui.setup.barcodescanning
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityCompat.OnRequestPermissionsResultCallback
import androidx.core.content.ContextCompat
import androidx.appcompat.app.AppCompatActivity
import android.util.Log
import com.google.android.gms.common.annotation.KeepName
import java.io.IOException
import java.util.ArrayList
import io.particle.mesh.ui.setup.barcodescanning.barcode.BarcodeScanningProcessor
import io.particle.mesh.ui.R
/**
* Demo app showing the various features of ML Kit for Firebase. This class is used to
* set up continuous frame processing on frames from a camera source.
*/
@KeepName
class LivePreviewActivity : AppCompatActivity(), OnRequestPermissionsResultCallback {
private var cameraSource: CameraSource? = null
private var preview: CameraSourcePreview? = null
private var graphicOverlay: GraphicOverlay? = null
private val selectedModel = "Barcode Detection"
private val requiredPermissions: Array<String>
get() {
return try {
val info = this.packageManager.getPackageInfo(
this.packageName, PackageManager.GET_PERMISSIONS)
val ps = info.requestedPermissions
if (ps != null && ps.size > 0) {
ps
} else {
Array(0) { "" }
}
} catch (e: Exception) {
Array(0) { "" }
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Log.d(TAG, "onCreate")
// setContentView(R.layout.activity_live_preview)
preview = findViewById(R.id.scanPreview)
if (preview == null) {
Log.d(TAG, "Preview is null")
}
graphicOverlay = findViewById(R.id.scanPreviewOverlay)
if (graphicOverlay == null) {
Log.d(TAG, "graphicOverlay is null")
}
if (allPermissionsGranted()) {
createCameraSource()
} else {
getRuntimePermissions()
}
}
private fun createCameraSource() {
// If there's no existing cameraSource, create one.
if (cameraSource == null) {
cameraSource = CameraSource(this, graphicOverlay)
}
cameraSource!!.setFacing(CameraSource.CAMERA_FACING_BACK)
cameraSource!!.setMachineLearningFrameProcessor(BarcodeScanningProcessor())
}
/**
* Starts or restarts the camera source, if it exists. If the camera source doesn't exist yet
* (e.g., because onResume was called before the camera source was created), this will be called
* again when the camera source is created.
*/
private fun startCameraSource() {
if (cameraSource != null) {
try {
if (preview == null) {
Log.d(TAG, "resume: Preview is null")
}
if (graphicOverlay == null) {
Log.d(TAG, "resume: graphOverlay is null")
}
preview!!.start(cameraSource, graphicOverlay)
} catch (e: IOException) {
Log.e(TAG, "Unable to start camera source.", e)
cameraSource!!.release()
cameraSource = null
}
}
}
public override fun onResume() {
super.onResume()
Log.d(TAG, "onResume")
startCameraSource()
}
/**
* Stops the camera.
*/
override fun onPause() {
super.onPause()
preview!!.stop()
}
public override fun onDestroy() {
super.onDestroy()
if (cameraSource != null) {
cameraSource!!.release()
}
}
private fun allPermissionsGranted(): Boolean {
for (permission in requiredPermissions) {
if (!isPermissionGranted(this, permission)) {
return false
}
}
return true
}
private fun getRuntimePermissions() {
val allNeededPermissions = ArrayList<String>()
for (permission in requiredPermissions) {
if (!isPermissionGranted(this, permission)) {
allNeededPermissions.add(permission)
}
}
if (!allNeededPermissions.isEmpty()) {
ActivityCompat.requestPermissions(
this, allNeededPermissions.toTypedArray(), PERMISSION_REQUESTS)
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
Log.i(TAG, "Permission granted!")
if (allPermissionsGranted()) {
createCameraSource()
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
companion object {
private val TAG = "LivePreviewActivity"
private val PERMISSION_REQUESTS = 1
private fun isPermissionGranted(context: Context, permission: String): Boolean {
if (ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED) {
Log.i(TAG, "Permission granted: $permission")
return true
}
Log.i(TAG, "Permission NOT granted: $permission")
return false
}
}
}
| apache-2.0 | b6ef2eaff6274d32ce1ad8da0964c8fd | 31.675676 | 110 | 0.616873 | 5.012438 | false | false | false | false |
wireapp/wire-android | app/src/main/kotlin/com/waz/zclient/feature/backup/conversations/ConversationsBackupDataSource.kt | 1 | 5010 | package com.waz.zclient.feature.backup.conversations
import com.waz.zclient.core.extension.empty
import com.waz.zclient.feature.backup.BackUpDataMapper
import com.waz.zclient.feature.backup.BackUpDataSource
import com.waz.zclient.feature.backup.BackUpIOHandler
import com.waz.zclient.storage.db.conversations.ConversationsEntity
import kotlinx.serialization.Serializable
import java.io.File
@Serializable
data class ConversationsBackUpModel(
val id: String,
val remoteId: String = String.empty(),
val name: String? = null,
val creator: String = String.empty(),
val conversationType: Int = 0,
val team: String? = null,
val managed: Boolean? = null,
val lastEventTime: Long = 0,
val active: Boolean = false,
val lastRead: Long = 0,
val mutedStatus: Int = 0,
val muteTime: Long = 0,
val archived: Boolean = false,
val archiveTime: Long = 0,
val cleared: Long? = null,
val generatedName: String = String.empty(),
val searchKey: String? = null,
val unreadCount: Int = 0,
val unsentCount: Int = 0,
val hidden: Boolean = false,
val missedCall: String? = null,
val incomingKnock: String? = null,
val verified: String? = null,
val ephemeral: Long? = null,
val globalEphemeral: Long? = null,
val unreadCallCount: Int = 0,
val unreadPingCount: Int = 0,
val access: String? = null,
val accessRole: String? = null,
val link: String? = null,
val unreadMentionsCount: Int = 0,
val unreadQuoteCount: Int = 0,
val receiptMode: Int? = null,
val legalHoldStatus: Int = 0,
val domain: String? = null
)
class ConversationsBackupMapper : BackUpDataMapper<ConversationsBackUpModel, ConversationsEntity> {
override fun fromEntity(entity: ConversationsEntity) = ConversationsBackUpModel(
id = entity.id,
remoteId = entity.remoteId,
name = entity.name,
creator = entity.creator,
conversationType = entity.conversationType,
team = entity.team,
managed = entity.managed,
lastEventTime = entity.lastEventTime,
active = entity.active,
lastRead = entity.lastRead,
mutedStatus = entity.mutedStatus,
muteTime = entity.muteTime,
archived = entity.archived,
archiveTime = entity.archiveTime,
cleared = entity.cleared,
generatedName = entity.generatedName,
searchKey = entity.searchKey,
unreadCount = entity.unreadCount,
unsentCount = entity.unsentCount,
hidden = entity.hidden,
missedCall = entity.missedCall,
incomingKnock = entity.incomingKnock,
verified = entity.verified,
ephemeral = entity.ephemeral,
globalEphemeral = entity.globalEphemeral,
unreadCallCount = entity.unreadCallCount,
unreadPingCount = entity.unreadPingCount,
access = entity.access,
accessRole = entity.accessRole,
link = entity.link,
unreadMentionsCount = entity.unreadMentionsCount,
unreadQuoteCount = entity.unreadQuoteCount,
receiptMode = entity.receiptMode,
legalHoldStatus = entity.legalHoldStatus,
domain = entity.domain
)
override fun toEntity(model: ConversationsBackUpModel) = ConversationsEntity(
id = model.id,
remoteId = model.remoteId,
name = model.name,
creator = model.creator,
conversationType = model.conversationType,
team = model.team,
managed = model.managed,
lastEventTime = model.lastEventTime,
active = model.active,
lastRead = model.lastRead,
mutedStatus = model.mutedStatus,
muteTime = model.muteTime,
archived = model.archived,
archiveTime = model.archiveTime,
cleared = model.cleared,
generatedName = model.generatedName,
searchKey = model.searchKey,
unreadCount = model.unreadCount,
unsentCount = model.unsentCount,
hidden = model.hidden,
missedCall = model.missedCall,
incomingKnock = model.incomingKnock,
verified = model.verified,
ephemeral = model.ephemeral,
globalEphemeral = model.globalEphemeral,
unreadCallCount = model.unreadCallCount,
unreadPingCount = model.unreadPingCount,
access = model.access,
accessRole = model.accessRole,
link = model.link,
unreadMentionsCount = model.unreadMentionsCount,
unreadQuoteCount = model.unreadQuoteCount,
receiptMode = model.receiptMode,
legalHoldStatus = model.legalHoldStatus,
domain = model.domain
)
}
class ConversationsBackupDataSource(
override val databaseLocalDataSource: BackUpIOHandler<ConversationsEntity, Unit>,
override val backUpLocalDataSource: BackUpIOHandler<ConversationsBackUpModel, File>,
override val mapper: BackUpDataMapper<ConversationsBackUpModel, ConversationsEntity>
) : BackUpDataSource<ConversationsBackUpModel, ConversationsEntity>()
| gpl-3.0 | c2705ca5cdc35ac9527a1fde98bac355 | 36.954545 | 99 | 0.682236 | 4.821944 | false | false | false | false |
7hens/KDroid | sample/src/main/java/cn/thens/kdroid/sample/nature/base/Sprite.kt | 1 | 932 | package cn.thens.kdroid.sample.nature.base
import android.graphics.Canvas
import android.graphics.PointF
import androidx.annotation.CallSuper
interface Sprite {
val stage: Stage
val position: PointF
val mas: Float
val velocity: PointF
val acceleration: Set<PointF>
var x: Float
get() = position.x
set(value) {
position.x = Math.min(stage.width.toFloat(), Math.max(0F, value))
}
var y: Float
get() = position.y
set(value) {
position.y = Math.min(stage.height.toFloat(), Math.max(0F, value))
}
@CallSuper fun onDraw(canvas: Canvas) {
var ax = 0F
var ay = 0F
acceleration.forEach { ax += it.x; ay += it.y }
velocity.offset(ax * Stage.SPEED_FACTOR, ay * Stage.SPEED_FACTOR)
x = position.x + velocity.x * Stage.SPEED_FACTOR
y = position.y + velocity.y * Stage.SPEED_FACTOR
}
} | apache-2.0 | 0069f170f605bfad98bb14daecd8216e | 26.441176 | 78 | 0.607296 | 3.698413 | false | false | false | false |
google/horologist | media-data/src/test/java/com/google/android/horologist/media/data/mapper/PlaylistDownloadMapperTest.kt | 1 | 3568 | /*
* 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
*
* 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.
*/
@file:OptIn(ExperimentalHorologistMediaDataApi::class)
package com.google.android.horologist.media.data.mapper
import com.google.android.horologist.media.data.ExperimentalHorologistMediaDataApi
import com.google.android.horologist.media.data.database.model.MediaDownloadEntity
import com.google.android.horologist.media.data.database.model.MediaEntity
import com.google.android.horologist.media.data.database.model.PlaylistEntity
import com.google.android.horologist.media.data.database.model.PopulatedPlaylist
import com.google.android.horologist.media.model.Media
import com.google.android.horologist.media.model.MediaDownload
import com.google.android.horologist.media.model.Playlist
import com.google.android.horologist.media.model.PlaylistDownload
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
class PlaylistDownloadMapperTest {
private lateinit var sut: PlaylistDownloadMapper
@Before
fun setUp() {
sut = PlaylistDownloadMapper(PlaylistMapper(MediaMapper(MediaExtrasMapperNoopImpl)))
}
@Test
fun mapsCorrectly() {
// given
val playlistId = "playlistId"
val playlistName = "playlistName"
val playlistArtworkUri = "playlistArtworkUri"
val mediaId = "mediaId"
val mediaUrl = "mediaUrl"
val artworkUrl = "artworkUrl"
val title = "title"
val artist = "artist"
val populatedPlaylist = PopulatedPlaylist(
PlaylistEntity(
playlistId = playlistId,
name = playlistName,
artworkUri = playlistArtworkUri
),
listOf(
MediaEntity(
mediaId = mediaId,
mediaUrl = mediaUrl,
artworkUrl = artworkUrl,
title = title,
artist = artist
)
)
)
val expectedMedia = Media(
id = mediaId,
uri = mediaUrl,
title = title,
artist = artist,
artworkUri = artworkUrl
)
val mediaDownloadEntity = listOf<MediaDownloadEntity>()
// then
val result = sut.map(populatedPlaylist, mediaDownloadEntity)
// then
assertThat(result).isEqualTo(
PlaylistDownload(
playlist = Playlist(
id = playlistId,
name = playlistName,
artworkUri = playlistArtworkUri,
mediaList = listOf(
expectedMedia
)
),
mediaList = listOf(
MediaDownload(
media = expectedMedia,
status = MediaDownload.Status.Idle,
size = MediaDownload.Size.Unknown
)
)
)
)
}
}
| apache-2.0 | e6bcea4fbc3daeea077ee456a9874397 | 32.660377 | 92 | 0.615191 | 5.201166 | false | false | false | false |
outersky/ystore | ystore-lib/src/main/java/chess.kt | 1 | 2362 | package com.ystore.lib.chess
import kotlin.io.*
import java.io.File
import java.util.zip.Inflater
import java.util.zip.DataFormatException
import java.io.ByteArrayOutputStream
import java.util.zip.Deflater
import com.ystore.lib.BytesReader
class CBL(val bytes:ByteArray){
val manuals = arrayListOf<Manual>()
val info = CBLInfo()
class object {
fun load(fileName:String):CBL{
return CBL(File(fileName).readBytes())
}
}
fun init(){
val zipByte = ByteArray(bytes.size-20)
System.arraycopy(bytes,20,zipByte,0,zipByte.size)
val textByte = decompress(zipByte)
val f = File("/tmp/unzip.cbl")
f.writeBytes(textByte)
val reader = BytesReader(textByte)
info.load(reader)
for (i in 0..info.getManualCount()-1) {
val manual = CBLManual()
manual.load(reader)
manuals.add(manual)
}
}
fun debug(){
manuals.forEach { m ->
println("======================================================")
println(m.getInfo())
println("=======================")
println(m.getTree())
}
}
private fun decompress(zipByte : ByteArray) : ByteArray {
var aos : ByteArrayOutputStream? = ByteArrayOutputStream()
var inflater : Inflater = Inflater()
inflater.setInput(zipByte)
var buff : ByteArray = ByteArray(1024 * 1000)
var byteNum: Int
while (!inflater.finished()){
try{
byteNum = inflater.inflate(buff)
aos?.write(buff, 0, byteNum)
} catch (e : DataFormatException) {
e.printStackTrace()
}
}
return aos?.toByteArray()!!
}
private fun compress(bytes : ByteArray) : ByteArray {
var aos : ByteArrayOutputStream = ByteArrayOutputStream()
var inflater : Deflater = Deflater()
inflater.setInput(bytes)
inflater.finish()
var buff : ByteArray = ByteArray(1024)
var byteNum : Int
while (!inflater.finished()) {
byteNum = inflater.deflate(buff)
aos.write(buff, 0, byteNum)
}
return aos.toByteArray()
}
}
fun main(args:Array<String>){
val cbl = CBL.load("/tmp/m3.cbl")
cbl.init()
cbl.debug()
}
| mit | f2d250d941c5c0ff0adaa922b34a42a9 | 26.465116 | 77 | 0.558848 | 4.414953 | false | false | false | false |
xfournet/intellij-community | python/src/com/jetbrains/python/codeInsight/typing/PyTypeShed.kt | 2 | 5035 | /*
* Copyright 2000-2017 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.jetbrains.python.codeInsight.typing
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.PythonHelpersLocator
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.TYPING
import com.jetbrains.python.packaging.PyPIPackageUtil
import com.jetbrains.python.packaging.PyPackageManagers
import com.jetbrains.python.packaging.PyPackageUtil
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.sdk.PythonSdkType
import java.io.File
/**
* Utilities for managing the local copy of the typeshed repository.
*
* The original Git repo is located [here](https://github.com/JetBrains/typeshed).
*
* @author vlan
*/
object PyTypeShed {
private val ONLY_SUPPORTED_PY2_MINOR = 7
private val SUPPORTED_PY3_MINORS = 2..7
val WHITE_LIST = setOf(TYPING, "six", "__builtin__", "builtins", "exceptions", "types", "datetime", "functools", "shutil", "re", "time",
"argparse", "uuid", "threading", "signal", "collections")
private val BLACK_LIST = setOf<String>()
/**
* Returns true if we allow to search typeshed for a stub for [name].
*/
fun maySearchForStubInRoot(name: QualifiedName, root: VirtualFile, sdk : Sdk): Boolean {
val topLevelPackage = name.firstComponent ?: return false
if (topLevelPackage in BLACK_LIST) {
return false
}
if (topLevelPackage !in WHITE_LIST) {
return false
}
if (isInStandardLibrary(root)) {
return true
}
if (isInThirdPartyLibraries(root)) {
if (ApplicationManager.getApplication().isUnitTestMode) {
return true
}
val pyPIPackages = PyPIPackageUtil.PACKAGES_TOPLEVEL[topLevelPackage] ?: emptyList()
val packages = PyPackageManagers.getInstance().forSdk(sdk).packages ?: return true
return PyPackageUtil.findPackage(packages, topLevelPackage) != null ||
pyPIPackages.any { PyPackageUtil.findPackage(packages, it) != null }
}
return false
}
/**
* Returns the list of roots in typeshed for the Python language level of [sdk].
*/
fun findRootsForSdk(sdk: Sdk): List<VirtualFile> {
val level = PythonSdkType.getLanguageLevelForSdk(sdk)
val dir = directory ?: return emptyList()
return findRootsForLanguageLevel(level)
.asSequence()
.map { dir.findFileByRelativePath(it) }
.filterNotNull()
.toList()
}
/**
* Returns the list of roots in typeshed for the specified Python language [level].
*/
fun findRootsForLanguageLevel(level: LanguageLevel): List<String> {
val minors = when (level.major) {
2 -> listOf(ONLY_SUPPORTED_PY2_MINOR)
3 -> SUPPORTED_PY3_MINORS.reversed().filter { it <= level.minor }
else -> return emptyList()
}
return minors.map { "stdlib/${level.major}.$it" } +
listOf("stdlib/${level.major}",
"stdlib/2and3",
"third_party/${level.major}",
"third_party/2and3")
}
/**
* Checks if the [file] is located inside the typeshed directory.
*/
fun isInside(file: VirtualFile): Boolean {
val dir = directory
return dir != null && VfsUtilCore.isAncestor(dir, file, true)
}
/**
* The actual typeshed directory.
*/
val directory: VirtualFile? by lazy {
val path = directoryPath ?: return@lazy null
StandardFileSystems.local().findFileByPath(path)
}
val directoryPath: String?
get() {
val paths = listOf("${PathManager.getConfigPath()}/typeshed",
"${PathManager.getConfigPath()}/../typeshed",
PythonHelpersLocator.getHelperPath("typeshed"))
return paths.asSequence()
.filter { File(it).exists() }
.firstOrNull()
}
/**
* A shallow check for a [file] being located inside the typeshed third-party stubs.
*/
fun isInThirdPartyLibraries(file: VirtualFile) = "third_party" in file.path
fun isInStandardLibrary(file: VirtualFile) = "stdlib" in file.path
private val LanguageLevel.major: Int
get() = this.version / 10
private val LanguageLevel.minor: Int
get() = this.version % 10
}
| apache-2.0 | 49fae364b65d5524d585a23bc47173e2 | 34.70922 | 138 | 0.68858 | 4.321888 | false | false | false | false |
Shynixn/BlockBall | blockball-api/src/main/java/com/github/shynixn/blockball/api/business/enumeration/Version.kt | 1 | 3132 | package com.github.shynixn.blockball.api.business.enumeration
/**
* Supported versions.
*/
enum class Version(
/**
* Id of the bukkit versions.
*/
val bukkitId: String,
/**
* General id.
*/
val id: String,
/**
* Numeric Id for calculations.
*/
val numericId: Double
) {
/**
* Unknown version.
*/
VERSION_UNKNOWN("", "", 0.0),
/**
* Version 1.8.0 - 1.8.2.
*/
VERSION_1_8_R1("v1_8_R1", "1.8.2", 1.081),
/**
* Version 1.8.3 - 1.8.4.
*/
VERSION_1_8_R2("v1_8_R2", "1.8.3", 1.082),
/**
* Version 1.8.5 - 1.8.9.
*/
VERSION_1_8_R3("v1_8_R3", "1.8.9", 1.083),
/**
* Version 1.9.0 - 1.9.1.
*/
VERSION_1_9_R1("v1_9_R1", "1.9.1", 1.091),
/**
* Version 1.9.2 - 1.9.4
*/
VERSION_1_9_R2("v1_9_R2", "1.9.4", 1.092),
/**
* Version 1.10.0 - 1.10.2.
*/
VERSION_1_10_R1("v1_10_R1", "1.10.2", 1.10),
/**
* Version 1.11.0 - 1.11.2.
*/
VERSION_1_11_R1("v1_11_R1", "1.11.2", 1.11),
/**
* Version 1.12.0 - 1.12.2.
*/
VERSION_1_12_R1("v1_12_R1", "1.12.2", 1.12),
/**
* Version 1.13.0 - 1.13.0.
*/
VERSION_1_13_R1("v1_13_R1", "1.13.0", 1.13),
/**
* Version 1.13.1 - 1.13.2.
*/
VERSION_1_13_R2("v1_13_R2", "1.13.2", 1.131),
/**
* Version 1.14.0 - 1.14.4.
*/
VERSION_1_14_R1("v1_14_R1", "1.14.4", 1.144),
/**
* Version 1.15.0 - 1.15.2.
*/
VERSION_1_15_R1("v1_15_R1", "1.15.2", 1.150),
/**
* Version 1.16.0 - 1.16.1.
*/
VERSION_1_16_R1("v1_16_R1", "1.16.1", 1.160),
/**
* Version 1.16.2 - 1.16.3.
*/
VERSION_1_16_R2("v1_16_R2", "1.16.2", 1.161),
/**
* Version 1.16.4 - 1.16.5.
*/
VERSION_1_16_R3("v1_16_R3", "1.16.5", 1.162),
/**
* Version 1.17.0 - 1.17.1.
*/
VERSION_1_17_R1("v1_17_R1", "1.17.0", 1.170),
/**
* Version 1.18.0 - 1.18.1.
*/
VERSION_1_18_R1("v1_18_R1", "1.18.0", 1.180),
/**
* Version 1.18.2 - 1.18.2.
*/
VERSION_1_18_R2("v1_18_R2", "1.18.2", 1.182),
/**
* Version 1.19.0 - 1.19.0.
*/
VERSION_1_19_R1("v1_19_R1", "1.19.0", 1.190);
/**
* Gets if this version is same or greater than the given version by parameter.
*/
fun isVersionSameOrGreaterThan(version: Version): Boolean {
val result = this.numericId.compareTo(version.numericId)
return result == 0 || result == 1
}
/**
* Gets if the version is the same or lower than the given version by parameter.
*/
fun isVersionSameOrLowerThan(version: Version): Boolean {
val result = this.numericId.compareTo(version.numericId)
return result == 0 || result == -1
}
/**
* Gets if this version is compatible to the versions given as parameter.
*/
fun isCompatible(vararg versions: Version): Boolean {
for (version in versions) {
if (this.bukkitId == version.bukkitId) {
return true
}
}
return false
}
}
| apache-2.0 | a86a169012791a81ee33bf13fffcd9cc | 20.162162 | 84 | 0.477011 | 2.601329 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/main/java/jp/toastkid/yobidashi/settings/view/screen/SettingTopUi.kt | 1 | 3391 | /*
* Copyright (c) 2022 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.settings.view.screen
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.padding
import androidx.compose.material.ScrollableTabRow
import androidx.compose.material.Tab
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelStoreOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.yobidashi.R
@Composable
fun SettingTopUi() {
val activityContext = LocalContext.current
val preferenceApplier = PreferenceApplier(activityContext)
val contentViewModel = (activityContext as? ViewModelStoreOwner)?.let {
viewModel(ContentViewModel::class.java, activityContext)
}
val selectedIndex = remember { mutableStateOf(0) }
SwitchContentWithTabIndex(selectedIndex)
contentViewModel?.replaceAppBarContent {
val pages = arrayOf(
R.string.subhead_displaying,
R.string.title_settings_color,
R.string.search,
R.string.subhead_browser,
R.string.subhead_editor,
R.string.title_color_filter,
R.string.subhead_others
)
ScrollableTabRow(
selectedTabIndex = selectedIndex.value,
edgePadding = 8.dp,
backgroundColor = Color.Transparent,
modifier = Modifier.fillMaxHeight()
) {
pages.forEachIndexed { index, page ->
Tab(
selected = selectedIndex.value == index,
onClick = {
selectedIndex.value = index
},
modifier = Modifier.padding(start = 4.dp, end = 4.dp)
) {
Text(
text = stringResource(id = page),
color = Color(preferenceApplier.fontColor),
fontSize = 16.sp
)
}
}
}
}
DisposableEffect(key1 = "refresh") {
onDispose {
contentViewModel?.refresh()
}
}
contentViewModel?.clearOptionMenus()
}
@Composable
private fun SwitchContentWithTabIndex(selectedIndex: MutableState<Int>) {
when (selectedIndex.value) {
0 -> DisplaySettingUi()
1 -> ColorSettingUi()
2 -> SearchSettingUi()
3 -> BrowserSettingUi()
4 -> EditorSettingUi()
5 -> ColorFilterSettingUi()
6 -> OtherSettingUi()
else -> DisplaySettingUi()
}
}
| epl-1.0 | 597a7fcbe2d3ebfd41af2e11b2f81791 | 32.245098 | 88 | 0.658803 | 4.935953 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.