repo_name
stringlengths
7
81
path
stringlengths
4
242
copies
stringclasses
95 values
size
stringlengths
1
6
content
stringlengths
3
991k
license
stringclasses
15 values
smmribeiro/intellij-community
plugins/toml/core/src/test/kotlin/org/toml/ide/wordSelection/TomlSelectionHandlerTestBase.kt
1
812
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.toml.ide.wordSelection import com.intellij.codeInsight.editorActions.SelectWordHandler import com.intellij.ide.DataManager import org.intellij.lang.annotations.Language import org.toml.TomlTestBase abstract class TomlSelectionHandlerTestBase : TomlTestBase() { protected fun doTest(@Language("TOML") before: String, @Language("TOML") vararg after: String) { InlineFile(before) val action = SelectWordHandler(null) val dataContext = DataManager.getInstance().getDataContext(myFixture.editor.component) for (text in after) { action.execute(myFixture.editor, null, dataContext) myFixture.checkResult(text, false) } } }
apache-2.0
smmribeiro/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/GHPRFilesManagerImpl.kt
3
3767
// 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.plugins.github.pullrequest.data import com.intellij.diff.editor.DiffEditorTabFilesManager import com.intellij.openapi.Disposable import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx import com.intellij.openapi.project.Project import com.intellij.util.EventDispatcher import com.intellij.util.containers.ContainerUtil import org.jetbrains.plugins.github.api.GHRepositoryCoordinates import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestShort import org.jetbrains.plugins.github.pullrequest.GHNewPRDiffVirtualFile import org.jetbrains.plugins.github.pullrequest.GHPRDiffVirtualFile import org.jetbrains.plugins.github.pullrequest.GHPRStatisticsCollector import org.jetbrains.plugins.github.pullrequest.GHPRTimelineVirtualFile import java.util.* internal class GHPRFilesManagerImpl(private val project: Project, private val repository: GHRepositoryCoordinates) : GHPRFilesManager { // current time should be enough to distinguish the manager between launches private val id = System.currentTimeMillis().toString() private val filesEventDispatcher = EventDispatcher.create(FileListener::class.java) private val files = ContainerUtil.createWeakValueMap<GHPRIdentifier, GHPRTimelineVirtualFile>() private val diffFiles = ContainerUtil.createWeakValueMap<GHPRIdentifier, GHPRDiffVirtualFile>() override val newPRDiffFile by lazy { GHNewPRDiffVirtualFile(id, project, repository) } override fun createAndOpenTimelineFile(pullRequest: GHPRIdentifier, requestFocus: Boolean) { files.getOrPut(SimpleGHPRIdentifier(pullRequest)) { GHPRTimelineVirtualFile(id, project, repository, pullRequest) }.let { filesEventDispatcher.multicaster.onBeforeFileOpened(it) FileEditorManager.getInstance(project).openFile(it, requestFocus) GHPRStatisticsCollector.logTimelineOpened(project) } } override fun createAndOpenDiffFile(pullRequest: GHPRIdentifier, requestFocus: Boolean) { diffFiles.getOrPut(SimpleGHPRIdentifier(pullRequest)) { GHPRDiffVirtualFile(id, project, repository, pullRequest) }.let { DiffEditorTabFilesManager.getInstance(project).showDiffFile(it, requestFocus) GHPRStatisticsCollector.logDiffOpened(project) } } override fun openNewPRDiffFile(requestFocus: Boolean) { DiffEditorTabFilesManager.getInstance(project).showDiffFile(newPRDiffFile, requestFocus) } override fun findTimelineFile(pullRequest: GHPRIdentifier): GHPRTimelineVirtualFile? = files[SimpleGHPRIdentifier(pullRequest)] override fun findDiffFile(pullRequest: GHPRIdentifier): GHPRDiffVirtualFile? = diffFiles[SimpleGHPRIdentifier(pullRequest)] override fun updateTimelineFilePresentation(details: GHPullRequestShort) { val file = findTimelineFile(details) if (file != null) { file.details = details FileEditorManagerEx.getInstanceEx(project).updateFilePresentation(file) } } override fun addBeforeTimelineFileOpenedListener(disposable: Disposable, listener: (file: GHPRTimelineVirtualFile) -> Unit) { filesEventDispatcher.addListener(object : FileListener { override fun onBeforeFileOpened(file: GHPRTimelineVirtualFile) = listener(file) }, disposable) } override fun dispose() { for (file in (files.values + diffFiles.values)) { FileEditorManager.getInstance(project).closeFile(file) file.isValid = false } } private interface FileListener : EventListener { fun onBeforeFileOpened(file: GHPRTimelineVirtualFile) } }
apache-2.0
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/openapi/util/registry/RegistryToAdvancedSettingsMigration.kt
8
3011
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.util.registry import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.editor.impl.TabCharacterPaintMode import com.intellij.openapi.options.advanced.AdvancedSettingBean import com.intellij.openapi.options.advanced.AdvancedSettings import com.intellij.openapi.project.Project import com.intellij.openapi.startup.StartupActivity private class RegistryToAdvancedSettingsMigration : StartupActivity.DumbAware { override fun runActivity(project: Project) { val propertyName = "registry.to.advanced.settings.migration.build" val lastMigratedVersion = PropertiesComponent.getInstance().getValue(propertyName) val currentVersion = ApplicationInfo.getInstance().build.asString() if (currentVersion != lastMigratedVersion) { val userProperties = Registry.getInstance().userProperties for (setting in AdvancedSettingBean.EP_NAME.extensions) { if (setting.id == "editor.tab.painting") { migrateEditorTabPainting(userProperties, setting) continue } if (setting.id == "vcs.process.ignored") { migrateVcsIgnoreProcessing(userProperties, setting) continue } val userProperty = userProperties[setting.id] ?: continue try { AdvancedSettings.getInstance().setSetting(setting.id, setting.valueFromString(userProperty), setting.type()) userProperties.remove(setting.id) } catch (e: IllegalArgumentException) { continue } } PropertiesComponent.getInstance().setValue(propertyName, currentVersion) } } private fun migrateEditorTabPainting(userProperties: MutableMap<String, String>, setting: AdvancedSettingBean) { val mode = if (userProperties["editor.old.tab.painting"] == "true") { userProperties.remove("editor.old.tab.painting") TabCharacterPaintMode.LONG_ARROW } else if (userProperties["editor.arrow.tab.painting"] == "true") { userProperties.remove("editor.arrow.tab.painting") TabCharacterPaintMode.ARROW } else { return } AdvancedSettings.getInstance().setSetting(setting.id, mode, setting.type()) } private fun migrateVcsIgnoreProcessing(userProperties: MutableMap<String, String>, setting: AdvancedSettingBean) { if (userProperties["git.process.ignored"] == "false") { userProperties.remove("git.process.ignored") } else if (userProperties["hg4idea.process.ignored"] == "false") { userProperties.remove("hg4idea.process.ignored") } else if (userProperties["p4.process.ignored"] == "false") { userProperties.remove("p4.process.ignored") } else { return } AdvancedSettings.getInstance().setSetting(setting.id, false, setting.type()) } }
apache-2.0
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/ChatRecyclerViewHolder.kt
1
10229
package com.habitrpg.android.habitica.ui.viewHolders import android.annotation.SuppressLint import android.content.Context import android.content.res.Resources import android.graphics.drawable.BitmapDrawable import android.text.method.LinkMovementMethod import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.LinearLayout import android.widget.TextView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.extensions.dpToPx import com.habitrpg.android.habitica.extensions.getAgoString import com.habitrpg.android.habitica.extensions.setScaledPadding import com.habitrpg.android.habitica.models.social.ChatMessage import com.habitrpg.android.habitica.models.user.User import com.habitrpg.android.habitica.ui.AvatarView import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils import com.habitrpg.android.habitica.ui.helpers.MarkdownParser import com.habitrpg.android.habitica.ui.helpers.bindView import com.habitrpg.android.habitica.ui.views.HabiticaEmojiTextView import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import com.habitrpg.android.habitica.ui.views.social.UsernameLabel import io.reactivex.Maybe import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers class ChatRecyclerViewHolder(itemView: View, private var userId: String, private val isTavern: Boolean) : RecyclerView.ViewHolder(itemView) { private val messageWrapper: ViewGroup by bindView(R.id.message_wrapper) private val avatarView: AvatarView by bindView(R.id.avatar_view) private val userLabel: UsernameLabel by bindView(R.id.user_label) private val messageText: HabiticaEmojiTextView by bindView(R.id.message_text) private val sublineTextView: TextView by bindView(R.id.subline_textview) private val likeBackground: LinearLayout by bindView(R.id.like_background_layout) private val tvLikes: TextView by bindView(R.id.tvLikes) private val buttonsWrapper: ViewGroup by bindView(R.id.buttons_wrapper) private val replyButton: Button by bindView(R.id.reply_button) private val copyButton: Button by bindView(R.id.copy_button) private val reportButton: Button by bindView(R.id.report_button) private val deleteButton: Button by bindView(R.id.delete_button) private val modView: TextView by bindView(R.id.mod_view) val context: Context = itemView.context val res: Resources = itemView.resources private var chatMessage: ChatMessage? = null private var user: User? = null var onShouldExpand: (() -> Unit)? = null var onLikeMessage: ((ChatMessage) -> Unit)? = null var onOpenProfile: ((String) -> Unit)? = null var onReply: ((String) -> Unit)? = null var onCopyMessage: ((ChatMessage) -> Unit)? = null var onFlagMessage: ((ChatMessage) -> Unit)? = null var onDeleteMessage: ((ChatMessage) -> Unit)? = null init { itemView.setOnClickListener { onShouldExpand?.invoke() } tvLikes.setOnClickListener { chatMessage?.let { onLikeMessage?.invoke(it) } } messageText.setOnClickListener { onShouldExpand?.invoke() } messageText.movementMethod = LinkMovementMethod.getInstance() userLabel.setOnClickListener { chatMessage?.uuid?.let { onOpenProfile?.invoke(it) } } avatarView.setOnClickListener { chatMessage?.uuid?.let { onOpenProfile?.invoke(it) } } replyButton.setOnClickListener { if (chatMessage?.username != null) { chatMessage?.username?.let { onReply?.invoke(it) } } else { chatMessage?.user?.let { onReply?.invoke(it) } } } replyButton.setCompoundDrawablesWithIntrinsicBounds(BitmapDrawable(res, HabiticaIconsHelper.imageOfChatReplyIcon()), null, null, null) copyButton.setOnClickListener { chatMessage?.let { onCopyMessage?.invoke(it) } } copyButton.setCompoundDrawablesWithIntrinsicBounds(BitmapDrawable(res, HabiticaIconsHelper.imageOfChatCopyIcon()), null, null, null) reportButton.setOnClickListener { chatMessage?.let { onFlagMessage?.invoke(it) } } reportButton.setCompoundDrawablesWithIntrinsicBounds(BitmapDrawable(res, HabiticaIconsHelper.imageOfChatReportIcon()), null, null, null) deleteButton.setOnClickListener { chatMessage?.let { onDeleteMessage?.invoke(it) } } deleteButton.setCompoundDrawablesWithIntrinsicBounds(BitmapDrawable(res, HabiticaIconsHelper.imageOfChatDeleteIcon()), null, null, null) } fun bind(msg: ChatMessage, uuid: String, user: User?, isExpanded: Boolean) { chatMessage = msg this.user = user userId = uuid setLikeProperties() val wasSent = messageWasSent() val name = user?.profile?.name if (wasSent) { userLabel.isNPC = user?.backer?.npc != null userLabel.tier = user?.contributor?.level ?: 0 userLabel.username = name if (user?.username != null) { @SuppressLint("SetTextI18n") sublineTextView.text = "${user.formattedUsername} ∙ ${msg.timestamp?.getAgoString(res)}" } else { sublineTextView.text = msg.timestamp?.getAgoString(res) } } else { userLabel.isNPC = msg.backer?.npc != null userLabel.tier = msg.contributor?.level ?: 0 userLabel.username = msg.user if (msg.username != null) { @SuppressLint("SetTextI18n") sublineTextView.text = "${msg.formattedUsername} ∙ ${msg.timestamp?.getAgoString(res)}" } else { sublineTextView.text = msg.timestamp?.getAgoString(res) } } when { userLabel.tier == 8 -> { modView.visibility = View.VISIBLE modView.text = context.getString(R.string.moderator) modView.background = ContextCompat.getDrawable(context, R.drawable.pill_bg_blue) modView.setScaledPadding(context, 12, 4, 12, 4) } userLabel.tier == 9 -> { modView.visibility = View.VISIBLE modView.text = context.getString(R.string.staff) modView.background = ContextCompat.getDrawable(context, R.drawable.pill_bg_purple_300) modView.setScaledPadding(context, 12, 4, 12, 4) } else -> modView.visibility = View.GONE } if (wasSent) { avatarView.visibility = View.GONE itemView.setPadding(64.dpToPx(context), itemView.paddingTop, itemView.paddingRight, itemView.paddingBottom) } else { val displayMetrics = res.displayMetrics val dpWidth = displayMetrics.widthPixels / displayMetrics.density if (dpWidth > 350) { avatarView.visibility = View.VISIBLE msg.userStyles?.let { avatarView.setAvatar(it) } } else { avatarView.visibility = View.GONE } itemView.setPadding(16.dpToPx(context), itemView.paddingTop, itemView.paddingRight, itemView.paddingBottom) } messageText.text = chatMessage?.parsedText if (msg.parsedText == null) { messageText.text = chatMessage?.text Maybe.just(chatMessage?.text ?: "") .map { MarkdownParser.parseMarkdown(it) } .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe({ parsedText -> chatMessage?.parsedText = parsedText messageText.text = chatMessage?.parsedText }, { it.printStackTrace() }) } val username = user?.formattedUsername messageWrapper.background = if ((name != null && msg.text?.contains("@$name") == true) || (username != null && msg.text?.contains(username) == true)) { ContextCompat.getDrawable(context, R.drawable.layout_rounded_bg_brand_700) } else { ContextCompat.getDrawable(context, R.drawable.layout_rounded_bg) } messageWrapper.setScaledPadding(context, 8, 8, 8, 8) if (isExpanded) { buttonsWrapper.visibility = View.VISIBLE deleteButton.visibility = if (shouldShowDelete()) View.VISIBLE else View.GONE replyButton.visibility = if (chatMessage?.isInboxMessage == true) View.GONE else View.VISIBLE } else { buttonsWrapper.visibility = View.GONE } } private fun messageWasSent(): Boolean { return chatMessage?.sent == true || chatMessage?.uuid == userId } private fun setLikeProperties() { likeBackground.visibility = if (isTavern) View.VISIBLE else View.INVISIBLE @SuppressLint("SetTextI18n") tvLikes.text = "+" + chatMessage?.likeCount val backgroundColorRes: Int val foregroundColorRes: Int if (chatMessage?.likeCount != 0) { if (chatMessage?.userLikesMessage(userId) == true) { backgroundColorRes = R.color.tavern_userliked_background foregroundColorRes = R.color.tavern_userliked_foreground } else { backgroundColorRes = R.color.tavern_somelikes_background foregroundColorRes = R.color.tavern_somelikes_foreground } } else { backgroundColorRes = R.color.tavern_nolikes_background foregroundColorRes = R.color.tavern_nolikes_foreground } DataBindingUtils.setRoundedBackground(likeBackground, ContextCompat.getColor(context, backgroundColorRes)) tvLikes.setTextColor(ContextCompat.getColor(context, foregroundColorRes)) } private fun shouldShowDelete(): Boolean { return chatMessage?.isSystemMessage != true && (chatMessage?.uuid == userId || user?.contributor?.admin == true || chatMessage?.isInboxMessage == true) } }
gpl-3.0
ozbek/quran_android
app/src/main/java/com/quran/labs/androidquran/worker/MissingPageDownloadWorker.kt
2
3858
package com.quran.labs.androidquran.worker import android.content.Context import androidx.work.CoroutineWorker import androidx.work.ListenableWorker import androidx.work.WorkerParameters import com.quran.data.core.QuranInfo import com.quran.labs.androidquran.core.worker.WorkerTaskFactory import com.quran.labs.androidquran.util.QuranFileUtils import com.quran.labs.androidquran.util.QuranScreenInfo import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.flowOn import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.toList import okhttp3.OkHttpClient import timber.log.Timber import java.io.File import javax.inject.Inject class MissingPageDownloadWorker(private val context: Context, params: WorkerParameters, private val okHttpClient: OkHttpClient, private val quranInfo: QuranInfo, private val quranScreenInfo: QuranScreenInfo, private val quranFileUtils: QuranFileUtils ) : CoroutineWorker(context, params) { override suspend fun doWork(): Result = coroutineScope { Timber.d("MissingPageDownloadWorker") val pagesToDownload = findMissingPagesToDownload() Timber.d("MissingPageDownloadWorker found $pagesToDownload missing pages") if (pagesToDownload.size < MISSING_PAGE_LIMIT) { // attempt to download missing pages val results = pagesToDownload.asFlow() .map { downloadPage(it) } .flowOn(Dispatchers.IO) .toList() val failures = results.count { !it } if (failures > 0) { Timber.d("MissingPageWorker failed with $failures from ${pagesToDownload.size}") } else { Timber.d("MissingPageWorker success with ${pagesToDownload.size}") } } Result.success() } private fun findMissingPagesToDownload(): List<PageToDownload> { val width = quranScreenInfo.widthParam val result = findMissingPagesForWidth(width) val tabletWidth = quranScreenInfo.tabletWidthParam return if (width == tabletWidth) { result } else { result + findMissingPagesForWidth(tabletWidth) } } private fun findMissingPagesForWidth(width: String): List<PageToDownload> { val result = mutableListOf<PageToDownload>() val pagesDirectory = File(quranFileUtils.getQuranImagesDirectory(context, width)) for (page in 1..quranInfo.numberOfPages) { val pageFile = QuranFileUtils.getPageFileName(page) if (!File(pagesDirectory, pageFile).exists()) { result.add(PageToDownload(width, page)) } } return result } data class PageToDownload(val width: String, val page: Int) private fun downloadPage(pageToDownload: PageToDownload): Boolean { Timber.d("downloading ${pageToDownload.page} for ${pageToDownload.width} - thread: %s", Thread.currentThread().name) val pageName = QuranFileUtils.getPageFileName(pageToDownload.page) return try { quranFileUtils.getImageFromWeb(okHttpClient, context, pageToDownload.width, pageName) .isSuccessful } catch (throwable: Throwable) { false } } class Factory @Inject constructor( private val quranInfo: QuranInfo, private val quranFileUtils: QuranFileUtils, private val quranScreenInfo: QuranScreenInfo, private val okHttpClient: OkHttpClient ) : WorkerTaskFactory { override fun makeWorker( appContext: Context, workerParameters: WorkerParameters ): ListenableWorker { return MissingPageDownloadWorker( appContext, workerParameters, okHttpClient, quranInfo, quranScreenInfo, quranFileUtils ) } } companion object { private const val MISSING_PAGE_LIMIT = 50 } }
gpl-3.0
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/comm/DanaRS_Packet_Bolus_Set_Extended_Bolus.kt
1
1436
package info.nightscout.androidaps.danars.comm import dagger.android.HasAndroidInjector import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.danars.encryption.BleEncryption class DanaRS_Packet_Bolus_Set_Extended_Bolus( injector: HasAndroidInjector, private var extendedAmount: Double = 0.0, private var extendedBolusDurationInHalfHours: Int = 0 ) : DanaRS_Packet(injector) { init { opCode = BleEncryption.DANAR_PACKET__OPCODE_BOLUS__SET_EXTENDED_BOLUS aapsLogger.debug(LTag.PUMPCOMM, "Extended bolus start : $extendedAmount U halfhours: $extendedBolusDurationInHalfHours") } override fun getRequestParams(): ByteArray { val extendedBolusRate = (extendedAmount * 100.0).toInt() val request = ByteArray(3) request[0] = (extendedBolusRate and 0xff).toByte() request[1] = (extendedBolusRate ushr 8 and 0xff).toByte() request[2] = (extendedBolusDurationInHalfHours and 0xff).toByte() return request } override fun handleMessage(data: ByteArray) { val result = intFromBuff(data, 0, 1) if (result == 0) { aapsLogger.debug(LTag.PUMPCOMM, "Result OK") failed = false } else { aapsLogger.error("Result Error: $result") failed = true } } override fun getFriendlyName(): String { return "BOLUS__SET_EXTENDED_BOLUS" } }
agpl-3.0
firebase/firebase-android-sdk
encoders/protoc-gen-firebase-encoders/src/test/kotlin/com/google/firebase/encoders/proto/codegen/ConfigTests.kt
1
1654
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.firebase.encoders.proto.codegen import com.google.common.truth.Truth.assertThat import com.google.firebase.encoders.proto.CodeGenConfig import java.nio.CharBuffer import org.junit.Assert.assertThrows import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class ConfigTests { @Test fun `read() with valid txtpb file should succeed`() { val vendorPackage = "com.example" val myProto = "com.example.proto.MyProto" val config = ConfigReader.read( """ vendor_package: "$vendorPackage" include: "$myProto" """ .trimIndent() ) assertThat(config) .isEqualTo( CodeGenConfig.newBuilder().setVendorPackage(vendorPackage).addInclude(myProto).build() ) } @Test fun `read() with invalid file should fail`() { assertThrows(InvalidConfigException::class.java) { ConfigReader.read("invalid") } } } private fun ConfigReader.read(value: String): CodeGenConfig = read(CharBuffer.wrap(value))
apache-2.0
jotomo/AndroidAPS
danars/src/main/java/info/nightscout/androidaps/danars/services/DanaRSService.kt
1
24091
package info.nightscout.androidaps.danars.services import android.app.Service import android.content.Context import android.content.Intent import android.os.Binder import android.os.IBinder import android.os.SystemClock import dagger.android.DaggerService import dagger.android.HasAndroidInjector import info.nightscout.androidaps.Constants import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.dana.comm.RecordTypes import info.nightscout.androidaps.dana.events.EventDanaRNewStatus import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.danars.R import info.nightscout.androidaps.danars.comm.* import info.nightscout.androidaps.data.Profile import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.db.Treatment import info.nightscout.androidaps.dialogs.BolusProgressDialog import info.nightscout.androidaps.events.EventAppExit import info.nightscout.androidaps.events.EventInitializationChanged import info.nightscout.androidaps.events.EventProfileNeedsUpdate import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.interfaces.ActivePluginProvider import info.nightscout.androidaps.interfaces.CommandQueueProvider import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.AAPSLogger import info.nightscout.androidaps.logging.LTag import info.nightscout.androidaps.plugins.bus.RxBusWrapper import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress import info.nightscout.androidaps.plugins.general.overview.notifications.Notification import info.nightscout.androidaps.plugins.pump.common.bolusInfo.DetailedBolusInfoStorage import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.queue.commands.Command import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.resources.ResourceHelper import info.nightscout.androidaps.utils.sharedPreferences.SP import io.reactivex.disposables.CompositeDisposable import io.reactivex.schedulers.Schedulers import org.joda.time.DateTime import org.joda.time.DateTimeZone import java.util.concurrent.TimeUnit import javax.inject.Inject import kotlin.math.abs import kotlin.math.min class DanaRSService : DaggerService() { @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var aapsLogger: AAPSLogger @Inject lateinit var rxBus: RxBusWrapper @Inject lateinit var sp: SP @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var commandQueue: CommandQueueProvider @Inject lateinit var context: Context @Inject lateinit var danaRSPlugin: DanaRSPlugin @Inject lateinit var danaPump: DanaPump @Inject lateinit var danaRSMessageHashTable: DanaRSMessageHashTable @Inject lateinit var activePlugin: ActivePluginProvider @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var detailedBolusInfoStorage: DetailedBolusInfoStorage @Inject lateinit var bleComm: BLEComm @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var nsUpload: NSUpload @Inject lateinit var dateUtil: DateUtil private val disposable = CompositeDisposable() private val mBinder: IBinder = LocalBinder() private var lastHistoryFetched: Long = 0 private var lastApproachingDailyLimit: Long = 0 override fun onCreate() { super.onCreate() disposable.add(rxBus .toObservable(EventAppExit::class.java) .observeOn(Schedulers.io()) .subscribe({ stopSelf() }) { fabricPrivacy.logException(it) } ) } override fun onDestroy() { disposable.clear() super.onDestroy() } val isConnected: Boolean get() = bleComm.isConnected val isConnecting: Boolean get() = bleComm.isConnecting fun connect(from: String, address: String): Boolean { return bleComm.connect(from, address) } fun stopConnecting() { bleComm.stopConnecting() } fun disconnect(from: String) { bleComm.disconnect(from) } fun sendMessage(message: DanaRS_Packet) { bleComm.sendMessage(message) } fun readPumpStatus() { try { val pump = activePlugin.activePump rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))) sendMessage(DanaRS_Packet_Etc_Keep_Connection(injector)) // test encryption for v3 sendMessage(DanaRS_Packet_General_Get_Shipping_Information(injector)) // serial no sendMessage(DanaRS_Packet_General_Get_Pump_Check(injector)) // firmware sendMessage(DanaRS_Packet_Basal_Get_Profile_Number(injector)) sendMessage(DanaRS_Packet_Bolus_Get_Bolus_Option(injector)) // isExtendedEnabled sendMessage(DanaRS_Packet_Basal_Get_Basal_Rate(injector)) // basal profile, basalStep, maxBasal sendMessage(DanaRS_Packet_Bolus_Get_Calculation_Information(injector)) // target if (danaPump.profile24) sendMessage(DanaRS_Packet_Bolus_Get_24_CIR_CF_Array(injector)) else sendMessage(DanaRS_Packet_Bolus_Get_CIR_CF_Array(injector)) sendMessage(DanaRS_Packet_Option_Get_User_Option(injector)) // Getting user options rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpstatus))) sendMessage(DanaRS_Packet_General_Initial_Screen_Information(injector)) rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingextendedbolusstatus))) sendMessage(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(injector)) rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))) sendMessage(DanaRS_Packet_Bolus_Get_Step_Bolus_Information(injector)) // last bolus, bolusStep, maxBolus rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingtempbasalstatus))) sendMessage(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector)) danaPump.lastConnection = System.currentTimeMillis() val profile = profileFunction.getProfile() if (profile != null && abs(danaPump.currentBasal - profile.basal) >= pump.pumpDescription.basalStep) { rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumpsettings))) sendMessage(DanaRS_Packet_Basal_Get_Basal_Rate(injector)) // basal profile, basalStep, maxBasal if (!pump.isThisProfileSet(profile) && !commandQueue.isRunning(Command.CommandType.BASAL_PROFILE)) { rxBus.send(EventProfileNeedsUpdate()) } } rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingpumptime))) if (danaPump.usingUTC) sendMessage(DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(injector)) else sendMessage(DanaRS_Packet_Option_Get_Pump_Time(injector)) var timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L if (danaPump.getPumpTime() == 0L) { // initial handshake was not successful // de-initialize pump danaPump.reset() rxBus.send(EventDanaRNewStatus()) rxBus.send(EventInitializationChanged()) return } aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds") // phone timezone val tz = DateTimeZone.getDefault() val instant = DateTime.now().millis val offsetInMilliseconds = tz.getOffset(instant).toLong() val offset = TimeUnit.MILLISECONDS.toHours(offsetInMilliseconds).toInt() if (abs(timeDiff) > 3 || danaPump.usingUTC && offset != danaPump.zoneOffset) { if (abs(timeDiff) > 60 * 60 * 1.5) { aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds - large difference") //If time-diff is very large, warn user until we can synchronize history readings properly val i = Intent(context, ErrorHelperActivity::class.java) i.putExtra("soundid", R.raw.error) i.putExtra("status", resourceHelper.gs(R.string.largetimediff)) i.putExtra("title", resourceHelper.gs(R.string.largetimedifftitle)) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) context.startActivity(i) //de-initialize pump danaPump.reset() rxBus.send(EventDanaRNewStatus()) rxBus.send(EventInitializationChanged()) return } else { if (danaPump.usingUTC) { sendMessage(DanaRS_Packet_Option_Set_Pump_UTC_And_TimeZone(injector, DateUtil.now(), offset)) } else if (danaPump.protocol >= 6) { // can set seconds sendMessage(DanaRS_Packet_Option_Set_Pump_Time(injector, DateUtil.now())) } else { waitForWholeMinute() // Dana can set only whole minute // add 10sec to be sure we are over minute (will be cut off anyway) sendMessage(DanaRS_Packet_Option_Set_Pump_Time(injector, DateUtil.now() + T.secs(10).msecs())) } if (danaPump.usingUTC) sendMessage(DanaRS_Packet_Option_Get_Pump_UTC_And_TimeZone(injector)) else sendMessage(DanaRS_Packet_Option_Get_Pump_Time(injector)) timeDiff = (danaPump.getPumpTime() - System.currentTimeMillis()) / 1000L aapsLogger.debug(LTag.PUMPCOMM, "Pump time difference: $timeDiff seconds") } } loadEvents() rxBus.send(EventDanaRNewStatus()) rxBus.send(EventInitializationChanged()) //NSUpload.uploadDeviceStatus(); if (danaPump.dailyTotalUnits > danaPump.maxDailyTotalUnits * Constants.dailyLimitWarning) { aapsLogger.debug(LTag.PUMPCOMM, "Approaching daily limit: " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits) if (System.currentTimeMillis() > lastApproachingDailyLimit + 30 * 60 * 1000) { val reportFail = Notification(Notification.APPROACHING_DAILY_LIMIT, resourceHelper.gs(R.string.approachingdailylimit), Notification.URGENT) rxBus.send(EventNewNotification(reportFail)) nsUpload.uploadError(resourceHelper.gs(R.string.approachingdailylimit) + ": " + danaPump.dailyTotalUnits + "/" + danaPump.maxDailyTotalUnits + "U") lastApproachingDailyLimit = System.currentTimeMillis() } } } catch (e: Exception) { aapsLogger.error(LTag.PUMPCOMM, "Unhandled exception", e) } aapsLogger.debug(LTag.PUMPCOMM, "Pump status loaded") } fun loadEvents(): PumpEnactResult { if (!danaRSPlugin.isInitialized) { val result = PumpEnactResult(injector).success(false) result.comment = "pump not initialized" return result } SystemClock.sleep(1000) val msg: DanaRS_Packet_APS_History_Events if (lastHistoryFetched == 0L) { msg = DanaRS_Packet_APS_History_Events(injector, 0) aapsLogger.debug(LTag.PUMPCOMM, "Loading complete event history") } else { msg = DanaRS_Packet_APS_History_Events(injector, lastHistoryFetched) aapsLogger.debug(LTag.PUMPCOMM, "Loading event history from: " + dateUtil.dateAndTimeString(lastHistoryFetched)) } sendMessage(msg) while (!danaPump.historyDoneReceived && bleComm.isConnected) { SystemClock.sleep(100) } lastHistoryFetched = if (danaPump.lastEventTimeLoaded != 0L) danaPump.lastEventTimeLoaded - T.mins(1).msecs() else 0 aapsLogger.debug(LTag.PUMPCOMM, "Events loaded") danaPump.lastConnection = System.currentTimeMillis() return PumpEnactResult(injector).success(msg.success()) } fun setUserSettings(): PumpEnactResult { val message = DanaRS_Packet_Option_Set_User_Option(injector) sendMessage(message) return PumpEnactResult(injector).success(message.success()) } fun bolus(insulin: Double, carbs: Int, carbTime: Long, t: Treatment): Boolean { if (!isConnected) return false if (BolusProgressDialog.stopPressed) return false rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.startingbolus))) val preferencesSpeed = sp.getInt(R.string.key_danars_bolusspeed, 0) danaPump.bolusDone = false danaPump.bolusingTreatment = t danaPump.bolusAmountToBeDelivered = insulin danaPump.bolusStopped = false danaPump.bolusStopForced = false danaPump.bolusProgressLastTimeStamp = DateUtil.now() val start = DanaRS_Packet_Bolus_Set_Step_Bolus_Start(injector, insulin, preferencesSpeed) if (carbs > 0) { // MsgSetCarbsEntry msg = new MsgSetCarbsEntry(carbTime, carbs); #### // sendMessage(msg); val msgSetHistoryEntryV2 = DanaRS_Packet_APS_Set_Event_History(injector, DanaPump.CARBS, carbTime, carbs, 0) sendMessage(msgSetHistoryEntryV2) lastHistoryFetched = min(lastHistoryFetched, carbTime - T.mins(1).msecs()) } val bolusStart = System.currentTimeMillis() if (insulin > 0) { if (!danaPump.bolusStopped) { sendMessage(start) } else { t.insulin = 0.0 return false } while (!danaPump.bolusStopped && !start.failed && !danaPump.bolusDone) { SystemClock.sleep(100) if (System.currentTimeMillis() - danaPump.bolusProgressLastTimeStamp > 15 * 1000L) { // if i didn't receive status for more than 20 sec expecting broken comm danaPump.bolusStopped = true danaPump.bolusStopForced = true aapsLogger.debug(LTag.PUMPCOMM, "Communication stopped") bleComm.disconnect("Communication stopped") } } } val bolusingEvent = EventOverviewBolusProgress bolusingEvent.t = t bolusingEvent.percent = 99 danaPump.bolusingTreatment = null var speed = 12 when (preferencesSpeed) { 0 -> speed = 12 1 -> speed = 30 2 -> speed = 60 } val bolusDurationInMSec = (insulin * speed * 1000).toLong() val expectedEnd = bolusStart + bolusDurationInMSec + 2000 while (System.currentTimeMillis() < expectedEnd) { val waitTime = expectedEnd - System.currentTimeMillis() bolusingEvent.status = String.format(resourceHelper.gs(R.string.waitingforestimatedbolusend), waitTime / 1000) rxBus.send(bolusingEvent) SystemClock.sleep(1000) } // do not call loadEvents() directly, reconnection may be needed commandQueue.loadEvents(object : Callback() { override fun run() { // reread bolus status rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.gettingbolusstatus))) sendMessage(DanaRS_Packet_Bolus_Get_Step_Bolus_Information(injector)) // last bolus bolusingEvent.percent = 100 rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.disconnecting))) } }) return !start.failed } fun bolusStop() { aapsLogger.debug(LTag.PUMPCOMM, "bolusStop >>>>> @ " + if (danaPump.bolusingTreatment == null) "" else danaPump.bolusingTreatment?.insulin) val stop = DanaRS_Packet_Bolus_Set_Step_Bolus_Stop(injector) danaPump.bolusStopForced = true if (isConnected) { sendMessage(stop) while (!danaPump.bolusStopped) { sendMessage(stop) SystemClock.sleep(200) } } else { danaPump.bolusStopped = true } } fun tempBasal(percent: Int, durationInHours: Int): Boolean { if (!isConnected) return false if (danaPump.isTempBasalInProgress) { rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) sendMessage(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector)) SystemClock.sleep(500) } rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) val msgTBR = DanaRS_Packet_Basal_Set_Temporary_Basal(injector, percent, durationInHours) sendMessage(msgTBR) SystemClock.sleep(200) sendMessage(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector)) loadEvents() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) return msgTBR.success() } fun highTempBasal(percent: Int): Boolean { if (danaPump.isTempBasalInProgress) { rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) sendMessage(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector)) SystemClock.sleep(500) } rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) val msgTBR = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(injector, percent) sendMessage(msgTBR) sendMessage(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector)) loadEvents() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) return msgTBR.success() } fun tempBasalShortDuration(percent: Int, durationInMinutes: Int): Boolean { if (durationInMinutes != 15 && durationInMinutes != 30) { aapsLogger.error(LTag.PUMPCOMM, "Wrong duration param") return false } if (danaPump.isTempBasalInProgress) { rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) sendMessage(DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector)) SystemClock.sleep(500) } rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingtempbasal))) val msgTBR = DanaRS_Packet_APS_Basal_Set_Temporary_Basal(injector, percent) sendMessage(msgTBR) sendMessage(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector)) loadEvents() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) return msgTBR.success() } fun tempBasalStop(): Boolean { if (!isConnected) return false rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingtempbasal))) val msgCancel = DanaRS_Packet_Basal_Set_Cancel_Temporary_Basal(injector) sendMessage(msgCancel) sendMessage(DanaRS_Packet_Basal_Get_Temporary_Basal_State(injector)) loadEvents() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) return msgCancel.success() } fun extendedBolus(insulin: Double, durationInHalfHours: Int): Boolean { if (!isConnected) return false rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.settingextendedbolus))) val msgExtended = DanaRS_Packet_Bolus_Set_Extended_Bolus(injector, insulin, durationInHalfHours) sendMessage(msgExtended) SystemClock.sleep(200) sendMessage(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(injector)) loadEvents() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) return msgExtended.success() } fun extendedBolusStop(): Boolean { if (!isConnected) return false rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.stoppingextendedbolus))) val msgStop = DanaRS_Packet_Bolus_Set_Extended_Bolus_Cancel(injector) sendMessage(msgStop) sendMessage(DanaRS_Packet_Bolus_Get_Extended_Bolus_State(injector)) loadEvents() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) return msgStop.success() } fun updateBasalsInPump(profile: Profile): Boolean { if (!isConnected) return false rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.updatingbasalrates))) val basal = danaPump.buildDanaRProfileRecord(profile) val msgSet = DanaRS_Packet_Basal_Set_Profile_Basal_Rate(injector, 0, basal) sendMessage(msgSet) val msgActivate = DanaRS_Packet_Basal_Set_Profile_Number(injector, 0) sendMessage(msgActivate) if (danaPump.profile24) { val msgProfile = DanaRS_Packet_Bolus_Set_24_CIR_CF_Array(injector, profile) sendMessage(msgProfile) } readPumpStatus() rxBus.send(EventPumpStatusChanged(EventPumpStatusChanged.Status.DISCONNECTING)) return msgSet.success() } fun loadHistory(type: Byte): PumpEnactResult { val result = PumpEnactResult(injector) if (!isConnected) return result var msg: DanaRS_Packet_History_? = null when (type) { RecordTypes.RECORD_TYPE_ALARM -> msg = DanaRS_Packet_History_Alarm(injector) RecordTypes.RECORD_TYPE_PRIME -> msg = DanaRS_Packet_History_Prime(injector) RecordTypes.RECORD_TYPE_BASALHOUR -> msg = DanaRS_Packet_History_Basal(injector) RecordTypes.RECORD_TYPE_BOLUS -> msg = DanaRS_Packet_History_Bolus(injector) RecordTypes.RECORD_TYPE_CARBO -> msg = DanaRS_Packet_History_Carbohydrate(injector) RecordTypes.RECORD_TYPE_DAILY -> msg = DanaRS_Packet_History_Daily(injector) RecordTypes.RECORD_TYPE_GLUCOSE -> msg = DanaRS_Packet_History_Blood_Glucose(injector) RecordTypes.RECORD_TYPE_REFILL -> msg = DanaRS_Packet_History_Refill(injector) RecordTypes.RECORD_TYPE_SUSPEND -> msg = DanaRS_Packet_History_Suspend(injector) } if (msg != null) { sendMessage(DanaRS_Packet_General_Set_History_Upload_Mode(injector, 1)) SystemClock.sleep(200) sendMessage(msg) while (!msg.done && isConnected) { SystemClock.sleep(100) } SystemClock.sleep(200) sendMessage(DanaRS_Packet_General_Set_History_Upload_Mode(injector, 0)) } result.success = msg?.success() ?: false return result } inner class LocalBinder : Binder() { val serviceInstance: DanaRSService get() = this@DanaRSService } override fun onBind(intent: Intent): IBinder { return mBinder } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { return Service.START_STICKY } private fun waitForWholeMinute() { while (true) { val time = DateUtil.now() val timeToWholeMinute = 60000 - time % 60000 if (timeToWholeMinute > 59800 || timeToWholeMinute < 300) break rxBus.send(EventPumpStatusChanged(resourceHelper.gs(R.string.waitingfortimesynchronization, (timeToWholeMinute / 1000).toInt()))) SystemClock.sleep(min(timeToWholeMinute, 100)) } } }
agpl-3.0
kickstarter/android-oss
app/src/test/java/com/kickstarter/KSRobolectricTestCase.kt
1
4097
package com.kickstarter import android.app.Application import android.content.Context import androidx.test.core.app.ApplicationProvider import com.kickstarter.libs.AnalyticEvents import com.kickstarter.libs.Environment import com.kickstarter.libs.KSCurrency import com.kickstarter.libs.KSString import com.kickstarter.libs.MockCurrentUser import com.kickstarter.libs.MockTrackingClient import com.kickstarter.libs.TrackingClientType import com.kickstarter.libs.utils.Secrets import com.kickstarter.mock.MockCurrentConfig import com.kickstarter.mock.MockExperimentsClientType import com.kickstarter.mock.factories.ConfigFactory import com.kickstarter.mock.services.MockApiClient import com.kickstarter.mock.services.MockApolloClient import com.kickstarter.mock.services.MockApolloClientV2 import com.kickstarter.mock.services.MockWebClient import com.kickstarter.models.User import com.stripe.android.Stripe import junit.framework.TestCase import org.joda.time.DateTimeUtils import org.junit.After import org.junit.Before import org.junit.runner.RunWith import org.robolectric.annotation.Config import rx.observers.TestSubscriber import kotlin.jvm.Throws @RunWith(KSRobolectricGradleTestRunner::class) @Config(shadows = [ShadowAndroidXMultiDex::class], sdk = [KSRobolectricGradleTestRunner.DEFAULT_SDK]) abstract class KSRobolectricTestCase : TestCase() { private val application: Application = ApplicationProvider.getApplicationContext() private lateinit var environment: Environment lateinit var experimentsTest: TestSubscriber<String> lateinit var segmentTrack: TestSubscriber<String> lateinit var segmentIdentify: TestSubscriber<User> @Before @Throws(Exception::class) public override fun setUp() { super.setUp() val mockCurrentConfig = MockCurrentConfig() val experimentsClientType = experimentsClient() val segmentTestClient = segmentTrackingClient(mockCurrentConfig, experimentsClientType) val component = DaggerApplicationComponent.builder() .applicationModule(TestApplicationModule(application())) .build() val config = ConfigFactory.config().toBuilder() .build() mockCurrentConfig.config(config) environment = component.environment().toBuilder() .ksCurrency(KSCurrency(mockCurrentConfig)) .apiClient(MockApiClient()) .apolloClient(MockApolloClient()) .apolloClientV2(MockApolloClientV2()) .currentConfig(mockCurrentConfig) .webClient(MockWebClient()) .stripe(Stripe(context(), Secrets.StripePublishableKey.STAGING)) .analytics(AnalyticEvents(listOf(segmentTestClient))) .optimizely(experimentsClientType) .build() } protected fun application() = this.application @After @Throws(Exception::class) public override fun tearDown() { super.tearDown() DateTimeUtils.setCurrentMillisSystem() } protected fun context(): Context = this.application().applicationContext protected fun environment() = environment protected fun ksString() = KSString(application().packageName, application().resources) private fun experimentsClient(): MockExperimentsClientType { experimentsTest = TestSubscriber() val experimentsClientType = MockExperimentsClientType() experimentsClientType.eventKeys.subscribe(experimentsTest) return experimentsClientType } private fun segmentTrackingClient(mockCurrentConfig: MockCurrentConfig, experimentsClientType: MockExperimentsClientType): MockTrackingClient { segmentTrack = TestSubscriber() segmentIdentify = TestSubscriber() val segmentTrackingClient = MockTrackingClient( MockCurrentUser(), mockCurrentConfig, TrackingClientType.Type.SEGMENT, experimentsClientType ) segmentTrackingClient.eventNames.subscribe(segmentTrack) segmentTrackingClient.identifiedUser.subscribe(segmentIdentify) return segmentTrackingClient } }
apache-2.0
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/extensions/Animal-Extensions.kt
1
650
package com.habitrpg.android.habitica.extensions import android.content.Context import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.models.inventory.Animal fun Animal.getTranslatedType(c: Context?): String { if (c == null) { return type } var currType: String = when (type) { "drop" -> c?.getString(R.string.standard).toString() "quest" -> c?.getString(R.string.quest).toString() "wacky" -> c?.getString(R.string.wacky).toString() "special" -> c?.getString(R.string.special).toString() else -> { type } } return currType }
gpl-3.0
cout970/Modeler
src/main/kotlin/com/cout970/modeler/util/collections/FloatArrayList.kt
1
6994
package com.cout970.modeler.util.collections import java.util.* /** * Created by cout970 on 2017/05/17. */ fun listOf(vararg values: Float) = FloatArrayList(values) class FloatArrayList internal constructor(private var array: FloatArray) : MutableList<Float>, RandomAccess { override var size: Int = 0 private set private var modCount = 0 constructor(capacity: Int = 10) : this(FloatArray(capacity)) internal fun internalArray(): FloatArray = array override fun contains(element: Float): Boolean { repeat(size) { if (array[it] == element) return true } return false } override fun containsAll(elements: Collection<Float>): Boolean { return elements.all { contains(it) } } override fun get(index: Int): Float { require(index in 0 until size) { "Index $index outside bounds (0, $size)" } return array[index] } override fun indexOf(element: Float): Int { repeat(size) { if (array[it] == element) return it } return -1 } override fun isEmpty(): Boolean = size == 0 override fun iterator(): MutableIterator<Float> = Itr() override fun lastIndexOf(element: Float): Int { repeat(size) { i -> val index = (size - 1) - i if (array[index] == element) return index } return -1 } override fun add(element: Float): Boolean { modCount++ if (array.size == size) { growArray() } array[size] = element size++ return true } private fun growArray() { val newArray = FloatArray(array.size * 2) System.arraycopy(array, 0, newArray, 0, array.size) array = newArray } override fun add(index: Int, element: Float) { require(index in 0 until size) { "Index $index outside bounds (0, $size)" } modCount++ array[index] = element } override fun set(index: Int, element: Float): Float { require(index in 0 until size) { "Index $index outside bounds (0, $size)" } modCount++ val old = array[index] array[index] = element return old } override fun addAll(index: Int, elements: Collection<Float>): Boolean { elements.forEachIndexed { pos, fl -> if (pos + index in 0 until size) { set(pos + index, fl) } else { add(fl) } } return true } override fun addAll(elements: Collection<Float>): Boolean { elements.forEach { add(it) } return true } override fun clear() { modCount++ size = 0 } override fun listIterator(): MutableListIterator<Float> = listIterator(0) override fun listIterator(index: Int): MutableListIterator<Float> = ListItr(index) override fun remove(element: Float): Boolean { val index = indexOf(element) if (index != -1) { removeAt(index) return true } return false } override fun removeAll(elements: Collection<Float>): Boolean { return elements.map { remove(it) }.any() } override fun removeAt(index: Int): Float { modCount++ val oldValue = array[index] val numMoved = size - index - 1 if (numMoved > 0) System.arraycopy(array, index + 1, array, index, numMoved) size-- return oldValue } override fun retainAll(elements: Collection<Float>): Boolean { val oldSize = size elements.forEach { remove(it) } return oldSize != size } override fun subList(fromIndex: Int, toIndex: Int): MutableList<Float> { require(fromIndex in 0 until size) { "FromIndex $fromIndex outside bounds [0, $size)" } require(toIndex in 0 until size) { "ToIndex $toIndex outside bounds [0, $size)" } return array.toMutableList().subList(fromIndex, toIndex) } private open inner class Itr : MutableIterator<Float>, FloatIterator() { internal var cursor: Int = 0 internal var lastRet = -1 internal var expectedModCount = modCount override fun hasNext(): Boolean { return cursor != size } override fun nextFloat(): Float { checkForComodification() val i = cursor if (i >= size) throw NoSuchElementException() val elementData = array if (i >= elementData.size) throw ConcurrentModificationException() cursor = i + 1 lastRet = i return elementData[i] } override fun remove() { if (lastRet < 0) throw IllegalStateException() checkForComodification() try { [email protected](lastRet) cursor = lastRet lastRet = -1 expectedModCount = modCount } catch (ex: IndexOutOfBoundsException) { throw ConcurrentModificationException() } } internal fun checkForComodification() { if (modCount != expectedModCount) throw ConcurrentModificationException() } } private inner class ListItr internal constructor(index: Int) : Itr(), MutableListIterator<Float> { init { cursor = index } override fun hasPrevious(): Boolean { return cursor != 0 } override fun previous(): Float { checkForComodification() try { val i = cursor - 1 val previous = get(i) cursor = i lastRet = cursor return previous } catch (e: IndexOutOfBoundsException) { checkForComodification() throw NoSuchElementException() } } override fun nextIndex(): Int { return cursor } override fun previousIndex(): Int { return cursor - 1 } override fun set(element: Float) { if (lastRet < 0) throw IllegalStateException() checkForComodification() try { this@FloatArrayList[lastRet] = element expectedModCount = modCount } catch (ex: IndexOutOfBoundsException) { throw ConcurrentModificationException() } } override fun add(element: Float) { checkForComodification() try { val i = cursor [email protected](i, element) lastRet = -1 cursor = i + 1 expectedModCount = modCount } catch (ex: IndexOutOfBoundsException) { throw ConcurrentModificationException() } } } }
gpl-3.0
cout970/Modeler
src/main/kotlin/com/cout970/modeler/core/animation/Animation.kt
1
4543
package com.cout970.modeler.core.animation import com.cout970.modeler.api.animation.* import com.cout970.modeler.api.model.IModel import com.cout970.modeler.api.model.ITransformation import com.cout970.modeler.api.model.`object`.RootGroupRef import com.cout970.modeler.core.model.TRTSTransformation import java.util.* /** * Created by cout970 on 2017/08/20. */ data class AnimationRef(override val id: UUID) : IAnimationRef object AnimationRefNone : IAnimationRef { override val id: UUID = UUID.fromString("94ca9fb4-bf93-4423-b27a-6b7320b1727a") } data class Animation( override val channels: Map<IChannelRef, IChannel>, override val channelMapping: Map<IChannelRef, AnimationTarget>, override val timeLength: Float, override val name: String, override val id: UUID = UUID.randomUUID() ) : IAnimation { override fun withName(name: String): IAnimation = copy(name = name) override fun withChannel(channel: IChannel): IAnimation { return copy(channels = channels + (channel.ref to channel)) } override fun withTimeLength(newLength: Float): IAnimation { return copy(timeLength = newLength) } override fun withMapping(channel: IChannelRef, target: AnimationTarget): IAnimation { require(target !is AnimationTargetGroup || target.ref != RootGroupRef) { "Cannot apply animation to the root group" } return copy(channelMapping = channelMapping + Pair(channel, target)) } override fun removeChannels(list: List<IChannelRef>): IAnimation { return copy(channels = channels.filterKeys { it !in list }) } override fun plus(other: IAnimation): IAnimation { return copy(channels = channels + other.channels) } companion object { fun of( name: String = "Animation", timeLength: Float = 1f, channels: Map<IChannelRef, IChannel> = emptyMap(), channelMapping: Map<IChannelRef, AnimationTarget> = emptyMap() ): IAnimation { return Animation( channels = channels, channelMapping = channelMapping, name = name, timeLength = timeLength ) } } } data class ChannelRef(override val id: UUID) : IChannelRef data class Channel( override val name: String, override val interpolation: InterpolationMethod, override val keyframes: List<IKeyframe>, override val enabled: Boolean = true, override val type: ChannelType = ChannelType.TRANSLATION, override val id: UUID = UUID.randomUUID() ) : IChannel { override fun withName(name: String): IChannel = copy(name = name) override fun withEnable(enabled: Boolean): IChannel = copy(enabled = enabled) override fun withInterpolation(method: InterpolationMethod): IChannel = copy(interpolation = method) override fun withKeyframes(keyframes: List<IKeyframe>): IChannel = copy(keyframes = keyframes) override fun withType(type: ChannelType): IChannel = copy(type = type) } data class Keyframe( override val time: Float, override val value: TRTSTransformation ) : IKeyframe { override fun withValue(trs: TRTSTransformation): IKeyframe = copy(value = trs) override fun withTime(time: Float): IKeyframe = copy(time = time) } inline val IChannel.ref: IChannelRef get() = ChannelRef(id) inline val IAnimation.ref: IAnimationRef get() = AnimationRef(id) object AnimationNone : IAnimation { override val id: UUID get() = AnimationRefNone.id override val name: String get() = "None" override val channels: Map<IChannelRef, IChannel> get() = emptyMap() override val channelMapping: Map<IChannelRef, AnimationTarget> get() = emptyMap() override val timeLength: Float get() = 1f override fun withName(name: String): IAnimation = this override fun withChannel(channel: IChannel): IAnimation = this override fun withTimeLength(newLength: Float): IAnimation = this override fun withMapping(channel: IChannelRef, target: AnimationTarget): IAnimation = this override fun removeChannels(list: List<IChannelRef>): IAnimation = this override fun plus(other: IAnimation): IAnimation = other } fun AnimationTarget.getTransformation(model: IModel): ITransformation { return when (this) { is AnimationTargetGroup -> model.getGroup(ref).transform // TODO is AnimationTargetObject -> model.getObject(refs.first()).transformation } }
gpl-3.0
kickstarter/android-oss
app/src/main/java/com/kickstarter/ui/ArgumentsKey.kt
1
661
package com.kickstarter.ui object ArgumentsKey { const val CANCEL_PLEDGE_PROJECT = "com.kickstarter.ui.fragments.CancelPledgeFragment.project" const val DISCOVERY_SORT_POSITION = "argument_discovery_position" const val NEW_CARD_MODAL = "com.kickstarter.ui.fragments.NewCardFragment.modal" const val NEW_CARD_PROJECT = "com.kickstarter.ui.fragments.NewCardFragment.project" const val PLEDGE_PLEDGE_DATA = "com.kickstarter.ui.fragments.PledgeFragment.pledge_data" const val PLEDGE_PLEDGE_REASON = "com.kickstarter.ui.fragments.PledgeFragment.pledge_reason" const val PROJECT_PAGER_POSITION = "com.kickstarter.ui.fragments.position" }
apache-2.0
siosio/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/fir/highlighter/HighlightingUtils.kt
1
3117
/* * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.fir.highlighter import com.intellij.lang.jvm.JvmModifier import com.intellij.openapi.editor.colors.TextAttributesKey import com.intellij.psi.* import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.isAbstract import org.jetbrains.kotlin.psi.psiUtil.isExtensionDeclaration import org.jetbrains.kotlin.idea.highlighter.KotlinHighlightingColors as Colors internal fun textAttributesKeyForPropertyDeclaration(declaration: PsiElement): TextAttributesKey? = when (declaration) { is KtProperty -> textAttributesForKtPropertyDeclaration(declaration) is KtParameter -> textAttributesForKtParameterDeclaration(declaration) is PsiLocalVariable -> Colors.LOCAL_VARIABLE is PsiParameter -> Colors.PARAMETER is PsiField -> Colors.INSTANCE_PROPERTY else -> null } internal fun textAttributesForKtParameterDeclaration(parameter: KtParameter) = if (parameter.valOrVarKeyword != null) Colors.INSTANCE_PROPERTY else Colors.PARAMETER internal fun textAttributesForKtPropertyDeclaration(property: KtProperty): TextAttributesKey? = when { property.isExtensionDeclaration() -> Colors.EXTENSION_PROPERTY property.isLocal -> Colors.LOCAL_VARIABLE property.isTopLevel -> { if (property.isCustomPropertyDeclaration()) Colors.PACKAGE_PROPERTY_CUSTOM_PROPERTY_DECLARATION else Colors.PACKAGE_PROPERTY } else -> { if (property.isCustomPropertyDeclaration()) Colors.INSTANCE_PROPERTY_CUSTOM_PROPERTY_DECLARATION else Colors.INSTANCE_PROPERTY } } private fun KtProperty.isCustomPropertyDeclaration() = getter?.bodyExpression != null || setter?.bodyExpression != null @Suppress("UnstableApiUsage") internal fun textAttributesKeyForTypeDeclaration(declaration: PsiElement): TextAttributesKey? = when { declaration is KtTypeParameter || declaration is PsiTypeParameter -> Colors.TYPE_PARAMETER declaration is KtTypeAlias -> Colors.TYPE_ALIAS declaration is KtClass -> textAttributesForClass(declaration) declaration is PsiClass && declaration.isInterface && !declaration.isAnnotationType -> Colors.TRAIT declaration.isAnnotationClass() -> Colors.ANNOTATION declaration is KtObjectDeclaration -> Colors.OBJECT declaration is PsiEnumConstant -> Colors.ENUM_ENTRY declaration is PsiClass && declaration.hasModifier(JvmModifier.ABSTRACT) -> Colors.ABSTRACT_CLASS declaration is PsiClass -> Colors.CLASS else -> null } fun textAttributesForClass(klass: KtClass): TextAttributesKey = when { klass.isInterface() -> Colors.TRAIT klass.isAnnotation() -> Colors.ANNOTATION klass.isEnum() -> Colors.ENUM klass is KtEnumEntry -> Colors.ENUM_ENTRY klass.isAbstract() -> Colors.ABSTRACT_CLASS else -> Colors.CLASS } internal fun PsiElement.isAnnotationClass() = this is KtClass && isAnnotation() || this is PsiClass && isAnnotationType
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/intentions/convertForEachToForLoop/complexReceiver.kt
4
87
// WITH_RUNTIME fun main() { val x = 1..4 x.reversed().forEach<caret> { it } }
apache-2.0
BijoySingh/Quick-Note-Android
base/src/main/java/com/maubis/scarlet/base/config/auth/IAuthenticator.kt
1
709
package com.maubis.scarlet.base.config.auth import android.content.Context import com.maubis.scarlet.base.support.ui.ThemedActivity interface IAuthenticator { fun setup(context: Context) fun isLoggedIn(context: Context): Boolean fun isLegacyLoggedIn(): Boolean fun userId(context: Context): String? fun openLoginActivity(context: Context): Runnable? fun openForgetMeActivity(context: Context): Runnable? fun openTransferDataActivity(context: Context): Runnable? fun openLogoutActivity(context: Context): Runnable? fun setPendingUploadListener(listener: IPendingUploadListener?) fun showPendingSync(activity: ThemedActivity) fun requestSync(forced: Boolean) fun logout() }
gpl-3.0
jwren/intellij-community
plugins/kotlin/completion/tests/testData/keywords/CompanionObjectBeforeObject.kt
10
111
// FIR_IDENTICAL // FIR_COMPARISON class TestClass { <caret> object O {} } // EXIST: companion object
apache-2.0
stefanmedack/cccTV
app/src/main/java/de/stefanmedack/ccctv/ui/detail/DetailViewModel.kt
1
4503
package de.stefanmedack.ccctv.ui.detail import de.stefanmedack.ccctv.persistence.entities.Event import de.stefanmedack.ccctv.repository.EventRepository import de.stefanmedack.ccctv.ui.base.BaseDisposableViewModel import de.stefanmedack.ccctv.ui.detail.uiModels.DetailUiModel import de.stefanmedack.ccctv.ui.detail.uiModels.SpeakerUiModel import de.stefanmedack.ccctv.ui.detail.uiModels.VideoPlaybackUiModel import de.stefanmedack.ccctv.util.EMPTY_STRING import de.stefanmedack.ccctv.util.getRelatedEventGuidsWeighted import io.reactivex.Completable import io.reactivex.Flowable import io.reactivex.Single import io.reactivex.rxkotlin.Singles import io.reactivex.rxkotlin.subscribeBy import io.reactivex.rxkotlin.withLatestFrom import io.reactivex.subjects.PublishSubject import timber.log.Timber import javax.inject.Inject import info.metadude.kotlin.library.c3media.models.Event as EventRemote class DetailViewModel @Inject constructor( private val repository: EventRepository ) : BaseDisposableViewModel(), Inputs, Outputs { internal val inputs: Inputs = this internal val outputs: Outputs = this private var eventId: String = EMPTY_STRING fun init(eventId: String) { this.eventId = eventId disposables.addAll( doToggleBookmark.subscribeBy(onError = { Timber.w("DetailViewModel - doToggleBookmark - onError $it") }), doSavePlayedSeconds.subscribeBy(onError = { Timber.w("DetailViewModel - doSavePlayedSeconds - onError $it") }) ) } //<editor-fold desc="Inputs"> override fun toggleBookmark() { bookmarkClickStream.onNext(0) } override fun savePlaybackPosition(playedSeconds: Int, totalDurationSeconds: Int) { savePlayPositionStream.onNext(PlaybackData(playedSeconds, totalDurationSeconds)) } //</editor-fold> //<editor-fold desc="Outputs"> override val detailData: Single<DetailUiModel> get() = Singles.zip( eventWithRelated.firstOrError(), wasPlayed, { first, wasPlayed -> first.copy(wasPlayed = wasPlayed) }) override val videoPlaybackData: Single<VideoPlaybackUiModel> get() = Singles.zip( repository.getEventWithRecordings(eventId), repository.getPlayedSeconds(eventId), ::VideoPlaybackUiModel) override val isBookmarked: Flowable<Boolean> get() = repository.isBookmarked(eventId) //</editor-fold> private val bookmarkClickStream = PublishSubject.create<Int>() private val savePlayPositionStream = PublishSubject.create<PlaybackData>() private val doToggleBookmark get() = bookmarkClickStream .withLatestFrom(isBookmarked.toObservable(), { _, t2 -> t2 }) .flatMapCompletable { updateBookmarkState(it) } private val doSavePlayedSeconds get() = savePlayPositionStream .flatMapCompletable { if (it.hasPlayedMinimumToSave() && !it.hasAlmostFinished()) { repository.savePlayedSeconds(eventId, it.playedSeconds) } else { repository.deletePlayedSeconds(eventId) } } private val eventWithRelated: Flowable<DetailUiModel> get() = repository.getEvent(eventId) .flatMap { event -> getRelatedEvents(event).map { DetailUiModel(event = event, speaker = event.persons.map { SpeakerUiModel(it) }, related = it) } } private fun getRelatedEvents(event: Event): Flowable<List<Event>> = repository.getEvents(event.getRelatedEventGuidsWeighted()) private val wasPlayed: Single<Boolean> get() = repository.getPlayedSeconds(eventId).map { it > 0 } private fun updateBookmarkState(isBookmarked: Boolean): Completable = repository.changeBookmarkState(eventId, !isBookmarked) private data class PlaybackData( val playedSeconds: Int, val totalDurationSeconds: Int ) { private val MINIMUM_PLAYBACK_SECONDS_TO_SAVE = 60 private val MAXIMUM_PLAYBACK_PERCENT_TO_SAVE = .9f fun hasPlayedMinimumToSave(): Boolean = this.playedSeconds > MINIMUM_PLAYBACK_SECONDS_TO_SAVE fun hasAlmostFinished(): Boolean = when { totalDurationSeconds > 0 -> (playedSeconds.toFloat() / totalDurationSeconds.toFloat()) > MAXIMUM_PLAYBACK_PERCENT_TO_SAVE else -> true } } }
apache-2.0
jwren/intellij-community
plugins/kotlin/jvm-debugger/coroutines/src/org/jetbrains/kotlin/idea/debugger/coroutine/view/CoroutineViewDebugSessionListener.kt
4
2028
// 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.debugger.coroutine.view import com.intellij.debugger.engine.SuspendContextImpl import com.intellij.xdebugger.XDebugSession import com.intellij.xdebugger.XDebugSessionListener import com.intellij.xdebugger.frame.XSuspendContext import com.intellij.xdebugger.impl.ui.DebuggerUIUtil import org.jetbrains.kotlin.idea.debugger.coroutine.util.logger import org.jetbrains.kotlin.idea.util.application.isUnitTestMode class CoroutineViewDebugSessionListener( private val session: XDebugSession, private val coroutineView: CoroutineView ) : XDebugSessionListener { val log by logger override fun sessionPaused() { val suspendContext = session.suspendContext ?: return requestClear() coroutineView.alarm.cancel() renew(suspendContext) } override fun sessionResumed() { coroutineView.saveState() val suspendContext = session.suspendContext ?: return requestClear() renew(suspendContext) } override fun sessionStopped() { val suspendContext = session.suspendContext ?: return requestClear() renew(suspendContext) } override fun stackFrameChanged() { coroutineView.saveState() } override fun beforeSessionResume() { } override fun settingsChanged() { val suspendContext = session.suspendContext ?: return requestClear() renew(suspendContext) } private fun renew(suspendContext: XSuspendContext) { if (suspendContext is SuspendContextImpl) { DebuggerUIUtil.invokeLater { coroutineView.renewRoot(suspendContext) } } } private fun requestClear() { if (isUnitTestMode()) { // no delay in tests coroutineView.resetRoot() } else { coroutineView.alarm.cancelAndRequest() } } }
apache-2.0
jwren/intellij-community
platform/statistics/src/com/intellij/internal/statistic/beans/MetricEventUtil.kt
3
7276
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.internal.statistic.beans import com.intellij.internal.statistic.eventLog.FeatureUsageData import com.intellij.internal.statistic.eventLog.events.EventField import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.EventPair import com.intellij.internal.statistic.eventLog.events.VarargEventId import com.intellij.openapi.util.Comparing import org.jetbrains.annotations.ApiStatus /** * Reports numerical or string value of the setting if it's not default. */ @ApiStatus.ScheduledForRemoval @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Any>, eventId: String) { addIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, null) } /** * Reports numerical or string value of the setting if it's not default. */ @ApiStatus.ScheduledForRemoval @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Any>, eventId: String, data: FeatureUsageData?) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { when (it) { is Int -> newMetric(eventId, it, data) is Float -> newMetric(eventId, it, data) else -> newMetric(eventId, it.toString(), data) } } } /** * Reports the value of boolean setting (i.e. enabled or disabled) if it's not default. */ @ApiStatus.ScheduledForRemoval @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addBoolIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Boolean>, eventId: String) { addBoolIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, null) } /** * Reports the value of boolean setting (i.e. enabled or disabled) if it's not default. */ @ApiStatus.ScheduledForRemoval @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addBoolIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Boolean>, eventId: String, data: FeatureUsageData?) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newBooleanMetric(eventId, it, data) } } /** * Adds counter value if count is greater than 0 */ @ApiStatus.ScheduledForRemoval @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addCounterIfNotZero(set: MutableSet<in MetricEvent>, eventId: String, count: Int) { if (count > 0) { set.add(newCounterMetric(eventId, count)) } } /** * Adds counter value if count is greater than 0 */ @ApiStatus.ScheduledForRemoval @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addCounterIfNotZero(set: MutableSet<in MetricEvent>, eventId: String, count: Int, data: FeatureUsageData?) { if (count > 0) { set.add(newCounterMetric(eventId, count, data)) } } @ApiStatus.ScheduledForRemoval @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addCounterIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Int>, eventId: String) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newCounterMetric(eventId, it) } } @ApiStatus.ScheduledForRemoval @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addCounterIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, Int>, eventId: String, data: FeatureUsageData?) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newCounterMetric(eventId, it, data) } } @ApiStatus.ScheduledForRemoval @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T, V : Enum<*>> addEnumIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: Function1<T, V>, eventId: String) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { newMetric(eventId, it, null) } } fun <T, V> addMetricIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: (T) -> V, eventIdFunc: (V) -> MetricEvent) { val value = valueFunction(settingsBean) val defaultValue = valueFunction(defaultSettingsBean) if (!Comparing.equal(value, defaultValue)) { set.add(eventIdFunc(value)) } } interface MetricDifferenceBuilder<T> { fun add(eventId: String, valueFunction: (T) -> Any) fun addBool(eventId: String, valueFunction: (T) -> Boolean) } @ApiStatus.ScheduledForRemoval @Deprecated("Use EventLogGroup#registerEvent and EventId#metric instead") fun <T> addMetricsIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, data: FeatureUsageData, callback: MetricDifferenceBuilder<T>.() -> Unit) { callback(object : MetricDifferenceBuilder<T> { override fun add(eventId: String, valueFunction: (T) -> Any) { addIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, data) } override fun addBool(eventId: String, valueFunction: (T) -> Boolean) { addBoolIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, data) } }) } @JvmOverloads fun <T> addBoolIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: (T) -> Boolean, eventId: VarargEventId, data: MutableList<EventPair<*>>? = null) { addIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction, eventId, EventFields.Enabled, data) } @JvmOverloads fun <T, V> addIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T, valueFunction: (T) -> V, eventId: VarargEventId, field: EventField<V>, data: MutableList<EventPair<*>>? = null) { addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) { val fields = data ?: mutableListOf() fields.add(field.with(it)) eventId.metric(fields) } } /** * Adds counter value if count is greater than 0 */ fun <T> addCounterIfNotZero(set: MutableSet<in MetricEvent>, eventId: VarargEventId, count: Int) { if (count > 0) { set.add(eventId.metric(EventFields.Count.with(count))) } } /** * Adds counter value if count is greater than 0 */ fun <T> addCounterIfNotZero(set: MutableSet<in MetricEvent>, eventId: VarargEventId, count: Int, data: MutableList<EventPair<*>>? = null) { if (count > 0) { val fields = data ?: mutableListOf() fields.add(EventFields.Count.with(count)) eventId.metric(fields) } }
apache-2.0
jwren/intellij-community
plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/SearchEverywhereMlSearchState.kt
1
3421
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions.searcheverywhere.ml import com.intellij.ide.actions.searcheverywhere.SearchEverywhereContributor import com.intellij.ide.actions.searcheverywhere.SearchRestartReason import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereElementFeaturesProvider import com.intellij.ide.actions.searcheverywhere.ml.features.SearchEverywhereStateFeaturesProvider import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereModelProvider import com.intellij.ide.actions.searcheverywhere.ml.model.SearchEverywhereRankingModel import com.intellij.internal.statistic.eventLog.events.EventPair internal class SearchEverywhereMlSearchState( val sessionStartTime: Long, val searchStartTime: Long, val searchIndex: Int, val searchStartReason: SearchRestartReason, val tabId: String, val keysTyped: Int, val backspacesTyped: Int, private val searchQuery: String, private val modelProvider: SearchEverywhereModelProvider, private val providersCaches: Map<Class<out SearchEverywhereElementFeaturesProvider>, Any> ) { private val cachedElementsInfo: MutableMap<Int, SearchEverywhereMLItemInfo> = hashMapOf() private val cachedMLWeight: MutableMap<Int, Double> = hashMapOf() val searchStateFeatures = SearchEverywhereStateFeaturesProvider().getSearchStateFeatures(tabId, searchQuery) private val model: SearchEverywhereRankingModel by lazy { SearchEverywhereRankingModel(modelProvider.getModel(tabId)) } @Synchronized fun getElementFeatures(elementId: Int, element: Any, contributor: SearchEverywhereContributor<*>, priority: Int): SearchEverywhereMLItemInfo { return cachedElementsInfo.computeIfAbsent(elementId) { val features = arrayListOf<EventPair<*>>() val contributorId = contributor.searchProviderId SearchEverywhereElementFeaturesProvider.getFeatureProvidersForContributor(contributorId).forEach { provider -> val cache = providersCaches[provider::class.java] features.addAll(provider.getElementFeatures(element, sessionStartTime, searchQuery, priority, cache)) } return@computeIfAbsent SearchEverywhereMLItemInfo(elementId, contributorId, features) } } @Synchronized fun getMLWeightIfDefined(elementId: Int): Double? { return cachedMLWeight[elementId] } @Synchronized fun getMLWeight(elementId: Int, element: Any, contributor: SearchEverywhereContributor<*>, context: SearchEverywhereMLContextInfo, priority: Int): Double { return cachedMLWeight.computeIfAbsent(elementId) { val features = ArrayList<EventPair<*>>() features.addAll(context.features) features.addAll(getElementFeatures(elementId, element, contributor, priority).features) features.addAll(searchStateFeatures) model.predict(features.associate { it.field.name to it.data }) } } } internal data class SearchEverywhereMLItemInfo(val id: Int, val contributorId: String, val features: List<EventPair<*>>) { fun featuresAsMap(): Map<String, Any> = features.mapNotNull { val data = it.data if (data == null) null else it.field.name to data }.toMap() }
apache-2.0
DevPicon/kotlin-marvel-hero-finder
app/src/main/kotlin/pe/devpicon/android/marvelheroes/app/MarvelHeroesApp.kt
1
272
package pe.devpicon.android.marvelheroes.app import android.app.Application class MarvelHeroesApp : Application() { lateinit var appContainer: AppContainer override fun onCreate() { super.onCreate() appContainer = AppContainer(this) } }
mit
google/j2cl
transpiler/java/com/google/j2cl/transpiler/backend/kotlin/common/Sets.kt
1
836
/* * Copyright 2022 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.j2cl.transpiler.backend.kotlin.common // TODO(b/204366308): Remove when the corresponding function in Kotlin stdlib is standarized. fun <V> buildSet(fn: MutableSet<V>.() -> Unit): Set<V> = mutableSetOf<V>().apply(fn).toSet()
apache-2.0
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/NumberConversionFix.kt
1
3893
// 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.quickfix import com.intellij.codeInsight.intention.IntentionAction import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import org.jetbrains.kotlin.config.ApiVersion import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.psi.psiUtil.endOffset import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.isNullable import org.jetbrains.kotlin.types.typeUtil.* class NumberConversionFix( element: KtExpression, fromType: KotlinType, toType: KotlinType, private val disableIfAvailable: IntentionAction? = null, private val enableNullableType: Boolean = false, private val intentionText: (String) -> String = { KotlinBundle.message("convert.expression.to.0", it) } ) : KotlinQuickFixAction<KtExpression>(element) { private val isConversionAvailable = fromType != toType && fromType.isNumberType() && toType.isNumberType() private val typePresentation = IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_NO_ANNOTATIONS.renderType(toType.makeNotNullable()) private val fromInt = fromType.isInt() private val fromChar = fromType.isChar() private val fromFloatOrDouble = fromType.isFloat() || fromType.isDouble() private val fromNullable = fromType.isNullable() private val toChar = toType.isChar() private val toInt = toType.isInt() private val toByteOrShort = toType.isByte() || toType.isShort() private fun KotlinType.isNumberType(): Boolean { val type = if (enableNullableType) this.makeNotNullable() else this return type.isSignedOrUnsignedNumberType() } override fun isAvailable(project: Project, editor: Editor?, file: KtFile) = disableIfAvailable?.isAvailable(project, editor, file) != true && isConversionAvailable override fun getFamilyName() = KotlinBundle.message("insert.number.conversion") override fun getText() = intentionText(typePresentation) override fun invoke(project: Project, editor: Editor?, file: KtFile) { val element = element ?: return val psiFactory = KtPsiFactory(project) val apiVersion = element.languageVersionSettings.apiVersion val dot = if (fromNullable) "?." else "." val expressionToInsert = when { fromChar && apiVersion >= ApiVersion.KOTLIN_1_5 -> if (toInt) { psiFactory.createExpressionByPattern("$0${dot}code", element) } else { psiFactory.createExpressionByPattern("$0${dot}code${dot}to$1()", element, typePresentation) } !fromInt && toChar && apiVersion >= ApiVersion.KOTLIN_1_5 -> psiFactory.createExpressionByPattern("$0${dot}toInt()${dot}toChar()", element) fromFloatOrDouble && toByteOrShort && apiVersion >= ApiVersion.KOTLIN_1_3 -> psiFactory.createExpressionByPattern("$0${dot}toInt()${dot}to$1()", element, typePresentation) else -> psiFactory.createExpressionByPattern("$0${dot}to$1()", element, typePresentation) } val newExpression = element.replaced(expressionToInsert) editor?.caretModel?.moveToOffset(newExpression.endOffset) } }
apache-2.0
taigua/exercism
kotlin/space-age/src/main/kotlin/SpaceAge.kt
1
857
class SpaceAge(val seconds: Long) { companion object { val EARTH_RATIO = 31557600.0 val MERCURY_RATIO = 0.2408467 val VENUS_RATIO = 0.61519726 val MARS_RATIO = 1.8808158 val JUPITER_RATIO = 11.862615 val SATURN_RATIO = 29.447498 val URANUS_RATIO = 84.016846 val NEPTUNE_RATIO = 164.79132 fun round(v: Double) = Math.round(v * 100) / 100.0 } private val earth = seconds / EARTH_RATIO fun onEarth() = round(earth) fun onMercury() = round(earth / MERCURY_RATIO) fun onVenus() = round(earth / VENUS_RATIO) fun onMars() = round(earth / MARS_RATIO) fun onJupiter() = round(earth / JUPITER_RATIO) fun onSaturn() = round(earth / SATURN_RATIO) fun onUranus() = round(earth / URANUS_RATIO) fun onNeptune() = round(earth / NEPTUNE_RATIO) }
mit
ebean-orm/avaje-ebeanorm-examples
e-kotlin-maven/src/main/java/org/example/domain/BaseModel.kt
1
838
package org.example.domain; import com.avaje.ebean.Model import com.avaje.ebean.annotation.WhenCreated import com.avaje.ebean.annotation.WhenModified import java.sql.Timestamp; import javax.persistence.Id; import javax.persistence.MappedSuperclass; import javax.persistence.Version; /** * Base domain object with Id, version, whenCreated and whenUpdated. * * <p> * Extending Model to enable the 'active record' style. * * <p> * whenCreated and whenUpdated are generally useful for maintaining external search services (like * elasticsearch) and audit. */ @MappedSuperclass public abstract class BaseModel : Model() { @Id public var id: Long? = null @Version public var version: Long? = null @WhenCreated public var whenCreated: Timestamp? = null @WhenModified public var whenModified: Timestamp? = null }
apache-2.0
sheungon/SotwtmSupportLib
lib-sotwtm-support/src/main/kotlin/com/sotwtm/support/activity/OnAppLocaleChangedListener.kt
1
525
package com.sotwtm.support.activity import android.content.SharedPreferences import com.sotwtm.support.SotwtmSupportLib import com.sotwtm.util.Log abstract class OnAppLocaleChangedListener : SharedPreferences.OnSharedPreferenceChangeListener { override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) { if (key == SotwtmSupportLib.PREF_KEY_APP_LOCALE) { Log.d("Locale changed") onAppLocalChange() } } abstract fun onAppLocalChange() }
apache-2.0
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/extensions/RecyclerViewExt.kt
1
343
package com.sedsoftware.yaptalker.presentation.extensions import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView fun RecyclerView.visibleItemPosition(): Int { val layoutManager = this.layoutManager as? LinearLayoutManager return layoutManager?.findFirstVisibleItemPosition() ?: -1 }
apache-2.0
djkovrik/YapTalker
app/src/main/java/com/sedsoftware/yaptalker/presentation/feature/blacklist/BlacklistActivity.kt
1
3887
package com.sedsoftware.yaptalker.presentation.feature.blacklist import android.content.Context import android.content.Intent import android.os.Bundle import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import android.view.Menu import android.view.MenuItem import androidx.core.view.isVisible import com.afollestad.materialdialogs.MaterialDialog import com.arellomobile.mvp.presenter.InjectPresenter import com.arellomobile.mvp.presenter.ProvidePresenter import com.sedsoftware.yaptalker.R import com.sedsoftware.yaptalker.common.annotation.LayoutResource import com.sedsoftware.yaptalker.presentation.base.BaseActivity import com.sedsoftware.yaptalker.presentation.delegate.MessagesDelegate import com.sedsoftware.yaptalker.presentation.extensions.string import com.sedsoftware.yaptalker.presentation.feature.blacklist.adapter.BlacklistAdapter import com.sedsoftware.yaptalker.presentation.model.base.BlacklistedTopicModel import kotlinx.android.synthetic.main.activity_blacklist.blacklisted_topics import kotlinx.android.synthetic.main.activity_blacklist.empty_label import kotlinx.android.synthetic.main.include_main_appbar.toolbar import javax.inject.Inject @LayoutResource(R.layout.activity_blacklist) class BlacklistActivity : BaseActivity(), BlacklistView { companion object { fun getIntent(ctx: Context): Intent = Intent(ctx, BlacklistActivity::class.java) } @Inject lateinit var blacklistAdapter: BlacklistAdapter @Inject lateinit var messagesDelegate: MessagesDelegate @Inject @InjectPresenter lateinit var presenter: BlacklistPresenter @ProvidePresenter fun providePresenter() = presenter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) with(blacklisted_topics) { val linearLayout = LinearLayoutManager(context) layoutManager = linearLayout adapter = blacklistAdapter addItemDecoration( DividerItemDecoration( context, DividerItemDecoration.VERTICAL ) ) setHasFixedSize(true) } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_blacklist, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.action_delete_all -> { presenter.clearBlacklist() true } R.id.action_delete_month -> { presenter.clearBlacklistMonthOld() true } else -> super.onOptionsItemSelected(item) } override fun showBlacklistedTopics(topics: List<BlacklistedTopicModel>) { if (topics.isNotEmpty()) { blacklisted_topics.isVisible = true empty_label.isVisible = false blacklistAdapter.setTopics(topics) } else { blacklisted_topics.isVisible = false empty_label.isVisible = true } } override fun showDeleteConfirmationDialog(topicId: Int) { MaterialDialog.Builder(this) .content(R.string.msg_blacklist_request_deletion) .positiveText(R.string.msg_blacklist_confirm_delete) .negativeText(R.string.msg_blacklist_confirm_no) .onPositive { _, _ -> presenter.deleteTopicFromBlacklist(topicId) } .show() } override fun showErrorMessage(message: String) { messagesDelegate.showMessageError(message) } override fun updateCurrentUiState() { supportActionBar?.title = string(R.string.title_blacklist) } }
apache-2.0
OnyxDevTools/onyx-database-parent
onyx-database/src/main/kotlin/com/onyx/persistence/collections/LazyQueryCollection.kt
1
8301
package com.onyx.persistence.collections import com.onyx.buffer.BufferStream import com.onyx.buffer.BufferStreamable import com.onyx.descriptor.EntityDescriptor import com.onyx.exception.BufferingException import com.onyx.exception.OnyxException import com.onyx.extension.common.ClassMetadata.classForName import com.onyx.extension.identifier import com.onyx.interactors.record.data.Reference import com.onyx.persistence.IManagedEntity import com.onyx.persistence.context.Contexts import com.onyx.persistence.context.SchemaContext import com.onyx.persistence.manager.PersistenceManager import java.util.* import java.util.function.Consumer /** * LazyQueryCollection is used to return query results that are lazily instantiated. * * If by calling executeLazyQuery it will return a list with record references. The references are then used to hydrate the results when referenced through the List interface methods. * * Also, this is not available using the Web API. It is a limitation due to the JSON serialization. * * @author Tim Osborn * @since 1.0.0 * * PersistenceManager manager = factory.getPersistenceManager(); * * Query query = new Query(); * query.setEntityType(MyEntity.class); * List myResults = manager.executeLazyQuery(query); // Returns an instance of LazyQueryCollection * */ class LazyQueryCollection<E : IManagedEntity> () : AbstractList<E>(), List<E>, BufferStreamable { @Transient private var values: MutableMap<Any, E?> = WeakHashMap() @Transient private lateinit var contextId: String @Transient private var persistenceManager: PersistenceManager? = null @Transient lateinit var entityDescriptor: EntityDescriptor lateinit var identifiers: MutableList<Reference> private var hasSelections = false constructor(entityDescriptor: EntityDescriptor, references: List<Reference>, context: SchemaContext):this() { this.entityDescriptor = entityDescriptor this.contextId = context.contextId this.persistenceManager = context.serializedPersistenceManager this.identifiers = synchronized(references) { ArrayList(references) } } /** * Quantity or record references within the List * * @since 1.0.0 * * @return Size of the List */ override val size: Int get() = identifiers.size /** * Boolean key indicating whether the list is empty * * @since 1.0.0 * * @return (size equals 0) */ override fun isEmpty(): Boolean = identifiers.isEmpty() /** * Contains an value and is initialized * * @since 1.0.0 * * @param element Object to check * @return Boolean */ override operator fun contains(element: E): Boolean = identifiers.contains((element as IManagedEntity).identifier(descriptor = entityDescriptor)) /** * Add an element to the lazy collection * * This must add a managed entity * * @since 1.0.0 * * @param element Record that implements ManagedEntity * @return Added or not */ override fun add(element: E?): Boolean = throw RuntimeException("Method unsupported") /** * Remove all objects * * @since 1.0.0 */ override fun clear() { values.clear() identifiers.clear() } /** * Get value at index and initialize it if it does not exist * * @since 1.0.0 * * @param index Record Index * @return ManagedEntity */ override fun get(index: Int): E { var entity: E? = values[index] if (entity == null) { entity = try { val reference = identifiers[index] persistenceManager!!.getWithReference(entityDescriptor.entityClass, reference) } catch (e: OnyxException) { null } values[index] = entity } return entity!! } /** * Get value at index and initialize it if it does not exist * * @since 1.0.0 * * @param index Record Index * @return ManagedEntity */ @Suppress("UNCHECKED_CAST") fun getDict(index: Int): Map<String, Any?>? = try { persistenceManager!!.getMapWithReferenceId(entityDescriptor.entityClass, identifiers[index]) } catch (e: OnyxException) { null } /** * Set value at index * * @since 1.0.0 * * @param index Record Index * @param element ManagedEntity * @return Record set */ override fun set(index: Int, element: E?): E = throw RuntimeException("Method unsupported") /** * Add value at index * * @since 1.0.0 * * @param index Record Index * @param element ManagedEntity */ override fun add(index: Int, element: E?) { this[index] = element } /** * Remove value at index * * * @since 1.0.0 * * @param index Record Index * @return ManagedEntity removed */ override fun removeAt(index: Int): E { val existingObject = identifiers[index] identifiers.remove(existingObject) return values.remove(existingObject) as E } override fun remove(element: E): Boolean { val identifier: Any? = (element as IManagedEntity?)!!.identifier(descriptor = entityDescriptor) values.remove(identifier) return identifiers.remove(identifier) } @Throws(BufferingException::class) @Suppress("UNCHECKED_CAST") override fun read(buffer: BufferStream) { this.values = WeakHashMap() this.identifiers = buffer.collection as MutableList<Reference> val className = buffer.string this.contextId = buffer.string this.hasSelections = buffer.boolean val context = Contexts.get(contextId) ?: Contexts.firstRemote() this.entityDescriptor = context.getBaseDescriptorForEntity(classForName(className, context))!! this.persistenceManager = context.systemPersistenceManager } @Throws(BufferingException::class) override fun write(buffer: BufferStream) { buffer.putCollection(this.identifiers) buffer.putString(this.entityDescriptor.entityClass.name) buffer.putString(contextId) buffer.putBoolean(hasSelections) } /** * Returns an iterator over the elements in this list in proper sequence. * * The returned iterator is [*fail-fast*](#fail-fast). * * @return an iterator over the elements in this list in proper sequence */ override fun iterator(): MutableIterator<E> = object : MutableIterator<E> { var i = 0 override fun hasNext(): Boolean = i < size override fun next(): E = try { get(i) } finally { i++ } override fun remove() = throw RuntimeException("Method unsupported, hydrate relationship using initialize before using listIterator.remove") } /** * For Each This is overridden to utilize the iterator * * @param action consumer to apply each iteration */ override fun forEach(action: Consumer<in E>) { val iterator = iterator() while (iterator.hasNext()) { action.accept(iterator.next()) } } /** * {@inheritDoc} */ override fun listIterator(): MutableListIterator<E> = object : MutableListIterator<E> { var i = -1 override fun hasNext(): Boolean = i + 1 < size override fun next(): E = try { get(i) } finally { i++ } override fun hasPrevious(): Boolean = i > 0 override fun previous(): E = try { get(i) } finally { i-- } override fun nextIndex(): Int = i + 1 override fun previousIndex(): Int = i - 1 override fun remove() = throw RuntimeException("Method unsupported, hydrate relationship using initialize before using listIterator.remove") override fun set(element: E) = throw RuntimeException("Method unsupported, hydrate relationship using initialize before using listIterator.set") override fun add(element: E) = throw RuntimeException("Method unsupported, hydrate relationship using initialize before using listIterator.add") } }
agpl-3.0
shogo4405/HaishinKit.java
haishinkit/src/main/java/com/haishinkit/graphics/PixelTransformFactory.kt
1
358
package com.haishinkit.graphics import com.haishinkit.util.FeatureUtil internal class PixelTransformFactory { fun create(): PixelTransform { if (FeatureUtil.isEnabled(FeatureUtil.FEATURE_VULKAN_PIXEL_TRANSFORM) && VkPixelTransform.isSupported()) { return VkPixelTransform() } return GlThreadPixelTransform() } }
bsd-3-clause
GunoH/intellij-community
platform/configuration-store-impl/src/ImportSettingsAction.kt
6
7418
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.configurationStore import com.intellij.ide.IdeBundle import com.intellij.ide.actions.ImportSettingsFilenameFilter import com.intellij.ide.plugins.PluginManager import com.intellij.ide.startup.StartupActionScriptManager import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.application.* import com.intellij.openapi.application.ex.ApplicationEx import com.intellij.openapi.fileChooser.FileChooserDescriptor import com.intellij.openapi.project.DumbAware import com.intellij.openapi.ui.Messages import com.intellij.openapi.ui.showOkCancelDialog import com.intellij.openapi.updateSettings.impl.UpdateSettings import com.intellij.openapi.util.NlsContexts import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.PathUtilRt import com.intellij.util.io.copy import com.intellij.util.io.exists import com.intellij.util.io.inputStream import com.intellij.util.io.isDirectory import java.io.IOException import java.io.InputStream import java.nio.file.Path import java.nio.file.Paths import java.util.zip.ZipException import java.util.zip.ZipInputStream // the class is open for Rider purpose open class ImportSettingsAction : AnAction(), DumbAware { override fun update(e: AnActionEvent) { e.presentation.isEnabled = true } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.BGT } override fun actionPerformed(e: AnActionEvent) { val dataContext = e.dataContext val component = PlatformCoreDataKeys.CONTEXT_COMPONENT.getData(dataContext) val descriptor = object : FileChooserDescriptor(true, true, true, true, false, false) { override fun isFileSelectable(file: VirtualFile?): Boolean { if (file?.isDirectory == true) { return file.fileSystem.getNioPath(file)?.let { path -> ConfigImportHelper.isConfigDirectory(path) } == true } return super.isFileSelectable(file) } }.apply { title = ConfigurationStoreBundle.message("title.import.file.location") description = ConfigurationStoreBundle.message("prompt.choose.import.file.path") isHideIgnored = false withFileFilter { ConfigImportHelper.isSettingsFile(it) } } chooseSettingsFile(descriptor, PathManager.getConfigPath(), component) { val saveFile = Paths.get(it.path) try { doImport(saveFile) } catch (e1: ZipException) { Messages.showErrorDialog( ConfigurationStoreBundle.message("error.reading.settings.file", saveFile, e1.message), ConfigurationStoreBundle.message("title.invalid.file")) } catch (e1: IOException) { Messages.showErrorDialog(ConfigurationStoreBundle.message("error.reading.settings.file.2", saveFile, e1.message), IdeBundle.message("title.error.reading.file")) } } } protected open fun getExportableComponents(relativePaths: Set<String>): Map<FileSpec, List<ExportableItem>> { return getExportableComponentsMap(isComputePresentableNames = true, withDeprecated = true) .filterKeys { relativePaths.contains(it.relativePath) } } protected open fun getMarkedComponents(components: Set<ExportableItem>): Set<ExportableItem> = components protected open fun doImport(saveFile: Path) { if (!saveFile.exists()) { Messages.showErrorDialog(ConfigurationStoreBundle.message("error.cannot.find.file", saveFile), ConfigurationStoreBundle.message("title.file.not.found")) return } if (saveFile.isDirectory()) { doImportFromDirectory(saveFile) return } val relativePaths = getPaths(saveFile.inputStream()) if (!relativePaths.contains(ImportSettingsFilenameFilter.SETTINGS_JAR_MARKER)) { Messages.showErrorDialog( ConfigurationStoreBundle.message("error.no.settings.to.import", saveFile), ConfigurationStoreBundle.message("title.invalid.file")) return } val configPath = Paths.get(PathManager.getConfigPath()) val dialog = ChooseComponentsToExportDialog( getExportableComponents(relativePaths), false, ConfigurationStoreBundle.message("title.select.components.to.import"), ConfigurationStoreBundle.message("prompt.check.components.to.import")) if (!dialog.showAndGet()) { return } val tempFile = Paths.get(PathManager.getPluginTempPath()).resolve(saveFile.fileName) saveFile.copy(tempFile) val filenameFilter = ImportSettingsFilenameFilter(getRelativeNamesToExtract(getMarkedComponents(dialog.exportableComponents))) StartupActionScriptManager.addActionCommands(listOf(StartupActionScriptManager.UnzipCommand(tempFile, configPath, filenameFilter), StartupActionScriptManager.DeleteCommand(tempFile))) UpdateSettings.getInstance().forceCheckForUpdateAfterRestart() if (confirmRestart(ConfigurationStoreBundle.message("message.settings.imported.successfully", getRestartActionName(), ApplicationNamesInfo.getInstance().fullProductName))) { restart() } } private fun restart() { invokeLater { (ApplicationManager.getApplication() as ApplicationEx).restart(true) } } private fun confirmRestart(@NlsContexts.DialogMessage message: String): Boolean = (Messages.OK == showOkCancelDialog( title = ConfigurationStoreBundle.message("import.settings.confirmation.title"), message = message, okText = getRestartActionName(), icon = Messages.getQuestionIcon() )) @NlsContexts.Button private fun getRestartActionName(): String = if (ApplicationManager.getApplication().isRestartCapable) ConfigurationStoreBundle.message("import.settings.confirmation.button.restart") else ConfigurationStoreBundle.message("import.default.settings.confirmation.button.shutdown") private fun doImportFromDirectory(saveFile: Path) { val confirmationMessage = ConfigurationStoreBundle.message("restore.default.settings.confirmation.message", ConfigBackup.getNextBackupPath(PathManager.getConfigDir())) if (confirmRestart(confirmationMessage)) { CustomConfigMigrationOption.MigrateFromCustomPlace(saveFile).writeConfigMarkerFile() restart() } } private fun getRelativeNamesToExtract(chosenComponents: Set<ExportableItem>): Set<String> { val result = HashSet<String>() for (item in chosenComponents) { result.add(item.fileSpec.relativePath) } result.add(PluginManager.INSTALLED_TXT) return result } } fun getPaths(input: InputStream): Set<String> { val result = mutableSetOf<String>() val zipIn = ZipInputStream(input) zipIn.use { while (true) { val entry = zipIn.nextEntry ?: break var path = entry.name.trimEnd('/') result.add(path) while (true) { path = PathUtilRt.getParentPath(path).takeIf { it.isNotEmpty() } ?: break result.add(path) } } } return result }
apache-2.0
GunoH/intellij-community
plugins/kotlin/j2k/old/tests/testData/fileOrElement/formatting/parameterList.kt
13
75
interface Aaa { fun foo( e1: String, e2: String ) }
apache-2.0
GunoH/intellij-community
plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/expressions/KotlinUThrowExpression.kt
4
732
// 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.uast.kotlin import org.jetbrains.annotations.ApiStatus import org.jetbrains.kotlin.psi.KtThrowExpression import org.jetbrains.uast.UElement import org.jetbrains.uast.UThrowExpression @ApiStatus.Internal class KotlinUThrowExpression( override val sourcePsi: KtThrowExpression, givenParent: UElement? ) : KotlinAbstractUExpression(givenParent), UThrowExpression, KotlinUElementWithType { override val thrownExpression by lz { baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.thrownExpression, this) } }
apache-2.0
GunoH/intellij-community
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/savedPatches/ShowDiffForSavedPatchesAction.kt
4
3135
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.openapi.vcs.changes.savedPatches import com.intellij.openapi.ListSelection import com.intellij.openapi.actionSystem.ActionUpdateThread import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.AnActionExtensionProvider import com.intellij.openapi.vcs.changes.ui.ChangeDiffRequestChain import com.intellij.openapi.vcs.changes.ui.ChangesBrowserBase import com.intellij.openapi.vcs.changes.ui.VcsTreeModelData abstract class AbstractShowDiffForSavedPatchesAction : AnActionExtensionProvider { override fun isActive(e: AnActionEvent): Boolean { return e.getData(SavedPatchesUi.SAVED_PATCHES_UI) != null } override fun getActionUpdateThread(): ActionUpdateThread { return ActionUpdateThread.EDT } override fun update(e: AnActionEvent) { val project = e.project val changesBrowser = e.getData(SavedPatchesUi.SAVED_PATCHES_UI)?.changesBrowser if (project == null || changesBrowser == null) { e.presentation.isEnabledAndVisible = false return } e.presentation.isVisible = true val selection = if (e.getData(ChangesBrowserBase.DATA_KEY) == null) { VcsTreeModelData.all(changesBrowser.viewer) } else { VcsTreeModelData.selected(changesBrowser.viewer) } e.presentation.isEnabled = selection.iterateUserObjects().any { getDiffRequestProducer(changesBrowser, it) != null } } override fun actionPerformed(e: AnActionEvent) { val changesBrowser = e.getRequiredData(SavedPatchesUi.SAVED_PATCHES_UI).changesBrowser val selection = if (e.getData(ChangesBrowserBase.DATA_KEY) == null) { ListSelection.createAt(VcsTreeModelData.all(changesBrowser.viewer).userObjects(), 0) } else { VcsTreeModelData.getListSelectionOrAll(changesBrowser.viewer) } ChangesBrowserBase.showStandaloneDiff(e.project!!, changesBrowser, selection) { change -> getDiffRequestProducer(changesBrowser, change) } } abstract fun getDiffRequestProducer(changesBrowser: SavedPatchesChangesBrowser, userObject: Any): ChangeDiffRequestChain.Producer? } class ShowDiffForSavedPatchesAction : AbstractShowDiffForSavedPatchesAction() { override fun getDiffRequestProducer(changesBrowser: SavedPatchesChangesBrowser, userObject: Any): ChangeDiffRequestChain.Producer? { return changesBrowser.getDiffRequestProducer(userObject) } } class CompareWithLocalForSavedPatchesAction : AbstractShowDiffForSavedPatchesAction() { override fun getDiffRequestProducer(changesBrowser: SavedPatchesChangesBrowser, userObject: Any): ChangeDiffRequestChain.Producer? { return changesBrowser.getDiffWithLocalRequestProducer(userObject, false) } } class CompareBeforeWithLocalForSavedPatchesAction : AbstractShowDiffForSavedPatchesAction() { override fun getDiffRequestProducer(changesBrowser: SavedPatchesChangesBrowser, userObject: Any): ChangeDiffRequestChain.Producer? { return changesBrowser.getDiffWithLocalRequestProducer(userObject, true) } }
apache-2.0
siosio/intellij-community
plugins/kotlin/completion/tests/testData/basic/common/fromUnresolvedNames/MemberProperty.kt
5
422
// RUN_HIGHLIGHTING_BEFORE class C { fun foo(p: Int) { print(unresolvedInFoo) } val <caret> fun bar(s: String, x: UnresolvedType) { print(unresolvedInBar) print(s.unresolvedWithReceiver) } } fun f() { print(unresolvedOutside) } // EXIST: unresolvedInFoo // EXIST: unresolvedInBar // ABSENT: unresolvedWithReceiver // ABSENT: unresolvedOutside // ABSENT: UnresolvedType
apache-2.0
siosio/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCallChain/mapToMap2.kt
5
193
// FIX: Merge call chain to 'associateBy' // WITH_RUNTIME fun getKey(i: Int): Long = 1L fun test(list: List<Int>) { val map: Map<Long, Int> = list.<caret>map { getKey(it) to it }.toMap() }
apache-2.0
vovagrechka/fucking-everything
pieces/pieces-100/src/main/java/alraune/alraune-package-3.kt
1
6579
package alraune import alraune.entity.* import pieces100.* import vgrechka.* import wasing.OoWasingLandingPage import java.sql.Timestamp import java.util.* import kotlin.properties.ReadOnlyProperty import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty import kotlin.reflect.KProperty0 import kotlin.reflect.KProperty1 fun redirect(path: String): Nothing { rctx0.commands.clear() btfSetLocationHref(path) spitFreakingPage {} throw ShitServed() } fun spitWindowOpenPage(href: String) { btfEval("window.open(${jsStringLiteral(href)})") spitUsualPage {div()} } fun redirectToLandingIfSiteIsNot(site: AlSite) { if (rctx0.al.site() != site) redirect(landingPagePath()) } fun landingPagePath() = when (rctx0.al.site()) { AlSite.BoloneCustomer -> OoCustomerLandingPage.path AlSite.BoloneWriter -> OoWriterLandingPage.path AlSite.BoloneAdmin -> OoAdminLandingPage.path AlSite.Wasing -> OoWasingLandingPage.path } fun bailOutToLittleErrorPage(content: String): Nothing { bailOutToLittleErrorPage(span(content)) } fun bailOutToLittleErrorPage_boldArg(template: String, arg: Any?): Nothing { val html = escapeHtml(template).replace("%s", when { arg == null || arg is String && arg.isBlank() -> "<i style='color: ${Color.Gray700};'>${t("blank", "пусто")}</i>" else -> "<b>" + escapeHtml(arg.toString()) + "</b>" }) bailOutToLittleErrorPage(rawHtml(html)) } fun bailOutToLittleErrorPage(content: Renderable): Nothing { cancelAllCommandsAndSpitLittleErrorPage(content) throw ShitServed() } fun cancelAllCommandsAndSpitLittleErrorPage(content: Renderable) { check(!rctx0.isPost) rctx0.commands.clear() spitFreakingPage { oo(content) } } fun largeUUID() = UUID.randomUUID().toString() // TODO:vgrechka Make it larger? fun <T> relateStack(stackCapture: StackCaptureException, f: () -> T): T { if (!alConfig.debug.enabled.relateStack) return f() AlGlobal_MergeMeToKotlinVersion.relatedStacks.get().addLast(stackCapture) try { return f() } finally { AlGlobal_MergeMeToKotlinVersion.relatedStacks.get().removeLast() } } annotation class LeJson(val withTypeInfo: Boolean = false) annotation class LeXStream interface WithUUID { val uuid: String } fun isLeJsonProperty(prop: KProperty1<Any, Any?>) = findLeJsonAnnotation(prop) != null fun findLeJsonAnnotation(prop: KProperty1<*, *>) = prop.annotations.find {it is LeJson} as LeJson? fun findLeXStreamAnnotation(prop: KProperty1<*, *>) = prop.annotations.find {it is LeXStream} as LeXStream? data class FAIconWithStyle( val icon: FA.Icon, val style: String = "", val nonFirstItemClass: AlCSS.Pack = AlCSS.fartus1.p1BlueGray, val amendTitleBar: (AlTag) -> Unit = {}) fun checkAtMostOneNotNull(vararg props: KProperty0<*>) { val notNulls = props.filter {it.get() != null} if (notNulls.size > 1) wtf("[${::checkAtMostOneNotNull.name}] notNulls = [${notNulls.joinToString(", ") {it.name}}]") } fun checkExactlyOneNotNull(vararg props: KProperty0<*>) { val notNulls = props.filter {it.get() != null} if (notNulls.size != 1) wtf("[${::checkExactlyOneNotNull.name}] notNulls = [${notNulls.joinToString(", ") {it.name}}]") } fun checkAtLeastOneNotNull(vararg props: KProperty0<*>) { val notNulls = props.filter {it.get() != null} if (notNulls.isEmpty()) wtf(::checkAtLeastOneNotNull.name) } fun <T> fqnamed(make: (List<String>) -> T) = object : ReadOnlyProperty<Any?, T> { private var value: T? = null override fun getValue(thisRef: Any?, property: KProperty<*>): T { if (value == null) { val clazz = thisRef!!::class val packageName = clazz.java.`package`.name var className = clazz.qualifiedName!! className = className.substring(packageName.length + 1) val pieces = className.split(".") value = make(pieces + listOf(property.name)) } return bang(value) } } fun myFqname_under() = fqnamed {it.joinToString("_")} fun <T : Any> getParamOrBailOut(param: AlBunchOfGetParams.Param<T>): T = param.get() ?: bailOutToLittleErrorPage(rawHtml(t("TOTE", "Я хочу в URL параметр <b>${param.name}</b>"))) interface GenericOperationInfoProps { val operationId: Long val actorDescr: String val title: String val time: Timestamp val timeString: String val userIcon: FA.Icon fun hasStateBefore(): Boolean } //sealed class OperationInfo : GenericOperationInfoProps { // class Order_V1( // override val operationId: Long, // val data: AlOperation_Order_V1, // override val actorDescr: String, // override val title: String, // override val time: Timestamp, // override val timeString: String, // override val userIcon: FA.Icon) : OperationInfo() { // // fun idAndTime() = AlText.numString(operationId) + ", " + timeString // override fun hasStateBefore() = data.orderBeforeOperation != null // } //} //fun drooOrderParamsComparison(entity1: AlUAOrder?, entity2: AlUAOrder) { // oo(div().with { // // Children are counted in CSS (nth-child stuff) relative to this div // fun drooPropComparisons(obj1: Any?, obj2: Any, exclude: List<KProperty1<*, *>> = listOf()) { // val props = (obj2::class.memberProperties - exclude) // for (prop in props) { // ooPropComparison(PropComparisonParams(prop), obj1, obj2) // } // } // // drooPropComparisons(entity1, entity2, exclude = listOf( // AlUAOrder::_id, AlUAOrder::createdAt, // AlUAOrder::updatedAt, AlUAOrder::deleted, AlUAOrder::dataPile)) // drooPropComparisons(entity1?.dataPile, entity2.dataPile) // }) //} fun isNullOrBlankString(x: Any?) = x == null || x is String && x.isBlank() //fun <T> T.fluent(block: () -> Unit): T { // block() // return this //} enum class Rightness { Left, Right; fun cssString(): String = name.toLowerCase() } interface Titled { val title: String } interface WithId { val id: Long } interface WithOptimisticVersion { var optimisticVersion: String } interface WithMutableId: WithId { override var id: Long } fun isWriterAssigned(order: Order) = false interface EncryptedDownloadableResource { var name: String var size: Int var downloadUrl: String var secretKeyBase64: String }
apache-2.0
GunoH/intellij-community
plugins/kotlin/idea/tests/testData/inspectionsLocal/removeToStringInStringTemplate/nameReference.kt
2
76
fun test(): String { val n = 1 return "n = ${n.<caret>toString()}" }
apache-2.0
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/InterfaceWithFieldConversion.kt
2
1407
// 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.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.declarationList import org.jetbrains.kotlin.nj2k.getOrCreateCompanionObject import org.jetbrains.kotlin.nj2k.tree.* class InterfaceWithFieldConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClass) return recurse(element) if (element.classKind != JKClass.ClassKind.INTERFACE && element.classKind != JKClass.ClassKind.ANNOTATION ) return recurse(element) val fieldsToMoveToCompanion = element.declarationList .filterIsInstance<JKField>() .filter { field -> field.modality == Modality.FINAL || element.classKind == JKClass.ClassKind.ANNOTATION } if (fieldsToMoveToCompanion.isNotEmpty()) { element.classBody.declarations -= fieldsToMoveToCompanion val companion = element.getOrCreateCompanionObject() companion.classBody.declarations += fieldsToMoveToCompanion } return recurse(element) } }
apache-2.0
smmribeiro/intellij-community
platform/lang-impl/src/com/intellij/codeInsight/navigation/impl/PsiFileNavigationTarget.kt
1
1907
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.codeInsight.navigation.impl import com.intellij.codeInsight.navigation.fileLocation import com.intellij.codeInsight.navigation.fileStatusAttributes import com.intellij.model.Pointer import com.intellij.navigation.NavigationRequest import com.intellij.navigation.NavigationTarget import com.intellij.navigation.TargetPresentation import com.intellij.openapi.vfs.newvfs.VfsPresentationUtil import com.intellij.psi.PsiFile import com.intellij.refactoring.suggested.createSmartPointer internal class PsiFileNavigationTarget( private val psiFile: PsiFile ) : NavigationTarget { override fun createPointer(): Pointer<out NavigationTarget> = Pointer.delegatingPointer( psiFile.createSmartPointer(), PsiFileNavigationTarget::class.java, ::PsiFileNavigationTarget ) override fun getTargetPresentation(): TargetPresentation { val project = psiFile.project var builder = TargetPresentation .builder(psiFile.name) .icon(psiFile.getIcon(0)) .containerText(psiFile.parent?.virtualFile?.presentableUrl) val file = psiFile.virtualFile ?: return builder.presentation() builder = builder .backgroundColor(VfsPresentationUtil.getFileBackgroundColor(project, file)) .presentableTextAttributes(fileStatusAttributes(project, file)) // apply file error and file status highlighting to file name val locationAndIcon = fileLocation(project, file) ?: return builder.presentation() @Suppress("HardCodedStringLiteral") builder = builder.locationText(locationAndIcon.text, locationAndIcon.icon) return builder.presentation() } override fun navigationRequest(): NavigationRequest? { return psiFile.navigationRequest() } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/compiler/configuration/BaseKotlinCompilerSettings.kt
1
4596
// 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.compiler.configuration import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.project.Project import com.intellij.openapi.util.Comparing import com.intellij.openapi.util.JDOMUtil import com.intellij.util.ReflectionUtil import com.intellij.util.messages.Topic import com.intellij.util.xmlb.Accessor import com.intellij.util.xmlb.SerializationFilterBase import com.intellij.util.xmlb.XmlSerializer import org.jdom.Element import org.jetbrains.kotlin.cli.common.arguments.* import org.jetbrains.kotlin.idea.syncPublisherWithDisposeCheck import kotlin.reflect.KClass abstract class BaseKotlinCompilerSettings<T : Freezable> protected constructor(private val project: Project) : PersistentStateComponent<Element>, Cloneable { // Based on com.intellij.util.xmlb.SkipDefaultValuesSerializationFilters private object DefaultValuesFilter : SerializationFilterBase() { private val defaultBeans = HashMap<Class<*>, Any>() private fun createDefaultBean(beanClass: Class<Any>): Any { return ReflectionUtil.newInstance<Any>(beanClass).apply { if (this is K2JSCompilerArguments) { sourceMapPrefix = "" } } } private fun getDefaultValue(accessor: Accessor, bean: Any): Any? { if (bean is K2JSCompilerArguments && accessor.name == K2JSCompilerArguments::sourceMapEmbedSources.name) { return if (bean.sourceMap) K2JsArgumentConstants.SOURCE_MAP_SOURCE_CONTENT_INLINING else null } val beanClass = bean.javaClass val defaultBean = defaultBeans.getOrPut(beanClass) { createDefaultBean(beanClass) } return accessor.read(defaultBean) } override fun accepts(accessor: Accessor, bean: Any, beanValue: Any?): Boolean { val defValue = getDefaultValue(accessor, bean) return if (defValue is Element && beanValue is Element) { !JDOMUtil.areElementsEqual(beanValue, defValue) } else { !Comparing.equal(beanValue, defValue) } } } @Suppress("LeakingThis") private var _settings: T = createSettings().frozen() private set(value) { field = value.frozen() } var settings: T get() = _settings set(value) { validateNewSettings(value) _settings = value ApplicationManager.getApplication().invokeLater { project.syncPublisherWithDisposeCheck(KotlinCompilerSettingsListener.TOPIC).settingsChanged(value) } } fun update(changer: T.() -> Unit) { settings = settings.unfrozen().apply { changer() } } protected fun validateInheritedFieldsUnchanged(settings: T) { @Suppress("UNCHECKED_CAST") val inheritedProperties = collectProperties<T>(settings::class as KClass<T>, true) val defaultInstance = createSettings() val invalidFields = inheritedProperties.filter { it.get(settings) != it.get(defaultInstance) } if (invalidFields.isNotEmpty()) { throw IllegalArgumentException("Following fields are expected to be left unchanged in ${settings.javaClass}: ${invalidFields.joinToString { it.name }}") } } protected open fun validateNewSettings(settings: T) { } protected abstract fun createSettings(): T override fun getState() = XmlSerializer.serialize(_settings, DefaultValuesFilter) override fun loadState(state: Element) { _settings = ReflectionUtil.newInstance(_settings.javaClass).apply { if (this is CommonCompilerArguments) { freeArgs = mutableListOf() internalArguments = mutableListOf() } XmlSerializer.deserializeInto(this, state) } ApplicationManager.getApplication().invokeLater { project.syncPublisherWithDisposeCheck(KotlinCompilerSettingsListener.TOPIC).settingsChanged(settings) } } public override fun clone(): Any = super.clone() } interface KotlinCompilerSettingsListener { fun <T> settingsChanged(newSettings: T) companion object { val TOPIC = Topic.create("KotlinCompilerSettingsListener", KotlinCompilerSettingsListener::class.java) } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/createFromUsage/callableBuilder/CallableBuilder.kt
1
62044
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder import com.intellij.codeInsight.daemon.impl.quickfix.CreateFromUsageUtils import com.intellij.codeInsight.navigation.NavigationUtil import com.intellij.codeInsight.template.* import com.intellij.codeInsight.template.impl.TemplateImpl import com.intellij.codeInsight.template.impl.TemplateManagerImpl import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.ScrollType import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.fileEditor.OpenFileDescriptor import com.intellij.openapi.ui.DialogWrapper import com.intellij.openapi.util.UnfairTextRange import com.intellij.psi.* import com.intellij.psi.codeStyle.CodeStyleManager import com.intellij.psi.codeStyle.JavaCodeStyleManager import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.builtins.functions.FunctionClassDescriptor import org.jetbrains.kotlin.cfg.pseudocode.Pseudocode import org.jetbrains.kotlin.cfg.pseudocode.getContainingPseudocode import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.MutablePackageFragmentDescriptor import org.jetbrains.kotlin.descriptors.impl.SimpleFunctionDescriptorImpl import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl import org.jetbrains.kotlin.idea.FrontendInternals import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithAllCompilerChecks import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.CodeInsightUtils import org.jetbrains.kotlin.idea.core.util.isMultiLine import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.quickfix.createFromUsage.createClass.ClassKind import org.jetbrains.kotlin.idea.refactoring.* import org.jetbrains.kotlin.idea.resolve.frontendService import org.jetbrains.kotlin.idea.util.DialogWithEditor import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers import org.jetbrains.kotlin.idea.util.application.executeWriteCommand import org.jetbrains.kotlin.idea.util.application.isUnitTestMode import org.jetbrains.kotlin.idea.util.application.runWriteAction import org.jetbrains.kotlin.idea.util.application.withPsiAttachment import org.jetbrains.kotlin.incremental.components.NoLookupLocation import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.* import org.jetbrains.kotlin.psi.typeRefHelpers.setReceiverTypeReference import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils import org.jetbrains.kotlin.resolve.descriptorUtil.getSuperClassOrAny import org.jetbrains.kotlin.resolve.scopes.HierarchicalScope import org.jetbrains.kotlin.resolve.scopes.LexicalScopeImpl import org.jetbrains.kotlin.resolve.scopes.LexicalScopeKind import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeProjectionImpl import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.Variance import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.makeNullable import org.jetbrains.kotlin.utils.KotlinExceptionWithAttachments import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull import java.util.* import kotlin.math.max /** * Represents a single choice for a type (e.g. parameter type or return type). */ class TypeCandidate(val theType: KotlinType, scope: HierarchicalScope? = null) { val typeParameters: Array<TypeParameterDescriptor> var renderedTypes: List<String> = emptyList() private set var renderedTypeParameters: List<RenderedTypeParameter>? = null private set fun render(typeParameterNameMap: Map<TypeParameterDescriptor, String>, fakeFunction: FunctionDescriptor?) { renderedTypes = theType.renderShort(typeParameterNameMap) renderedTypeParameters = typeParameters.map { RenderedTypeParameter(it, it.containingDeclaration == fakeFunction, typeParameterNameMap.getValue(it)) } } init { val typeParametersInType = theType.getTypeParameters() if (scope == null) { typeParameters = typeParametersInType.toTypedArray() renderedTypes = theType.renderShort(Collections.emptyMap()) } else { typeParameters = getTypeParameterNamesNotInScope(typeParametersInType, scope).toTypedArray() } } override fun toString() = theType.toString() } data class RenderedTypeParameter( val typeParameter: TypeParameterDescriptor, val fake: Boolean, val text: String ) fun List<TypeCandidate>.getTypeByRenderedType(renderedTypes: List<String>): KotlinType? = firstOrNull { it.renderedTypes == renderedTypes }?.theType class CallableBuilderConfiguration( val callableInfos: List<CallableInfo>, val originalElement: KtElement, val currentFile: KtFile = originalElement.containingKtFile, val currentEditor: Editor? = null, val isExtension: Boolean = false, val enableSubstitutions: Boolean = true ) sealed class CallablePlacement { class WithReceiver(val receiverTypeCandidate: TypeCandidate) : CallablePlacement() class NoReceiver(val containingElement: PsiElement) : CallablePlacement() } class CallableBuilder(val config: CallableBuilderConfiguration) { private var finished: Boolean = false val currentFileContext = config.currentFile.analyzeWithContent() private lateinit var _currentFileModule: ModuleDescriptor val currentFileModule: ModuleDescriptor get() { if (!_currentFileModule.isValid) { updateCurrentModule() } return _currentFileModule } init { updateCurrentModule() } val pseudocode: Pseudocode? by lazy { config.originalElement.getContainingPseudocode(currentFileContext) } private val typeCandidates = HashMap<TypeInfo, List<TypeCandidate>>() var placement: CallablePlacement? = null private val elementsToShorten = ArrayList<KtElement>() private fun updateCurrentModule() { _currentFileModule = config.currentFile.analyzeWithAllCompilerChecks().moduleDescriptor } fun computeTypeCandidates(typeInfo: TypeInfo): List<TypeCandidate> = typeCandidates.getOrPut(typeInfo) { typeInfo.getPossibleTypes(this).map { TypeCandidate(it) } } private fun computeTypeCandidates( typeInfo: TypeInfo, substitutions: List<KotlinTypeSubstitution>, scope: HierarchicalScope ): List<TypeCandidate> { if (!typeInfo.substitutionsAllowed) return computeTypeCandidates(typeInfo) return typeCandidates.getOrPut(typeInfo) { val types = typeInfo.getPossibleTypes(this).asReversed() // We have to use semantic equality here data class EqWrapper(val _type: KotlinType) { override fun equals(other: Any?) = this === other || other is EqWrapper && KotlinTypeChecker.DEFAULT.equalTypes(_type, other._type) override fun hashCode() = 0 // no good way to compute hashCode() that would agree with our equals() } val newTypes = LinkedHashSet(types.map(::EqWrapper)) for (substitution in substitutions) { // each substitution can be applied or not, so we offer all options val toAdd = newTypes.map { it._type.substitute(substitution, typeInfo.variance) } // substitution.byType are type arguments, but they cannot already occur in the type before substitution val toRemove = newTypes.filter { substitution.byType in it._type } newTypes.addAll(toAdd.map(::EqWrapper)) newTypes.removeAll(toRemove) } if (newTypes.isEmpty()) { newTypes.add(EqWrapper(currentFileModule.builtIns.anyType)) } newTypes.map { TypeCandidate(it._type, scope) }.asReversed() } } private fun buildNext(iterator: Iterator<CallableInfo>) { if (iterator.hasNext()) { val context = Context(iterator.next()) runWriteAction { context.buildAndRunTemplate { buildNext(iterator) } } ApplicationManager.getApplication().invokeLater { context.showDialogIfNeeded() } } else { runWriteAction { ShortenReferences.DEFAULT.process(elementsToShorten) } } } fun build(onFinish: () -> Unit = {}) { try { assert(config.currentEditor != null) { "Can't run build() without editor" } check(!finished) { "Current builder has already finished" } buildNext(config.callableInfos.iterator()) } finally { finished = true onFinish() } } private inner class Context(val callableInfo: CallableInfo) { val skipReturnType: Boolean val ktFileToEdit: KtFile val containingFileEditor: Editor val containingElement: PsiElement val dialogWithEditor: DialogWithEditor? val receiverClassDescriptor: ClassifierDescriptor? val typeParameterNameMap: Map<TypeParameterDescriptor, String> val receiverTypeCandidate: TypeCandidate? val mandatoryTypeParametersAsCandidates: List<TypeCandidate> val substitutions: List<KotlinTypeSubstitution> var finished: Boolean = false init { // gather relevant information val placement = placement var nullableReceiver = false when (placement) { is CallablePlacement.NoReceiver -> { containingElement = placement.containingElement receiverClassDescriptor = with(placement.containingElement) { when (this) { is KtClassOrObject -> currentFileContext[BindingContext.CLASS, this] is PsiClass -> getJavaClassDescriptor() else -> null } } } is CallablePlacement.WithReceiver -> { val theType = placement.receiverTypeCandidate.theType nullableReceiver = theType.isMarkedNullable receiverClassDescriptor = theType.constructor.declarationDescriptor val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) } containingElement = if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile } else -> throw IllegalArgumentException("Placement wan't initialized") } val receiverType = receiverClassDescriptor?.defaultType?.let { if (nullableReceiver) it.makeNullable() else it } val project = config.currentFile.project if (containingElement.containingFile != config.currentFile) { NavigationUtil.activateFileWithPsiElement(containingElement) } dialogWithEditor = if (containingElement is KtElement) { ktFileToEdit = containingElement.containingKtFile containingFileEditor = if (ktFileToEdit != config.currentFile) { FileEditorManager.getInstance(project).selectedTextEditor!! } else { config.currentEditor!! } null } else { val dialog = object : DialogWithEditor(project, KotlinBundle.message("fix.create.from.usage.dialog.title"), "") { override fun doOKAction() { project.executeWriteCommand(KotlinBundle.message("premature.end.of.template")) { TemplateManagerImpl.getTemplateState(editor)?.gotoEnd(false) } super.doOKAction() } } containingFileEditor = dialog.editor with(containingFileEditor.settings) { additionalColumnsCount = config.currentEditor!!.settings.getRightMargin(project) additionalLinesCount = 5 } ktFileToEdit = PsiDocumentManager.getInstance(project).getPsiFile(containingFileEditor.document) as KtFile ktFileToEdit.analysisContext = config.currentFile dialog } val scope = getDeclarationScope() receiverTypeCandidate = receiverType?.let { TypeCandidate(it, scope) } val fakeFunction: FunctionDescriptor? // figure out type substitutions for type parameters val substitutionMap = LinkedHashMap<KotlinType, KotlinType>() if (config.enableSubstitutions) { collectSubstitutionsForReceiverTypeParameters(receiverType, substitutionMap) val typeArgumentsForFakeFunction = callableInfo.typeParameterInfos .map { val typeCandidates = computeTypeCandidates(it) assert(typeCandidates.size == 1) { "Ambiguous type candidates for type parameter $it: $typeCandidates" } typeCandidates.first().theType } .subtract(substitutionMap.keys) fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size) collectSubstitutionsForCallableTypeParameters(fakeFunction, typeArgumentsForFakeFunction, substitutionMap) mandatoryTypeParametersAsCandidates = listOfNotNull(receiverTypeCandidate) + typeArgumentsForFakeFunction.map { TypeCandidate(substitutionMap[it]!!, scope) } } else { fakeFunction = null mandatoryTypeParametersAsCandidates = Collections.emptyList() } substitutions = substitutionMap.map { KotlinTypeSubstitution(it.key, it.value) } callableInfo.parameterInfos.forEach { computeTypeCandidates(it.typeInfo, substitutions, scope) } val returnTypeCandidate = computeTypeCandidates(callableInfo.returnTypeInfo, substitutions, scope).singleOrNull() skipReturnType = when (callableInfo.kind) { CallableKind.FUNCTION -> returnTypeCandidate?.theType?.isUnit() ?: false CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> callableInfo.returnTypeInfo == TypeInfo.Empty || returnTypeCandidate?.theType?.isAnyOrNullableAny() ?: false CallableKind.CONSTRUCTOR -> true CallableKind.PROPERTY -> containingElement is KtBlockExpression } // figure out type parameter renames to avoid conflicts typeParameterNameMap = getTypeParameterRenames(scope) callableInfo.parameterInfos.forEach { renderTypeCandidates(it.typeInfo, typeParameterNameMap, fakeFunction) } if (!skipReturnType) { renderTypeCandidates(callableInfo.returnTypeInfo, typeParameterNameMap, fakeFunction) } receiverTypeCandidate?.render(typeParameterNameMap, fakeFunction) mandatoryTypeParametersAsCandidates.forEach { it.render(typeParameterNameMap, fakeFunction) } } private fun getDeclarationScope(): HierarchicalScope { if (config.isExtension || receiverClassDescriptor == null) { return currentFileModule.getPackage(config.currentFile.packageFqName).memberScope.memberScopeAsImportingScope() } if (receiverClassDescriptor is ClassDescriptorWithResolutionScopes) { return receiverClassDescriptor.scopeForMemberDeclarationResolution } assert(receiverClassDescriptor is JavaClassDescriptor) { "Unexpected receiver class: $receiverClassDescriptor" } val projections = ((receiverClassDescriptor as JavaClassDescriptor).declaredTypeParameters) .map { TypeProjectionImpl(it.defaultType) } val memberScope = receiverClassDescriptor.getMemberScope(projections) return LexicalScopeImpl( memberScope.memberScopeAsImportingScope(), receiverClassDescriptor, false, null, LexicalScopeKind.SYNTHETIC ) { receiverClassDescriptor.typeConstructor.parameters.forEach { addClassifierDescriptor(it) } } } private fun collectSubstitutionsForReceiverTypeParameters( receiverType: KotlinType?, result: MutableMap<KotlinType, KotlinType> ) { if (placement is CallablePlacement.NoReceiver) return val classTypeParameters = receiverType?.arguments ?: Collections.emptyList() val ownerTypeArguments = (placement as? CallablePlacement.WithReceiver)?.receiverTypeCandidate?.theType?.arguments ?: Collections.emptyList() assert(ownerTypeArguments.size == classTypeParameters.size) ownerTypeArguments.zip(classTypeParameters).forEach { result[it.first.type] = it.second.type } } private fun collectSubstitutionsForCallableTypeParameters( fakeFunction: FunctionDescriptor, typeArguments: Set<KotlinType>, result: MutableMap<KotlinType, KotlinType> ) { for ((typeArgument, typeParameter) in typeArguments.zip(fakeFunction.typeParameters)) { result[typeArgument] = typeParameter.defaultType } } @OptIn(FrontendInternals::class) private fun createFakeFunctionDescriptor(scope: HierarchicalScope, typeParameterCount: Int): FunctionDescriptor { val fakeFunction = SimpleFunctionDescriptorImpl.create( MutablePackageFragmentDescriptor(currentFileModule, FqName("fake")), Annotations.EMPTY, Name.identifier("fake"), CallableMemberDescriptor.Kind.SYNTHESIZED, SourceElement.NO_SOURCE ) val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } val parameterNames = KotlinNameSuggester.suggestNamesForTypeParameters(typeParameterCount, validator) val typeParameters = (0 until typeParameterCount).map { TypeParameterDescriptorImpl.createWithDefaultBound( fakeFunction, Annotations.EMPTY, false, Variance.INVARIANT, Name.identifier(parameterNames[it]), it, ktFileToEdit.getResolutionFacade().frontendService() ) } return fakeFunction.initialize( null, null, typeParameters, Collections.emptyList(), null, null, DescriptorVisibilities.INTERNAL ) } private fun renderTypeCandidates( typeInfo: TypeInfo, typeParameterNameMap: Map<TypeParameterDescriptor, String>, fakeFunction: FunctionDescriptor? ) { typeCandidates[typeInfo]?.forEach { it.render(typeParameterNameMap, fakeFunction) } } private fun isInsideInnerOrLocalClass(): Boolean { val classOrObject = containingElement.getNonStrictParentOfType<KtClassOrObject>() return classOrObject is KtClass && (classOrObject.isInner() || classOrObject.isLocal) } private fun createDeclarationSkeleton(): KtNamedDeclaration { with(config) { val assignmentToReplace = if (containingElement is KtBlockExpression && (callableInfo as? PropertyInfo)?.writable == true) { originalElement as KtBinaryExpression } else null val pointerOfAssignmentToReplace = assignmentToReplace?.createSmartPointer() val ownerTypeString = if (isExtension) { val renderedType = receiverTypeCandidate!!.renderedTypes.first() val isFunctionType = receiverTypeCandidate.theType.constructor.declarationDescriptor is FunctionClassDescriptor if (isFunctionType) "($renderedType)." else "$renderedType." } else "" val classKind = (callableInfo as? ClassWithPrimaryConstructorInfo)?.classInfo?.kind fun renderParamList(): String { val prefix = if (classKind == ClassKind.ANNOTATION_CLASS) "val " else "" val list = callableInfo.parameterInfos.indices.joinToString(", ") { i -> "${prefix}p$i: Any" } return if (callableInfo.parameterInfos.isNotEmpty() || callableInfo.kind == CallableKind.FUNCTION || callableInfo.kind == CallableKind.CONSTRUCTOR ) "($list)" else list } val paramList = when (callableInfo.kind) { CallableKind.FUNCTION, CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR, CallableKind.CONSTRUCTOR -> renderParamList() CallableKind.PROPERTY -> "" } val returnTypeString = if (skipReturnType || assignmentToReplace != null) "" else ": Any" val header = "$ownerTypeString${callableInfo.name.quoteIfNeeded()}$paramList$returnTypeString" val psiFactory = KtPsiFactory(currentFile) val modifiers = buildString { val modifierList = callableInfo.modifierList?.copied() ?: psiFactory.createEmptyModifierList() val visibilityKeyword = modifierList.visibilityModifierType() if (visibilityKeyword == null) { val defaultVisibility = if (callableInfo.isAbstract) "" else if (containingElement is KtClassOrObject && !(containingElement is KtClass && containingElement.isInterface()) && containingElement.isAncestor(config.originalElement) && callableInfo.kind != CallableKind.CONSTRUCTOR ) "private " else if (isExtension) "private " else "" append(defaultVisibility) } // TODO: Get rid of isAbstract if (callableInfo.isAbstract && containingElement is KtClass && !containingElement.isInterface() && !modifierList.hasModifier(KtTokens.ABSTRACT_KEYWORD) ) { modifierList.appendModifier(KtTokens.ABSTRACT_KEYWORD) } val text = modifierList.normalize().text if (text.isNotEmpty()) { append("$text ") } } val isExpectClassMember by lazy { containingElement is KtClassOrObject && containingElement.resolveToDescriptorIfAny()?.isExpect ?: false } val declaration: KtNamedDeclaration = when (callableInfo.kind) { CallableKind.FUNCTION, CallableKind.CONSTRUCTOR -> { val body = when { callableInfo is ConstructorInfo -> if (callableInfo.withBody) "{\n\n}" else "" callableInfo.isAbstract -> "" containingElement is KtClass && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" containingElement is KtObjectDeclaration && containingElement.hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" containingElement is KtObjectDeclaration && containingElement.isCompanion() && containingElement.parent.parent is KtClass && (containingElement.parent.parent as KtClass).hasModifier(KtTokens.EXTERNAL_KEYWORD) -> "" isExpectClassMember -> "" else -> "{\n\n}" } @Suppress("USELESS_CAST") // KT-10755 when { callableInfo is FunctionInfo -> psiFactory.createFunction("${modifiers}fun<> $header $body") as KtNamedDeclaration (callableInfo as ConstructorInfo).isPrimary -> { val constructorText = if (modifiers.isNotEmpty()) "${modifiers}constructor$paramList" else paramList psiFactory.createPrimaryConstructor(constructorText) as KtNamedDeclaration } else -> psiFactory.createSecondaryConstructor("${modifiers}constructor$paramList $body") as KtNamedDeclaration } } CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR -> { val classWithPrimaryConstructorInfo = callableInfo as ClassWithPrimaryConstructorInfo with(classWithPrimaryConstructorInfo.classInfo) { val classBody = when (kind) { ClassKind.ANNOTATION_CLASS, ClassKind.ENUM_ENTRY -> "" else -> "{\n\n}" } val safeName = name.quoteIfNeeded() when (kind) { ClassKind.ENUM_ENTRY -> { val targetParent = applicableParents.singleOrNull() if (!(targetParent is KtClass && targetParent.isEnum())) { throw KotlinExceptionWithAttachments("Enum class expected: ${targetParent?.let { it::class.java }}") .withPsiAttachment("targetParent", targetParent) } val hasParameters = targetParent.primaryConstructorParameters.isNotEmpty() psiFactory.createEnumEntry("$safeName${if (hasParameters) "()" else " "}") } else -> { val openMod = if (open && kind != ClassKind.INTERFACE) "open " else "" val innerMod = if (inner || isInsideInnerOrLocalClass()) "inner " else "" val typeParamList = when (kind) { ClassKind.PLAIN_CLASS, ClassKind.INTERFACE -> "<>" else -> "" } val ctor = classWithPrimaryConstructorInfo.primaryConstructorVisibility?.name?.let { " $it constructor" } ?: "" psiFactory.createDeclaration<KtClassOrObject>( "$openMod$innerMod${kind.keyword} $safeName$typeParamList$ctor$paramList$returnTypeString $classBody" ) } } } } CallableKind.PROPERTY -> { val isVar = (callableInfo as PropertyInfo).writable val const = if (callableInfo.isConst) "const " else "" val valVar = if (isVar) "var" else "val" val accessors = if (isExtension && !isExpectClassMember) { buildString { append("\nget() {}") if (isVar) { append("\nset() {}") } } } else "" psiFactory.createProperty("$modifiers$const$valVar<> $header$accessors") } } if (callableInfo is PropertyInfo) { callableInfo.annotations.forEach { declaration.addAnnotationEntry(it) } } val newInitializer = pointerOfAssignmentToReplace?.element if (newInitializer != null) { (declaration as KtProperty).initializer = newInitializer.right return newInitializer.replace(declaration) as KtCallableDeclaration } val container = if (containingElement is KtClass && callableInfo.isForCompanion) { containingElement.getOrCreateCompanionObject() } else containingElement val declarationInPlace = placeDeclarationInContainer(declaration, container, config.originalElement, ktFileToEdit) if (declarationInPlace is KtSecondaryConstructor) { val containingClass = declarationInPlace.containingClassOrObject!! val primaryConstructorParameters = containingClass.primaryConstructorParameters if (primaryConstructorParameters.isNotEmpty()) { declarationInPlace.replaceImplicitDelegationCallWithExplicit(true) } else if ((receiverClassDescriptor as ClassDescriptor).getSuperClassOrAny().constructors .all { it.valueParameters.isNotEmpty() } ) { declarationInPlace.replaceImplicitDelegationCallWithExplicit(false) } if (declarationInPlace.valueParameters.size > primaryConstructorParameters.size) { val hasCompatibleTypes = primaryConstructorParameters.zip(callableInfo.parameterInfos).all { (primary, secondary) -> val primaryType = currentFileContext[BindingContext.TYPE, primary.typeReference] ?: return@all false val secondaryType = computeTypeCandidates(secondary.typeInfo).firstOrNull()?.theType ?: return@all false secondaryType.isSubtypeOf(primaryType) } if (hasCompatibleTypes) { val delegationCallArgumentList = declarationInPlace.getDelegationCall().valueArgumentList primaryConstructorParameters.forEach { val name = it.name if (name != null) delegationCallArgumentList?.addArgument(psiFactory.createArgument(name)) } } } } return declarationInPlace } } private fun getTypeParameterRenames(scope: HierarchicalScope): Map<TypeParameterDescriptor, String> { val allTypeParametersNotInScope = LinkedHashSet<TypeParameterDescriptor>() mandatoryTypeParametersAsCandidates.asSequence() .plus(callableInfo.parameterInfos.asSequence().flatMap { typeCandidates[it.typeInfo]!!.asSequence() }) .flatMap { it.typeParameters.asSequence() } .toCollection(allTypeParametersNotInScope) if (!skipReturnType) { computeTypeCandidates(callableInfo.returnTypeInfo).asSequence().flatMapTo(allTypeParametersNotInScope) { it.typeParameters.asSequence() } } val validator = CollectingNameValidator { scope.findClassifier(Name.identifier(it), NoLookupLocation.FROM_IDE) == null } val typeParameterNames = allTypeParametersNotInScope.map { KotlinNameSuggester.suggestNameByName(it.name.asString(), validator) } return allTypeParametersNotInScope.zip(typeParameterNames).toMap() } private fun setupTypeReferencesForShortening( declaration: KtNamedDeclaration, parameterTypeExpressions: List<TypeExpression> ) { if (config.isExtension) { val receiverTypeText = receiverTypeCandidate!!.theType.renderLong(typeParameterNameMap).first() val replacingTypeRef = KtPsiFactory(declaration).createType(receiverTypeText) (declaration as KtCallableDeclaration).setReceiverTypeReference(replacingTypeRef)!! } val returnTypeRefs = declaration.getReturnTypeReferences() if (returnTypeRefs.isNotEmpty()) { val returnType = typeCandidates[callableInfo.returnTypeInfo]!!.getTypeByRenderedType( returnTypeRefs.map { it.text } ) if (returnType != null) { // user selected a given type replaceWithLongerName(returnTypeRefs, returnType) } } val valueParameters = declaration.getValueParameters() val parameterIndicesToShorten = ArrayList<Int>() assert(valueParameters.size == parameterTypeExpressions.size) for ((i, parameter) in valueParameters.asSequence().withIndex()) { val parameterTypeRef = parameter.typeReference if (parameterTypeRef != null) { val parameterType = parameterTypeExpressions[i].typeCandidates.getTypeByRenderedType( listOf(parameterTypeRef.text) ) if (parameterType != null) { replaceWithLongerName(listOf(parameterTypeRef), parameterType) parameterIndicesToShorten.add(i) } } } } private fun postprocessDeclaration(declaration: KtNamedDeclaration) { if (callableInfo is PropertyInfo && callableInfo.isLateinitPreferred) { if (declaration.containingClassOrObject == null) return val propertyDescriptor = declaration.resolveToDescriptorIfAny() as? PropertyDescriptor ?: return val returnType = propertyDescriptor.returnType ?: return if (TypeUtils.isNullableType(returnType) || KotlinBuiltIns.isPrimitiveType(returnType)) return declaration.addModifier(KtTokens.LATEINIT_KEYWORD) } if (callableInfo.isAbstract) { val containingClass = declaration.containingClassOrObject if (containingClass is KtClass && containingClass.isInterface()) { declaration.removeModifier(KtTokens.ABSTRACT_KEYWORD) } } } private fun setupDeclarationBody(func: KtDeclarationWithBody) { if (func !is KtNamedFunction && func !is KtPropertyAccessor) return if (skipReturnType && callableInfo is FunctionInfo && callableInfo.preferEmptyBody) return val oldBody = func.bodyExpression ?: return val bodyText = getFunctionBodyTextFromTemplate( func.project, TemplateKind.FUNCTION, if (callableInfo.name.isNotEmpty()) callableInfo.name else null, if (skipReturnType) "Unit" else (func as? KtFunction)?.typeReference?.text ?: "", receiverClassDescriptor?.importableFqName ?: receiverClassDescriptor?.name?.let { FqName.topLevel(it) } ) oldBody.replace(KtPsiFactory(func).createBlock(bodyText)) } private fun setupCallTypeArguments(callElement: KtCallElement, typeParameters: List<TypeParameterDescriptor>) { val oldTypeArgumentList = callElement.typeArgumentList ?: return val renderedTypeArgs = typeParameters.map { typeParameter -> val type = substitutions.first { it.byType.constructor.declarationDescriptor == typeParameter }.forType IdeDescriptorRenderers.SOURCE_CODE.renderType(type) } if (renderedTypeArgs.isEmpty()) { oldTypeArgumentList.delete() } else { oldTypeArgumentList.replace(KtPsiFactory(callElement).createTypeArguments(renderedTypeArgs.joinToString(", ", "<", ">"))) elementsToShorten.add(callElement.typeArgumentList!!) } } private fun setupReturnTypeTemplate(builder: TemplateBuilder, declaration: KtNamedDeclaration): TypeExpression? { val candidates = typeCandidates[callableInfo.returnTypeInfo]!! if (candidates.isEmpty()) return null val elementToReplace: KtElement? val expression: TypeExpression = when (declaration) { is KtCallableDeclaration -> { elementToReplace = declaration.typeReference TypeExpression.ForTypeReference(candidates) } is KtClassOrObject -> { elementToReplace = declaration.superTypeListEntries.firstOrNull() TypeExpression.ForDelegationSpecifier(candidates) } else -> throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}") .withPsiAttachment("declaration", declaration) } if (elementToReplace == null) return null if (candidates.size == 1) { builder.replaceElement(elementToReplace, (expression.calculateResult(null) as TextResult).text) return null } builder.replaceElement(elementToReplace, expression) return expression } private fun setupValVarTemplate(builder: TemplateBuilder, property: KtProperty) { if (!(callableInfo as PropertyInfo).writable) { builder.replaceElement(property.valOrVarKeyword, ValVarExpression) } } private fun setupTypeParameterListTemplate( builder: TemplateBuilderImpl, declaration: KtNamedDeclaration ): TypeParameterListExpression? { when (declaration) { is KtObjectDeclaration -> return null !is KtTypeParameterListOwner -> { throw KotlinExceptionWithAttachments("Unexpected declaration kind: ${declaration::class.java}") .withPsiAttachment("declaration", declaration) } } val typeParameterList = (declaration as KtTypeParameterListOwner).typeParameterList ?: return null val typeParameterMap = HashMap<String, List<RenderedTypeParameter>>() val mandatoryTypeParameters = ArrayList<RenderedTypeParameter>() //receiverTypeCandidate?.let { mandatoryTypeParameters.addAll(it.renderedTypeParameters!!) } mandatoryTypeParametersAsCandidates.asSequence().flatMapTo(mandatoryTypeParameters) { it.renderedTypeParameters!!.asSequence() } callableInfo.parameterInfos.asSequence() .flatMap { typeCandidates[it.typeInfo]!!.asSequence() } .forEach { typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! } if (declaration.getReturnTypeReference() != null) { typeCandidates[callableInfo.returnTypeInfo]!!.forEach { typeParameterMap[it.renderedTypes.first()] = it.renderedTypeParameters!! } } val expression = TypeParameterListExpression( mandatoryTypeParameters, typeParameterMap, callableInfo.kind != CallableKind.CLASS_WITH_PRIMARY_CONSTRUCTOR ) val leftSpace = typeParameterList.prevSibling as? PsiWhiteSpace val rangeStart = leftSpace?.startOffset ?: typeParameterList.startOffset val offset = typeParameterList.startOffset val range = UnfairTextRange(rangeStart - offset, typeParameterList.endOffset - offset) builder.replaceElement(typeParameterList, range, "TYPE_PARAMETER_LIST", expression, false) return expression } private fun setupParameterTypeTemplates(builder: TemplateBuilder, parameterList: List<KtParameter>): List<TypeExpression> { assert(parameterList.size == callableInfo.parameterInfos.size) val typeParameters = ArrayList<TypeExpression>() for ((parameter, ktParameter) in callableInfo.parameterInfos.zip(parameterList)) { val parameterTypeExpression = TypeExpression.ForTypeReference(typeCandidates[parameter.typeInfo]!!) val parameterTypeRef = ktParameter.typeReference!! builder.replaceElement(parameterTypeRef, parameterTypeExpression) // add parameter name to the template val possibleNamesFromExpression = parameter.typeInfo.getPossibleNamesFromExpression(currentFileContext) val possibleNames = arrayOf(*parameter.nameSuggestions.toTypedArray(), *possibleNamesFromExpression) // figure out suggested names for each type option val parameterTypeToNamesMap = HashMap<String, Array<String>>() typeCandidates[parameter.typeInfo]!!.forEach { typeCandidate -> val suggestedNames = KotlinNameSuggester.suggestNamesByType(typeCandidate.theType, { true }) parameterTypeToNamesMap[typeCandidate.renderedTypes.first()] = suggestedNames.toTypedArray() } // add expression to builder val parameterNameExpression = ParameterNameExpression(possibleNames, parameterTypeToNamesMap) val parameterNameIdentifier = ktParameter.nameIdentifier!! builder.replaceElement(parameterNameIdentifier, parameterNameExpression) typeParameters.add(parameterTypeExpression) } return typeParameters } private fun replaceWithLongerName(typeRefs: List<KtTypeReference>, theType: KotlinType) { val psiFactory = KtPsiFactory(ktFileToEdit.project) val fullyQualifiedReceiverTypeRefs = theType.renderLong(typeParameterNameMap).map { psiFactory.createType(it) } (typeRefs zip fullyQualifiedReceiverTypeRefs).forEach { (shortRef, longRef) -> shortRef.replace(longRef) } } private fun transformToJavaMemberIfApplicable(declaration: KtNamedDeclaration): Boolean { fun convertToJava(targetClass: PsiClass): PsiMember? { val psiFactory = KtPsiFactory(declaration) psiFactory.createPackageDirectiveIfNeeded(config.currentFile.packageFqName)?.let { declaration.containingFile.addBefore(it, null) } val adjustedDeclaration = when (declaration) { is KtNamedFunction, is KtProperty -> { val klass = psiFactory.createClass("class Foo {}") klass.body!!.add(declaration) (declaration.replace(klass) as KtClass).body!!.declarations.first() } else -> declaration } return when (adjustedDeclaration) { is KtNamedFunction, is KtSecondaryConstructor -> { createJavaMethod(adjustedDeclaration as KtFunction, targetClass) } is KtProperty -> { createJavaField(adjustedDeclaration, targetClass) } is KtClass -> { createJavaClass(adjustedDeclaration, targetClass) } else -> null } } if (config.isExtension || receiverClassDescriptor !is JavaClassDescriptor) return false val targetClass = DescriptorToSourceUtils.getSourceFromDescriptor(receiverClassDescriptor) as? PsiClass if (targetClass == null || !targetClass.canRefactor()) return false val project = declaration.project val newJavaMember = convertToJava(targetClass) ?: return false val modifierList = newJavaMember.modifierList!! if (newJavaMember is PsiMethod || newJavaMember is PsiClass) { modifierList.setModifierProperty(PsiModifier.FINAL, false) } val needStatic = when (callableInfo) { is ClassWithPrimaryConstructorInfo -> with(callableInfo.classInfo) { !inner && kind != ClassKind.ENUM_ENTRY && kind != ClassKind.ENUM_CLASS } else -> callableInfo.receiverTypeInfo.staticContextRequired } modifierList.setModifierProperty(PsiModifier.STATIC, needStatic) JavaCodeStyleManager.getInstance(project).shortenClassReferences(newJavaMember) val descriptor = OpenFileDescriptor(project, targetClass.containingFile.virtualFile) val targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true)!! targetEditor.selectionModel.removeSelection() when (newJavaMember) { is PsiMethod -> CreateFromUsageUtils.setupEditor(newJavaMember, targetEditor) is PsiField -> targetEditor.caretModel.moveToOffset(newJavaMember.endOffset - 1) is PsiClass -> { val constructor = newJavaMember.constructors.firstOrNull() val superStatement = constructor?.body?.statements?.firstOrNull() as? PsiExpressionStatement val superCall = superStatement?.expression as? PsiMethodCallExpression if (superCall != null) { val lParen = superCall.argumentList.firstChild targetEditor.caretModel.moveToOffset(lParen.endOffset) } else { targetEditor.caretModel.moveToOffset(newJavaMember.nameIdentifier?.startOffset ?: newJavaMember.startOffset) } } } targetEditor.scrollingModel.scrollToCaret(ScrollType.RELATIVE) return true } private fun setupEditor(declaration: KtNamedDeclaration) { if (declaration is KtProperty && !declaration.hasInitializer() && containingElement is KtBlockExpression) { val defaultValueType = typeCandidates[callableInfo.returnTypeInfo]!!.firstOrNull()?.theType val defaultValue = defaultValueType?.let { CodeInsightUtils.defaultInitializer(it) } ?: "null" val initializer = declaration.setInitializer(KtPsiFactory(declaration).createExpression(defaultValue))!! val range = initializer.textRange containingFileEditor.selectionModel.setSelection(range.startOffset, range.endOffset) containingFileEditor.caretModel.moveToOffset(range.endOffset) return } if (declaration is KtSecondaryConstructor && !declaration.hasImplicitDelegationCall()) { containingFileEditor.caretModel.moveToOffset(declaration.getDelegationCall().valueArgumentList!!.startOffset + 1) return } setupEditorSelection(containingFileEditor, declaration) } // build templates fun buildAndRunTemplate(onFinish: () -> Unit) { val declarationSkeleton = createDeclarationSkeleton() val project = declarationSkeleton.project val declarationPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(declarationSkeleton) // build templates val documentManager = PsiDocumentManager.getInstance(project) val document = containingFileEditor.document documentManager.commitDocument(document) documentManager.doPostponedOperationsAndUnblockDocument(document) val caretModel = containingFileEditor.caretModel caretModel.moveToOffset(ktFileToEdit.node.startOffset) val declaration = declarationPointer.element ?: return val declarationMarker = document.createRangeMarker(declaration.textRange) val builder = TemplateBuilderImpl(ktFileToEdit) if (declaration is KtProperty) { setupValVarTemplate(builder, declaration) } if (!skipReturnType) { setupReturnTypeTemplate(builder, declaration) } val parameterTypeExpressions = setupParameterTypeTemplates(builder, declaration.getValueParameters()) // add a segment for the parameter list // Note: because TemplateBuilderImpl does not have a replaceElement overload that takes in both a TextRange and alwaysStopAt, we // need to create the segment first and then hack the Expression into the template later. We use this template to update the type // parameter list as the user makes selections in the parameter types, and we need alwaysStopAt to be false so the user can't tab to // it. val expression = setupTypeParameterListTemplate(builder, declaration) documentManager.doPostponedOperationsAndUnblockDocument(document) // the template built by TemplateBuilderImpl is ordered by element position, but we want types to be first, so hack it val templateImpl = builder.buildInlineTemplate() as TemplateImpl val variables = templateImpl.variables!! if (variables.isNotEmpty()) { val typeParametersVar = if (expression != null) variables.removeAt(0) else null for (i in callableInfo.parameterInfos.indices) { Collections.swap(variables, i * 2, i * 2 + 1) } typeParametersVar?.let { variables.add(it) } } // TODO: Disabled shortening names because it causes some tests fail. Refactor code to use automatic reference shortening templateImpl.isToShortenLongNames = false // run the template TemplateManager.getInstance(project).startTemplate(containingFileEditor, templateImpl, object : TemplateEditingAdapter() { private fun finishTemplate(brokenOff: Boolean) { try { documentManager.commitDocument(document) dialogWithEditor?.close(DialogWrapper.OK_EXIT_CODE) if (brokenOff && !isUnitTestMode()) return // file templates val newDeclaration = PsiTreeUtil.findElementOfClassAtOffset( ktFileToEdit, declarationMarker.startOffset, declaration::class.java, false ) ?: return runWriteAction { postprocessDeclaration(newDeclaration) // file templates if (newDeclaration is KtNamedFunction || newDeclaration is KtSecondaryConstructor) { setupDeclarationBody(newDeclaration as KtFunction) } if (newDeclaration is KtProperty) { newDeclaration.getter?.let { setupDeclarationBody(it) } if (callableInfo is PropertyInfo && callableInfo.initializer != null) { newDeclaration.initializer = callableInfo.initializer } } val callElement = config.originalElement as? KtCallElement if (callElement != null) { setupCallTypeArguments(callElement, expression?.currentTypeParameters ?: Collections.emptyList()) } CodeStyleManager.getInstance(project).reformat(newDeclaration) // change short type names to fully qualified ones (to be shortened below) if (newDeclaration.getValueParameters().size == parameterTypeExpressions.size) { setupTypeReferencesForShortening(newDeclaration, parameterTypeExpressions) } if (!transformToJavaMemberIfApplicable(newDeclaration)) { elementsToShorten.add(newDeclaration) setupEditor(newDeclaration) } } } finally { declarationMarker.dispose() finished = true onFinish() } } override fun templateCancelled(template: Template?) { finishTemplate(true) } override fun templateFinished(template: Template, brokenOff: Boolean) { finishTemplate(brokenOff) } }) } fun showDialogIfNeeded() { if (!isUnitTestMode() && dialogWithEditor != null && !finished) { dialogWithEditor.show() } } } } // TODO: Simplify and use formatter as much as possible @Suppress("UNCHECKED_CAST") internal fun <D : KtNamedDeclaration> placeDeclarationInContainer( declaration: D, container: PsiElement, anchor: PsiElement, fileToEdit: KtFile = container.containingFile as KtFile ): D { val psiFactory = KtPsiFactory(container) val newLine = psiFactory.createNewLine() fun calcNecessaryEmptyLines(decl: KtDeclaration, after: Boolean): Int { var lineBreaksPresent = 0 var neighbor: PsiElement? = null siblingsLoop@ for (sibling in decl.siblings(forward = after, withItself = false)) { when (sibling) { is PsiWhiteSpace -> lineBreaksPresent += (sibling.text ?: "").count { it == '\n' } else -> { neighbor = sibling break@siblingsLoop } } } val neighborType = neighbor?.node?.elementType val lineBreaksNeeded = when { neighborType == KtTokens.LBRACE || neighborType == KtTokens.RBRACE -> 1 neighbor is KtDeclaration && (neighbor !is KtProperty || decl !is KtProperty) -> 2 else -> 1 } return max(lineBreaksNeeded - lineBreaksPresent, 0) } val actualContainer = (container as? KtClassOrObject)?.getOrCreateBody() ?: container fun addDeclarationToClassOrObject( classOrObject: KtClassOrObject, declaration: KtNamedDeclaration ): KtNamedDeclaration { val classBody = classOrObject.getOrCreateBody() return if (declaration is KtNamedFunction) { val neighbor = PsiTreeUtil.skipSiblingsBackward( classBody.rBrace ?: classBody.lastChild!!, PsiWhiteSpace::class.java ) classBody.addAfter(declaration, neighbor) as KtNamedDeclaration } else classBody.addAfter(declaration, classBody.lBrace!!) as KtNamedDeclaration } fun addNextToOriginalElementContainer(addBefore: Boolean): D { val sibling = anchor.parentsWithSelf.first { it.parent == actualContainer } return if (addBefore || PsiTreeUtil.hasErrorElements(sibling)) { actualContainer.addBefore(declaration, sibling) } else { actualContainer.addAfter(declaration, sibling) } as D } val declarationInPlace = when { declaration is KtPrimaryConstructor -> { (container as KtClass).createPrimaryConstructorIfAbsent().replaced(declaration) } declaration is KtProperty && container !is KtBlockExpression -> { val sibling = actualContainer.getChildOfType<KtProperty>() ?: when (actualContainer) { is KtClassBody -> actualContainer.declarations.firstOrNull() ?: actualContainer.rBrace is KtFile -> actualContainer.declarations.first() else -> null } sibling?.let { actualContainer.addBefore(declaration, it) as D } ?: fileToEdit.add(declaration) as D } actualContainer.isAncestor(anchor, true) -> { val insertToBlock = container is KtBlockExpression if (insertToBlock) { val parent = container.parent if (parent is KtFunctionLiteral) { if (!parent.isMultiLine()) { parent.addBefore(newLine, container) parent.addAfter(newLine, container) } } } addNextToOriginalElementContainer(insertToBlock || declaration is KtTypeAlias) } container is KtFile -> container.add(declaration) as D container is PsiClass -> { if (declaration is KtSecondaryConstructor) { val wrappingClass = psiFactory.createClass("class ${container.name} {\n}") addDeclarationToClassOrObject(wrappingClass, declaration) (fileToEdit.add(wrappingClass) as KtClass).declarations.first() as D } else { fileToEdit.add(declaration) as D } } container is KtClassOrObject -> { var sibling: PsiElement? = container.declarations.lastOrNull { it::class == declaration::class } if (sibling == null && declaration is KtProperty) { sibling = container.body?.lBrace } insertMember(null, container, declaration, sibling) } else -> throw KotlinExceptionWithAttachments("Invalid containing element: ${container::class.java}") .withPsiAttachment("container", container) } when (declaration) { is KtEnumEntry -> { val prevEnumEntry = declarationInPlace.siblings(forward = false, withItself = false).firstIsInstanceOrNull<KtEnumEntry>() if (prevEnumEntry != null) { if ((prevEnumEntry.prevSibling as? PsiWhiteSpace)?.text?.contains('\n') == true) { declarationInPlace.parent.addBefore(psiFactory.createNewLine(), declarationInPlace) } val comma = psiFactory.createComma() if (prevEnumEntry.allChildren.any { it.node.elementType == KtTokens.COMMA }) { declarationInPlace.add(comma) } else { prevEnumEntry.add(comma) } val semicolon = prevEnumEntry.allChildren.firstOrNull { it.node?.elementType == KtTokens.SEMICOLON } if (semicolon != null) { (semicolon.prevSibling as? PsiWhiteSpace)?.text?.let { declarationInPlace.add(psiFactory.createWhiteSpace(it)) } declarationInPlace.add(psiFactory.createSemicolon()) semicolon.delete() } } } !is KtPrimaryConstructor -> { val parent = declarationInPlace.parent calcNecessaryEmptyLines(declarationInPlace, false).let { if (it > 0) parent.addBefore(psiFactory.createNewLine(it), declarationInPlace) } calcNecessaryEmptyLines(declarationInPlace, true).let { if (it > 0) parent.addAfter(psiFactory.createNewLine(it), declarationInPlace) } } } return declarationInPlace } fun KtNamedDeclaration.getReturnTypeReference() = getReturnTypeReferences().singleOrNull() internal fun KtNamedDeclaration.getReturnTypeReferences(): List<KtTypeReference> { return when (this) { is KtCallableDeclaration -> listOfNotNull(typeReference) is KtClassOrObject -> superTypeListEntries.mapNotNull { it.typeReference } else -> throw AssertionError("Unexpected declaration kind: $text") } } fun CallableBuilderConfiguration.createBuilder(): CallableBuilder = CallableBuilder(this)
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/structuralsearch/function/funPrivateModifier.kt
4
63
<warning descr="SSR">private fun a() { }</warning> fun b() { }
apache-2.0
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/formatter/settings/MarkdownCustomCodeStyleSettings.kt
1
1416
// 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.lang.formatter.settings import com.intellij.psi.codeStyle.CodeStyleSettings import com.intellij.psi.codeStyle.CustomCodeStyleSettings import org.intellij.plugins.markdown.lang.MarkdownLanguage @Suppress("PropertyName") class MarkdownCustomCodeStyleSettings(settings: CodeStyleSettings) : CustomCodeStyleSettings(MarkdownLanguage.INSTANCE.id, settings) { //BLANK LINES @JvmField var MAX_LINES_AROUND_HEADER: Int = 1 @JvmField var MIN_LINES_AROUND_HEADER: Int = 1 @JvmField var MAX_LINES_AROUND_BLOCK_ELEMENTS: Int = 1 @JvmField var MIN_LINES_AROUND_BLOCK_ELEMENTS: Int = 1 @JvmField var MAX_LINES_BETWEEN_PARAGRAPHS: Int = 1 @JvmField var MIN_LINES_BETWEEN_PARAGRAPHS: Int = 1 //SPACES @JvmField var FORCE_ONE_SPACE_BETWEEN_WORDS: Boolean = true @JvmField var FORCE_ONE_SPACE_AFTER_HEADER_SYMBOL: Boolean = true @JvmField var FORCE_ONE_SPACE_AFTER_LIST_BULLET: Boolean = true @JvmField var FORCE_ONE_SPACE_AFTER_BLOCKQUOTE_SYMBOL: Boolean = true @JvmField var WRAP_TEXT_IF_LONG = true @JvmField var KEEP_LINE_BREAKS_INSIDE_TEXT_BLOCKS = true @JvmField var WRAP_TEXT_INSIDE_BLOCKQUOTES = true @JvmField var INSERT_QUOTE_ARROWS_ON_WRAP = true }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/test/testData/exceptionFilter/inlineFunCallSiteNewSmapSyntax/inlineFunCallSiteNewSmapSyntax.kt
12
246
fun box() { foo() } inline fun foo() { val unused = 1 null!! } // !LANGUAGE: +CorrectSourceMappingSyntax // MAIN_CLASS: InlineFunCallSiteNewSmapSyntaxKt // NAVIGATE_TO_CALL_SITE // FILE: inlineFunCallSiteNewSmapSyntax.kt // LINE: 2
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/jvm-debugger/test/testData/stepping/stepOver/soInlineIfConditionLambdaTrue.kt
13
455
package soInlineIfConditionLambdaTrue fun main(args: Array<String>) { bar { true } } // 4 inline fun bar(f: (Int) -> Boolean) { //Breakpoint! if (f(42)) { // 1 foo() // 2 } else { foo() } foo() // 3 } fun foo() {} // STEP_OVER: 4
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/inspections/canBeVal/assignedTwice.kt
13
65
fun foo(p: Int) { var v: Int v = 0 if (p > 0) v = 1 }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/formatter/callChain/KT22115.kt
26
167
private fun String.foo(): List<String> = emptyList() fun test(s: String) { s.foo().flatMap { m -> m.foo().map { e -> e to m } } }
apache-2.0
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/remote/ext/FormWithAlignableLabelsColumn.kt
9
607
// 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.intellij.remote.ext import com.intellij.ui.components.JBLabel /** * This interface could be implemented by [CredentialsEditor] to allow the * alignment of fields in the editor within the form. */ interface FormWithAlignableLabelsColumn { val labelsColumn: List<JBLabel> companion object { @JvmStatic fun FormWithAlignableLabelsColumn.findLabelWithMaxPreferredWidth(): JBLabel? = labelsColumn.maxByOrNull { it.preferredSize.width } } }
apache-2.0
LouisCAD/Splitties
modules/resources/src/androidMain/kotlin/splitties/resources/PrimitiveResources.kt
1
4138
/* * Copyright 2019 Louis Cognault Ayeva Derman. Use of this source code is governed by the Apache 2.0 license. */ @file:Suppress("NOTHING_TO_INLINE") @file:OptIn(InternalSplittiesApi::class) package splitties.resources import android.content.Context import android.util.TypedValue import android.view.View import androidx.annotation.ArrayRes import androidx.annotation.AttrRes import androidx.annotation.BoolRes import androidx.annotation.IntegerRes import androidx.fragment.app.Fragment import splitties.experimental.InternalSplittiesApi import splitties.init.appCtx inline fun Context.bool(@BoolRes boolResId: Int): Boolean = resources.getBoolean(boolResId) inline fun Fragment.bool(@BoolRes boolResId: Int) = context!!.bool(boolResId) inline fun View.bool(@BoolRes boolResId: Int) = context.bool(boolResId) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appBool(@BoolRes boolResId: Int) = appCtx.bool(boolResId) inline fun Context.int(@IntegerRes intResId: Int): Int = resources.getInteger(intResId) inline fun Fragment.int(@IntegerRes intResId: Int) = context!!.int(intResId) inline fun View.int(@IntegerRes intResId: Int) = context.int(intResId) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appInt(@IntegerRes intResId: Int) = appCtx.int(intResId) inline fun Context.intArray( @ArrayRes intArrayResId: Int ): IntArray = resources.getIntArray(intArrayResId) inline fun Fragment.intArray(@ArrayRes intArrayResId: Int) = context!!.intArray(intArrayResId) inline fun View.intArray(@ArrayRes intArrayResId: Int) = context.intArray(intArrayResId) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appIntArray(@ArrayRes intArrayResId: Int) = appCtx.intArray(intArrayResId) // Styled resources below fun Context.styledBool(@AttrRes attr: Int): Boolean = withResolvedThemeAttribute(attr) { require(type == TypedValue.TYPE_INT_BOOLEAN) { unexpectedThemeAttributeTypeErrorMessage(expectedKind = "bool") } when (val value = data) { 0 -> false 1 -> true else -> error("Expected 0 or 1 but got $value") } } inline fun Fragment.styledBool(@AttrRes attr: Int) = context!!.styledBool(attr) inline fun View.styledBool(@AttrRes attr: Int) = context.styledBool(attr) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appStyledBool(@AttrRes attr: Int) = appCtx.styledBool(attr) fun Context.styledInt(@AttrRes attr: Int): Int = withResolvedThemeAttribute(attr) { require(type == TypedValue.TYPE_INT_DEC || type == TypedValue.TYPE_INT_HEX) { unexpectedThemeAttributeTypeErrorMessage(expectedKind = "int") } data } inline fun Fragment.styledInt(@AttrRes attr: Int) = context!!.styledInt(attr) inline fun View.styledInt(@AttrRes attr: Int) = context.styledInt(attr) /** * Use this method for non configuration dependent resources when you don't have a [Context] * or when you're calling it from an Activity or a Fragment member (as the Context is not * initialized yet). * * For theme dependent resources, the application theme will be implicitly used. */ inline fun appStyledInt(@AttrRes attr: Int) = appCtx.styledInt(attr)
apache-2.0
ThatsNoMoon/KDA
src/main/kotlin/com/thatsnomoon/kda/entities/KAsyncListenerAdapter.kt
1
32528
/* * Copyright 2018 Benjamin Scherer * * 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.thatsnomoon.kda.entities import net.dv8tion.jda.client.events.call.CallCreateEvent import net.dv8tion.jda.client.events.call.CallDeleteEvent import net.dv8tion.jda.client.events.call.GenericCallEvent import net.dv8tion.jda.client.events.call.update.CallUpdateRegionEvent import net.dv8tion.jda.client.events.call.update.CallUpdateRingingUsersEvent import net.dv8tion.jda.client.events.call.update.GenericCallUpdateEvent import net.dv8tion.jda.client.events.call.voice.* import net.dv8tion.jda.client.events.group.* import net.dv8tion.jda.client.events.group.update.GenericGroupUpdateEvent import net.dv8tion.jda.client.events.group.update.GroupUpdateIconEvent import net.dv8tion.jda.client.events.group.update.GroupUpdateNameEvent import net.dv8tion.jda.client.events.group.update.GroupUpdateOwnerEvent import net.dv8tion.jda.client.events.message.group.* import net.dv8tion.jda.client.events.message.group.react.GenericGroupMessageReactionEvent import net.dv8tion.jda.client.events.message.group.react.GroupMessageReactionAddEvent import net.dv8tion.jda.client.events.message.group.react.GroupMessageReactionRemoveAllEvent import net.dv8tion.jda.client.events.message.group.react.GroupMessageReactionRemoveEvent import net.dv8tion.jda.client.events.relationship.* import net.dv8tion.jda.core.AccountType import net.dv8tion.jda.core.events.* import net.dv8tion.jda.core.events.channel.category.CategoryCreateEvent import net.dv8tion.jda.core.events.channel.category.CategoryDeleteEvent import net.dv8tion.jda.core.events.channel.category.GenericCategoryEvent import net.dv8tion.jda.core.events.channel.category.update.CategoryUpdateNameEvent import net.dv8tion.jda.core.events.channel.category.update.CategoryUpdatePermissionsEvent import net.dv8tion.jda.core.events.channel.category.update.CategoryUpdatePositionEvent import net.dv8tion.jda.core.events.channel.category.update.GenericCategoryUpdateEvent import net.dv8tion.jda.core.events.channel.priv.PrivateChannelCreateEvent import net.dv8tion.jda.core.events.channel.priv.PrivateChannelDeleteEvent import net.dv8tion.jda.core.events.channel.text.GenericTextChannelEvent import net.dv8tion.jda.core.events.channel.text.TextChannelCreateEvent import net.dv8tion.jda.core.events.channel.text.TextChannelDeleteEvent import net.dv8tion.jda.core.events.channel.text.update.* import net.dv8tion.jda.core.events.channel.voice.GenericVoiceChannelEvent import net.dv8tion.jda.core.events.channel.voice.VoiceChannelCreateEvent import net.dv8tion.jda.core.events.channel.voice.VoiceChannelDeleteEvent import net.dv8tion.jda.core.events.channel.voice.update.* import net.dv8tion.jda.core.events.emote.EmoteAddedEvent import net.dv8tion.jda.core.events.emote.EmoteRemovedEvent import net.dv8tion.jda.core.events.emote.GenericEmoteEvent import net.dv8tion.jda.core.events.emote.update.EmoteUpdateNameEvent import net.dv8tion.jda.core.events.emote.update.EmoteUpdateRolesEvent import net.dv8tion.jda.core.events.emote.update.GenericEmoteUpdateEvent import net.dv8tion.jda.core.events.guild.* import net.dv8tion.jda.core.events.guild.member.* import net.dv8tion.jda.core.events.guild.update.* import net.dv8tion.jda.core.events.guild.voice.* import net.dv8tion.jda.core.events.http.HttpRequestEvent import net.dv8tion.jda.core.events.message.* import net.dv8tion.jda.core.events.message.guild.* import net.dv8tion.jda.core.events.message.guild.react.GenericGuildMessageReactionEvent import net.dv8tion.jda.core.events.message.guild.react.GuildMessageReactionAddEvent import net.dv8tion.jda.core.events.message.guild.react.GuildMessageReactionRemoveAllEvent import net.dv8tion.jda.core.events.message.guild.react.GuildMessageReactionRemoveEvent import net.dv8tion.jda.core.events.message.priv.* import net.dv8tion.jda.core.events.message.priv.react.GenericPrivateMessageReactionEvent import net.dv8tion.jda.core.events.message.priv.react.PrivateMessageReactionAddEvent import net.dv8tion.jda.core.events.message.priv.react.PrivateMessageReactionRemoveEvent import net.dv8tion.jda.core.events.message.react.GenericMessageReactionEvent import net.dv8tion.jda.core.events.message.react.MessageReactionAddEvent import net.dv8tion.jda.core.events.message.react.MessageReactionRemoveAllEvent import net.dv8tion.jda.core.events.message.react.MessageReactionRemoveEvent import net.dv8tion.jda.core.events.role.GenericRoleEvent import net.dv8tion.jda.core.events.role.RoleCreateEvent import net.dv8tion.jda.core.events.role.RoleDeleteEvent import net.dv8tion.jda.core.events.role.update.* import net.dv8tion.jda.core.events.self.* import net.dv8tion.jda.core.events.user.GenericUserEvent import net.dv8tion.jda.core.events.user.UserTypingEvent import net.dv8tion.jda.core.events.user.update.* /** * An abstract implementation of [KAsyncEventListener][KAsyncEventListener] which divides [Events][Event] for you. * * This is an exact translation of [ListenerAdapter][net.dv8tion.jda.core.hooks.ListenerAdapter] but using suspending functions. * * * **Example:** * ``` * class MyListener: KListenerAdapter() { * override suspend fun onReady(event: ReadyEvent) { * println("Bot online!") * } * * override suspend fun onMessageReceived(event: MessageReceivedEvent) { * println("Got message in channel ${event.channel.id}: ${event.message.contentDisplay}") * } * } * ``` * * @see KAsyncEventListener * * @see net.dv8tion.jda.core.hooks.ListenerAdapter * * @see net.dv8tion.jda.core.hooks.InterfacedEventManager */ abstract class KAsyncListenerAdapter : KAsyncEventListener { open suspend fun onGenericEvent(event: Event) {} open suspend fun onGenericUpdate(event: UpdateEvent<*, *>) {} open suspend fun onReady(event: ReadyEvent) {} open suspend fun onResume(event: ResumedEvent) {} open suspend fun onReconnect(event: ReconnectedEvent) {} open suspend fun onDisconnect(event: DisconnectEvent) {} open suspend fun onShutdown(event: ShutdownEvent) {} open suspend fun onStatusChange(event: StatusChangeEvent) {} open suspend fun onException(event: ExceptionEvent) {} open suspend fun onUserUpdateName(event: UserUpdateNameEvent) {} open suspend fun onUserUpdateDiscriminator(event: UserUpdateDiscriminatorEvent) {} open suspend fun onUserUpdateAvatar(event: UserUpdateAvatarEvent) {} open suspend fun onUserUpdateOnlineStatus(event: UserUpdateOnlineStatusEvent) {} open suspend fun onUserUpdateGame(event: UserUpdateGameEvent) {} open suspend fun onUserTyping(event: UserTypingEvent) {} open suspend fun onSelfUpdateAvatar(event: SelfUpdateAvatarEvent) {} open suspend fun onSelfUpdateEmail(event: SelfUpdateEmailEvent) {} open suspend fun onSelfUpdateMFA(event: SelfUpdateMFAEvent) {} open suspend fun onSelfUpdateName(event: SelfUpdateNameEvent) {} open suspend fun onSelfUpdateVerified(event: SelfUpdateVerifiedEvent) {} open suspend fun onGuildMessageReceived(event: GuildMessageReceivedEvent) {} open suspend fun onGuildMessageUpdate(event: GuildMessageUpdateEvent) {} open suspend fun onGuildMessageDelete(event: GuildMessageDeleteEvent) {} open suspend fun onGuildMessageEmbed(event: GuildMessageEmbedEvent) {} open suspend fun onGuildMessageReactionAdd(event: GuildMessageReactionAddEvent) {} open suspend fun onGuildMessageReactionRemove(event: GuildMessageReactionRemoveEvent) {} open suspend fun onGuildMessageReactionRemoveAll(event: GuildMessageReactionRemoveAllEvent) {} open suspend fun onPrivateMessageReceived(event: PrivateMessageReceivedEvent) {} open suspend fun onPrivateMessageUpdate(event: PrivateMessageUpdateEvent) {} open suspend fun onPrivateMessageDelete(event: PrivateMessageDeleteEvent) {} open suspend fun onPrivateMessageEmbed(event: PrivateMessageEmbedEvent) {} open suspend fun onPrivateMessageReactionAdd(event: PrivateMessageReactionAddEvent) {} open suspend fun onPrivateMessageReactionRemove(event: PrivateMessageReactionRemoveEvent) {} open suspend fun onMessageReceived(event: MessageReceivedEvent) {} open suspend fun onMessageUpdate(event: MessageUpdateEvent) {} open suspend fun onMessageDelete(event: MessageDeleteEvent) {} open suspend fun onMessageBulkDelete(event: MessageBulkDeleteEvent) {} open suspend fun onMessageEmbed(event: MessageEmbedEvent) {} open suspend fun onMessageReactionAdd(event: MessageReactionAddEvent) {} open suspend fun onMessageReactionRemove(event: MessageReactionRemoveEvent) {} open suspend fun onMessageReactionRemoveAll(event: MessageReactionRemoveAllEvent) {} open suspend fun onTextChannelDelete(event: TextChannelDeleteEvent) {} open suspend fun onTextChannelUpdateName(event: TextChannelUpdateNameEvent) {} open suspend fun onTextChannelUpdateTopic(event: TextChannelUpdateTopicEvent) {} open suspend fun onTextChannelUpdatePosition(event: TextChannelUpdatePositionEvent) {} open suspend fun onTextChannelUpdatePermissions(event: TextChannelUpdatePermissionsEvent) {} open suspend fun onTextChannelUpdateNSFW(event: TextChannelUpdateNSFWEvent) {} open suspend fun onTextChannelUpdateParent(event: TextChannelUpdateParentEvent) {} open suspend fun onTextChannelCreate(event: TextChannelCreateEvent) {} open suspend fun onVoiceChannelDelete(event: VoiceChannelDeleteEvent) {} open suspend fun onVoiceChannelUpdateName(event: VoiceChannelUpdateNameEvent) {} open suspend fun onVoiceChannelUpdatePosition(event: VoiceChannelUpdatePositionEvent) {} open suspend fun onVoiceChannelUpdateUserLimit(event: VoiceChannelUpdateUserLimitEvent) {} open suspend fun onVoiceChannelUpdateBitrate(event: VoiceChannelUpdateBitrateEvent) {} open suspend fun onVoiceChannelUpdatePermissions(event: VoiceChannelUpdatePermissionsEvent) {} open suspend fun onVoiceChannelUpdateParent(event: VoiceChannelUpdateParentEvent) {} open suspend fun onVoiceChannelCreate(event: VoiceChannelCreateEvent) {} open suspend fun onCategoryDelete(event: CategoryDeleteEvent) {} open suspend fun onCategoryUpdateName(event: CategoryUpdateNameEvent) {} open suspend fun onCategoryUpdatePosition(event: CategoryUpdatePositionEvent) {} open suspend fun onCategoryUpdatePermissions(event: CategoryUpdatePermissionsEvent) {} open suspend fun onCategoryCreate(event: CategoryCreateEvent) {} open suspend fun onPrivateChannelCreate(event: PrivateChannelCreateEvent) {} open suspend fun onPrivateChannelDelete(event: PrivateChannelDeleteEvent) {} open suspend fun onGuildJoin(event: GuildJoinEvent) {} open suspend fun onGuildLeave(event: GuildLeaveEvent) {} open suspend fun onGuildAvailable(event: GuildAvailableEvent) {} open suspend fun onGuildUnavailable(event: GuildUnavailableEvent) {} open suspend fun onUnavailableGuildJoined(event: UnavailableGuildJoinedEvent) {} open suspend fun onGuildBan(event: GuildBanEvent) {} open suspend fun onGuildUnban(event: GuildUnbanEvent) {} open suspend fun onGuildUpdateAfkChannel(event: GuildUpdateAfkChannelEvent) {} open suspend fun onGuildUpdateSystemChannel(event: GuildUpdateSystemChannelEvent) {} open suspend fun onGuildUpdateAfkTimeout(event: GuildUpdateAfkTimeoutEvent) {} open suspend fun onGuildUpdateExplicitContentLevel(event: GuildUpdateExplicitContentLevelEvent) {} open suspend fun onGuildUpdateIcon(event: GuildUpdateIconEvent) {} open suspend fun onGuildUpdateMFALevel(event: GuildUpdateMFALevelEvent) {} open suspend fun onGuildUpdateName(event: GuildUpdateNameEvent) {} open suspend fun onGuildUpdateNotificationLevel(event: GuildUpdateNotificationLevelEvent) {} open suspend fun onGuildUpdateOwner(event: GuildUpdateOwnerEvent) {} open suspend fun onGuildUpdateRegion(event: GuildUpdateRegionEvent) {} open suspend fun onGuildUpdateSplash(event: GuildUpdateSplashEvent) {} open suspend fun onGuildUpdateVerificationLevel(event: GuildUpdateVerificationLevelEvent) {} open suspend fun onGuildUpdateFeatures(event: GuildUpdateFeaturesEvent) {} open suspend fun onGuildMemberJoin(event: GuildMemberJoinEvent) {} open suspend fun onGuildMemberLeave(event: GuildMemberLeaveEvent) {} open suspend fun onGuildMemberRoleAdd(event: GuildMemberRoleAddEvent) {} open suspend fun onGuildMemberRoleRemove(event: GuildMemberRoleRemoveEvent) {} open suspend fun onGuildMemberNickChange(event: GuildMemberNickChangeEvent) {} open suspend fun onGuildVoiceUpdate(event: GuildVoiceUpdateEvent) {} open suspend fun onGuildVoiceJoin(event: GuildVoiceJoinEvent) {} open suspend fun onGuildVoiceMove(event: GuildVoiceMoveEvent) {} open suspend fun onGuildVoiceLeave(event: GuildVoiceLeaveEvent) {} open suspend fun onGuildVoiceMute(event: GuildVoiceMuteEvent) {} open suspend fun onGuildVoiceDeafen(event: GuildVoiceDeafenEvent) {} open suspend fun onGuildVoiceGuildMute(event: GuildVoiceGuildMuteEvent) {} open suspend fun onGuildVoiceGuildDeafen(event: GuildVoiceGuildDeafenEvent) {} open suspend fun onGuildVoiceSelfMute(event: GuildVoiceSelfMuteEvent) {} open suspend fun onGuildVoiceSelfDeafen(event: GuildVoiceSelfDeafenEvent) {} open suspend fun onGuildVoiceSuppress(event: GuildVoiceSuppressEvent) {} open suspend fun onRoleCreate(event: RoleCreateEvent) {} open suspend fun onRoleDelete(event: RoleDeleteEvent) {} open suspend fun onRoleUpdateColor(event: RoleUpdateColorEvent) {} open suspend fun onRoleUpdateHoisted(event: RoleUpdateHoistedEvent) {} open suspend fun onRoleUpdateMentionable(event: RoleUpdateMentionableEvent) {} open suspend fun onRoleUpdateName(event: RoleUpdateNameEvent) {} open suspend fun onRoleUpdatePermissions(event: RoleUpdatePermissionsEvent) {} open suspend fun onRoleUpdatePosition(event: RoleUpdatePositionEvent) {} open suspend fun onEmoteAdded(event: EmoteAddedEvent) {} open suspend fun onEmoteRemoved(event: EmoteRemovedEvent) {} open suspend fun onEmoteUpdateName(event: EmoteUpdateNameEvent) {} open suspend fun onEmoteUpdateRoles(event: EmoteUpdateRolesEvent) {} open suspend fun onHttpRequest(event: HttpRequestEvent) {} open suspend fun onGenericMessage(event: GenericMessageEvent) {} open suspend fun onGenericMessageReaction(event: GenericMessageReactionEvent) {} open suspend fun onGenericGuildMessage(event: GenericGuildMessageEvent) {} open suspend fun onGenericGuildMessageReaction(event: GenericGuildMessageReactionEvent) {} open suspend fun onGenericPrivateMessage(event: GenericPrivateMessageEvent) {} open suspend fun onGenericPrivateMessageReaction(event: GenericPrivateMessageReactionEvent) {} open suspend fun onGenericUser(event: GenericUserEvent) {} open suspend fun onGenericUserPresence(event: GenericUserPresenceEvent<*>) {} open suspend fun onGenericSelfUpdate(event: GenericSelfUpdateEvent<*>) {} open suspend fun onGenericTextChannel(event: GenericTextChannelEvent) {} open suspend fun onGenericTextChannelUpdate(event: GenericTextChannelUpdateEvent<*>) {} open suspend fun onGenericVoiceChannel(event: GenericVoiceChannelEvent) {} open suspend fun onGenericVoiceChannelUpdate(event: GenericVoiceChannelUpdateEvent<*>) {} open suspend fun onGenericCategory(event: GenericCategoryEvent) {} open suspend fun onGenericCategoryUpdate(event: GenericCategoryUpdateEvent<*>) {} open suspend fun onGenericGuild(event: GenericGuildEvent) {} open suspend fun onGenericGuildUpdate(event: GenericGuildUpdateEvent<*>) {} open suspend fun onGenericGuildMember(event: GenericGuildMemberEvent) {} open suspend fun onGenericGuildVoice(event: GenericGuildVoiceEvent) {} open suspend fun onGenericRole(event: GenericRoleEvent) {} open suspend fun onGenericRoleUpdate(event: GenericRoleUpdateEvent<*>) {} open suspend fun onGenericEmote(event: GenericEmoteEvent) {} open suspend fun onGenericEmoteUpdate(event: GenericEmoteUpdateEvent<*>) {} open suspend fun onFriendAdded(event: FriendAddedEvent) {} open suspend fun onFriendRemoved(event: FriendRemovedEvent) {} open suspend fun onUserBlocked(event: UserBlockedEvent) {} open suspend fun onUserUnblocked(event: UserUnblockedEvent) {} open suspend fun onFriendRequestSent(event: FriendRequestSentEvent) {} open suspend fun onFriendRequestCanceled(event: FriendRequestCanceledEvent) {} open suspend fun onFriendRequestReceived(event: FriendRequestReceivedEvent) {} open suspend fun onFriendRequestIgnored(event: FriendRequestIgnoredEvent) {} open suspend fun onGroupJoin(event: GroupJoinEvent) {} open suspend fun onGroupLeave(event: GroupLeaveEvent) {} open suspend fun onGroupUserJoin(event: GroupUserJoinEvent) {} open suspend fun onGroupUserLeave(event: GroupUserLeaveEvent) {} open suspend fun onGroupMessageReceived(event: GroupMessageReceivedEvent) {} open suspend fun onGroupMessageUpdate(event: GroupMessageUpdateEvent) {} open suspend fun onGroupMessageDelete(event: GroupMessageDeleteEvent) {} open suspend fun onGroupMessageEmbed(event: GroupMessageEmbedEvent) {} open suspend fun onGroupMessageReactionAdd(event: GroupMessageReactionAddEvent) {} open suspend fun onGroupMessageReactionRemove(event: GroupMessageReactionRemoveEvent) {} open suspend fun onGroupMessageReactionRemoveAll(event: GroupMessageReactionRemoveAllEvent) {} open suspend fun onGroupUpdateIcon(event: GroupUpdateIconEvent) {} open suspend fun onGroupUpdateName(event: GroupUpdateNameEvent) {} open suspend fun onGroupUpdateOwner(event: GroupUpdateOwnerEvent) {} open suspend fun onCallCreate(event: CallCreateEvent) {} open suspend fun onCallDelete(event: CallDeleteEvent) {} open suspend fun onCallUpdateRegion(event: CallUpdateRegionEvent) {} open suspend fun onCallUpdateRingingUsers(event: CallUpdateRingingUsersEvent) {} open suspend fun onCallVoiceJoin(event: CallVoiceJoinEvent) {} open suspend fun onCallVoiceLeave(event: CallVoiceLeaveEvent) {} open suspend fun onCallVoiceSelfMute(event: CallVoiceSelfMuteEvent) {} open suspend fun onCallVoiceSelfDeafen(event: CallVoiceSelfDeafenEvent) {} open suspend fun onGenericRelationship(event: GenericRelationshipEvent) {} open suspend fun onGenericRelationshipAdd(event: GenericRelationshipAddEvent) {} open suspend fun onGenericRelationshipRemove(event: GenericRelationshipRemoveEvent) {} open suspend fun onGenericGroup(event: GenericGroupEvent) {} open suspend fun onGenericGroupMessage(event: GenericGroupMessageEvent) {} open suspend fun onGenericGroupMessageReaction(event: GenericGroupMessageReactionEvent) {} open suspend fun onGenericGroupUpdate(event: GenericGroupUpdateEvent) {} open suspend fun onGenericCall(event: GenericCallEvent) {} open suspend fun onGenericCallUpdate(event: GenericCallUpdateEvent) {} open suspend fun onGenericCallVoice(event: GenericCallVoiceEvent) {} override suspend fun onEventAsync(event: Event) { onGenericEvent(event) when (event) { is UpdateEvent<*, *> -> onGenericUpdate(event as UpdateEvent<*, *>) } when (event) { is ReadyEvent -> onReady(event) is ResumedEvent -> onResume(event) is ReconnectedEvent -> onReconnect(event) is DisconnectEvent -> onDisconnect(event) is ShutdownEvent -> onShutdown(event) is StatusChangeEvent -> onStatusChange(event) is ExceptionEvent -> onException(event) is GuildMessageReceivedEvent -> onGuildMessageReceived(event) is GuildMessageUpdateEvent -> onGuildMessageUpdate(event) is GuildMessageDeleteEvent -> onGuildMessageDelete(event) is GuildMessageEmbedEvent -> onGuildMessageEmbed(event) is GuildMessageReactionAddEvent -> onGuildMessageReactionAdd(event) is GuildMessageReactionRemoveEvent -> onGuildMessageReactionRemove(event) is GuildMessageReactionRemoveAllEvent -> onGuildMessageReactionRemoveAll(event) is PrivateMessageReceivedEvent -> onPrivateMessageReceived(event) is PrivateMessageUpdateEvent -> onPrivateMessageUpdate(event) is PrivateMessageDeleteEvent -> onPrivateMessageDelete(event) is PrivateMessageEmbedEvent -> onPrivateMessageEmbed(event) is PrivateMessageReactionAddEvent -> onPrivateMessageReactionAdd(event) is PrivateMessageReactionRemoveEvent -> onPrivateMessageReactionRemove(event) is MessageReceivedEvent -> onMessageReceived(event) is MessageUpdateEvent -> onMessageUpdate(event) is MessageDeleteEvent -> onMessageDelete(event) is MessageBulkDeleteEvent -> onMessageBulkDelete(event) is MessageEmbedEvent -> onMessageEmbed(event) is MessageReactionAddEvent -> onMessageReactionAdd(event) is MessageReactionRemoveEvent -> onMessageReactionRemove(event) is MessageReactionRemoveAllEvent -> onMessageReactionRemoveAll(event) is UserUpdateNameEvent -> onUserUpdateName(event) is UserUpdateDiscriminatorEvent -> onUserUpdateDiscriminator(event) is UserUpdateAvatarEvent -> onUserUpdateAvatar(event) is UserUpdateGameEvent -> onUserUpdateGame(event) is UserUpdateOnlineStatusEvent -> onUserUpdateOnlineStatus(event) is UserTypingEvent -> onUserTyping(event) is SelfUpdateAvatarEvent -> onSelfUpdateAvatar(event) is SelfUpdateEmailEvent -> onSelfUpdateEmail(event) is SelfUpdateMFAEvent -> onSelfUpdateMFA(event) is SelfUpdateNameEvent -> onSelfUpdateName(event) is SelfUpdateVerifiedEvent -> onSelfUpdateVerified(event) is TextChannelCreateEvent -> onTextChannelCreate(event) is TextChannelUpdateNameEvent -> onTextChannelUpdateName(event) is TextChannelUpdateTopicEvent -> onTextChannelUpdateTopic(event) is TextChannelUpdatePositionEvent -> onTextChannelUpdatePosition(event) is TextChannelUpdatePermissionsEvent -> onTextChannelUpdatePermissions(event) is TextChannelUpdateNSFWEvent -> onTextChannelUpdateNSFW(event) is TextChannelUpdateParentEvent -> onTextChannelUpdateParent(event) is TextChannelDeleteEvent -> onTextChannelDelete(event) is VoiceChannelCreateEvent -> onVoiceChannelCreate(event) is VoiceChannelUpdateNameEvent -> onVoiceChannelUpdateName(event) is VoiceChannelUpdatePositionEvent -> onVoiceChannelUpdatePosition(event) is VoiceChannelUpdateUserLimitEvent -> onVoiceChannelUpdateUserLimit(event) is VoiceChannelUpdateBitrateEvent -> onVoiceChannelUpdateBitrate(event) is VoiceChannelUpdatePermissionsEvent -> onVoiceChannelUpdatePermissions(event) is VoiceChannelUpdateParentEvent -> onVoiceChannelUpdateParent(event) is VoiceChannelDeleteEvent -> onVoiceChannelDelete(event) is CategoryCreateEvent -> onCategoryCreate(event) is CategoryUpdateNameEvent -> onCategoryUpdateName(event) is CategoryUpdatePositionEvent -> onCategoryUpdatePosition(event) is CategoryUpdatePermissionsEvent -> onCategoryUpdatePermissions(event) is CategoryDeleteEvent -> onCategoryDelete(event) is PrivateChannelCreateEvent -> onPrivateChannelCreate(event) is PrivateChannelDeleteEvent -> onPrivateChannelDelete(event) is GuildJoinEvent -> onGuildJoin(event) is GuildLeaveEvent -> onGuildLeave(event) is GuildAvailableEvent -> onGuildAvailable(event) is GuildUnavailableEvent -> onGuildUnavailable(event) is UnavailableGuildJoinedEvent -> onUnavailableGuildJoined(event) is GuildBanEvent -> onGuildBan(event) is GuildUnbanEvent -> onGuildUnban(event) is GuildUpdateAfkChannelEvent -> onGuildUpdateAfkChannel(event) is GuildUpdateSystemChannelEvent -> onGuildUpdateSystemChannel(event) is GuildUpdateAfkTimeoutEvent -> onGuildUpdateAfkTimeout(event) is GuildUpdateExplicitContentLevelEvent -> onGuildUpdateExplicitContentLevel(event) is GuildUpdateIconEvent -> onGuildUpdateIcon(event) is GuildUpdateMFALevelEvent -> onGuildUpdateMFALevel(event) is GuildUpdateNameEvent -> onGuildUpdateName(event) is GuildUpdateNotificationLevelEvent -> onGuildUpdateNotificationLevel(event) is GuildUpdateOwnerEvent -> onGuildUpdateOwner(event) is GuildUpdateRegionEvent -> onGuildUpdateRegion(event) is GuildUpdateSplashEvent -> onGuildUpdateSplash(event) is GuildUpdateVerificationLevelEvent -> onGuildUpdateVerificationLevel(event) is GuildUpdateFeaturesEvent -> onGuildUpdateFeatures(event) is GuildMemberJoinEvent -> onGuildMemberJoin(event) is GuildMemberLeaveEvent -> onGuildMemberLeave(event) is GuildMemberRoleAddEvent -> onGuildMemberRoleAdd(event) is GuildMemberRoleRemoveEvent -> onGuildMemberRoleRemove(event) is GuildMemberNickChangeEvent -> onGuildMemberNickChange(event) is GuildVoiceJoinEvent -> onGuildVoiceJoin(event) is GuildVoiceMoveEvent -> onGuildVoiceMove(event) is GuildVoiceLeaveEvent -> onGuildVoiceLeave(event) is GuildVoiceMuteEvent -> onGuildVoiceMute(event) is GuildVoiceDeafenEvent -> onGuildVoiceDeafen(event) is GuildVoiceGuildMuteEvent -> onGuildVoiceGuildMute(event) is GuildVoiceGuildDeafenEvent -> onGuildVoiceGuildDeafen(event) is GuildVoiceSelfMuteEvent -> onGuildVoiceSelfMute(event) is GuildVoiceSelfDeafenEvent -> onGuildVoiceSelfDeafen(event) is GuildVoiceSuppressEvent -> onGuildVoiceSuppress(event) is RoleCreateEvent -> onRoleCreate(event) is RoleDeleteEvent -> onRoleDelete(event) is RoleUpdateColorEvent -> onRoleUpdateColor(event) is RoleUpdateHoistedEvent -> onRoleUpdateHoisted(event) is RoleUpdateMentionableEvent -> onRoleUpdateMentionable(event) is RoleUpdateNameEvent -> onRoleUpdateName(event) is RoleUpdatePermissionsEvent -> onRoleUpdatePermissions(event) is RoleUpdatePositionEvent -> onRoleUpdatePosition(event) is EmoteAddedEvent -> onEmoteAdded(event) is EmoteRemovedEvent -> onEmoteRemoved(event) is EmoteUpdateNameEvent -> onEmoteUpdateName(event) is EmoteUpdateRolesEvent -> onEmoteUpdateRoles(event) is HttpRequestEvent -> onHttpRequest(event) } when (event) { is GuildVoiceUpdateEvent -> onGuildVoiceUpdate(event) } when (event) { is GenericMessageReactionEvent -> onGenericMessageReaction(event) is GenericPrivateMessageReactionEvent -> onGenericPrivateMessageReaction(event) is GenericTextChannelUpdateEvent<*> -> onGenericTextChannelUpdate(event) is GenericCategoryUpdateEvent<*> -> onGenericCategoryUpdate(event) is GenericGuildMessageReactionEvent -> onGenericGuildMessageReaction(event) is GenericVoiceChannelUpdateEvent<*> -> onGenericVoiceChannelUpdate(event) is GenericGuildUpdateEvent<*> -> onGenericGuildUpdate(event) is GenericGuildMemberEvent -> onGenericGuildMember(event) is GenericGuildVoiceEvent -> onGenericGuildVoice(event) is GenericRoleUpdateEvent<*> -> onGenericRoleUpdate(event) is GenericEmoteUpdateEvent<*> -> onGenericEmoteUpdate(event) is GenericUserPresenceEvent<*> -> onGenericUserPresence(event) } when (event) { is GenericMessageEvent -> onGenericMessage(event) is GenericPrivateMessageEvent -> onGenericPrivateMessage(event) is GenericGuildMessageEvent -> onGenericGuildMessage(event) is GenericUserEvent -> onGenericUser(event) is GenericSelfUpdateEvent<*> -> onGenericSelfUpdate(event) is GenericTextChannelEvent -> onGenericTextChannel(event) is GenericVoiceChannelEvent -> onGenericVoiceChannel(event) is GenericCategoryEvent -> onGenericCategory(event) is GenericRoleEvent -> onGenericRole(event) is GenericEmoteEvent -> onGenericEmote(event) } when (event) { is GenericGuildEvent -> onGenericGuild(event) } if (event.jda.accountType == AccountType.CLIENT) { when (event) { is FriendAddedEvent -> onFriendAdded(event) is FriendRemovedEvent -> onFriendRemoved(event) is UserBlockedEvent -> onUserBlocked(event) is UserUnblockedEvent -> onUserUnblocked(event) is FriendRequestSentEvent -> onFriendRequestSent(event) is FriendRequestCanceledEvent -> onFriendRequestCanceled(event) is FriendRequestReceivedEvent -> onFriendRequestReceived(event) is FriendRequestIgnoredEvent -> onFriendRequestIgnored(event) is GroupJoinEvent -> onGroupJoin(event) is GroupLeaveEvent -> onGroupLeave(event) is GroupUserJoinEvent -> onGroupUserJoin(event) is GroupUserLeaveEvent -> onGroupUserLeave(event) } when (event) { is GroupMessageReceivedEvent -> onGroupMessageReceived(event) is GroupMessageUpdateEvent -> onGroupMessageUpdate(event) is GroupMessageDeleteEvent -> onGroupMessageDelete(event) is GroupMessageEmbedEvent -> onGroupMessageEmbed(event) is GroupMessageReactionAddEvent -> onGroupMessageReactionAdd(event) is GroupMessageReactionRemoveEvent -> onGroupMessageReactionRemove(event) is GroupMessageReactionRemoveAllEvent -> onGroupMessageReactionRemoveAll(event) is GroupUpdateIconEvent -> onGroupUpdateIcon(event) is GroupUpdateNameEvent -> onGroupUpdateName(event) is GroupUpdateOwnerEvent -> onGroupUpdateOwner(event) is CallCreateEvent -> onCallCreate(event) is CallDeleteEvent -> onCallDelete(event) is CallUpdateRegionEvent -> onCallUpdateRegion(event) is CallUpdateRingingUsersEvent -> onCallUpdateRingingUsers(event) is CallVoiceJoinEvent -> onCallVoiceJoin(event) is CallVoiceLeaveEvent -> onCallVoiceLeave(event) is CallVoiceSelfMuteEvent -> onCallVoiceSelfMute(event) is CallVoiceSelfDeafenEvent -> onCallVoiceSelfDeafen(event) } when (event) { is GenericRelationshipAddEvent -> onGenericRelationshipAdd(event) is GenericRelationshipRemoveEvent -> onGenericRelationshipRemove(event) is GenericGroupMessageReactionEvent -> onGenericGroupMessageReaction(event) is GenericGroupUpdateEvent -> onGenericGroupUpdate(event) is GenericCallUpdateEvent -> onGenericCallUpdate(event) is GenericCallVoiceEvent -> onGenericCallVoice(event) } when (event) { is GenericGroupMessageEvent -> onGenericGroupMessage(event) } when (event) { is GenericRelationshipEvent -> onGenericRelationship(event) is GenericGroupEvent -> onGenericGroup(event) is GenericCallEvent -> onGenericCall(event) } } } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/rename/labeledLambdaByLabelRefAfterLabel/before/test.kt
13
90
fun <R> foo(f: () -> R) = f() fun test() { foo bar@ { return@bar /*rename*/ false } }
apache-2.0
smmribeiro/intellij-community
plugins/kotlin/completion/tests/testData/handlers/basic/stringTemplate/AfterDot2.kt
9
88
fun foo(param: String) { val s = "$param.<caret>bla-bla-bla" } // ELEMENT: hashCode
apache-2.0
MartinStyk/AndroidApkAnalyzer
app/src/main/java/sk/styk/martin/apkanalyzer/util/bindingadapters/RecyclerViewBindingAdapters.kt
1
382
package sk.styk.martin.apkanalyzer.util.bindingadapters import androidx.databinding.BindingAdapter import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.RecyclerView @BindingAdapter("itemDecoration") fun RecyclerView.itemDecoration(decorate: Boolean) { addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) }
gpl-3.0
ThiagoGarciaAlves/intellij-community
platform/lang-impl/src/com/intellij/execution/impl/TimedIconCache.kt
9
3683
/* * 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.intellij.execution.impl import com.intellij.execution.ProgramRunnerUtil import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.configurations.RuntimeConfigurationException import com.intellij.openapi.project.DumbService import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.registry.Registry import com.intellij.ui.IconDeferrer import com.intellij.util.containers.ObjectLongHashMap import gnu.trove.THashMap import java.util.concurrent.locks.ReentrantReadWriteLock import javax.swing.Icon import kotlin.concurrent.read import kotlin.concurrent.write class TimedIconCache { private val idToIcon = THashMap<String, Icon>() private val iconCheckTimes = ObjectLongHashMap<String>() private val iconCalcTime = ObjectLongHashMap<String>() private val lock = ReentrantReadWriteLock() fun remove(id: String) { lock.write { idToIcon.remove(id) iconCheckTimes.remove(id) iconCalcTime.remove(id) } } fun get(id: String, settings: RunnerAndConfigurationSettings, project: Project): Icon { return lock.read { idToIcon.get(id) } ?: lock.write { idToIcon.get(id)?.let { return it } val icon = IconDeferrer.getInstance().deferAutoUpdatable(settings.configuration.icon, project.hashCode() xor settings.hashCode()) { if (project.isDisposed) { return@deferAutoUpdatable null } lock.write { iconCalcTime.remove(id) } val startTime = System.currentTimeMillis() val icon = calcIcon(settings, project) lock.write { iconCalcTime.put(id, System.currentTimeMillis() - startTime) } icon } set(id, icon) icon } } private fun calcIcon(settings: RunnerAndConfigurationSettings, project: Project): Icon { try { settings.checkSettings() return ProgramRunnerUtil.getConfigurationIcon(settings, false) } catch (e: IndexNotReadyException) { return ProgramRunnerUtil.getConfigurationIcon(settings, false) } catch (ignored: RuntimeConfigurationException) { return ProgramRunnerUtil.getConfigurationIcon(settings, !DumbService.isDumb(project)) } } private fun set(id: String, icon: Icon) { idToIcon.put(id, icon) iconCheckTimes.put(id, System.currentTimeMillis()) } fun clear() { lock.write { idToIcon.clear() iconCheckTimes.clear() iconCalcTime.clear() } } fun checkValidity(id: String) { lock.read { val lastCheckTime = iconCheckTimes.get(id) var expired = lastCheckTime == -1L if (!expired) { var calcTime = iconCalcTime.get(id) if (calcTime == -1L || calcTime < 150) { calcTime = 150L } expired = (System.currentTimeMillis() - lastCheckTime) > (calcTime * 10) } if (expired) { lock.write { idToIcon.remove(id) } } } } }
apache-2.0
hsz/idea-gitignore
src/main/kotlin/mobi/hsz/idea/gitignore/lang/kind/DarcsLanguage.kt
1
794
// 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 mobi.hsz.idea.gitignore.lang.kind import mobi.hsz.idea.gitignore.IgnoreBundle import mobi.hsz.idea.gitignore.file.type.kind.DarcsFileType import mobi.hsz.idea.gitignore.lang.IgnoreLanguage import mobi.hsz.idea.gitignore.util.Icons /** * Darcs [IgnoreLanguage] definition. */ class DarcsLanguage private constructor() : IgnoreLanguage("Darcs", "boringignore", ".darcs", Icons.DARCS) { companion object { val INSTANCE = DarcsLanguage() } override val fileType get() = DarcsFileType.INSTANCE override val defaultSyntax get() = IgnoreBundle.Syntax.REGEXP override val isVCS get() = true }
mit
softappeal/yass
kotlin/yass/main/ch/softappeal/yass/remote/Message.kt
1
420
package ch.softappeal.yass.remote sealed class Message class Request(val serviceId: Int, val methodId: Int, val arguments: List<Any?>) : Message() abstract class Reply : Message() { internal abstract fun process(): Any? } class ValueReply(val value: Any?) : Reply() { override fun process() = value } class ExceptionReply(val exception: Exception) : Reply() { override fun process() = throw exception }
bsd-3-clause
kerubistan/kerub
src/test/kotlin/com/github/kerubistan/kerub/stories/websocket/WebsocketNotificationsDefs.kt
2
8212
package com.github.kerubistan.kerub.stories.websocket import com.github.kerubistan.kerub.createClient import com.github.kerubistan.kerub.login import com.github.kerubistan.kerub.model.Entity import com.github.kerubistan.kerub.model.Pool import com.github.kerubistan.kerub.model.messages.EntityAddMessage import com.github.kerubistan.kerub.model.messages.EntityRemoveMessage import com.github.kerubistan.kerub.model.messages.EntityUpdateMessage import com.github.kerubistan.kerub.model.messages.Message import com.github.kerubistan.kerub.model.messages.SubscribeMessage import com.github.kerubistan.kerub.runRestAction import com.github.kerubistan.kerub.services.HostService import com.github.kerubistan.kerub.services.PoolService import com.github.kerubistan.kerub.services.RestCrud import com.github.kerubistan.kerub.services.VirtualMachineService import com.github.kerubistan.kerub.services.VirtualNetworkService import com.github.kerubistan.kerub.services.VirtualStorageDeviceService import com.github.kerubistan.kerub.services.getServiceBaseUrl import com.github.kerubistan.kerub.stories.entities.EntityDefs import com.github.kerubistan.kerub.testDisk import com.github.kerubistan.kerub.testVirtualNetwork import com.github.kerubistan.kerub.testVm import com.github.kerubistan.kerub.testWsUrl import com.github.kerubistan.kerub.utils.createObjectMapper import com.github.kerubistan.kerub.utils.getLogger import cucumber.api.java.en.Given import cucumber.api.java.en.Then import cucumber.api.java.en.When import io.github.kerubistan.kroki.time.now import org.eclipse.jetty.websocket.api.Session import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect import org.eclipse.jetty.websocket.api.annotations.OnWebSocketError import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage import org.eclipse.jetty.websocket.api.annotations.WebSocket import org.eclipse.jetty.websocket.client.WebSocketClient import org.junit.After import java.net.CookieManager import java.net.HttpCookie import java.net.URI import java.util.UUID import java.util.concurrent.ArrayBlockingQueue import java.util.concurrent.BlockingQueue import java.util.concurrent.TimeUnit import kotlin.reflect.KClass import kotlin.test.fail class WebsocketNotificationsDefs { private var socketClient: WebSocketClient? = null private var session: Session? = null private val events: BlockingQueue<Any> = ArrayBlockingQueue<Any>(1024) private var entities = listOf<Any>() private var listener: Listener? = null data class ConnectEvent(val time: Long = now()) data class DisconnectEvent(val time: Long = now()) data class MessageEvent(val time: Long = now(), val message: Message) @WebSocket class Listener(private val messages: BlockingQueue<Any>) { companion object { private val mapper = createObjectMapper() } @OnWebSocketConnect fun connect(session: Session) { logger.info("connected: ${session.isOpen}") messages.put(ConnectEvent()) } @OnWebSocketClose fun close(code: Int, msg: String?) { logger.info("connection closed {} {}", code, msg) messages.put(DisconnectEvent()) } @OnWebSocketMessage fun message(session: Session, input: String) { logger.info("message: {}", input) val msg = mapper.readValue(input, Message::class.java) messages.add(MessageEvent(message = msg)) logger.info("message: {}", msg) } @OnWebSocketError fun error(error: Throwable) { logger.info("socket error", error) } } companion object { private val logger = getLogger() private val mapper = createObjectMapper(prettyPrint = true) } @Given("(\\S+) is connected to websocket") fun connectToWebsocket(listenerUser: String) { val client = createClient() val response = client.login(username = listenerUser, password = "password") socketClient = WebSocketClient() socketClient!!.cookieStore = CookieManager().cookieStore response.cookies.forEach { socketClient!!.cookieStore.add(URI(getServiceBaseUrl()), HttpCookie(it.value.name, it.value.value)) } socketClient!!.start() listener = Listener(events) session = socketClient!!.connect(listener, URI(testWsUrl)).get() } @Given("user subscribed to message feed (\\S+)") fun subscribeToMessageFeed(messageFeed: String) { session!!.remote.sendString(mapper.writeValueAsString(SubscribeMessage(channel = messageFeed))) } private val actions = mapOf<String, (RestCrud<Entity<UUID>>, Entity<UUID>) -> Any>( "creates" to { x, obj -> entities += x.add(obj) obj }, "updates" to { x, obj -> x.update(obj.id, obj) }, "deletes" to { x, obj -> x.delete(obj.id) EntityDefs.instance.entityDropped(obj) } ) private val entityTypes = mapOf<String, KClass<*>>( "vm" to VirtualMachineService::class, "virtual network" to VirtualNetworkService::class, "virtual disk" to VirtualStorageDeviceService::class, "pool" to PoolService::class, "host" to HostService::class ) @When("the user (\\S+) creates (vm|virtual network|virtual disk|pool)") fun runUserAdd(userName: String, entityType: String) { val client = createClient() client.login(userName, "password") when(entityType) { "vm" -> client.runRestAction(VirtualMachineService::class) { entities += it.add(testVm.copy(id= UUID.randomUUID())) } "virtual network" -> client.runRestAction(VirtualNetworkService::class) { entities += it.add(testVirtualNetwork.copy(id = UUID.randomUUID())) } "virtual disk" -> client.runRestAction(VirtualStorageDeviceService::class) { entities += it.add(testDisk.copy(id = UUID.randomUUID())) } "pool" -> client.runRestAction(PoolService::class) { entities += it.add(Pool(name = "test pool", templateId = UUID.randomUUID())) } } } @When("the user (\\S+) (updates|deletes) (vm|virtual network|virtual disk|pool) (\\S+)") fun runUserAction(userName: String, action: String, entityType: String, entityName: String) { val client = createClient() client.login(userName, "password") client.runRestAction(requireNotNull(entityTypes[entityType]) { "Unknown type: $entityType" }) { val actionFn = requireNotNull(actions[action]) { "Unhandled action: $action" } actionFn(it as RestCrud<Entity<UUID>>, EntityDefs.instance.getEntity(entityName)) } } @Then("listener user must not receive socket notification( with type.*)?") fun checkNoNotification(type: String?) { logger.info("expecting NO message....") val expectedType = type?.substringAfter(" with type ")?.trim() var event = events.poll(100, TimeUnit.MILLISECONDS) while (event != null) { logger.info("event: {}", event) if (event is MessageEvent && matchesType(expectedType, event)) { fail("expected no ${expectedType ?: ""} message, got $event") } event = events.poll(100, TimeUnit.MILLISECONDS) } } @Then("listener user must receive socket notification( with type .*)?") fun checkNotification(type: String?) { val eventsReceived = mutableListOf<Any>() val expectedType = type?.substringAfter(" with type ")?.trim() logger.info("expecting message....") var event = events.poll(1000, TimeUnit.MILLISECONDS) while (event != null) { eventsReceived.add(event) logger.info("event: {}", event) if (event is MessageEvent && matchesType(expectedType, event)) { logger.info("pass...") return } event = events.poll(1000, TimeUnit.MILLISECONDS) } fail("expected ${expectedType ?: ""} message not received\n got instead: $eventsReceived") } private val eventTypes = mapOf( "update" to EntityUpdateMessage::class, "delete" to EntityRemoveMessage::class, "create" to EntityAddMessage::class ) private fun matchesType(expectedType: String?, event: MessageEvent): Boolean = expectedType == null || event.message.javaClass.kotlin == eventTypes[expectedType] @After fun cleanup() { socketClient?.stop() val client = createClient() client.login("admin", "password") entities.forEach { entity -> when (entity) { is Entity<*> -> client.runRestAction(VirtualMachineService::class) { it.delete(entity.id as UUID) } else -> fail("can not clean up $entity") } } } }
apache-2.0
quran/quran_android
app/src/test/java/com/quran/labs/androidquran/presenter/translation/BaseTranslationPresenterTest.kt
2
5438
package com.quran.labs.androidquran.presenter.translation import com.quran.data.core.QuranInfo import com.quran.data.model.QuranText import com.quran.data.model.VerseRange import com.quran.data.pageinfo.common.MadaniDataSource import com.quran.labs.androidquran.common.LocalTranslation import com.quran.labs.androidquran.common.TranslationMetadata import com.quran.labs.androidquran.database.TranslationsDBAdapter import com.quran.labs.androidquran.model.translation.TranslationModel import com.quran.labs.androidquran.presenter.Presenter import com.quran.labs.androidquran.util.TranslationUtil import org.junit.Before import org.junit.Test import java.util.ArrayList import java.util.HashMap import com.google.common.truth.Truth.assertThat import org.mockito.Mockito class BaseTranslationPresenterTest { private lateinit var presenter: BaseTranslationPresenter<TestPresenter> @Before fun setupTest() { presenter = BaseTranslationPresenter( Mockito.mock(TranslationModel::class.java), Mockito.mock(TranslationsDBAdapter::class.java), object : TranslationUtil(0, QuranInfo(MadaniDataSource())) { override fun parseTranslationText(quranText: QuranText, translationId: Int): TranslationMetadata { return TranslationMetadata(quranText.sura, quranText.ayah, quranText.text, translationId) } }, QuranInfo(MadaniDataSource()) ) } @Test fun testGetTranslationNames() { val databases = listOf("one.db", "two.db") val map = object : HashMap<String, LocalTranslation>() { init { put("one.db", LocalTranslation(1, "one.db", "One", "First", null, "", null, 1, 2)) put("two.db", LocalTranslation(2, "two.db", "Two", "Second", null, "", null, 1, 2)) put("three.db", LocalTranslation(3, "three.db", "Three", "Third", null, "", null, 1, 2)) } } val translations = presenter.getTranslations(databases, map) assertThat(translations).hasLength(2) assertThat(translations[0].translator).isEqualTo("First") assertThat(translations[1].translator).isEqualTo("Second") } @Test fun testHashlessGetTranslationNames() { val databases = listOf("one.db", "two.db") val map = HashMap<String, LocalTranslation>() val translations = presenter.getTranslations(databases, map) assertThat(translations).hasLength(2) assertThat(translations[0].filename).isEqualTo(databases[0]) assertThat(translations[1].filename).isEqualTo(databases[1]) } @Test fun testCombineAyahDataOneVerse() { val verseRange = VerseRange(1, 1, 1, 1, 1) val arabic = listOf(QuranText(1, 1, "first ayah")) val info = presenter.combineAyahData(verseRange, arabic, listOf(listOf(QuranText(1, 1, "translation"))), arrayOf(LocalTranslation(1, "one.db", "One", "First", null, "", null, 1, 2))) assertThat(info).hasSize(1) val first = info[0] assertThat(first.sura).isEqualTo(1) assertThat(first.ayah).isEqualTo(1) assertThat(first.texts).hasSize(1) assertThat(first.arabicText).isEqualTo("first ayah") assertThat(first.texts[0].text).isEqualTo("translation") assertThat(first.texts[0].localTranslationId).isEqualTo(1) } @Test fun testCombineAyahDataOneVerseEmpty() { val verseRange = VerseRange(1, 1, 1, 1, 1) val arabic = emptyList<QuranText>() val info = presenter.combineAyahData(verseRange, arabic, emptyList(), emptyArray()) assertThat(info).hasSize(0) } @Test fun testCombineAyahDataOneVerseNoArabic() { val verseRange = VerseRange(1, 1, 1, 1, 1) val arabic = emptyList<QuranText>() val info = presenter.combineAyahData(verseRange, arabic, listOf(listOf(QuranText(1, 1, "translation"))), emptyArray()) assertThat(info).hasSize(1) val first = info[0] assertThat(first.sura).isEqualTo(1) assertThat(first.ayah).isEqualTo(1) assertThat(first.texts).hasSize(1) assertThat(first.arabicText).isNull() assertThat(first.texts[0].text).isEqualTo("translation") } @Test fun testCombineAyahDataArabicEmptyTranslations() { val verseRange = VerseRange(1, 1, 1, 2, 2) val arabic = listOf( QuranText(1, 1, "first ayah"), QuranText(1, 2, "second ayah") ) val info = presenter.combineAyahData(verseRange, arabic, ArrayList(), emptyArray()) assertThat(info).hasSize(2) assertThat(info[0].sura).isEqualTo(1) assertThat(info[0].ayah).isEqualTo(1) assertThat(info[0].texts).hasSize(0) assertThat(info[0].arabicText).isEqualTo("first ayah") assertThat(info[1].sura).isEqualTo(1) assertThat(info[1].ayah).isEqualTo(2) assertThat(info[1].texts).hasSize(0) assertThat(info[1].arabicText).isEqualTo("second ayah") } @Test fun testEnsureProperTranslations() { val verseRange = VerseRange(1, 1, 1, 2, 2) val text = listOf(QuranText(1, 1, "bismillah")) val result = presenter.ensureProperTranslations(verseRange, text) assertThat(result).hasSize(2) val first = result[0] assertThat(first.sura).isEqualTo(1) assertThat(first.ayah).isEqualTo(1) assertThat(first.text).isEqualTo("bismillah") val second = result[1] assertThat(second.sura).isEqualTo(1) assertThat(second.ayah).isEqualTo(2) assertThat(second.text).isEmpty() } private class TestPresenter : Presenter<Any> { override fun bind(what: Any) {} override fun unbind(what: Any) {} } }
gpl-3.0
orgzly/orgzly-android
app/src/main/java/com/orgzly/android/NotificationChannels.kt
1
3609
package com.orgzly.android import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.graphics.Color import android.os.Build import androidx.annotation.RequiresApi import com.orgzly.R import com.orgzly.android.reminders.RemindersNotifications import com.orgzly.android.ui.util.getNotificationManager /** * Creates all channels for notifications. */ object NotificationChannels { const val ONGOING = "ongoing" const val REMINDERS = "reminders" const val SYNC_PROGRESS = "sync-progress" const val SYNC_FAILED = "sync-failed" @JvmStatic fun createAll(context: Context) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { createForOngoing(context) createForReminders(context) createForSyncProgress(context) createForSyncFailed(context) } } @RequiresApi(Build.VERSION_CODES.O) private fun createForReminders(context: Context) { val id = REMINDERS val name = context.getString(R.string.reminders_channel_name) val description = context.getString(R.string.reminders_channel_description) val importance = NotificationManager.IMPORTANCE_HIGH val channel = NotificationChannel(id, name, importance) channel.description = description channel.enableLights(true) channel.lightColor = Color.BLUE channel.vibrationPattern = RemindersNotifications.VIBRATION_PATTERN channel.setShowBadge(false) context.getNotificationManager().createNotificationChannel(channel) } @RequiresApi(Build.VERSION_CODES.O) private fun createForOngoing(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return } val id = ONGOING val name = context.getString(R.string.ongoing_channel_name) val description = context.getString(R.string.ongoing_channel_description) val importance = NotificationManager.IMPORTANCE_MIN val channel = NotificationChannel(id, name, importance) channel.description = description channel.setShowBadge(false) context.getNotificationManager().createNotificationChannel(channel) } @RequiresApi(Build.VERSION_CODES.O) private fun createForSyncProgress(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return } val id = SYNC_PROGRESS val name = context.getString(R.string.sync_progress_channel_name) val description = context.getString(R.string.sync_progress_channel_description) val importance = NotificationManager.IMPORTANCE_LOW val channel = NotificationChannel(id, name, importance) channel.description = description channel.setShowBadge(false) context.getNotificationManager().createNotificationChannel(channel) } @RequiresApi(Build.VERSION_CODES.O) private fun createForSyncFailed(context: Context) { if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) { return } val id = SYNC_FAILED val name = context.getString(R.string.sync_failed_channel_name) val description = context.getString(R.string.sync_failed_channel_description) val importance = NotificationManager.IMPORTANCE_DEFAULT val channel = NotificationChannel(id, name, importance) channel.description = description channel.setShowBadge(true) context.getNotificationManager().createNotificationChannel(channel) } }
gpl-3.0
seventhroot/elysium
bukkit/rpk-essentials-bukkit/src/main/kotlin/com/rpkit/essentials/bukkit/logmessage/RPKLogMessagesEnabled.kt
1
300
package com.rpkit.essentials.bukkit.logmessage import com.rpkit.core.database.Entity import com.rpkit.players.bukkit.profile.RPKMinecraftProfile class RPKLogMessagesEnabled( override var id: Int = 0, val minecraftProfile: RPKMinecraftProfile, var enabled: Boolean ): Entity
apache-2.0
seventhroot/elysium
bukkit/rpk-stores-bukkit/src/main/kotlin/com/rpkit/store/bukkit/purchase/RPKPurchaseProviderImpl.kt
1
3617
/* * Copyright 2018 Ross Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.store.bukkit.purchase import com.rpkit.players.bukkit.profile.RPKProfile import com.rpkit.store.bukkit.RPKStoresBukkit import com.rpkit.store.bukkit.database.table.RPKConsumablePurchaseTable import com.rpkit.store.bukkit.database.table.RPKPermanentPurchaseTable import com.rpkit.store.bukkit.database.table.RPKPurchaseTable import com.rpkit.store.bukkit.database.table.RPKTimedPurchaseTable import com.rpkit.store.bukkit.event.purchase.RPKBukkitPurchaseCreateEvent import com.rpkit.store.bukkit.event.purchase.RPKBukkitPurchaseDeleteEvent import com.rpkit.store.bukkit.event.purchase.RPKBukkitPurchaseUpdateEvent class RPKPurchaseProviderImpl(private val plugin: RPKStoresBukkit): RPKPurchaseProvider { override fun getPurchases(profile: RPKProfile): List<RPKPurchase> { return plugin.core.database.getTable(RPKPurchaseTable::class).get(profile) } override fun getPurchase(id: Int): RPKPurchase? { return plugin.core.database.getTable(RPKPurchaseTable::class)[id] } override fun addPurchase(purchase: RPKPurchase) { val event = RPKBukkitPurchaseCreateEvent(purchase) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val eventPurchase = event.purchase when (eventPurchase) { is RPKConsumablePurchase -> plugin.core.database.getTable(RPKConsumablePurchaseTable::class).insert(eventPurchase) is RPKPermanentPurchase -> plugin.core.database.getTable(RPKPermanentPurchaseTable::class).insert(eventPurchase) is RPKTimedPurchase -> plugin.core.database.getTable(RPKTimedPurchaseTable::class).insert(eventPurchase) } } override fun updatePurchase(purchase: RPKPurchase) { val event = RPKBukkitPurchaseUpdateEvent(purchase) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val eventPurchase = event.purchase when (eventPurchase) { is RPKConsumablePurchase -> plugin.core.database.getTable(RPKConsumablePurchaseTable::class).update(eventPurchase) is RPKPermanentPurchase -> plugin.core.database.getTable(RPKPermanentPurchaseTable::class).update(eventPurchase) is RPKTimedPurchase -> plugin.core.database.getTable(RPKTimedPurchaseTable::class).update(eventPurchase) } } override fun removePurchase(purchase: RPKPurchase) { val event = RPKBukkitPurchaseDeleteEvent(purchase) plugin.server.pluginManager.callEvent(event) if (event.isCancelled) return val eventPurchase = event.purchase when (eventPurchase) { is RPKConsumablePurchase -> plugin.core.database.getTable(RPKConsumablePurchaseTable::class).delete(eventPurchase) is RPKPermanentPurchase -> plugin.core.database.getTable(RPKPermanentPurchaseTable::class).delete(eventPurchase) is RPKTimedPurchase -> plugin.core.database.getTable(RPKTimedPurchaseTable::class).delete(eventPurchase) } } }
apache-2.0
Litote/kmongo
kmongo-annotation-processor/src/test/kotlin/org/litote/kmongo/model/NotAnnotatedData.kt
1
701
/* * Copyright (C) 2016/2022 Litote * * 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.litote.kmongo.model /** * */ open class NotAnnotatedData { var test: String? = null }
apache-2.0
RSDT/Japp
app/src/main/java/nl/rsdt/japp/jotial/maps/wrapper/osm/OsmJotiMap.kt
1
5973
package nl.rsdt.japp.jotial.maps.wrapper.osm import android.graphics.Bitmap import android.location.Location import android.util.Pair import android.view.PixelCopy import com.google.android.gms.maps.GoogleMap import com.google.android.gms.maps.model.* import nl.rsdt.japp.jotial.maps.window.CustomInfoWindowAdapter import nl.rsdt.japp.jotial.maps.wrapper.* import org.osmdroid.events.MapEventsReceiver import org.osmdroid.events.MapListener import org.osmdroid.events.ScrollEvent import org.osmdroid.events.ZoomEvent import org.osmdroid.util.GeoPoint import org.osmdroid.views.MapView import org.osmdroid.views.overlay.MapEventsOverlay import java.util.* /** * Created by mattijn on 07/08/17. */ class OsmJotiMap private constructor(val osmMap: MapView //todo fix type ) : IJotiMap { private var eventsOverlay: MapEventsOverlay? = null override val uiSettings: IUiSettings get() = OsmUiSettings(osmMap) override val previousCameraPosition: ICameraPosition get() = OsmCameraPosition(osmMap) init { eventsOverlay = MapEventsOverlay(object : MapEventsReceiver { override fun singleTapConfirmedHelper(p: GeoPoint): Boolean { return false } override fun longPressHelper(p: GeoPoint): Boolean { return false } }) osmMap.overlays.add(0, eventsOverlay) } override fun setPreviousCameraPosition(latitude: Double, longitude: Double) { val previousCameraPosition = GeoPoint(latitude, longitude) } override fun setPreviousZoom(previousZoom: Int) { //TODO } override fun setPreviousRotation(rotation: Float) { //TODO } override fun delete() { if (osm_instances.containsValue(this)) { osm_instances.remove(this.osmMap) } } override fun setInfoWindowAdapter(infoWindowAdapter: CustomInfoWindowAdapter) { //// TODO: 30/08/17 } override fun setGMapType(mapType: Int) { //// TODO: 30/08/17 } override fun setMapStyle(mapStyleOptions: MapStyleOptions): Boolean { return false //// TODO: 30/08/17 } override fun animateCamera(latLng: LatLng, zoom: Int) { osmMap.controller.animateTo(GeoPoint(latLng.latitude, latLng.longitude)) osmMap.controller.zoomTo(zoom)//// TODO: 07/08/17 controleren of de zoomlevels van googlemaps en osm enigzins overeenkomen. } override fun addMarker(markerOptions: Pair<MarkerOptions, Bitmap?>): IMarker { return OsmMarker(markerOptions, osmMap) } override fun addPolyline(polylineOptions: PolylineOptions): IPolyline { return OsmPolyline(polylineOptions, osmMap) } override fun addPolygon(polygonOptions: PolygonOptions): IPolygon { return OsmPolygon(polygonOptions, osmMap) } override fun addCircle(circleOptions: CircleOptions): ICircle { return OsmCircle(circleOptions, osmMap) } override fun setOnMapClickListener(onMapClickListener: IJotiMap.OnMapClickListener?) { osmMap.overlays.remove(eventsOverlay) eventsOverlay = MapEventsOverlay(object : MapEventsReceiver { override fun singleTapConfirmedHelper(p: GeoPoint): Boolean { return onMapClickListener?.onMapClick(LatLng(p.latitude, p.longitude)) ?: false } override fun longPressHelper(p: GeoPoint): Boolean { return false } }) osmMap.overlays.add(0, eventsOverlay) } override fun snapshot(snapshotReadyCallback: IJotiMap.SnapshotReadyCallback?) { this.osmMap.isDrawingCacheEnabled = false this.osmMap.isDrawingCacheEnabled = true this.osmMap.buildDrawingCache() val bm = this.osmMap.drawingCache snapshotReadyCallback?.onSnapshotReady(bm) } override fun animateCamera(latLng: LatLng, zoom: Int, cancelableCallback: IJotiMap.CancelableCallback?) { osmMap.controller.setCenter(GeoPoint(latLng.latitude, latLng.longitude)) osmMap.controller.setZoom(zoom) cancelableCallback?.onFinish() } override fun setOnCameraMoveStartedListener(onCameraMoveStartedListener: GoogleMap.OnCameraMoveStartedListener?) { if (onCameraMoveStartedListener != null) { osmMap.setMapListener(object : MapListener { override fun onScroll(event: ScrollEvent): Boolean { onCameraMoveStartedListener.onCameraMoveStarted(GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) return false } override fun onZoom(event: ZoomEvent): Boolean { onCameraMoveStartedListener.onCameraMoveStarted(GoogleMap.OnCameraMoveStartedListener.REASON_GESTURE) return false } }) } else { osmMap.setMapListener(null) } } override fun cameraToLocation(b: Boolean, location: Location, zoom: Float, aoa: Float, bearing: Float) { osmMap.controller.animateTo(GeoPoint(location.latitude, location.longitude)) } override fun clear() { osmMap.overlays.clear() } override fun setOnInfoWindowLongClickListener(onInfoWindowLongClickListener: GoogleMap.OnInfoWindowLongClickListener?) { //// TODO: 30/08/17 } override fun setMarkerOnClickListener(listener: IJotiMap.OnMarkerClickListener?) { OsmMarker.setAllOnClickLister(listener) } override fun getMapAsync(callback: IJotiMap.OnMapReadyCallback) { callback.onMapReady(this) } companion object { private val osm_instances = HashMap<MapView, OsmJotiMap>() fun getJotiMapInstance(map: MapView): OsmJotiMap? { if (!osm_instances.containsKey(map)) { val jm = OsmJotiMap(map) osm_instances[map] = jm } return osm_instances[map] } } }
apache-2.0
uPhyca/CreditCardEditText
library-test/src/androidTest/java/com/uphyca/creditcardedittext/subject/CreditCardNumberEditTextSubject.kt
1
1492
package com.uphyca.creditcardedittext.subject import com.google.common.truth.FailureMetadata import com.google.common.truth.Subject import com.google.common.truth.Subject.Factory import com.google.common.truth.Truth.assertAbout import com.uphyca.creditcardedittext.CreditCardBrand import com.uphyca.creditcardedittext.CreditCardNumberEditText /** * Subject for [CreditCardNumberEditText] instances. */ class CreditCardNumberEditTextSubject private constructor( failureMetadata: FailureMetadata, private val actual: CreditCardNumberEditText ) : Subject(failureMetadata, actual) { fun hasNumber(number: String?) { check("getNumber()") .that(actual.number) .isEqualTo(number) } fun hasTextString(number: String?) { check("getNumber()") .that(actual.text.toString()) .isEqualTo(number) } fun hasBrand(brand: CreditCardBrand?) { check("getNumber()") .that(actual.brand) .isEqualTo(brand) } companion object { @JvmStatic fun assertThat(editText: CreditCardNumberEditText?): CreditCardNumberEditTextSubject { return assertAbout(editTexts()).that(editText) } private fun editTexts(): Factory<CreditCardNumberEditTextSubject, CreditCardNumberEditText> { return Factory { failureMetadata, actual -> CreditCardNumberEditTextSubject(failureMetadata, actual) } } } }
apache-2.0
artjimlop/clean-architecture-kotlin
data/src/main/java/com/example/data/datasources/LocalComicDatasource.kt
1
405
package com.example.data.datasources import com.example.data.datasources.dtos.entities.ComicEntity import com.example.data.datasources.dtos.entities.ImageEntity interface LocalComicDatasource { fun loadComicById(comicId: Int): Pair<ComicEntity, List<ImageEntity>> fun saveComics(comicPairs: List<Pair<ComicEntity, List<ImageEntity>>>) fun loadImagesByComic(comicId: Int): List<ImageEntity> }
apache-2.0
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/atlas2/Atlas2TokenType.kt
1
844
package com.gmail.blueboxware.libgdxplugin.filetypes.atlas2 import com.intellij.psi.tree.IElementType import org.jetbrains.annotations.NonNls /* * Copyright 2022 Blue Box Ware * * 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. */ class Atlas2TokenType(@NonNls debugName: String) : IElementType(debugName, LibGDXAtlas2Language.INSTANCE)
apache-2.0
fuzhouch/qbranch
compiler/src/main/kotlin/net/dummydigit/qbranch/compiler/symbols/ImportDef.kt
1
482
// Licensed under the MIT license. See LICENSE file in the project root // for full license information. package net.dummydigit.qbranch.compiler.symbols import net.dummydigit.qbranch.compiler.SourceCodeInfo import net.dummydigit.qbranch.compiler.Translator internal class ImportDef(sourceCodeInfo : SourceCodeInfo, val importPath : String) : Symbol(sourceCodeInfo, SymbolType.Import, importPath) { override fun toTargetCode(gen: Translator): String = gen.generate(this) }
mit
RocketChat/Rocket.Chat.Android
app/src/main/java/chat/rocket/android/mentions/ui/MentionsFragment.kt
2
4234
package chat.rocket.android.mentions.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.recyclerview.widget.DefaultItemAnimator import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import chat.rocket.android.R import chat.rocket.android.analytics.AnalyticsManager import chat.rocket.android.analytics.event.ScreenViewEvent import chat.rocket.android.chatroom.adapter.ChatRoomAdapter import chat.rocket.android.chatroom.ui.ChatRoomActivity import chat.rocket.android.chatroom.uimodel.BaseUiModel import chat.rocket.android.helper.EndlessRecyclerViewScrollListener import chat.rocket.android.mentions.presentention.MentionsPresenter import chat.rocket.android.mentions.presentention.MentionsView import chat.rocket.android.util.extensions.inflate import chat.rocket.android.util.extensions.showToast import chat.rocket.android.util.extensions.ui import dagger.android.support.AndroidSupportInjection import kotlinx.android.synthetic.main.fragment_mentions.* import javax.inject.Inject fun newInstance(chatRoomId: String): Fragment = MentionsFragment().apply { arguments = Bundle(1).apply { putString(BUNDLE_CHAT_ROOM_ID, chatRoomId) } } internal const val TAG_MENTIONS_FRAGMENT = "MentionsFragment" private const val BUNDLE_CHAT_ROOM_ID = "chat_room_id" class MentionsFragment : Fragment(), MentionsView { @Inject lateinit var presenter: MentionsPresenter @Inject lateinit var analyticsManager: AnalyticsManager private lateinit var chatRoomId: String private val adapter = ChatRoomAdapter(enableActions = false) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) arguments?.run { chatRoomId = getString(BUNDLE_CHAT_ROOM_ID, "") } ?: requireNotNull(arguments) { "no arguments supplied when the fragment was instantiated" } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? = container?.inflate(R.layout.fragment_mentions) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupToolbar() presenter.loadMentions(chatRoomId) analyticsManager.logScreenView(ScreenViewEvent.Mentions) } override fun showMentions(mentions: List<BaseUiModel<*>>) { ui { if (recycler_view.adapter == null) { recycler_view.adapter = adapter val linearLayoutManager = LinearLayoutManager(context) recycler_view.layoutManager = linearLayoutManager recycler_view.itemAnimator = DefaultItemAnimator() if (mentions.size >= 30) { recycler_view.addOnScrollListener(object : EndlessRecyclerViewScrollListener(linearLayoutManager) { override fun onLoadMore( page: Int, totalItemsCount: Int, recyclerView: RecyclerView ) { presenter.loadMentions(chatRoomId) } }) } group_no_mention.isVisible = mentions.isEmpty() } adapter.appendData(mentions) } } override fun showMessage(resId: Int) { ui { showToast(resId) } } override fun showMessage(message: String) { ui { showToast(message) } } override fun showGenericErrorMessage() = showMessage(getString(R.string.msg_generic_error)) override fun showLoading() { ui { view_loading.isVisible = true } } override fun hideLoading() { ui { view_loading.isVisible = false } } private fun setupToolbar() { (activity as ChatRoomActivity).setupToolbarTitle((getString(R.string.msg_mentions))) } }
mit
KrenVpravo/CheckReaction
app/src/test/java/com/two_two/checkreaction/domain/science/colors/ColourShakerTest.kt
1
1448
package com.two_two.checkreaction.domain.science.colors import com.two_two.checkreaction.utils.Constants import org.junit.Assert.* import org.junit.Before import org.junit.Test import java.util.* /** * @author Dmitry Borodin on 2017-02-09. */ class ColourShakerTest { var shaker = ColourShaker() @Before fun setUp() { shaker = ColourShaker() } @Test fun testShakeSize() { val ZERO_INDEX = 1 for (i in 0..100) { shaker.shake() assertEquals(Constants.COLOURS_AVAILABLE_SCIENCE + ZERO_INDEX, shaker.shakedOrder.size) } } @Test fun testShakeNotRepeated() { shaker.shake() for (i in 0..100) { val oldShaked = ArrayList(shaker.shakedOrder) shaker.shake() val newShaked = ArrayList(shaker.shakedOrder) assertOrderDifferent(newShaked, oldShaked) } } private fun assertOrderDifferent(newShaked: ArrayList<Int>, oldShaked: ArrayList<Int>) { val LAST_ELEMENT = 1 for (j in 0..(newShaked.size - LAST_ELEMENT)) { assertNotEquals(oldShaked.get(j), newShaked.get(j)) } } @Test fun testsRestorebleColors() { shaker.shake() for (i in 0..shaker.shakedOrder.lastIndex) { val realIndex = shaker.getRealIndex(shakedIndex = i) assertEquals(realIndex, shaker.shakedOrder.indexOf(i)) } } }
mit
EdenYoon/LifeLogging
src/com/humanebyte/lifelogging/MyActivity.kt
1
2980
package com.humanebyte.lifelogging import android.app.Activity import android.content.Intent import android.os.Bundle import android.provider.Settings import android.view.View import android.widget.Button import android.widget.TextView class MyActivity : Activity(), View.OnClickListener { internal lateinit var service_status: TextView internal lateinit var setting: Button internal lateinit var button_force_speaker: Button internal lateinit var button_cancel_force_use: Button internal lateinit var button_bypass_keyevent: Button internal lateinit var button_eat_keyevent: Button public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main) service_status = findViewById(R.id.accessibility_service_status) as TextView setting = findViewById(R.id.setting) as Button setting.setOnClickListener(this) button_force_speaker = findViewById(R.id.force_speaker) as Button button_force_speaker.setOnClickListener(this) button_cancel_force_use = findViewById(R.id.cancel_force_use) as Button button_cancel_force_use.setOnClickListener(this) button_bypass_keyevent = findViewById(R.id.bypass_keyevent) as Button button_bypass_keyevent.setOnClickListener(this) button_eat_keyevent = findViewById(R.id.eat_keyevent) as Button button_eat_keyevent.setOnClickListener(this) } override fun onResume() { val isSet = AccessibilityServiceUtil.isAccessibilityServiceOn( applicationContext, "com.humanebyte.lifelogging", "com.humanebyte.lifelogging.MyAccessibilityService") if (isSet) { service_status.setText(R.string.accessibility_service_on) } else { service_status.setText(R.string.accessibility_service_off) } super.onResume() } override fun onClick(v: View) { when (v.id) { R.id.setting -> { val accessibilityServiceIntent = Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS) startActivity(accessibilityServiceIntent) } R.id.force_speaker -> { val i = Intent("com.humanebyte.lifelogging.force_speaker").putExtra("force_speaker", true) this.sendBroadcast(i) } R.id.cancel_force_use -> { val i = Intent("com.humanebyte.lifelogging.force_speaker").putExtra("force_speaker", false) this.sendBroadcast(i) } R.id.bypass_keyevent -> { val i = Intent("com.humanebyte.lifelogging.eat_keyevent").putExtra("eat", false) this.sendBroadcast(i) } R.id.eat_keyevent -> { val i = Intent("com.humanebyte.lifelogging.eat_keyevent").putExtra("eat", true) this.sendBroadcast(i) } } } }
mit
Esri/arcgis-runtime-samples-android
kotlin/group-layers/src/main/java/com/esri/arcgisruntime/sample/grouplayers/MainActivity.kt
1
8114
/* * Copyright 2020 Esri * * 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.esri.arcgisruntime.sample.grouplayers import android.os.Bundle import android.view.View import android.widget.ImageView import android.widget.LinearLayout import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.widget.ConstraintLayout import androidx.coordinatorlayout.widget.CoordinatorLayout import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.esri.arcgisruntime.ArcGISRuntimeEnvironment import com.esri.arcgisruntime.data.ServiceFeatureTable import com.esri.arcgisruntime.layers.* import com.esri.arcgisruntime.mapping.ArcGISScene import com.esri.arcgisruntime.mapping.BasemapStyle import com.esri.arcgisruntime.mapping.LayerList import com.esri.arcgisruntime.mapping.view.Camera import com.esri.arcgisruntime.mapping.view.SceneView import com.esri.arcgisruntime.sample.grouplayers.databinding.ActivityMainBinding import com.google.android.material.bottomsheet.BottomSheetBehavior class MainActivity : AppCompatActivity() { private val activityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } private val sceneView: SceneView by lazy { activityMainBinding.sceneView } private val bottomSheet: LinearLayout by lazy { activityMainBinding.bottomSheet.bottomSheetLayout } private val header: ConstraintLayout by lazy { activityMainBinding.bottomSheet.header } private val arrowImageView: ImageView by lazy { activityMainBinding.bottomSheet.arrowImageView } private val recyclerView: RecyclerView by lazy { activityMainBinding.bottomSheet.recyclerView } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(activityMainBinding.root) // authentication with an API key or named user is required to access basemaps and other // location services ArcGISRuntimeEnvironment.setApiKey(BuildConfig.API_KEY) // create different types of layers val trees = ArcGISSceneLayer("https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/DevA_Trees/SceneServer/layers/0").apply { name = "Trees" } val pathways = FeatureLayer(ServiceFeatureTable("https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/DevA_Pathways/FeatureServer/1")).apply { name = "Pathways" } val projectArea = FeatureLayer(ServiceFeatureTable("https://services.arcgis.com/P3ePLMYs2RVChkJx/arcgis/rest/services/DevelopmentProjectArea/FeatureServer/0")).apply { name = "Project area" // set the scene's viewpoint based on this layer's extent addDoneLoadingListener { sceneView.setViewpointCamera( Camera( fullExtent.center, 700.0, 0.0, 60.0, 0.0 ) ) } } val buildingsA = ArcGISSceneLayer("https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/DevA_BuildingShells/SceneServer/layers/0").apply { name = "Dev A" } val buildingsB = ArcGISSceneLayer("https://tiles.arcgis.com/tiles/P3ePLMYs2RVChkJx/arcgis/rest/services/DevB_BuildingShells/SceneServer/layers/0").apply { name = "Dev B" } // create a group layer from scratch by adding the trees, pathways, and project area as children val projectAreaGroupLayer = GroupLayer().apply { name = "Project area group" layers.addAll(arrayOf(trees, pathways, projectArea)) } // create a group layer for the buildings and set its visibility mode to exclusive val buildingsGroupLayer = GroupLayer().apply { name = "Buildings group" layers.addAll(arrayOf(buildingsA, buildingsB)) visibilityMode = GroupVisibilityMode.EXCLUSIVE } // create a scene with an imagery basemap val scene = ArcGISScene(BasemapStyle.ARCGIS_IMAGERY).apply { // add the group layer and other layers to the scene as operational layers operationalLayers.addAll(arrayOf(projectAreaGroupLayer, buildingsGroupLayer)) addDoneLoadingListener { setupBottomSheet(operationalLayers) } } // set the scene to be displayed in the scene view sceneView.scene = scene } private fun onLayerCheckedChanged(layer: Layer, isChecked: Boolean) { layer.isVisible = isChecked } /** Creates a bottom sheet to display a list of group layers. * * @param layers a list of layers and group layers to be displayed on the scene */ private fun setupBottomSheet(layers: LayerList) { // create a bottom sheet behavior from the bottom sheet view in the main layout val bottomSheetBehavior = BottomSheetBehavior.from(bottomSheet).apply { // expand the bottom sheet, and ensure it is displayed on the screen when collapsed state = BottomSheetBehavior.STATE_EXPANDED peekHeight = header.height // animate the arrow when the bottom sheet slides addBottomSheetCallback(object : BottomSheetBehavior.BottomSheetCallback() { override fun onSlide(bottomSheet: View, slideOffset: Float) { arrowImageView.rotation = slideOffset * 180f } override fun onStateChanged(bottomSheet: View, newState: Int) { arrowImageView.rotation = when (newState) { BottomSheetBehavior.STATE_EXPANDED -> 180f else -> arrowImageView.rotation } } }) } bottomSheet.apply { visibility = View.VISIBLE // expand or collapse the bottom sheet when the header is clicked header.setOnClickListener { bottomSheetBehavior.state = when (bottomSheetBehavior.state) { BottomSheetBehavior.STATE_COLLAPSED -> BottomSheetBehavior.STATE_EXPANDED else -> BottomSheetBehavior.STATE_COLLAPSED } } // initialize the recycler view with the group layers and set the callback for the checkboxes recyclerView.adapter = LayerListAdapter(layers) { layer: Layer, isChecked: Boolean -> onLayerCheckedChanged( layer, isChecked ) } recyclerView.layoutManager = LinearLayoutManager(applicationContext) // rotate the arrow so it starts off in the correct rotation arrowImageView.rotation = 180f } // shrink the scene view so it is not hidden under the bottom sheet header when collapsed (sceneView.layoutParams as CoordinatorLayout.LayoutParams).bottomMargin = header.height } override fun onResume() { super.onResume() sceneView.resume() } override fun onPause() { sceneView.pause() super.onPause() } override fun onDestroy() { sceneView.dispose() super.onDestroy() } }
apache-2.0
duftler/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/ThreadPoolQueueExecutor.kt
6
1256
/* * Copyright 2017 Netflix, 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 com.netflix.spinnaker.orca.q import com.netflix.spinnaker.q.QueueExecutor import org.springframework.beans.factory.annotation.Qualifier import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor import org.springframework.stereotype.Component @Component class ThreadPoolQueueExecutor( @Qualifier("messageHandlerPool") executor: ThreadPoolTaskExecutor ) : QueueExecutor<ThreadPoolTaskExecutor>(executor) { override fun hasCapacity() = executor.threadPoolExecutor.run { activeCount < maximumPoolSize } override fun availableCapacity() = executor.threadPoolExecutor.run { maximumPoolSize - activeCount } }
apache-2.0
googlecodelabs/android-compose-codelabs
AdvancedStateAndSideEffectsCodelab/app/src/main/java/androidx/compose/samples/crane/data/Cities.kt
1
2651
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.samples.crane.data val MADRID = City( name = "Madrid", country = "Spain", latitude = "40.416775", longitude = "-3.703790" ) val NAPLES = City( name = "Naples", country = "Italy", latitude = "40.853294", longitude = "14.305573" ) val DALLAS = City( name = "Dallas", country = "US", latitude = "32.779167", longitude = "-96.808891" ) val CORDOBA = City( name = "Cordoba", country = "Argentina", latitude = "-31.416668", longitude = "-64.183334" ) val MALDIVAS = City( name = "Maldivas", country = "South Asia", latitude = "1.924992", longitude = "73.399658" ) val ASPEN = City( name = "Aspen", country = "Colorado", latitude = "39.191097", longitude = "-106.817535" ) val BALI = City( name = "Bali", country = "Indonesia", latitude = "-8.3405", longitude = "115.0920" ) val BIGSUR = City( name = "Big Sur", country = "California", latitude = "36.2704", longitude = "-121.8081" ) val KHUMBUVALLEY = City( name = "Khumbu Valley", country = "Nepal", latitude = "27.9320", longitude = "86.8050" ) val ROME = City( name = "Rome", country = "Italy", latitude = "41.902782", longitude = "12.496366" ) val GRANADA = City( name = "Granada", country = "Spain", latitude = "37.18817", longitude = "-3.60667" ) val WASHINGTONDC = City( name = "Washington DC", country = "USA", latitude = "38.9072", longitude = "-77.0369" ) val BARCELONA = City( name = "Barcelona", country = "Spain", latitude = "41.390205", longitude = "2.154007" ) val CRETE = City( name = "Crete", country = "Greece", latitude = "35.2401", longitude = "24.8093" ) val LONDON = City( name = "London", country = "United Kingdom", latitude = "51.509865", longitude = "-0.118092" ) val PARIS = City( name = "Paris", country = "France", latitude = "48.864716", longitude = "2.349014" )
apache-2.0
summerlly/Quiet
app/src/main/java/tech/summerly/quiet/module/common/view/LoadStateView.kt
1
2924
/* * Copyright (C) 2017 YangBin * * 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 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package tech.summerly.quiet.module.common.view import android.annotation.SuppressLint import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import kotlinx.android.synthetic.main.common_view_load_state.view.* import tech.summerly.quiet.R /** * author : yangbin10 * date : 2017/11/17 * 放在需要加载数据的view上,提供一个加载的动画和加载失败的重试按钮 */ class LoadStateView : FrameLayout { private val root: View constructor(context: Context) : this(context, null) constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { @SuppressLint("InflateParams") root = LayoutInflater.from(context).inflate(R.layout.common_view_load_state, null, false) root.setOnTouchListener { _, _ -> //拦截触摸事件.. true } addView(root, FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)) } var loadingText: String = "载入中..." var failedText: String = "载入失败,点击重试." private var onRetryClickListener: View.OnClickListener? = null fun setLoading() { visibility = View.VISIBLE progressBar.visibility = View.VISIBLE imageStateIndicator.visibility = View.GONE textHint.text = loadingText } fun setLoadFailed() { visibility = View.VISIBLE progressBar.visibility = View.GONE imageStateIndicator.visibility = View.VISIBLE imageStateIndicator.setImageResource(R.drawable.ic_error_outline_black_24dp) textHint.text = failedText textHint.setOnClickListener { textHint.setOnClickListener(null) textHint.isClickable = false onRetryClickListener?.onClick(it) } } fun hide() { visibility = View.GONE } fun setRetryClickListener(listener: View.OnClickListener) { onRetryClickListener = listener } }
gpl-2.0
sdoward/RxGoogleMaps
rxgooglemap/src/main/java/com/sdoward/rxgooglemap/SnapshotFunc.kt
1
447
package com.sdoward.rxgooglemap import android.graphics.Bitmap import com.google.android.gms.maps.GoogleMap import io.reactivex.Observable import io.reactivex.functions.Function class SnapshotFunc : Function<GoogleMap, Observable<Bitmap>> { override fun apply(t: GoogleMap): Observable<Bitmap> { return Observable.create { subscriber -> t.snapshot { subscriber.onNext(it) } } } }
apache-2.0
cketti/k-9
app/core/src/test/java/com/fsck/k9/mailstore/MessageListRepositoryTest.kt
1
14809
package com.fsck.k9.mailstore import com.fsck.k9.mail.Address import com.fsck.k9.mail.Flag import com.fsck.k9.message.extractors.PreviewResult import com.google.common.truth.Truth.assertThat import java.util.UUID import org.junit.After import org.junit.Before import org.junit.Test import org.koin.core.context.startKoin import org.koin.core.context.stopKoin import org.koin.dsl.module import org.mockito.kotlin.any import org.mockito.kotlin.doAnswer import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq import org.mockito.kotlin.mock import org.mockito.kotlin.stub private const val MESSAGE_ID = 1L private const val MESSAGE_ID_2 = 2L private const val MESSAGE_ID_3 = 3L private const val FOLDER_ID = 20L private const val FOLDER_ID_2 = 21L private const val THREAD_ROOT = 30L private const val THREAD_ROOT_2 = 31L private const val SELECTION = "irrelevant" private val SELECTION_ARGS = arrayOf("irrelevant") private const val SORT_ORDER = "irrelevant" class MessageListRepositoryTest { private val accountUuid = UUID.randomUUID().toString() private val messageStore = mock<ListenableMessageStore>() private val messageStoreManager = mock<MessageStoreManager> { on { getMessageStore(accountUuid) } doReturn messageStore } private val messageListRepository = MessageListRepository(messageStoreManager) @Before fun setUp() { startKoin { modules( module { single { messageListRepository } } ) } } @After fun tearDown() { stopKoin() } @Test fun `adding and removing listener`() { var messageListChanged = 0 val listener = MessageListChangedListener { messageListChanged++ } messageListRepository.addListener(accountUuid, listener) messageListRepository.notifyMessageListChanged(accountUuid) assertThat(messageListChanged).isEqualTo(1) messageListRepository.removeListener(listener) messageListRepository.notifyMessageListChanged(accountUuid) assertThat(messageListChanged).isEqualTo(1) } @Test fun `only notify listener when account UUID matches`() { var messageListChanged = 0 val listener = MessageListChangedListener { messageListChanged++ } messageListRepository.addListener(accountUuid, listener) messageListRepository.notifyMessageListChanged("otherAccountUuid") assertThat(messageListChanged).isEqualTo(0) } @Test fun `notifyMessageListChanged() without any listeners should not throw`() { messageListRepository.notifyMessageListChanged(accountUuid) } @Test fun `getMessages() should use flag values from the cache`() { addMessages( MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = false, isStarred = true, isAnswered = false, isForwarded = true ) ) MessageListCache.getCache(accountUuid).apply { setFlagForMessages(listOf(MESSAGE_ID), Flag.SEEN, true) setValueForThreads(listOf(THREAD_ROOT), Flag.FLAGGED, false) } val result = messageListRepository.getMessages(accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER) { message -> MessageData( messageId = message.id, folderId = message.folderId, threadRoot = message.threadRoot, isRead = message.isRead, isStarred = message.isStarred, isAnswered = message.isAnswered, isForwarded = message.isForwarded ) } assertThat(result).containsExactly( MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = true, isStarred = false, isAnswered = false, isForwarded = true ) ) } @Test fun `getMessages() should skip messages marked as hidden in the cache`() { addMessages( MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT) ) hideMessage(MESSAGE_ID, FOLDER_ID) val result = messageListRepository.getMessages(accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID_2) } @Test fun `getMessages() should not skip message when marked as hidden in a different folder`() { addMessages( MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT) ) hideMessage(MESSAGE_ID, FOLDER_ID_2) val result = messageListRepository.getMessages(accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID, MESSAGE_ID_2) } @Test fun `getThreadedMessages() should use flag values from the cache`() { addThreadedMessages( MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = false, isStarred = true, isAnswered = false, isForwarded = true ) ) MessageListCache.getCache(accountUuid).apply { setFlagForMessages(listOf(MESSAGE_ID), Flag.SEEN, true) setValueForThreads(listOf(THREAD_ROOT), Flag.FLAGGED, false) } val result = messageListRepository.getThreadedMessages( accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER ) { message -> MessageData( messageId = message.id, folderId = message.folderId, threadRoot = message.threadRoot, isRead = message.isRead, isStarred = message.isStarred, isAnswered = message.isAnswered, isForwarded = message.isForwarded ) } assertThat(result).containsExactly( MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = true, isStarred = false, isAnswered = false, isForwarded = true ) ) } @Test fun `getThreadedMessages() should skip messages marked as hidden in the cache`() { addThreadedMessages( MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT_2) ) hideMessage(MESSAGE_ID, FOLDER_ID) val result = messageListRepository.getThreadedMessages( accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER ) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID_2) } @Test fun `getThreadedMessages() should not skip message when marked as hidden in a different folder`() { addThreadedMessages( MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT_2) ) hideMessage(MESSAGE_ID, FOLDER_ID_2) val result = messageListRepository.getThreadedMessages( accountUuid, SELECTION, SELECTION_ARGS, SORT_ORDER ) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID, MESSAGE_ID_2) } @Test fun `getThread() should use flag values from the cache`() { addMessagesToThread( THREAD_ROOT, MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = false, isStarred = true, isAnswered = false, isForwarded = true ), MessageData( messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = false, isStarred = true, isAnswered = true, isForwarded = false ) ) MessageListCache.getCache(accountUuid).apply { setFlagForMessages(listOf(MESSAGE_ID), Flag.SEEN, true) setValueForThreads(listOf(THREAD_ROOT), Flag.FLAGGED, false) } val result = messageListRepository.getThread( accountUuid, THREAD_ROOT, SORT_ORDER ) { message -> MessageData( messageId = message.id, folderId = message.folderId, threadRoot = message.threadRoot, isRead = message.isRead, isStarred = message.isStarred, isAnswered = message.isAnswered, isForwarded = message.isForwarded ) } assertThat(result).containsExactly( MessageData( messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = true, isStarred = false, isAnswered = false, isForwarded = true ), MessageData( messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT, isRead = false, isStarred = false, isAnswered = true, isForwarded = false ) ) } @Test fun `getThread() should skip messages marked as hidden in the cache`() { addMessagesToThread( THREAD_ROOT, MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_3, folderId = FOLDER_ID, threadRoot = THREAD_ROOT) ) hideMessage(MESSAGE_ID, FOLDER_ID) val result = messageListRepository.getThread(accountUuid, THREAD_ROOT, SORT_ORDER) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID_2, MESSAGE_ID_3) } @Test fun `getThread() should not skip message when marked as hidden in a different folder`() { addMessagesToThread( THREAD_ROOT, MessageData(messageId = MESSAGE_ID, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_2, folderId = FOLDER_ID, threadRoot = THREAD_ROOT), MessageData(messageId = MESSAGE_ID_3, folderId = FOLDER_ID, threadRoot = THREAD_ROOT) ) hideMessage(MESSAGE_ID, FOLDER_ID_2) val result = messageListRepository.getThread(accountUuid, THREAD_ROOT, SORT_ORDER) { message -> message.id } assertThat(result).containsExactly(MESSAGE_ID, MESSAGE_ID_2, MESSAGE_ID_3) } private fun addMessages(vararg messages: MessageData) { messageStore.stub { on { getMessages<Any>(eq(SELECTION), eq(SELECTION_ARGS), eq(SORT_ORDER), any()) } doAnswer { val mapper: MessageMapper<Any?> = it.getArgument(3) runMessageMapper(messages, mapper) } } } private fun addThreadedMessages(vararg messages: MessageData) { messageStore.stub { on { getThreadedMessages<Any>(eq(SELECTION), eq(SELECTION_ARGS), eq(SORT_ORDER), any()) } doAnswer { val mapper: MessageMapper<Any?> = it.getArgument(3) runMessageMapper(messages, mapper) } } } @Suppress("SameParameterValue") private fun addMessagesToThread(threadRoot: Long, vararg messages: MessageData) { messageStore.stub { on { getThread<Any>(eq(threadRoot), eq(SORT_ORDER), any()) } doAnswer { val mapper: MessageMapper<Any?> = it.getArgument(2) runMessageMapper(messages, mapper) } } } private fun runMessageMapper(messages: Array<out MessageData>, mapper: MessageMapper<Any?>): List<Any> { return messages.mapNotNull { message -> mapper.map(object : MessageDetailsAccessor { override val id = message.messageId override val messageServerId = "irrelevant" override val folderId = message.folderId override val fromAddresses = emptyList<Address>() override val toAddresses = emptyList<Address>() override val ccAddresses = emptyList<Address>() override val messageDate = 0L override val internalDate = 0L override val subject = "irrelevant" override val preview = PreviewResult.error() override val isRead = message.isRead override val isStarred = message.isStarred override val isAnswered = message.isAnswered override val isForwarded = message.isForwarded override val hasAttachments = false override val threadRoot = message.threadRoot override val threadCount = 0 }) } } @Suppress("SameParameterValue") private fun hideMessage(messageId: Long, folderId: Long) { val cache = MessageListCache.getCache(accountUuid) val localFolder = mock<LocalFolder> { on { databaseId } doReturn folderId } val localMessage = mock<LocalMessage> { on { databaseId } doReturn messageId on { folder } doReturn localFolder } cache.hideMessages(listOf(localMessage)) } } private data class MessageData( val messageId: Long, val folderId: Long, val threadRoot: Long, val isRead: Boolean = false, val isStarred: Boolean = false, val isAnswered: Boolean = false, val isForwarded: Boolean = false, )
apache-2.0
zhengjiong/ZJ_KotlinStudy
src/main/kotlin/com/zj/example/kotlin/basicsknowledge/15.InFixExample.kt
1
515
package com.zj.example.kotlin.basicsknowledge /** * * CreateTime: 17/9/13 16:23 * @author 郑炯 */ fun main(args: Array<String>) { var o = InFixExample() /** * 如果不使用中缀标签,调用方法是这样的: * o.on(1) * * 使用中缀标签就可以写成o on 1 */ println(o on 1) } class InFixExample{ /** * infix是中缀标签, 在方法只有一个参数的时候可以使用 */ infix fun on(x: Int): Boolean{ return true } }
mit
mbernier85/pet-finder
app/src/main/java/im/bernier/petfinder/mvp/view/ResultView.kt
1
831
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * If it is not possible or desirable to put the notice in a particular * file, then You may include the notice in a location (such as a LICENSE * file in a relevant directory) where a recipient would be likely to look * for such a notice. * * You may add additional accurate notices of copyright ownership. */ package im.bernier.petfinder.mvp.view import java.util.ArrayList import im.bernier.petfinder.model.Pet /** * Created by Michael on 2016-07-09. */ interface ResultView { fun updateResults(pets: ArrayList<Pet>) fun openPet(pet: Pet) fun showError(error: String) fun doFinish() }
mpl-2.0
dnkolegov/klox
src/test/kotlin/com/craftinkinterpreters/klox/Scanner.kt
1
1695
package com.craftinkinterpreters.klox import com.craftinginterpreters.klox.Scanner import com.craftinginterpreters.klox.TokenType.* import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test @DisplayName("Scanner tests") class ScannerTests { @Test fun basicTest() { Scanner("1 2 3 4").scanTokens().apply { assertEquals(5, size) } Scanner("//comment").scanTokens().apply { assertEquals(1, size) } Scanner(" \t \n \n \n").scanTokens().apply { assertEquals(1, size) } Scanner("123.45").scanTokens().apply { assertEquals(2, size) assertEquals("123.45", this[0].lexeme) } Scanner("""if (condition) {print "yes";} else {print "no";}""").scanTokens().apply { assertEquals(16, size) assertEquals(IF, this[0].type) assertEquals(LEFT_PAREN, this[1].type) assertEquals(IDENTIFIER, this[2].type) assertEquals(RIGHT_PAREN, this[3].type) assertEquals(LEFT_BRACE, this[4].type) assertEquals(PRINT, this[5].type) assertEquals(STRING, this[6].type) assertEquals(SEMICOLON, this[7].type) assertEquals(RIGHT_BRACE, this[8].type) assertEquals(ELSE, this[9].type) assertEquals(LEFT_BRACE, this[10].type) assertEquals(PRINT, this[11].type) assertEquals(STRING, this[12].type) assertEquals(SEMICOLON, this[13].type) assertEquals(RIGHT_BRACE, this[14].type) assertEquals(EOF, this[15].type) } } }
mit
LorittaBot/Loritta
web/showtime/backend/src/main/kotlin/net/perfectdreams/loritta/cinnamon/showtime/backend/views/home/ThankYou.kt
1
2174
package net.perfectdreams.loritta.cinnamon.showtime.backend.views.home import com.mrpowergamerbr.loritta.utils.locale.BaseLocale import kotlinx.html.DIV import kotlinx.html.a import kotlinx.html.div import kotlinx.html.h1 import kotlinx.html.h2 import kotlinx.html.img import kotlinx.html.p import kotlinx.html.style fun DIV.thankYou(locale: BaseLocale, sectionClassName: String) { div(classes = "$sectionClassName wobbly-bg") { style = "text-align: center;" h1 { + locale["website.home.thankYou.title"] } div(classes = "media") { div(classes = "media-figure") { img(src = "https://www.yourkit.com/images/yklogo.png") {} } div(classes = "media-body") { div { style = "text-align: left;" div { style = "text-align: center;" h2 { + "YourKit" } } p { + "YourKit supports open source projects with its full-featured Java Profiler. YourKit, LLC is the creator of "; a(href = "https://www.yourkit.com/java/profiler/") { + "YourKit Java Profiler" }; + " and "; a(href = "https://www.yourkit.com/.net/profiler/") { + "YourKit .NET Profiler" }; + " innovative and intelligent tools for profiling Java and .NET applications." } } } } /* div(classes = "cards") { div { img(src = "https://cdn.worldvectorlogo.com/logos/kotlin-2.svg") {} } div { img(src = "https://camo.githubusercontent.com/f2e0860a3b1a34658f23a8bcea96f9725b1f8a73/68747470733a2f2f692e696d6775722e636f6d2f4f4737546e65382e706e67") {} } div { img(src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/IntelliJ_IDEA_Logo.svg/1024px-IntelliJ_IDEA_Logo.svg.png") {} } div { img(src = "https://ktor.io/assets/images/ktor_logo_white.svg") {} } } */ } }
agpl-3.0
MoonCheesez/sstannouncer
sstannouncer/app/src/main/java/sst/com/anouncements/feed/data/parser/w3dom/DateParser.kt
1
352
package sst.com.anouncements.feed.data.parser.w3dom import java.text.SimpleDateFormat import java.util.* // Parse the dates when any are encountered const val dateFormat = "yyyy-MM-dd'T'kk:mm:ss.SSSz" fun parseDate(dateString: String): Date { val format = SimpleDateFormat(dateFormat, Locale.getDefault()) return format.parse(dateString)!! }
mit
j2ghz/tachiyomi-extensions
src/all/nhentai/src/eu/kanade/tachiyomi/extension/all/nhentai/NHentaiMetadata.kt
1
954
package eu.kanade.tachiyomi.extension.all.nhentai /** * NHentai metadata */ class NHentaiMetadata { var id: Long? = null var url: String? get() = id?.let { "/g/$it" } set(a) { id = a?.substringAfterLast('/')?.toLong() } var uploadDate: Long? = null var favoritesCount: Long? = null var mediaId: String? = null var japaneseTitle: String? = null var englishTitle: String? = null var shortTitle: String? = null var coverImageType: String? = null var pageImageTypes: MutableList<String> = mutableListOf() var thumbnailImageType: String? = null var scanlator: String? = null val tags: MutableMap<String, MutableList<Tag>> = mutableMapOf() companion object { fun typeToExtension(t: String?) = when (t) { "p" -> "png" "j" -> "jpg" else -> null } } }
apache-2.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/roleplay/RoleplayDanceExecutor.kt
1
407
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.roleplay import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.randomroleplaypictures.client.RandomRoleplayPicturesClient class RoleplayDanceExecutor( loritta: LorittaBot, client: RandomRoleplayPicturesClient, ) : RoleplayPictureExecutor( loritta, client, RoleplayUtils.DANCE_ATTRIBUTES )
agpl-3.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/images/DrawnMaskSignExecutor.kt
1
662
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images import net.perfectdreams.gabrielaimageserver.client.GabrielaImageServerClient import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.base.GabrielaImageServerSingleCommandBase import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.images.base.SingleImageOptions class DrawnMaskSignExecutor( loritta: LorittaBot, client: GabrielaImageServerClient ) : GabrielaImageServerSingleCommandBase( loritta, client, { client.images.drawnMaskSign(it) }, "drawn_mask_sign.png" )
agpl-3.0
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/DemonCommand.kt
1
1406
package net.perfectdreams.loritta.morenitta.commands.vanilla.images import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.gifs.DemonGIF import net.perfectdreams.loritta.morenitta.utils.Constants import net.perfectdreams.loritta.morenitta.utils.MiscUtils import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.api.commands.Command import net.perfectdreams.loritta.morenitta.LorittaBot class DemonCommand(loritta: LorittaBot) : AbstractCommand(loritta, "demon", listOf("demônio", "demonio", "demónio"), category = net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) { override fun getDescriptionKey() = LocaleKeyData("commands.command.demon.description") override fun getExamplesKey() = Command.TWO_IMAGES_EXAMPLES_KEY // TODO: Fix Usage override fun needsToUploadFiles() = true override suspend fun run(context: CommandContext,locale: BaseLocale) { val contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; } val file = DemonGIF.getGIF(contextImage, context.config.localeId) loritta.gifsicle.optimizeGIF(file) context.sendFile(file, "demon.gif", context.getAsMention(true)) file.delete() } }
agpl-3.0
Haldir65/AndroidRepo
otherprojects/_008_textview/app/src/main/java/com/me/harris/textviewtest/model/News.kt
1
1210
package com.me.harris.textviewtest.model data class News(val name: String, val id: Long, val creater: Customer) data class Customer(val id: Long, val name: String) data class User(val name: String, val title: String) data class MainPage(val error:Boolean = false, val results:List<Topic>) data class Topic(val _id: String, val createdAt: String, val desc: String, val images: List<String>, val publishedAt: String , val source: String, val type: String, val url: String, val used: Boolean, val who: String) class FoodStore : Production<Food> { override fun produce(): Food { println("Produce food") return Food() } } class FastFoodStore : Production<FastFood> { override fun produce(): FastFood { println("Produce food") return FastFood() } } class InOutBurger : Production<Burger> { override fun produce(): Burger { println("Produce burger") return Burger() } } open class Food open class FastFood : Food() class Burger : FastFood() interface Production<out T> { fun produce(): T }
apache-2.0
cketti/okhttp
okhttp/src/test/java/okhttp3/internal/platform/android/AndroidSocketAdapterTest.kt
1
3452
/* * Copyright (C) 2019 Square, 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 okhttp3.internal.platform.android import java.security.Provider import javax.net.ssl.SSLContext import javax.net.ssl.SSLSocket import okhttp3.DelegatingSSLSocket import okhttp3.DelegatingSSLSocketFactory import okhttp3.Protocol.HTTP_1_1 import okhttp3.Protocol.HTTP_2 import okhttp3.testing.PlatformRule import org.conscrypt.Conscrypt import org.junit.Assert.assertFalse import org.junit.Assert.assertNotNull import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Assume.assumeFalse import org.junit.Assume.assumeTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized @RunWith(Parameterized::class) class AndroidSocketAdapterTest(private val adapter: SocketAdapter) { @Suppress("RedundantVisibilityModifier") @JvmField @Rule public val platform = PlatformRule.conscrypt() val context by lazy { val provider: Provider = Conscrypt.newProviderBuilder().provideTrustManager(true).build() SSLContext.getInstance("TLS", provider).apply { init(null, null, null) } } @Test fun testMatchesSupportedSocket() { val socketFactory = context.socketFactory val sslSocket = socketFactory.createSocket() as SSLSocket assertTrue(adapter.matchesSocket(sslSocket)) adapter.configureTlsExtensions(sslSocket, null, listOf(HTTP_2, HTTP_1_1)) // not connected assertNull(adapter.getSelectedProtocol(sslSocket)) } @Test fun testMatchesSupportedAndroidSocketFactory() { assumeTrue(adapter is StandardAndroidSocketAdapter) assertTrue(adapter.matchesSocketFactory(context.socketFactory)) assertNotNull(adapter.trustManager(context.socketFactory)) } @Test fun testDoesntMatchSupportedCustomSocketFactory() { assumeFalse(adapter is StandardAndroidSocketAdapter) assertFalse(adapter.matchesSocketFactory(context.socketFactory)) assertNull(adapter.trustManager(context.socketFactory)) } @Test fun testCustomSocket() { val socketFactory = DelegatingSSLSocketFactory(context.socketFactory) assertFalse(adapter.matchesSocketFactory(socketFactory)) val sslSocket = object : DelegatingSSLSocket(context.socketFactory.createSocket() as SSLSocket) {} assertFalse(adapter.matchesSocket(sslSocket)) adapter.configureTlsExtensions(sslSocket, null, listOf(HTTP_2, HTTP_1_1)) // not connected assertNull(adapter.getSelectedProtocol(sslSocket)) } companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun data(): Collection<SocketAdapter> { return listOfNotNull( DeferredSocketAdapter(ConscryptSocketAdapter.factory), DeferredSocketAdapter(AndroidSocketAdapter.factory("org.conscrypt")), StandardAndroidSocketAdapter.buildIfSupported("org.conscrypt") ) } } }
apache-2.0
Nagarajj/orca
orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/memory/InMemoryQueue.kt
1
3436
/* * Copyright 2017 Netflix, 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 com.netflix.spinnaker.orca.q.memory import com.netflix.spinnaker.orca.q.Message import com.netflix.spinnaker.orca.q.Queue import com.netflix.spinnaker.orca.q.ScheduledAction import org.slf4j.Logger import org.slf4j.LoggerFactory.getLogger import org.threeten.extra.Temporals.chronoUnit import java.io.Closeable import java.time.Clock import java.time.Duration import java.time.Instant import java.time.temporal.TemporalAmount import java.util.* import java.util.UUID.randomUUID import java.util.concurrent.DelayQueue import java.util.concurrent.Delayed import java.util.concurrent.TimeUnit import java.util.concurrent.TimeUnit.MILLISECONDS import javax.annotation.PreDestroy class InMemoryQueue( private val clock: Clock, override val ackTimeout: TemporalAmount = Duration.ofMinutes(1), override val deadMessageHandler: (Queue, Message) -> Unit ) : Queue, Closeable { private val log: Logger = getLogger(javaClass) private val queue = DelayQueue<Envelope>() private val unacked = DelayQueue<Envelope>() private val redeliveryWatcher = ScheduledAction(this::redeliver) override fun poll(callback: (Message, () -> Unit) -> Unit) { queue.poll()?.let { envelope -> unacked.put(envelope.copy(scheduledTime = clock.instant().plus(ackTimeout))) callback.invoke(envelope.payload) { ack(envelope.id) } } } override fun push(message: Message, delay: TemporalAmount) = queue.put(Envelope(message, clock.instant().plus(delay), clock)) private fun ack(messageId: UUID) { unacked.removeIf { it.id == messageId } } @PreDestroy override fun close() { log.info("stopping redelivery watcher for $this") redeliveryWatcher.close() } internal fun redeliver() { unacked.pollAll { if (it.count >= Queue.maxRedeliveries) { deadMessageHandler.invoke(this, it.payload) } else { log.warn("redelivering unacked message ${it.payload}") queue.put(it.copy(scheduledTime = clock.instant(), count = it.count + 1)) } } } private fun <T : Delayed> DelayQueue<T>.pollAll(block: (T) -> Unit) { var done = false while (!done) { val value = poll() if (value == null) { done = true } else { block.invoke(value) } } } } internal data class Envelope( val id: UUID, val payload: Message, val scheduledTime: Instant, val clock: Clock, val count: Int = 1 ) : Delayed { constructor(payload: Message, scheduledTime: Instant, clock: Clock) : this(randomUUID(), payload, scheduledTime, clock) override fun compareTo(other: Delayed) = getDelay(MILLISECONDS).compareTo(other.getDelay(MILLISECONDS)) override fun getDelay(unit: TimeUnit) = clock.instant().until(scheduledTime, unit.toChronoUnit()) } private fun TimeUnit.toChronoUnit() = chronoUnit(this)
apache-2.0
christophpickl/kpotpourri
common4k/src/main/kotlin/com/github/christophpickl/kpotpourri/common/random/random.kt
1
3108
package com.github.christophpickl.kpotpourri.common.random import com.github.christophpickl.kpotpourri.common.KPotpourriException import java.lang.IllegalArgumentException /** * Random generator as an interface in order to be testable. */ interface RandX { /** * Generate a random number based on the given range (inclusive), optionally specifying an item to be excluded. */ fun randomBetween(from: Int, to: Int, except: Int? = null): Int /** * Retrieve a single element from the given list, optionally specifying an item to be excluded. */ fun <T> randomOf(items: List<T>, exceptItem: T? = null): T // fun <T> randomElementsExcept(items: List<T>, randomElementsCount: Int, except: T): List<T> } private val MAX_ITERATIONS = 9000 /** * Default implementation of RandX. */ class RandXImpl(private val generator: RandGenerator = RealRandGenerator) : RandX { override fun randomBetween(from: Int, to: Int, except: Int?): Int { if (from < 0 || to < 0) throw IllegalArgumentException("No negative values are allowed: from=$from, to=$to") if (from >= to) throw IllegalArgumentException("From must be bigger then from: from=$from, to=$to") val diff = to - from if (except == null) { return generator.rand(diff) + from } if (except < from || except > to) throw IllegalArgumentException("Except value of '$except' must be within from=$from, to=$to") var randPos: Int? var count = 0 do { randPos = generator.rand(diff) + from if (count++ >= MAX_ITERATIONS) { throw KPotpourriException("Maximum random iterations was reached! Generator: $generator") } } while (randPos == except) return randPos!! } // override fun <T> randomOf(items: List<T>) = items[randomBetween(0, items.size - 1)] override fun <T> randomOf(items: List<T>, exceptItem: T?): T { if (items.isEmpty()) throw IllegalArgumentException("list must not be empty") if (items.size == 1) return items[0] var randItem: T? var count = 0 do { randItem = items[randomBetween(0, items.size - 1)] if (count++ >= MAX_ITERATIONS) { throw KPotpourriException("Maximum random iterations was reached! Generator: $generator") } } while (randItem == exceptItem) return randItem!! } // override fun <T> randomElementsExcept(items: List<T>, randomElementsCount: Int, except: T): List<T> { // if (items.size < randomElementsCount) { // throw IllegalArgumentException("items.size [${items.size}] < randomElementsCount [$randomElementsCount]") // } // val result = mutableListOf<T>() // var honeypot = items.toMutableList().minus(except) // while (result.size != randomElementsCount) { // val randomElement = randomOf(honeypot) // result += randomElement // honeypot = honeypot.minus(randomElement) // } // return result // } // // // // }
apache-2.0
SerenityEnterprises/SerenityCE
src/main/java/host/serenity/serenity/api/value/Value.kt
1
1375
package host.serenity.serenity.api.value import java.util.* interface ValueChangeListener { fun onChanged(oldValue: Any?) } abstract class Value<T>(val name: String, value: T) { val defaultValue: T = value open var value: T = value set(_value) { val oldValue = value field = _value changed(oldValue) } val changeListeners: List<ValueChangeListener> = ArrayList() private fun changed(oldValue: T) { changeListeners.forEach { it.onChanged(oldValue) } } abstract fun setValueFromString(string: String) } abstract class BoundedValue<T : Number>(name: String, value: T, var min: T, var max: T) : Value<T>(name, value) { override var value: T get() = super.value set(value) { if (isWithinBounds(value)) { super.value = value } else { if (value.toDouble() < min.toDouble()) { super.value = min } if (value.toDouble() > max.toDouble()) { super.value = max } } } fun isWithinBounds(value: T): Boolean { return value.toDouble() >= min.toDouble() && value.toDouble() <= max.toDouble() } } @Target(AnnotationTarget.FIELD) @Retention(AnnotationRetention.RUNTIME) annotation class ModuleValue
gpl-3.0
pronghorn-tech/server
src/main/kotlin/tech/pronghorn/server/services/ConnectionAcceptService.kt
1
5289
/* * Copyright 2017 Pronghorn Technology 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 tech.pronghorn.server.services import tech.pronghorn.coroutines.services.InternalSleepableService import tech.pronghorn.server.* import tech.pronghorn.server.selectionhandlers.AcceptHandler import java.io.IOException import java.net.InetSocketAddress import java.nio.channels.* import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.locks.ReentrantLock internal sealed class SocketManagerService : InternalSleepableService() { protected abstract val serverSocket: ServerSocketChannel override fun onStart() { worker.registerSelectionKeyHandler(serverSocket, AcceptHandler(this), SelectionKey.OP_ACCEPT) } override suspend fun run() { while (isRunning()) { accept() sleepAsync() } } protected abstract suspend fun accept() } internal class SingleSocketManager(internal val address: InetSocketAddress, internal val listenBacklog: Int, internal val distributionStrategy: ConnectionDistributionStrategy) { val serverSocket = ServerSocketChannel.open() init { serverSocket.configureBlocking(false) } private val hasStarted = AtomicBoolean(false) private val hasShutdown = AtomicBoolean(false) internal val acceptLock = ReentrantLock() internal fun start() { if (hasStarted.compareAndSet(false, true)) { serverSocket.bind(address, listenBacklog) } } internal fun shutdown() { if (hasShutdown.compareAndSet(false, true)) { serverSocket.close() } } } internal class SingleSocketManagerService(override val worker: HttpServerWorker, internal val manager: SingleSocketManager) : SocketManagerService() { override val serverSocket: ServerSocketChannel = manager.serverSocket private val config = worker.server.config override fun onStart() { super.onStart() manager.start() } override fun onShutdown() { super.onShutdown() manager.shutdown() } override suspend fun accept() { if (serverSocket.socket().isBound && manager.acceptLock.tryLock()) { try { logger.debug { "Accepting connections..." } var acceptedSocket: SocketChannel? = serverSocket.accept() var acceptedCount = 0 while (acceptedSocket != null) { acceptedCount += 1 var handled = false while (!handled) { handled = manager.distributionStrategy.distributeConnection(acceptedSocket) } if (acceptedCount >= config.acceptGrouping) { break } acceptedSocket = serverSocket.accept() } logger.debug { "Accepted $acceptedCount connections." } } catch (ex: IOException) { // no-op } finally { manager.acceptLock.unlock() } } } } internal class MultiSocketManagerService(override val worker: HttpServerWorker) : SocketManagerService() { override val serverSocket: ServerSocketChannel = ServerSocketChannel.open() init { ReusePort.setReusePort(serverSocket) serverSocket.configureBlocking(false) } private val config = worker.server.config override fun onStart() { super.onStart() serverSocket.bind(config.address, config.listenBacklog) } override fun onShutdown() { super.onShutdown() serverSocket.close() } override suspend fun accept() { var acceptedCount = 0 try { var acceptedSocket = serverSocket.accept() while (acceptedSocket != null) { acceptedCount += 1 acceptedSocket.configureBlocking(false) acceptedSocket.socket().tcpNoDelay = true acceptedSocket.socket().keepAlive = true acceptedSocket.socket().receiveBufferSize = config.socketReadBufferSize acceptedSocket.socket().sendBufferSize = config.socketWriteBufferSize val connection = HttpServerConnection(worker, acceptedSocket) worker.addConnection(connection) if (acceptedCount >= config.acceptGrouping) { break } acceptedSocket = serverSocket.accept() } } catch (ex: IOException) { // no-op } } }
apache-2.0
kotlintest/kotlintest
kotest-assertions/src/jvmMain/kotlin/io/kotest/assertions/AssertionCounter.kt
1
520
package io.kotest.assertions actual object AssertionCounter { private val context = object : ThreadLocal<Int>() { override fun initialValue(): Int = 0 } /** * Returns the number of assertions executed in the current context. */ actual fun get(): Int = context.get() /** * Resets the count for the current context */ actual fun reset() = context.set(0) /** * Increments the counter for the current context. */ actual fun inc() = context.set(context.get() + 1) }
apache-2.0
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/playback/file/exoplayer/GivenAPlayingFile/ThatIsThenPaused/AndThePlayerIdles/WhenThePlayerWillNotPlayWhenReady.kt
1
2369
package com.lasthopesoftware.bluewater.client.playback.file.exoplayer.GivenAPlayingFile.ThatIsThenPaused.AndThePlayerIdles import com.annimon.stream.Stream import com.google.android.exoplayer2.Player import com.lasthopesoftware.any import com.lasthopesoftware.bluewater.client.playback.exoplayer.PromisingExoPlayer import com.lasthopesoftware.bluewater.client.playback.file.exoplayer.ExoPlayerPlaybackHandler import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import org.junit.BeforeClass import org.junit.Test import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.Mockito import java.util.* import java.util.concurrent.ExecutionException import java.util.concurrent.TimeUnit import java.util.concurrent.TimeoutException class WhenThePlayerWillNotPlayWhenReady { companion object { private val eventListeners: MutableCollection<Player.EventListener> = ArrayList() private val mockExoPlayer = Mockito.mock(PromisingExoPlayer::class.java) @JvmStatic @BeforeClass @Throws(InterruptedException::class, ExecutionException::class) fun before() { Mockito.`when`(mockExoPlayer.setPlayWhenReady(anyBoolean())).thenReturn(mockExoPlayer.toPromise()) Mockito.`when`(mockExoPlayer.getPlayWhenReady()).thenReturn(true.toPromise()) Mockito.`when`(mockExoPlayer.getCurrentPosition()).thenReturn(50L.toPromise()) Mockito.`when`(mockExoPlayer.getDuration()).thenReturn(100L.toPromise()) Mockito.doAnswer { invocation -> eventListeners.add(invocation.getArgument(0)) mockExoPlayer.toPromise() }.`when`(mockExoPlayer).addListener(any()) val exoPlayerPlaybackHandler = ExoPlayerPlaybackHandler(mockExoPlayer) val playbackPromise = exoPlayerPlaybackHandler.promisePlayback() playbackPromise .eventually { p -> val playableFilePromise = p.promisePause() Stream.of(eventListeners) .forEach { e -> e.onPlayerStateChanged(false, Player.STATE_IDLE) } playableFilePromise } val playedPromise = playbackPromise .eventually { obj -> obj.promisePlayedFile() } try { FuturePromise(playedPromise)[1, TimeUnit.SECONDS] } catch (ignored: TimeoutException) { } } } @Test fun thenPlaybackIsNotRestarted() { Mockito.verify(mockExoPlayer, Mockito.times(1)).setPlayWhenReady(true) } }
lgpl-3.0
raniejade/kspec
kspec-engine/src/test/kotlin/io/polymorphicpanda/kspec/engine/FilterTest.kt
1
10527
package io.polymorphicpanda.kspec.engine import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import io.polymorphicpanda.kspec.KSpec import io.polymorphicpanda.kspec.config.KSpecConfig import io.polymorphicpanda.kspec.context import io.polymorphicpanda.kspec.context.Context import io.polymorphicpanda.kspec.describe import io.polymorphicpanda.kspec.engine.discovery.DiscoveryRequest import io.polymorphicpanda.kspec.engine.execution.ExecutionListenerAdapter import io.polymorphicpanda.kspec.engine.execution.ExecutionNotifier import io.polymorphicpanda.kspec.it import io.polymorphicpanda.kspec.tag.SimpleTag import org.junit.Test /** * @author Ranie Jade Ramiso */ class FilterTest { object Tag1: SimpleTag() object Tag2: SimpleTag() object Tag3: SimpleTag() @Test fun testIncludeExample() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class IncludeSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.include(Tag1::class) } override fun spec() { describe("group") { it("example") { } it("included example", Tag1) { } } } } val result = engine.discover(DiscoveryRequest(listOf(IncludeSpec::class), KSpecConfig(), null)) val expected = """ it: included example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testIncludeExampleGroup() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class IncludeSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.include(Tag1::class) } override fun spec() { describe("group") { it("example") { } context("context", Tag1) { it("included example") { } } } } } val result = engine.discover(DiscoveryRequest(listOf(IncludeSpec::class), KSpecConfig(), null)) val expected = """ it: included example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testExcludeExample() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class ExcludeSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.exclude(Tag1::class) } override fun spec() { describe("group") { it("example") { } it("included example", Tag1) { } } } } val result = engine.discover(DiscoveryRequest(listOf(ExcludeSpec::class), KSpecConfig(), null)) val expected = """ it: example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testExcludeExampleGroup() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class ExcludeSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.exclude(Tag1::class) } override fun spec() { describe("group") { it("example") { } context("context", Tag1) { it("included example") { } } } } } val result = engine.discover(DiscoveryRequest(listOf(ExcludeSpec::class), KSpecConfig(), null)) val expected = """ it: example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testMatchExample() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class MatchSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.matching(Tag1::class) } override fun spec() { describe("group") { it("example") { } it("included example", Tag1) { } } } } val result = engine.discover(DiscoveryRequest(listOf(MatchSpec::class), KSpecConfig(), null)) val expected = """ it: included example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testMatchExampleGroup() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class MatchSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.matching(Tag1::class) } override fun spec() { describe("group") { it("example") { } context("context", Tag1) { it("included example") { } } } } } val result = engine.discover(DiscoveryRequest(listOf(MatchSpec::class), KSpecConfig(), null)) val expected = """ it: included example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testNoMatch() { val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class MatchSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.matching(Tag1::class) } override fun spec() { describe("group") { it("example") { } context("context") { it("another example") { } } } } } val result = engine.discover(DiscoveryRequest(listOf(MatchSpec::class), KSpecConfig())) val expected = """ it: example it: another example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } @Test fun testFilterPrecedence() { /** * The order filters are applied is: * 1. Match * 2. Include * 3. Exclude */ val builder = StringBuilder() val notifier = ExecutionNotifier() notifier.addListener(object: ExecutionListenerAdapter() { override fun exampleStarted(example: Context.Example) { builder.appendln(example.description) } }) val engine = KSpecEngine(notifier) class FilterSpec: KSpec() { override fun configure(config: KSpecConfig) { config.filter.matching(Tag1::class) config.filter.include(Tag2::class) config.filter.exclude(Tag3::class) } override fun spec() { describe("group") { it("first included example", Tag1) { /** * not executed, has match filter but not include filter tag */ } it("unmatched example", Tag2) { } context("matched context", Tag1) { it("excluded example", Tag3) { } it ("included example", Tag2) { /** * Executed as parent has match filter and example has include tag */ } describe("included group", Tag2) { it ("some example") { /** * Executed as parent has include filter tag */ } } } } } } val result = engine.discover(DiscoveryRequest(listOf(FilterSpec::class), KSpecConfig())) val expected = """ it: included example it: some example """.trimIndent() engine.execute(result) assertThat(builder.trimEnd().toString(), equalTo(expected)) } }
mit
alessio-b-zak/myRivers
android/app/src/main/java/com/epimorphics/android/myrivers/fragments/WIMSDetailsFragment.kt
1
8766
package com.epimorphics.android.myrivers.fragments import android.content.Intent import android.net.Uri import android.os.Bundle import android.support.v7.widget.Toolbar import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.ImageButton import android.widget.TableLayout import android.widget.TextView import com.epimorphics.android.myrivers.R import com.epimorphics.android.myrivers.activities.DataViewActivity import com.epimorphics.android.myrivers.data.Measurement import com.epimorphics.android.myrivers.data.WIMSPoint import com.epimorphics.android.myrivers.helpers.FragmentHelper /** * A fragment occupying full screen showcasing all the data stored inside a WIMSPoint. * It is initiated by clicking a "More Info" button in WIMSDataFragment * * @see <a href="https://github.com/alessio-b-zak/myRivers/blob/master/graphic%20assets/screenshots/wims_details_view.png">Screenshot</a> * @see WIMSDataFragment */ open class WIMSDetailsFragment : FragmentHelper() { private lateinit var mDataViewActivity: DataViewActivity private lateinit var mWIMSDetailsFragment: WIMSDetailsFragment private lateinit var mWIMSDetailsView: View private lateinit var mToolbar: Toolbar private lateinit var mBackButton: ImageButton private lateinit var mFullReportButton: Button private lateinit var mGeneralTable: TableLayout private lateinit var mDissolvedOxygenTable: TableLayout private lateinit var mOxygenDemandTable: TableLayout private lateinit var mNitratesTable: TableLayout private lateinit var mPhosphatesTable: TableLayout private lateinit var mMetalsTable: TableLayout private lateinit var mSolidsTable: TableLayout private val TAG = "WIMS_DETAILS_FRAGMENT" private val URL_PREFIX = "http://environment.data.gov.uk/water-quality/view/sampling-point/" /** * Called when a fragment is created. Initiates mDataViewActivity * * @param savedInstanceState Saved state of the fragment */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true mDataViewActivity = activity as DataViewActivity } /** * Called when a fragment view is created. Initiates and manipulates all required layout elements. * * @param inflater LayoutInflater * @param container ViewGroup * @param savedInstanceState Saved state of the fragment * * @return inflated and fully populated View */ override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater!!.inflate(R.layout.fragment_wims_details_view, container, false) mWIMSDetailsView = view mWIMSDetailsFragment = this mGeneralTable = view.bind(R.id.wims_details_general_table) mDissolvedOxygenTable = view.bind(R.id.wims_details_diss_oxygen_table) mOxygenDemandTable = view.bind(R.id.wims_details_oxygen_demand_table) mNitratesTable = view.bind(R.id.wims_details_nitrates_table) mPhosphatesTable = view.bind(R.id.wims_details_phosphates_table) mMetalsTable = view.bind(R.id.wims_details_metals_table) mSolidsTable = view.bind(R.id.wims_details_solids_table) val wimsPoint = mDataViewActivity.selectedWIMSPoint val wimsPointLabel: TextView = view.bind(R.id.wims_details_title) // If wimsPoint.label is not null show wimsPoint.label as name, otherwise show wimsPoint.id wimsPointLabel.text = if(wimsPoint.label != null) "Samples from ${wimsPoint.label}" else "Samples from ${wimsPoint.id}" mToolbar = view.bind(R.id.wims_details_toolbar) // Links to the WIMS web view mFullReportButton = view.bind(R.id.wims_full_report_button) mFullReportButton.setOnClickListener { val intent = Intent() intent.action = Intent.ACTION_VIEW intent.addCategory(Intent.CATEGORY_BROWSABLE) intent.data = Uri.parse(URL_PREFIX + wimsPoint.id) startActivity(intent) } mBackButton = view.bind(R.id.back_button_wims_details_view) mBackButton.setOnClickListener { activity.onBackPressed() } populateData(wimsPoint) return view } /** * Populates data into the data tables * * @param wimsPoint WIMSPoint containing data to be populated */ fun populateData(wimsPoint: WIMSPoint) { val groupList = arrayListOf<String>("general", "diss_oxygen", "oxygen_demand", "nitrates", "phosphates", "metals", "solids") var emptyGroupCount = 0 // Loops through all the measurement groups and populates the data for (group in groupList) { var groupDeterminandList: ArrayList<String> var groupTable: TableLayout val groupTitle: TextView = mWIMSDetailsView.bind(resources.getIdentifier( "wims_details_" + group + "_title", "id", mDataViewActivity.packageName)) when (group) { "general" -> { groupDeterminandList = WIMSPoint.generalGroup groupTable = mGeneralTable } "diss_oxygen" -> { groupDeterminandList = WIMSPoint.dissolvedOxygenGroup groupTable = mDissolvedOxygenTable } "oxygen_demand" -> { groupDeterminandList = WIMSPoint.oxygenDemandGroup groupTable = mOxygenDemandTable } "nitrates" -> { groupDeterminandList = WIMSPoint.nitrateGroup groupTable = mNitratesTable } "phosphates" -> { groupDeterminandList = WIMSPoint.phosphateGroup groupTable = mPhosphatesTable } "solids" -> { groupDeterminandList = WIMSPoint.solidGroup groupTable = mSolidsTable } else -> { // metals val filterMap = wimsPoint.measurementMap.filterKeys { key: String -> !WIMSPoint.nonMetalGroup.contains(key) } groupDeterminandList = ArrayList(filterMap.keys) groupTable = mMetalsTable } } val groupHasRecords = wimsPoint.measurementMap.any { entry: Map.Entry<String, ArrayList<Measurement>> -> groupDeterminandList.contains(entry.key) } if (groupHasRecords) { var rowIndex = 0 // Set Header Row var tableHeaderRow = newTableRow(rowIndex++) addTextView(tableHeaderRow, "Determinand", 0.3, R.style.text_view_table_parent, Gravity.START) addTextView(tableHeaderRow, "Unit", 0.2, R.style.text_view_table_parent) addTextView(tableHeaderRow, "Result", 0.2, R.style.text_view_table_parent) addTextView(tableHeaderRow, "Date", 0.3, R.style.text_view_table_parent) groupTable.addView(tableHeaderRow) for (entry: String in groupDeterminandList) { if (wimsPoint.measurementMap.containsKey(entry)) { tableHeaderRow = newTableRow(rowIndex++) addTextView(tableHeaderRow, entry, 0.3, R.style.text_view_table_child, Gravity.START, 0, wimsPoint.measurementMap[entry]!![0].descriptor) addTextView(tableHeaderRow, wimsPoint.measurementMap[entry]!![0].unit, 0.2, R.style.text_view_table_child) addTextView(tableHeaderRow, wimsPoint.measurementMap[entry]!![0].result.toString(), 0.2, R.style.text_view_table_child) addTextView(tableHeaderRow, simplifyDate(wimsPoint.measurementMap[entry]!![0].date), 0.3, R.style.text_view_table_child) groupTable.addView(tableHeaderRow) } } } else { groupTitle.visibility = View.GONE groupTable.visibility = View.GONE emptyGroupCount++ } } // If there is not data show an info message pointing out the "Detailed Report" button available if (groupList.size == emptyGroupCount) { val noDataExplanation: TextView = mWIMSDetailsView.bind(R.id.wims_details_no_data) noDataExplanation.visibility = View.VISIBLE } } }
mit
FurhatRobotics/example-skills
Dog/src/main/kotlin/furhatos/app/dog/gestures/yawns.kt
1
573
package furhatos.app.dog.gestures import furhatos.app.dog.utils._defineGesture import furhatos.app.dog.utils.getAudioURL import furhatos.gestures.BasicParams val yawn1 = _defineGesture("yawn1", frameTimes = listOf(0.2), audioURL = getAudioURL("Medium_large_dog_yawning_02.wav")) { // This empty frame needs to be here for the audio to not play twice frame(1.0) { } frame(0.2, 1.5) { BasicParams.PHONE_AAH to 1.0 BasicParams.NECK_TILT to -15.0 BasicParams.NECK_ROLL to 8.0 BasicParams.GAZE_PAN to -18.0 } reset(2.0) }
mit
bealex/SwiftLintAppCode
src/com/lonelybytes/swiftlint/SwiftLintConfig.kt
1
1505
package com.lonelybytes.swiftlint import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.vfs.VirtualFile import java.io.File class SwiftLintConfig { companion object { const val FILE_NAME = ".swiftlint.yml" private fun configExistsInDir(aPath: String): Boolean { return File("$aPath/$FILE_NAME").exists() } private fun configPathInBetween(rootPath: String, upToPath: String): String? { var testPath = upToPath.substringBeforeLast("/") while (testPath.contains(rootPath) && !configExistsInDir(testPath)) { testPath = testPath.substringBeforeLast("/") } return if (configExistsInDir(testPath)) testPath else null } fun swiftLintConfigPath(aProject: Project, aFileToFindConfigFor: VirtualFile): String? { val projectBasePath = aProject.basePath val filePath = aFileToFindConfigFor.path return if (projectBasePath != null && configExistsInDir(projectBasePath) && filePath.contains(projectBasePath)) { projectBasePath } else { ProjectRootManager.getInstance(aProject) .contentSourceRoots .filter { it.isDirectory && filePath.contains(it.path) } .mapNotNull { configPathInBetween(it.path, filePath) } .firstOrNull() } } } }
mit
Ph1b/MaterialAudiobookPlayer
data/src/main/kotlin/de/ph1b/audiobook/data/repo/internals/migrations/Migration41to42.kt
2
717
package de.ph1b.audiobook.data.repo.internals.migrations import android.content.ContentValues import android.database.sqlite.SQLiteDatabase import androidx.sqlite.db.SupportSQLiteDatabase class Migration41to42 : IncrementalMigration(41) { override fun migrate(db: SupportSQLiteDatabase) { // invalidate modification time stamps so the chapters will be re-scanned val lastModifiedCv = ContentValues().apply { put("lastModified", 0) } db.update("tableChapters", SQLiteDatabase.CONFLICT_FAIL, lastModifiedCv, null, null) val marksCv = ContentValues().apply { put("marks", null as String?) } db.update("tableChapters", SQLiteDatabase.CONFLICT_FAIL, marksCv, null, null) } }
lgpl-3.0